@opentiny/next-sdk 0.3.3 → 0.4.1

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 (134) hide show
  1. package/agent/AgentModelProvider.ts +78 -81
  2. package/agent/type.ts +6 -9
  3. package/agent/utils/getAISDKTools.ts +0 -1
  4. package/agent/utils/getBuiltinMcpTools.ts +7 -7
  5. package/core.ts +1 -3
  6. package/dist/SimulatorMask-BHVXyogh-iNUb4dyF.js +361 -0
  7. package/dist/agent/type.d.ts +4 -12
  8. package/dist/agent/utils/getBuiltinMcpTools.d.ts +3 -3
  9. package/dist/core.d.ts +1 -1
  10. package/dist/core.js +18 -18
  11. package/dist/index-CXK8CcKq.js +6076 -0
  12. package/dist/index.d.ts +2 -4
  13. package/dist/index.js +57 -2783
  14. package/dist/initialize-builtin-WebMCP-rALfqS-o.js +6389 -0
  15. package/dist/page-tools/a11y/build.d.ts +11 -0
  16. package/dist/page-tools/a11y/constants.d.ts +9 -0
  17. package/dist/page-tools/a11y/search.d.ts +17 -0
  18. package/dist/page-tools/a11y/types.d.ts +104 -0
  19. package/dist/page-tools/a11y/utils.d.ts +34 -0
  20. package/dist/page-tools/a11y/vnode.d.ts +37 -0
  21. package/dist/page-tools/a11y-tree.d.ts +12 -0
  22. package/dist/page-tools/bridge.d.ts +0 -6
  23. package/dist/page-tools/constants.d.ts +22 -0
  24. package/dist/page-tools/context.d.ts +28 -0
  25. package/dist/page-tools/handlers/browserState.d.ts +8 -0
  26. package/dist/page-tools/handlers/click.d.ts +8 -0
  27. package/dist/page-tools/handlers/executeJavascript.d.ts +8 -0
  28. package/dist/page-tools/handlers/fill.d.ts +8 -0
  29. package/dist/page-tools/handlers/scroll.d.ts +8 -0
  30. package/dist/page-tools/handlers/searchTree.d.ts +8 -0
  31. package/dist/page-tools/handlers/select.d.ts +8 -0
  32. package/dist/page-tools/initialize-builtin-WebMCP.d.ts +1 -0
  33. package/dist/page-tools/page-agent-highlight/index.d.ts +9 -0
  34. package/dist/page-tools/page-agent-mask/SimulatorMask.d.ts +14 -0
  35. package/dist/page-tools/page-agent-mask/checkDarkMode.d.ts +5 -0
  36. package/dist/page-tools/page-agent-tool.d.ts +4 -0
  37. package/dist/page-tools/page-state-cache.d.ts +36 -0
  38. package/dist/page-tools/schema.d.ts +43 -0
  39. package/dist/page-tools/utils/dom.d.ts +6 -0
  40. package/dist/page-tools/utils/scroll.d.ts +15 -0
  41. package/dist/runtime.d.ts +4 -0
  42. package/dist/runtime.js +744 -0
  43. package/dist/utils/builtinProxy.d.ts +1 -1
  44. package/index.ts +2 -19
  45. package/package.json +14 -18
  46. package/page-tools/a11y/build.ts +70 -0
  47. package/page-tools/a11y/constants.ts +110 -0
  48. package/page-tools/a11y/search.ts +129 -0
  49. package/page-tools/a11y/types.ts +108 -0
  50. package/page-tools/a11y/utils.ts +266 -0
  51. package/page-tools/a11y/vnode.ts +229 -0
  52. package/page-tools/a11y-tree.ts +13 -0
  53. package/page-tools/bridge.ts +49 -15
  54. package/page-tools/constants.ts +72 -0
  55. package/page-tools/context.ts +13 -0
  56. package/page-tools/handlers/browserState.ts +12 -0
  57. package/page-tools/handlers/click.ts +26 -0
  58. package/page-tools/handlers/executeJavascript.ts +22 -0
  59. package/page-tools/handlers/fill.ts +60 -0
  60. package/page-tools/handlers/scroll.ts +66 -0
  61. package/page-tools/handlers/searchTree.ts +30 -0
  62. package/page-tools/handlers/select.ts +34 -0
  63. package/page-tools/initialize-builtin-WebMCP.ts +20 -0
  64. package/page-tools/page-agent-highlight/index.ts +198 -0
  65. package/page-tools/page-agent-mask/SimulatorMask.module.css +14 -0
  66. package/page-tools/page-agent-mask/SimulatorMask.ts +279 -0
  67. package/page-tools/page-agent-mask/checkDarkMode.ts +181 -0
  68. package/page-tools/page-agent-mask/cursor-border.svg +3 -0
  69. package/page-tools/page-agent-mask/cursor-fill.svg +5 -0
  70. package/page-tools/page-agent-mask/cursor.module.css +70 -0
  71. package/page-tools/page-agent-prompt.md +139 -0
  72. package/page-tools/page-agent-tool.ts +175 -0
  73. package/page-tools/page-state-cache.ts +78 -0
  74. package/page-tools/schema.ts +51 -0
  75. package/page-tools/utils/dom.ts +155 -0
  76. package/page-tools/utils/scroll.ts +58 -0
  77. package/runtime.ts +13 -0
  78. package/utils/builtinProxy.ts +45 -13
  79. package/vite.config.runtime.ts +22 -0
  80. package/vite.config.ts +52 -8
  81. package/McpSdk.ts +0 -14
  82. package/WebAgent.ts +0 -5
  83. package/WebMcp.ts +0 -20
  84. package/Zod.ts +0 -1
  85. package/dist/AgentModelProvider-CwqOT28f.js +0 -4198
  86. package/dist/McpSdk.d.ts +0 -14
  87. package/dist/WebAgent.d.ts +0 -5
  88. package/dist/WebMcp.d.ts +0 -20
  89. package/dist/Zod.d.ts +0 -1
  90. package/dist/index.es.dev.js +0 -53427
  91. package/dist/index.es.js +0 -42147
  92. package/dist/index.umd.dev.js +0 -53820
  93. package/dist/index.umd.js +0 -814
  94. package/dist/mcpsdk@1.25.3.dev.js +0 -22621
  95. package/dist/mcpsdk@1.25.3.es.dev.js +0 -22619
  96. package/dist/mcpsdk@1.25.3.es.js +0 -16802
  97. package/dist/mcpsdk@1.25.3.js +0 -43
  98. package/dist/transport/ExtensionClientTransport.d.ts +0 -24
  99. package/dist/transport/ExtensionContentServerTransport.d.ts +0 -39
  100. package/dist/transport/ExtensionPageServerTransport.d.ts +0 -36
  101. package/dist/transport/messages.d.ts +0 -9
  102. package/dist/vite.config.mcpSdk.d.ts +0 -2
  103. package/dist/vite.config.webAgent.d.ts +0 -2
  104. package/dist/vite.config.webMcp.d.ts +0 -2
  105. package/dist/vite.config.webMcpFull.d.ts +0 -2
  106. package/dist/vite.config.zod.d.ts +0 -2
  107. package/dist/webagent.dev.js +0 -47597
  108. package/dist/webagent.es.dev.js +0 -47204
  109. package/dist/webagent.es.js +0 -37494
  110. package/dist/webagent.js +0 -634
  111. package/dist/webmcp-full.dev.js +0 -24430
  112. package/dist/webmcp-full.es.dev.js +0 -24426
  113. package/dist/webmcp-full.es.js +0 -18333
  114. package/dist/webmcp-full.js +0 -43
  115. package/dist/webmcp.dev.js +0 -1595
  116. package/dist/webmcp.es.dev.js +0 -1589
  117. package/dist/webmcp.es.js +0 -1406
  118. package/dist/webmcp.js +0 -1
  119. package/dist/zod@3.25.76.dev.js +0 -4037
  120. package/dist/zod@3.25.76.es.dev.js +0 -4033
  121. package/dist/zod@3.25.76.es.js +0 -2945
  122. package/dist/zod@3.25.76.js +0 -1
  123. package/transport/ExtensionClientTransport.ts +0 -100
  124. package/transport/ExtensionContentServerTransport.ts +0 -162
  125. package/transport/ExtensionPageServerTransport.ts +0 -149
  126. package/transport/messages.ts +0 -63
  127. package/vite-build-tsc.ts +0 -63
  128. package/vite-env.d.ts +0 -5
  129. package/vite.config.mcpSdk.ts +0 -28
  130. package/vite.config.webAgent.ts +0 -19
  131. package/vite.config.webMcp.ts +0 -40
  132. package/vite.config.webMcpFull.ts +0 -19
  133. package/vite.config.zod.ts +0 -23
  134. /package/dist/{vite-build-tsc.d.ts → vite.config.runtime.d.ts} +0 -0
package/dist/webagent.js DELETED
@@ -1,634 +0,0 @@
1
- (function(zr,Wn){typeof exports=="object"&&typeof module<"u"?Wn(exports):typeof define=="function"&&define.amd?define(["exports"],Wn):(zr=typeof globalThis<"u"?globalThis:zr||self,Wn(zr.WebAgent={}))})(this,(function(zr){"use strict";var Wn="vercel.ai.error",wv=Symbol.for(Wn),md,gd,be=class mv extends(gd=Error,md=wv,gd){constructor({name:t,message:r,cause:n}){super(r),this[md]=!0,this.name=t,this.cause=n}static isInstance(t){return mv.hasMarker(t,Wn)}static hasMarker(t,r){const n=Symbol.for(r);return t!=null&&typeof t=="object"&&n in t&&typeof t[n]=="boolean"&&t[n]===!0}},_d="AI_APICallError",yd=`vercel.ai.error.${_d}`,bv=Symbol.for(yd),vd,wd,at=class extends(wd=be,vd=bv,wd){constructor({message:t,url:r,requestBodyValues:n,statusCode:o,responseHeaders:s,responseBody:i,cause:a,isRetryable:l=o!=null&&(o===408||o===409||o===429||o>=500),data:c}){super({name:_d,message:t,cause:a}),this[vd]=!0,this.url=r,this.requestBodyValues=n,this.statusCode=o,this.responseHeaders=s,this.responseBody=i,this.isRetryable=l,this.data=c}static isInstance(t){return be.hasMarker(t,yd)}},bd="AI_EmptyResponseBodyError",kd=`vercel.ai.error.${bd}`,kv=Symbol.for(kd),Td,Cd,Tv=class extends(Cd=be,Td=kv,Cd){constructor({message:t="Empty response body"}={}){super({name:bd,message:t}),this[Td]=!0}static isInstance(t){return be.hasMarker(t,kd)}};function Tn(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var Sd="AI_InvalidArgumentError",Id=`vercel.ai.error.${Sd}`,Cv=Symbol.for(Id),xd,Ed,$d=class extends(Ed=be,xd=Cv,Ed){constructor({message:t,cause:r,argument:n}){super({name:Sd,message:t,cause:r}),this[xd]=!0,this.argument=n}static isInstance(t){return be.hasMarker(t,Id)}},Rd="AI_InvalidPromptError",Pd=`vercel.ai.error.${Rd}`,Sv=Symbol.for(Pd),Md,Nd,Cn=class extends(Nd=be,Md=Sv,Nd){constructor({prompt:e,message:t,cause:r}){super({name:Rd,message:`Invalid prompt: ${t}`,cause:r}),this[Md]=!0,this.prompt=e}static isInstance(e){return be.hasMarker(e,Pd)}},Od="AI_InvalidResponseDataError",Ad=`vercel.ai.error.${Od}`,Iv=Symbol.for(Ad),qd,Ld,Qi=class extends(Ld=be,qd=Iv,Ld){constructor({data:t,message:r=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:Od,message:r}),this[qd]=!0,this.data=t}static isInstance(t){return be.hasMarker(t,Ad)}},jd="AI_JSONParseError",Dd=`vercel.ai.error.${jd}`,xv=Symbol.for(Dd),Ud,zd,Ds=class extends(zd=be,Ud=xv,zd){constructor({text:t,cause:r}){super({name:jd,message:`JSON parsing failed: Text: ${t}.
2
- Error message: ${Tn(r)}`,cause:r}),this[Ud]=!0,this.text=t}static isInstance(t){return be.hasMarker(t,Dd)}},Fd="AI_LoadAPIKeyError",Vd=`vercel.ai.error.${Fd}`,Ev=Symbol.for(Vd),Zd,Bd,Us=class extends(Bd=be,Zd=Ev,Bd){constructor({message:t}){super({name:Fd,message:t}),this[Zd]=!0}static isInstance(t){return be.hasMarker(t,Vd)}},Hd="AI_TooManyEmbeddingValuesForCallError",Jd=`vercel.ai.error.${Hd}`,$v=Symbol.for(Jd),Gd,Wd,Rv=class extends(Wd=be,Gd=$v,Wd){constructor(e){super({name:Hd,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[Gd]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return be.hasMarker(e,Jd)}},Kd="AI_TypeValidationError",Yd=`vercel.ai.error.${Kd}`,Pv=Symbol.for(Yd),Qd,Xd,Sn=class fd extends(Xd=be,Qd=Pv,Xd){constructor({value:t,cause:r,context:n}){let o="Type validation failed";if(n?.field&&(o+=` for ${n.field}`),n?.entityName||n?.entityId){o+=" (";const s=[];n.entityName&&s.push(n.entityName),n.entityId&&s.push(`id: "${n.entityId}"`),o+=s.join(", "),o+=")"}super({name:Kd,message:`${o}: Value: ${JSON.stringify(t)}.
3
- Error message: ${Tn(r)}`,cause:r}),this[Qd]=!0,this.value=t,this.context=n}static isInstance(t){return be.hasMarker(t,Yd)}static wrap({value:t,cause:r,context:n}){var o,s,i;return fd.isInstance(r)&&r.value===t&&((o=r.context)==null?void 0:o.field)===n?.field&&((s=r.context)==null?void 0:s.entityName)===n?.entityName&&((i=r.context)==null?void 0:i.entityId)===n?.entityId?r:new fd({value:t,cause:r,context:n})}},ep="AI_UnsupportedFunctionalityError",tp=`vercel.ai.error.${ep}`,Mv=Symbol.for(tp),rp,np,Pr=class extends(np=be,rp=Mv,np){constructor({functionality:t,message:r=`'${t}' functionality not supported.`}){super({name:ep,message:r}),this[rp]=!0,this.functionality=t}static isInstance(t){return be.hasMarker(t,tp)}};const op=Object.freeze({status:"aborted"});function W(e,t,r){function n(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=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:e});function i(a){var l;const c=r?.Parent?new s:this;n(c,a),(l=c._zod).deferred??(l.deferred=[]);for(const u of c._zod.deferred)u();return c}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}class Mo extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const sp={};function en(e){return sp}function ap(e){const t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function Nv(e,t){return typeof t=="bigint"?t.toString():t}function Xi(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function el(e){return e==null}function tl(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function Ov(e,t){const r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(e.toFixed(o).replace(".","")),i=Number.parseInt(t.toFixed(o).replace(".",""));return s%i/10**o}function Ve(e,t,r){Object.defineProperty(e,t,{get(){{const n=r();return e[t]=n,n}},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function zs(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function No(e){return JSON.stringify(e)}const ip=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function Fs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Av=Xi(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Vs(e){if(Fs(e)===!1)return!1;const t=e.constructor;if(t===void 0)return!0;const r=t.prototype;return!(Fs(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}const qv=new Set(["string","number","symbol"]);function Oo(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function In(e,t,r){const n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function fe(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function Lv(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const jv={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 Dv(e,t){const r={},n=e._zod.def;for(const o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&(r[o]=n.shape[o])}return In(e,{...e._zod.def,shape:r,checks:[]})}function Uv(e,t){const r={...e._zod.def.shape},n=e._zod.def;for(const o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&delete r[o]}return In(e,{...e._zod.def,shape:r,checks:[]})}function zv(e,t){if(!Vs(t))throw new Error("Invalid input to extend: expected a plain object");const r={...e._zod.def,get shape(){const n={...e._zod.def.shape,...t};return zs(this,"shape",n),n},checks:[]};return In(e,r)}function Fv(e,t){return In(e,{...e._zod.def,get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return zs(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function Vv(e,t,r){const n=t._zod.def.shape,o={...n};if(r)for(const s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=e?new e({type:"optional",innerType:n[s]}):n[s])}else for(const s in n)o[s]=e?new e({type:"optional",innerType:n[s]}):n[s];return In(t,{...t._zod.def,shape:o,checks:[]})}function Zv(e,t,r){const n=t._zod.def.shape,o={...n};if(r)for(const s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new e({type:"nonoptional",innerType:n[s]}))}else for(const s in n)o[s]=new e({type:"nonoptional",innerType:n[s]});return In(t,{...t._zod.def,shape:o,checks:[]})}function Ao(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function xn(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function Zs(e){return typeof e=="string"?e:e?.message}function tn(e,t,r){const n={...e,path:e.path??[]};if(!e.message){const o=Zs(e.inst?._zod.def?.error?.(e))??Zs(t?.error?.(e))??Zs(r.customError?.(e))??Zs(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function rl(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function qo(...e){const[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}const lp=(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,Nv,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},cp=W("$ZodError",lp),up=W("$ZodError",lp,{Parent:Error});function Bv(e,t=r=>r.message){const r={},n=[];for(const o of e.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o))):n.push(t(o));return{formErrors:n,fieldErrors:r}}function Hv(e,t){const r=t||function(s){return s.message},n={_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)n._errors.push(r(i));else{let a=n,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(r(i))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return o(e),n}const Jv=e=>(t,r,n,o)=>{const s=n?Object.assign(n,{async:!1}):{async:!1},i=t._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new Mo;if(i.issues.length){const a=new(o?.Err??e)(i.issues.map(l=>tn(l,s,en())));throw ip(a,o?.callee),a}return i.value},Gv=e=>async(t,r,n,o)=>{const s=n?Object.assign(n,{async:!0}):{async:!0};let i=t._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){const a=new(o?.Err??e)(i.issues.map(l=>tn(l,s,en())));throw ip(a,o?.callee),a}return i.value},dp=e=>(t,r,n)=>{const o=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Mo;return s.issues.length?{success:!1,error:new(e??cp)(s.issues.map(i=>tn(i,o,en())))}:{success:!0,data:s.value}},pp=dp(up),fp=e=>async(t,r,n)=>{const o=n?Object.assign(n,{async:!0}):{async:!0};let s=t._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(i=>tn(i,o,en())))}:{success:!0,data:s.value}},Wv=fp(up),Kv=/^[cC][^\s-]{8,}$/,Yv=/^[0-9a-z]+$/,Qv=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Xv=/^[0-9a-vA-V]{20}$/,e1=/^[A-Za-z0-9]{27}$/,t1=/^[a-zA-Z0-9_-]{21}$/,r1=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,n1=/^([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})$/,hp=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)$/,o1=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,s1="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function a1(){return new RegExp(s1,"u")}const i1=/^(?:(?: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])$/,l1=/^(([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})$/,c1=/^((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])$/,u1=/^(([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])$/,d1=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,mp=/^[A-Za-z0-9_-]*$/,p1=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,f1=/^\+(?:[0-9]){6,14}[0-9]$/,gp="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",h1=new RegExp(`^${gp}$`);function _p(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 m1(e){return new RegExp(`^${_p(e)}$`)}function g1(e){const t=_p({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-]\\d{2}:\\d{2})");const n=`${t}(?:${r.join("|")})`;return new RegExp(`^${gp}T(?:${n})$`)}const _1=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},y1=/^\d+$/,v1=/^-?\d+(?:\.\d+)?/i,w1=/true|false/i,b1=/null/i,k1=/^[^A-Z]*$/,T1=/^[^a-z]*$/,Ht=W("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),yp={number:"number",bigint:"bigint",object:"date"},vp=W("$ZodCheckLessThan",(e,t)=>{Ht.init(e,t);const r=yp[typeof t.value];e._zod.onattach.push(n=>{const o=n._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=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),wp=W("$ZodCheckGreaterThan",(e,t)=>{Ht.init(e,t);const r=yp[typeof t.value];e._zod.onattach.push(n=>{const o=n._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=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),C1=W("$ZodCheckMultipleOf",(e,t)=>{Ht.init(e,t),e._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):Ov(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),S1=W("$ZodCheckNumberFormat",(e,t)=>{Ht.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),n=r?"int":"number",[o,s]=jv[t.format];e._zod.onattach.push(i=>{const a=i._zod.bag;a.format=t.format,a.minimum=o,a.maximum=s,r&&(a.pattern=y1)}),e._zod.check=i=>{const a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:t.format,code:"invalid_type",input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort});return}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:e})}}),I1=W("$ZodCheckMaxLength",(e,t)=>{var r;Ht.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!el(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{const o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{const o=n.value;if(o.length<=t.maximum)return;const i=rl(o);n.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),x1=W("$ZodCheckMinLength",(e,t)=>{var r;Ht.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!el(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{const o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{const o=n.value;if(o.length>=t.minimum)return;const i=rl(o);n.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),E1=W("$ZodCheckLengthEquals",(e,t)=>{var r;Ht.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!el(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{const o=n._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=n=>{const o=n.value,s=o.length;if(s===t.length)return;const i=rl(o),a=s>t.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Bs=W("$ZodCheckStringFormat",(e,t)=>{var r,n;Ht.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?(r=e._zod).check??(r.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})}):(n=e._zod).check??(n.check=()=>{})}),$1=W("$ZodCheckRegex",(e,t)=>{Bs.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),R1=W("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=k1),Bs.init(e,t)}),P1=W("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=T1),Bs.init(e,t)}),M1=W("$ZodCheckIncludes",(e,t)=>{Ht.init(e,t);const r=Oo(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(o=>{const s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),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})}}),N1=W("$ZodCheckStartsWith",(e,t)=>{Ht.init(e,t);const r=new RegExp(`^${Oo(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{const o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),O1=W("$ZodCheckEndsWith",(e,t)=>{Ht.init(e,t);const r=new RegExp(`.*${Oo(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{const o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),A1=W("$ZodCheckOverwrite",(e,t)=>{Ht.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});class q1{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 n=t.split(`
4
- `).filter(i=>i),o=Math.min(...n.map(i=>i.length-i.trimStart().length)),s=n.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,r=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new t(...r,o.join(`
5
- `))}}const L1={major:4,minor:0,patch:0},Ke=W("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=L1;const n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(const o of n)for(const s of o._zod.onattach)s(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const o=(s,i,a)=>{let l=Ao(s),c;for(const u of i){if(u._zod.def.when){if(!u._zod.def.when(s))continue}else if(l)continue;const f=s.issues.length,p=u._zod.check(s);if(p instanceof Promise&&a?.async===!1)throw new Mo;if(c||p instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await p,s.issues.length!==f&&(l||(l=Ao(s,f)))});else{if(s.issues.length===f)continue;l||(l=Ao(s,f))}}return c?c.then(()=>s):s};e._zod.run=(s,i)=>{const a=e._zod.parse(s,i);if(a instanceof Promise){if(i.async===!1)throw new Mo;return a.then(l=>o(l,n,i))}return o(a,n,i)}}e["~standard"]={validate:o=>{try{const s=pp(e,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Wv(e,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),nl=W("$ZodString",(e,t)=>{Ke.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??_1(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),rt=W("$ZodStringFormat",(e,t)=>{Bs.init(e,t),nl.init(e,t)}),j1=W("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=n1),rt.init(e,t)}),D1=W("$ZodUUID",(e,t)=>{if(t.version){const n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=hp(n))}else t.pattern??(t.pattern=hp());rt.init(e,t)}),U1=W("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=o1),rt.init(e,t)}),z1=W("$ZodURL",(e,t)=>{rt.init(e,t),e._zod.check=r=>{try{const n=r.value,o=new URL(n),s=o.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:p1.source,input:r.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)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),!n.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),F1=W("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=a1()),rt.init(e,t)}),V1=W("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=t1),rt.init(e,t)}),Z1=W("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Kv),rt.init(e,t)}),B1=W("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Yv),rt.init(e,t)}),H1=W("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Qv),rt.init(e,t)}),J1=W("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Xv),rt.init(e,t)}),G1=W("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=e1),rt.init(e,t)}),W1=W("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=g1(t)),rt.init(e,t)}),K1=W("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=h1),rt.init(e,t)}),Y1=W("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=m1(t)),rt.init(e,t)}),Q1=W("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=r1),rt.init(e,t)}),X1=W("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=i1),rt.init(e,t),e._zod.onattach.push(r=>{const n=r._zod.bag;n.format="ipv4"})}),ew=W("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=l1),rt.init(e,t),e._zod.onattach.push(r=>{const n=r._zod.bag;n.format="ipv6"}),e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),tw=W("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=c1),rt.init(e,t)}),rw=W("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=u1),rt.init(e,t),e._zod.check=r=>{const[n,o]=r.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://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function bp(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const nw=W("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=d1),rt.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{bp(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function ow(e){if(!mp.test(e))return!1;const t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return bp(r)}const sw=W("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=mp),rt.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{ow(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),aw=W("$ZodE164",(e,t)=>{t.pattern??(t.pattern=f1),rt.init(e,t)});function iw(e,t=null){try{const r=e.split(".");if(r.length!==3)return!1;const[n]=r;if(!n)return!1;const o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}const lw=W("$ZodJWT",(e,t)=>{rt.init(e,t),e._zod.check=r=>{iw(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),kp=W("$ZodNumber",(e,t)=>{Ke.init(e,t),e._zod.pattern=e._zod.bag.pattern??v1,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}const o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;const s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...s?{received:s}:{}}),r}}),cw=W("$ZodNumber",(e,t)=>{S1.init(e,t),kp.init(e,t)}),uw=W("$ZodBoolean",(e,t)=>{Ke.init(e,t),e._zod.pattern=w1,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=!!r.value}catch{}const o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),r}}),dw=W("$ZodNull",(e,t)=>{Ke.init(e,t),e._zod.pattern=b1,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{const o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),r}}),pw=W("$ZodAny",(e,t)=>{Ke.init(e,t),e._zod.parse=r=>r}),fw=W("$ZodUnknown",(e,t)=>{Ke.init(e,t),e._zod.parse=r=>r}),hw=W("$ZodNever",(e,t)=>{Ke.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function Tp(e,t,r){e.issues.length&&t.issues.push(...xn(r,e.issues)),t.value[r]=e.value}const mw=W("$ZodArray",(e,t)=>{Ke.init(e,t),e._zod.parse=(r,n)=>{const o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.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:[]},n);l instanceof Promise?s.push(l.then(c=>Tp(c,r,i))):Tp(l,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function Hs(e,t,r){e.issues.length&&t.issues.push(...xn(r,e.issues)),t.value[r]=e.value}function Cp(e,t,r,n){e.issues.length?n[r]===void 0?r in n?t.value[r]=void 0:t.value[r]=e.value:t.issues.push(...xn(r,e.issues)):e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}const gw=W("$ZodObject",(e,t)=>{Ke.init(e,t);const r=Xi(()=>{const f=Object.keys(t.shape);for(const h of f)if(!(t.shape[h]instanceof Ke))throw new Error(`Invalid element at key "${h}": expected a Zod schema`);const p=Lv(t.shape);return{shape:t.shape,keys:f,keySet:new Set(f),numKeys:f.length,optionalKeys:new Set(p)}});Ve(e._zod,"propValues",()=>{const f=t.shape,p={};for(const h in f){const g=f[h]._zod;if(g.values){p[h]??(p[h]=new Set);for(const v of g.values)p[h].add(v)}}return p});const n=f=>{const p=new q1(["shape","payload","ctx"]),h=r.value,g=y=>{const m=No(y);return`shape[${m}]._zod.run({ value: input[${m}], issues: [] }, ctx)`};p.write("const input = payload.value;");const v=Object.create(null);let _=0;for(const y of h.keys)v[y]=`key_${_++}`;p.write("const newResult = {}");for(const y of h.keys)if(h.optionalKeys.has(y)){const m=v[y];p.write(`const ${m} = ${g(y)};`);const C=No(y);p.write(`
6
- if (${m}.issues.length) {
7
- if (input[${C}] === undefined) {
8
- if (${C} in input) {
9
- newResult[${C}] = undefined;
10
- }
11
- } else {
12
- payload.issues = payload.issues.concat(
13
- ${m}.issues.map((iss) => ({
14
- ...iss,
15
- path: iss.path ? [${C}, ...iss.path] : [${C}],
16
- }))
17
- );
18
- }
19
- } else if (${m}.value === undefined) {
20
- if (${C} in input) newResult[${C}] = undefined;
21
- } else {
22
- newResult[${C}] = ${m}.value;
23
- }
24
- `)}else{const m=v[y];p.write(`const ${m} = ${g(y)};`),p.write(`
25
- if (${m}.issues.length) payload.issues = payload.issues.concat(${m}.issues.map(iss => ({
26
- ...iss,
27
- path: iss.path ? [${No(y)}, ...iss.path] : [${No(y)}]
28
- })));`),p.write(`newResult[${No(y)}] = ${m}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");const w=p.compile();return(y,m)=>w(f,y,m)};let o;const s=Fs,i=!sp.jitless,l=i&&Av.value,c=t.catchall;let u;e._zod.parse=(f,p)=>{u??(u=r.value);const h=f.value;if(!s(h))return f.issues.push({expected:"object",code:"invalid_type",input:h,inst:e}),f;const g=[];if(i&&l&&p?.async===!1&&p.jitless!==!0)o||(o=n(t.shape)),f=o(f,p);else{f.value={};const m=u.shape;for(const C of u.keys){const b=m[C],T=b._zod.run({value:h[C],issues:[]},p),I=b._zod.optin==="optional"&&b._zod.optout==="optional";T instanceof Promise?g.push(T.then(R=>I?Cp(R,f,C,h):Hs(R,f,C))):I?Cp(T,f,C,h):Hs(T,f,C)}}if(!c)return g.length?Promise.all(g).then(()=>f):f;const v=[],_=u.keySet,w=c._zod,y=w.def.type;for(const m of Object.keys(h)){if(_.has(m))continue;if(y==="never"){v.push(m);continue}const C=w.run({value:h[m],issues:[]},p);C instanceof Promise?g.push(C.then(b=>Hs(b,f,m))):Hs(C,f,m)}return v.length&&f.issues.push({code:"unrecognized_keys",keys:v,input:h,inst:e}),g.length?Promise.all(g).then(()=>f):f}});function Sp(e,t,r,n){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:r,errors:e.map(o=>o.issues.map(s=>tn(s,n,en())))}),t}const Ip=W("$ZodUnion",(e,t)=>{Ke.init(e,t),Ve(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Ve(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Ve(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),Ve(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){const r=t.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>tl(n.source)).join("|")})$`)}}),e._zod.parse=(r,n)=>{let o=!1;const s=[];for(const i of t.options){const a=i._zod.run({value:r.value,issues:[]},n);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=>Sp(i,r,e,n)):Sp(s,r,e,n)}}),_w=W("$ZodDiscriminatedUnion",(e,t)=>{Ip.init(e,t);const r=e._zod.parse;Ve(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 n=Xi(()=>{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(!Fs(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:e}),o;const a=n.value.get(i?.[t.discriminator]);return a?a._zod.run(o,s):t.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[t.discriminator],inst:e}),o)}}),yw=W("$ZodIntersection",(e,t)=>{Ke.init(e,t),e._zod.parse=(r,n)=>{const o=r.value,s=t.left._zod.run({value:o,issues:[]},n),i=t.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([l,c])=>xp(r,l,c)):xp(r,s,i)}});function ol(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(Vs(e)&&Vs(t)){const r=Object.keys(t),n=Object.keys(e).filter(s=>r.indexOf(s)!==-1),o={...e,...t};for(const s of n){const i=ol(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 r=[];for(let n=0;n<e.length;n++){const o=e[n],s=t[n],i=ol(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function xp(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),Ao(e))return e;const n=ol(t.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return e.value=n.data,e}const vw=W("$ZodRecord",(e,t)=>{Ke.init(e,t),e._zod.parse=(r,n)=>{const o=r.value;if(!Vs(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;const s=[];if(t.keyType._zod.values){const i=t.keyType._zod.values;r.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:[]},n);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&r.issues.push(...xn(l,u.issues)),r.value[l]=u.value})):(c.issues.length&&r.issues.push(...xn(l,c.issues)),r.value[l]=c.value)}let a;for(const l in o)i.has(l)||(a=a??[],a.push(l));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:a})}else{r.value={};for(const i of Reflect.ownKeys(o)){if(i==="__proto__")continue;const a=t.keyType._zod.run({value:i,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(c=>tn(c,n,en())),input:i,path:[i],inst:e}),r.value[a.value]=a.value;continue}const l=t.valueType._zod.run({value:o[i],issues:[]},n);l instanceof Promise?s.push(l.then(c=>{c.issues.length&&r.issues.push(...xn(i,c.issues)),r.value[a.value]=c.value})):(l.issues.length&&r.issues.push(...xn(i,l.issues)),r.value[a.value]=l.value)}}return s.length?Promise.all(s).then(()=>r):r}}),ww=W("$ZodEnum",(e,t)=>{Ke.init(e,t);const r=ap(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(n=>qv.has(typeof n)).map(n=>typeof n=="string"?Oo(n):n.toString()).join("|")})$`),e._zod.parse=(n,o)=>{const s=n.value;return e._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:e}),n}}),bw=W("$ZodLiteral",(e,t)=>{Ke.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?Oo(r):r?r.toString():String(r)).join("|")})$`),e._zod.parse=(r,n)=>{const o=r.value;return e._zod.values.has(o)||r.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),r}}),kw=W("$ZodTransform",(e,t)=>{Ke.init(e,t),e._zod.parse=(r,n)=>{const o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new Mo;return r.value=o,r}}),Tw=W("$ZodOptional",(e,t)=>{Ke.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Ve(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Ve(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${tl(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>t.innerType._zod.optin==="optional"?t.innerType._zod.run(r,n):r.value===void 0?r:t.innerType._zod.run(r,n)}),Cw=W("$ZodNullable",(e,t)=>{Ke.init(e,t),Ve(e._zod,"optin",()=>t.innerType._zod.optin),Ve(e._zod,"optout",()=>t.innerType._zod.optout),Ve(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${tl(r.source)}|null)$`):void 0}),Ve(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>r.value===null?r:t.innerType._zod.run(r,n)}),Sw=W("$ZodDefault",(e,t)=>{Ke.init(e,t),e._zod.optin="optional",Ve(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=t.defaultValue,r;const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>Ep(s,t)):Ep(o,t)}});function Ep(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const Iw=W("$ZodPrefault",(e,t)=>{Ke.init(e,t),e._zod.optin="optional",Ve(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>(r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,n))}),xw=W("$ZodNonOptional",(e,t)=>{Ke.init(e,t),Ve(e._zod,"values",()=>{const r=t.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),e._zod.parse=(r,n)=>{const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>$p(s,e)):$p(o,e)}});function $p(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 Ew=W("$ZodCatch",(e,t)=>{Ke.init(e,t),e._zod.optin="optional",Ve(e._zod,"optout",()=>t.innerType._zod.optout),Ve(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=t.catchValue({...r,error:{issues:s.issues.map(i=>tn(i,n,en()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(s=>tn(s,n,en()))},input:r.value}),r.issues=[]),r)}}),$w=W("$ZodPipe",(e,t)=>{Ke.init(e,t),Ve(e._zod,"values",()=>t.in._zod.values),Ve(e._zod,"optin",()=>t.in._zod.optin),Ve(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(r,n)=>{const o=t.in._zod.run(r,n);return o instanceof Promise?o.then(s=>Rp(s,t,n)):Rp(o,t,n)}});function Rp(e,t,r){return Ao(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}const Rw=W("$ZodReadonly",(e,t)=>{Ke.init(e,t),Ve(e._zod,"propValues",()=>t.innerType._zod.propValues),Ve(e._zod,"values",()=>t.innerType._zod.values),Ve(e._zod,"optin",()=>t.innerType._zod.optin),Ve(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(r,n)=>{const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(Pp):Pp(o)}});function Pp(e){return e.value=Object.freeze(e.value),e}const Pw=W("$ZodLazy",(e,t)=>{Ke.init(e,t),Ve(e._zod,"innerType",()=>t.getter()),Ve(e._zod,"pattern",()=>e._zod.innerType._zod.pattern),Ve(e._zod,"propValues",()=>e._zod.innerType._zod.propValues),Ve(e._zod,"optin",()=>e._zod.innerType._zod.optin),Ve(e._zod,"optout",()=>e._zod.innerType._zod.optout),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)}),Mw=W("$ZodCustom",(e,t)=>{Ht.init(e,t),Ke.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=r=>{const n=r.value,o=t.fn(n);if(o instanceof Promise)return o.then(s=>Mp(s,r,n,e));Mp(o,r,n,e)}});function Mp(e,t,r,n){if(!e){const o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),t.issues.push(qo(o))}}class Np{constructor(){this._map=new Map,this._idmap=new Map}add(t,...r){const n=r[0];if(this._map.set(t,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,t)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(t){const r=this._map.get(t);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){const r=t._zod.parent;if(r){const n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(t)}}return this._map.get(t)}has(t){return this._map.has(t)}}function Nw(){return new Np}const Lo=Nw();function Ow(e,t){return new e({type:"string",...fe(t)})}function Aw(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...fe(t)})}function Op(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...fe(t)})}function qw(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...fe(t)})}function Lw(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...fe(t)})}function jw(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...fe(t)})}function Dw(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...fe(t)})}function Ap(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...fe(t)})}function Uw(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...fe(t)})}function zw(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...fe(t)})}function Fw(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...fe(t)})}function Vw(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...fe(t)})}function Zw(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...fe(t)})}function Bw(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...fe(t)})}function Hw(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...fe(t)})}function Jw(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...fe(t)})}function Gw(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...fe(t)})}function Ww(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...fe(t)})}function Kw(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...fe(t)})}function qp(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...fe(t)})}function Yw(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...fe(t)})}function Qw(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...fe(t)})}function Xw(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...fe(t)})}function eb(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...fe(t)})}function tb(e,t){return new e({type:"string",format:"date",check:"string_format",...fe(t)})}function rb(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...fe(t)})}function nb(e,t){return new e({type:"string",format:"duration",check:"string_format",...fe(t)})}function ob(e,t){return new e({type:"number",checks:[],...fe(t)})}function sb(e,t){return new e({type:"number",coerce:!0,checks:[],...fe(t)})}function ab(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...fe(t)})}function ib(e,t){return new e({type:"boolean",...fe(t)})}function lb(e,t){return new e({type:"null",...fe(t)})}function cb(e){return new e({type:"any"})}function ub(e){return new e({type:"unknown"})}function db(e,t){return new e({type:"never",...fe(t)})}function Lp(e,t){return new vp({check:"less_than",...fe(t),value:e,inclusive:!1})}function sl(e,t){return new vp({check:"less_than",...fe(t),value:e,inclusive:!0})}function jp(e,t){return new wp({check:"greater_than",...fe(t),value:e,inclusive:!1})}function al(e,t){return new wp({check:"greater_than",...fe(t),value:e,inclusive:!0})}function Dp(e,t){return new C1({check:"multiple_of",...fe(t),value:e})}function Up(e,t){return new I1({check:"max_length",...fe(t),maximum:e})}function Js(e,t){return new x1({check:"min_length",...fe(t),minimum:e})}function zp(e,t){return new E1({check:"length_equals",...fe(t),length:e})}function pb(e,t){return new $1({check:"string_format",format:"regex",...fe(t),pattern:e})}function fb(e){return new R1({check:"string_format",format:"lowercase",...fe(e)})}function hb(e){return new P1({check:"string_format",format:"uppercase",...fe(e)})}function mb(e,t){return new M1({check:"string_format",format:"includes",...fe(t),includes:e})}function gb(e,t){return new N1({check:"string_format",format:"starts_with",...fe(t),prefix:e})}function _b(e,t){return new O1({check:"string_format",format:"ends_with",...fe(t),suffix:e})}function jo(e){return new A1({check:"overwrite",tx:e})}function yb(e){return jo(t=>t.normalize(e))}function vb(){return jo(e=>e.trim())}function wb(){return jo(e=>e.toLowerCase())}function bb(){return jo(e=>e.toUpperCase())}function kb(e,t,r){return new e({type:"array",element:t,...fe(r)})}function Tb(e,t,r){const n=fe(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function Cb(e,t,r){return new e({type:"custom",check:"custom",fn:t,...fe(r)})}class Fp{constructor(t){this.counter=0,this.metadataRegistry=t?.metadata??Lo,this.target=t?.target??"draft-2020-12",this.unrepresentable=t?.unrepresentable??"throw",this.override=t?.override??(()=>{}),this.io=t?.io??"output",this.seen=new Map}process(t,r={path:[],schemaPath:[]}){var n;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++,r.schemaPath.includes(t)&&(i.cycle=r.path),i.schema;const a={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(t,a);const l=t._zod.toJSONSchema?.();if(l)a.schema=l;else{const f={...r,schemaPath:[...r.schemaPath,t],path:r.path},p=t._zod.parent;if(p)a.ref=p,this.process(p,f),this.seen.get(p).isParent=!0;else{const h=a.schema;switch(o.type){case"string":{const g=h;g.type="string";const{minimum:v,maximum:_,format:w,patterns:y,contentEncoding:m}=t._zod.bag;if(typeof v=="number"&&(g.minLength=v),typeof _=="number"&&(g.maxLength=_),w&&(g.format=s[w]??w,g.format===""&&delete g.format),m&&(g.contentEncoding=m),y&&y.size>0){const C=[...y];C.length===1?g.pattern=C[0].source:C.length>1&&(a.schema.allOf=[...C.map(b=>({...this.target==="draft-7"?{type:"string"}:{},pattern:b.source}))])}break}case"number":{const g=h,{minimum:v,maximum:_,format:w,multipleOf:y,exclusiveMaximum:m,exclusiveMinimum:C}=t._zod.bag;typeof w=="string"&&w.includes("int")?g.type="integer":g.type="number",typeof C=="number"&&(g.exclusiveMinimum=C),typeof v=="number"&&(g.minimum=v,typeof C=="number"&&(C>=v?delete g.minimum:delete g.exclusiveMinimum)),typeof m=="number"&&(g.exclusiveMaximum=m),typeof _=="number"&&(g.maximum=_,typeof m=="number"&&(m<=_?delete g.maximum:delete g.exclusiveMaximum)),typeof y=="number"&&(g.multipleOf=y);break}case"boolean":{const g=h;g.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":{h.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":{h.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const g=h,{minimum:v,maximum:_}=t._zod.bag;typeof v=="number"&&(g.minItems=v),typeof _=="number"&&(g.maxItems=_),g.type="array",g.items=this.process(o.element,{...f,path:[...f.path,"items"]});break}case"object":{const g=h;g.type="object",g.properties={};const v=o.shape;for(const y in v)g.properties[y]=this.process(v[y],{...f,path:[...f.path,"properties",y]});const _=new Set(Object.keys(v)),w=new Set([..._].filter(y=>{const m=o.shape[y]._zod;return this.io==="input"?m.optin===void 0:m.optout===void 0}));w.size>0&&(g.required=Array.from(w)),o.catchall?._zod.def.type==="never"?g.additionalProperties=!1:o.catchall?o.catchall&&(g.additionalProperties=this.process(o.catchall,{...f,path:[...f.path,"additionalProperties"]})):this.io==="output"&&(g.additionalProperties=!1);break}case"union":{const g=h;g.anyOf=o.options.map((v,_)=>this.process(v,{...f,path:[...f.path,"anyOf",_]}));break}case"intersection":{const g=h,v=this.process(o.left,{...f,path:[...f.path,"allOf",0]}),_=this.process(o.right,{...f,path:[...f.path,"allOf",1]}),w=m=>"allOf"in m&&Object.keys(m).length===1,y=[...w(v)?v.allOf:[v],...w(_)?_.allOf:[_]];g.allOf=y;break}case"tuple":{const g=h;g.type="array";const v=o.items.map((y,m)=>this.process(y,{...f,path:[...f.path,"prefixItems",m]}));if(this.target==="draft-2020-12"?g.prefixItems=v:g.items=v,o.rest){const y=this.process(o.rest,{...f,path:[...f.path,"items"]});this.target==="draft-2020-12"?g.items=y:g.additionalItems=y}o.rest&&(g.items=this.process(o.rest,{...f,path:[...f.path,"items"]}));const{minimum:_,maximum:w}=t._zod.bag;typeof _=="number"&&(g.minItems=_),typeof w=="number"&&(g.maxItems=w);break}case"record":{const g=h;g.type="object",g.propertyNames=this.process(o.keyType,{...f,path:[...f.path,"propertyNames"]}),g.additionalProperties=this.process(o.valueType,{...f,path:[...f.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 g=h,v=ap(o.entries);v.every(_=>typeof _=="number")&&(g.type="number"),v.every(_=>typeof _=="string")&&(g.type="string"),g.enum=v;break}case"literal":{const g=h,v=[];for(const _ of o.values)if(_===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof _=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");v.push(Number(_))}else v.push(_);if(v.length!==0)if(v.length===1){const _=v[0];g.type=_===null?"null":typeof _,g.const=_}else v.every(_=>typeof _=="number")&&(g.type="number"),v.every(_=>typeof _=="string")&&(g.type="string"),v.every(_=>typeof _=="boolean")&&(g.type="string"),v.every(_=>_===null)&&(g.type="null"),g.enum=v;break}case"file":{const g=h,v={type:"string",format:"binary",contentEncoding:"binary"},{minimum:_,maximum:w,mime:y}=t._zod.bag;_!==void 0&&(v.minLength=_),w!==void 0&&(v.maxLength=w),y?y.length===1?(v.contentMediaType=y[0],Object.assign(g,v)):g.anyOf=y.map(m=>({...v,contentMediaType:m})):Object.assign(g,v);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const g=this.process(o.innerType,f);h.anyOf=[g,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,f),a.ref=o.innerType;break}case"success":{const g=h;g.type="boolean";break}case"default":{this.process(o.innerType,f),a.ref=o.innerType,h.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,f),a.ref=o.innerType,this.io==="input"&&(h._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,f),a.ref=o.innerType;let g;try{g=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}h.default=g;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const g=h,v=t._zod.pattern;if(!v)throw new Error("Pattern not found in template literal");g.type="string",g.pattern=v.source;break}case"pipe":{const g=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(g,f),a.ref=g;break}case"readonly":{this.process(o.innerType,f),a.ref=o.innerType,h.readOnly=!0;break}case"promise":{this.process(o.innerType,f),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,f),a.ref=o.innerType;break}case"lazy":{const g=t._zod.innerType;this.process(g,f),a.ref=g;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"&&vt(t)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(t).schema}emit(t,r){const n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},o=this.seen.get(t);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=u=>{const f=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){const v=n.external.registry.get(u[0])?.id,_=n.external.uri??(y=>y);if(v)return{ref:_(v)};const w=u[1].defId??u[1].schema.id??`schema${this.counter++}`;return u[1].defId=w,{defId:w,ref:`${_("__shared")}#/${f}/${w}`}}if(u[1]===o)return{ref:"#"};const h=`#/${f}/`,g=u[1].schema.id??`__schema${this.counter++}`;return{defId:g,ref:h+g}},i=u=>{if(u[1].schema.$ref)return;const f=u[1],{ref:p,defId:h}=s(u);f.def={...f.schema},h&&(f.defId=h);const g=f.schema;for(const v in g)delete g[v];g.$ref=p};if(n.cycles==="throw")for(const u of this.seen.entries()){const f=u[1];if(f.cycle)throw new Error(`Cycle detected: #/${f.cycle?.join("/")}/<root>
29
-
30
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const u of this.seen.entries()){const f=u[1];if(t===u[0]){i(u);continue}if(n.external){const h=n.external.registry.get(u[0])?.id;if(t!==u[0]&&h){i(u);continue}}if(this.metadataRegistry.get(u[0])?.id){i(u);continue}if(f.cycle){i(u);continue}if(f.count>1&&n.reused==="ref"){i(u);continue}}const a=(u,f)=>{const p=this.seen.get(u),h=p.def??p.schema,g={...h};if(p.ref===null)return;const v=p.ref;if(p.ref=null,v){a(v,f);const _=this.seen.get(v).schema;_.$ref&&f.target==="draft-7"?(h.allOf=h.allOf??[],h.allOf.push(_)):(Object.assign(h,_),Object.assign(h,g))}p.isParent||this.override({zodSchema:u,jsonSchema:h,path:p.path??[]})};for(const u of[...this.seen.entries()].reverse())a(u[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}`),n.external?.uri){const u=n.external.registry.get(t)?.id;if(!u)throw new Error("Schema is missing an `id` property");l.$id=n.external.uri(u)}Object.assign(l,o.def);const c=n.external?.defs??{};for(const u of this.seen.entries()){const f=u[1];f.def&&f.defId&&(c[f.defId]=f.def)}n.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 Sb(e,t){if(e instanceof Np){const n=new Fp(t),o={};for(const a of e._idmap.entries()){const[l,c]=a;n.process(c)}const s={},i={registry:e,uri:t?.uri,defs:o};for(const a of e._idmap.entries()){const[l,c]=a;s[l]=n.emit(c,{...t,external:i})}if(Object.keys(o).length>0){const a=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[a]:o}}return{schemas:s}}const r=new Fp(t);return r.process(e),r.emit(e,t)}function vt(e,t){const r=t??{seen:new Set};if(r.seen.has(e))return!1;r.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 vt(o.element,r);case"object":{for(const s in o.shape)if(vt(o.shape[s],r))return!0;return!1}case"union":{for(const s of o.options)if(vt(s,r))return!0;return!1}case"intersection":return vt(o.left,r)||vt(o.right,r);case"tuple":{for(const s of o.items)if(vt(s,r))return!0;return!!(o.rest&&vt(o.rest,r))}case"record":return vt(o.keyType,r)||vt(o.valueType,r);case"map":return vt(o.keyType,r)||vt(o.valueType,r);case"set":return vt(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return vt(o.innerType,r);case"lazy":return vt(o.getter(),r);case"default":return vt(o.innerType,r);case"prefault":return vt(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return vt(o.in,r)||vt(o.out,r);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${o.type}`)}const Ib=W("ZodISODateTime",(e,t)=>{W1.init(e,t),it.init(e,t)});function Vp(e){return eb(Ib,e)}const xb=W("ZodISODate",(e,t)=>{K1.init(e,t),it.init(e,t)});function Eb(e){return tb(xb,e)}const $b=W("ZodISOTime",(e,t)=>{Y1.init(e,t),it.init(e,t)});function Rb(e){return rb($b,e)}const Pb=W("ZodISODuration",(e,t)=>{Q1.init(e,t),it.init(e,t)});function Mb(e){return nb(Pb,e)}const Gs=W("ZodError",(e,t)=>{cp.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>Hv(e,r)},flatten:{value:r=>Bv(e,r)},addIssue:{value:r=>e.issues.push(r)},addIssues:{value:r=>e.issues.push(...r)},isEmpty:{get(){return e.issues.length===0}}})},{Parent:Error}),Nb=Jv(Gs),Ob=Gv(Gs),Ab=dp(Gs),Zp=fp(Gs),Xe=W("ZodType",(e,t)=>(Ke.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),e.clone=(r,n)=>In(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.parse=(r,n)=>Nb(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>Ab(e,r,n),e.parseAsync=async(r,n)=>Ob(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>Zp(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check(S3(r,n)),e.superRefine=r=>e.check(I3(r)),e.overwrite=r=>e.check(jo(r)),e.optional=()=>de(e),e.nullable=()=>tf(e),e.nullish=()=>de(tf(e)),e.nonoptional=r=>_3(e,r),e.array=()=>q(e),e.or=r=>ae([e,r]),e.and=r=>ll(e,r),e.transform=r=>ul(e,Xp(r)),e.default=r=>h3(e,r),e.prefault=r=>g3(e,r),e.catch=r=>v3(e,r),e.pipe=r=>ul(e,r),e.readonly=()=>k3(e),e.describe=r=>{const n=e.clone();return Lo.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return Lo.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return Lo.get(e);const n=e.clone();return Lo.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),Bp=W("_ZodString",(e,t)=>{nl.init(e,t),Xe.init(e,t);const r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...n)=>e.check(pb(...n)),e.includes=(...n)=>e.check(mb(...n)),e.startsWith=(...n)=>e.check(gb(...n)),e.endsWith=(...n)=>e.check(_b(...n)),e.min=(...n)=>e.check(Js(...n)),e.max=(...n)=>e.check(Up(...n)),e.length=(...n)=>e.check(zp(...n)),e.nonempty=(...n)=>e.check(Js(1,...n)),e.lowercase=n=>e.check(fb(n)),e.uppercase=n=>e.check(hb(n)),e.trim=()=>e.check(vb()),e.normalize=(...n)=>e.check(yb(...n)),e.toLowerCase=()=>e.check(wb()),e.toUpperCase=()=>e.check(bb())}),qb=W("ZodString",(e,t)=>{nl.init(e,t),Bp.init(e,t),e.email=r=>e.check(Aw(Lb,r)),e.url=r=>e.check(Ap(Jp,r)),e.jwt=r=>e.check(Xw(Qb,r)),e.emoji=r=>e.check(Uw(Db,r)),e.guid=r=>e.check(Op(Hp,r)),e.uuid=r=>e.check(qw(Ws,r)),e.uuidv4=r=>e.check(Lw(Ws,r)),e.uuidv6=r=>e.check(jw(Ws,r)),e.uuidv7=r=>e.check(Dw(Ws,r)),e.nanoid=r=>e.check(zw(Ub,r)),e.guid=r=>e.check(Op(Hp,r)),e.cuid=r=>e.check(Fw(zb,r)),e.cuid2=r=>e.check(Vw(Fb,r)),e.ulid=r=>e.check(Zw(Vb,r)),e.base64=r=>e.check(qp(Gp,r)),e.base64url=r=>e.check(Yw(Kb,r)),e.xid=r=>e.check(Bw(Zb,r)),e.ksuid=r=>e.check(Hw(Bb,r)),e.ipv4=r=>e.check(Jw(Hb,r)),e.ipv6=r=>e.check(Gw(Jb,r)),e.cidrv4=r=>e.check(Ww(Gb,r)),e.cidrv6=r=>e.check(Kw(Wb,r)),e.e164=r=>e.check(Qw(Yb,r)),e.datetime=r=>e.check(Vp(r)),e.date=r=>e.check(Eb(r)),e.time=r=>e.check(Rb(r)),e.duration=r=>e.check(Mb(r))});function d(e){return Ow(qb,e)}const it=W("ZodStringFormat",(e,t)=>{rt.init(e,t),Bp.init(e,t)}),Lb=W("ZodEmail",(e,t)=>{U1.init(e,t),it.init(e,t)}),Hp=W("ZodGUID",(e,t)=>{j1.init(e,t),it.init(e,t)}),Ws=W("ZodUUID",(e,t)=>{D1.init(e,t),it.init(e,t)}),Jp=W("ZodURL",(e,t)=>{z1.init(e,t),it.init(e,t)});function jb(e){return Ap(Jp,e)}const Db=W("ZodEmoji",(e,t)=>{F1.init(e,t),it.init(e,t)}),Ub=W("ZodNanoID",(e,t)=>{V1.init(e,t),it.init(e,t)}),zb=W("ZodCUID",(e,t)=>{Z1.init(e,t),it.init(e,t)}),Fb=W("ZodCUID2",(e,t)=>{B1.init(e,t),it.init(e,t)}),Vb=W("ZodULID",(e,t)=>{H1.init(e,t),it.init(e,t)}),Zb=W("ZodXID",(e,t)=>{J1.init(e,t),it.init(e,t)}),Bb=W("ZodKSUID",(e,t)=>{G1.init(e,t),it.init(e,t)}),Hb=W("ZodIPv4",(e,t)=>{X1.init(e,t),it.init(e,t)}),Jb=W("ZodIPv6",(e,t)=>{ew.init(e,t),it.init(e,t)}),Gb=W("ZodCIDRv4",(e,t)=>{tw.init(e,t),it.init(e,t)}),Wb=W("ZodCIDRv6",(e,t)=>{rw.init(e,t),it.init(e,t)}),Gp=W("ZodBase64",(e,t)=>{nw.init(e,t),it.init(e,t)});function Wp(e){return qp(Gp,e)}const Kb=W("ZodBase64URL",(e,t)=>{sw.init(e,t),it.init(e,t)}),Yb=W("ZodE164",(e,t)=>{aw.init(e,t),it.init(e,t)}),Qb=W("ZodJWT",(e,t)=>{lw.init(e,t),it.init(e,t)}),il=W("ZodNumber",(e,t)=>{kp.init(e,t),Xe.init(e,t),e.gt=(n,o)=>e.check(jp(n,o)),e.gte=(n,o)=>e.check(al(n,o)),e.min=(n,o)=>e.check(al(n,o)),e.lt=(n,o)=>e.check(Lp(n,o)),e.lte=(n,o)=>e.check(sl(n,o)),e.max=(n,o)=>e.check(sl(n,o)),e.int=n=>e.check(Kp(n)),e.safe=n=>e.check(Kp(n)),e.positive=n=>e.check(jp(0,n)),e.nonnegative=n=>e.check(al(0,n)),e.negative=n=>e.check(Lp(0,n)),e.nonpositive=n=>e.check(sl(0,n)),e.multipleOf=(n,o)=>e.check(Dp(n,o)),e.step=(n,o)=>e.check(Dp(n,o)),e.finite=()=>e;const r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function N(e){return ob(il,e)}const Xb=W("ZodNumberFormat",(e,t)=>{cw.init(e,t),il.init(e,t)});function Kp(e){return ab(Xb,e)}const e3=W("ZodBoolean",(e,t)=>{uw.init(e,t),Xe.init(e,t)});function ge(e){return ib(e3,e)}const t3=W("ZodNull",(e,t)=>{dw.init(e,t),Xe.init(e,t)});function Do(e){return lb(t3,e)}const r3=W("ZodAny",(e,t)=>{pw.init(e,t),Xe.init(e,t)});function ht(){return cb(r3)}const n3=W("ZodUnknown",(e,t)=>{fw.init(e,t),Xe.init(e,t)});function Ie(){return ub(n3)}const o3=W("ZodNever",(e,t)=>{hw.init(e,t),Xe.init(e,t)});function s3(e){return db(o3,e)}const a3=W("ZodArray",(e,t)=>{mw.init(e,t),Xe.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(Js(r,n)),e.nonempty=r=>e.check(Js(1,r)),e.max=(r,n)=>e.check(Up(r,n)),e.length=(r,n)=>e.check(zp(r,n)),e.unwrap=()=>e.element});function q(e,t){return kb(a3,e,t)}const Yp=W("ZodObject",(e,t)=>{gw.init(e,t),Xe.init(e,t),Ve(e,"shape",()=>t.shape),e.keyof=()=>ce(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Ie()}),e.loose=()=>e.clone({...e._zod.def,catchall:Ie()}),e.strict=()=>e.clone({...e._zod.def,catchall:s3()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>zv(e,r),e.merge=r=>Fv(e,r),e.pick=r=>Dv(e,r),e.omit=r=>Uv(e,r),e.partial=(...r)=>Vv(ef,e,r[0]),e.required=(...r)=>Zv(rf,e,r[0])});function k(e,t){const r={type:"object",get shape(){return zs(this,"shape",{...e}),this.shape},...fe(t)};return new Yp(r)}function lt(e,t){return new Yp({type:"object",get shape(){return zs(this,"shape",{...e}),this.shape},catchall:Ie(),...fe(t)})}const Qp=W("ZodUnion",(e,t)=>{Ip.init(e,t),Xe.init(e,t),e.options=t.options});function ae(e,t){return new Qp({type:"union",options:e,...fe(t)})}const i3=W("ZodDiscriminatedUnion",(e,t)=>{Qp.init(e,t),_w.init(e,t)});function Ue(e,t,r){return new i3({type:"union",options:t,discriminator:e,...fe(r)})}const l3=W("ZodIntersection",(e,t)=>{yw.init(e,t),Xe.init(e,t)});function ll(e,t){return new l3({type:"intersection",left:e,right:t})}const c3=W("ZodRecord",(e,t)=>{vw.init(e,t),Xe.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function he(e,t,r){return new c3({type:"record",keyType:e,valueType:t,...fe(r)})}const cl=W("ZodEnum",(e,t)=>{ww.init(e,t),Xe.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);const r=new Set(Object.keys(t.entries));e.extract=(n,o)=>{const s={};for(const i of n)if(r.has(i))s[i]=t.entries[i];else throw new Error(`Key ${i} not found in enum`);return new cl({...t,checks:[],...fe(o),entries:s})},e.exclude=(n,o)=>{const s={...t.entries};for(const i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new cl({...t,checks:[],...fe(o),entries:s})}});function ce(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new cl({type:"enum",entries:r,...fe(t)})}const u3=W("ZodLiteral",(e,t)=>{bw.init(e,t),Xe.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 P(e,t){return new u3({type:"literal",values:Array.isArray(e)?e:[e],...fe(t)})}const d3=W("ZodTransform",(e,t)=>{kw.init(e,t),Xe.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(qo(s,r.value,t));else{const i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=e),i.continue??(i.continue=!0),r.issues.push(qo(i))}};const o=t.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});function Xp(e){return new d3({type:"transform",transform:e})}const ef=W("ZodOptional",(e,t)=>{Tw.init(e,t),Xe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function de(e){return new ef({type:"optional",innerType:e})}const p3=W("ZodNullable",(e,t)=>{Cw.init(e,t),Xe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function tf(e){return new p3({type:"nullable",innerType:e})}const f3=W("ZodDefault",(e,t)=>{Sw.init(e,t),Xe.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function h3(e,t){return new f3({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const m3=W("ZodPrefault",(e,t)=>{Iw.init(e,t),Xe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function g3(e,t){return new m3({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const rf=W("ZodNonOptional",(e,t)=>{xw.init(e,t),Xe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function _3(e,t){return new rf({type:"nonoptional",innerType:e,...fe(t)})}const y3=W("ZodCatch",(e,t)=>{Ew.init(e,t),Xe.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function v3(e,t){return new y3({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const w3=W("ZodPipe",(e,t)=>{$w.init(e,t),Xe.init(e,t),e.in=t.in,e.out=t.out});function ul(e,t){return new w3({type:"pipe",in:e,out:t})}const b3=W("ZodReadonly",(e,t)=>{Rw.init(e,t),Xe.init(e,t)});function k3(e){return new b3({type:"readonly",innerType:e})}const T3=W("ZodLazy",(e,t)=>{Pw.init(e,t),Xe.init(e,t),e.unwrap=()=>e._zod.def.getter()});function Ks(e){return new T3({type:"lazy",getter:e})}const dl=W("ZodCustom",(e,t)=>{Mw.init(e,t),Xe.init(e,t)});function C3(e){const t=new Ht({check:"custom"});return t._zod.check=e,t}function nf(e,t){return Tb(dl,e??(()=>!0),t)}function S3(e,t={}){return Cb(dl,e,t)}function I3(e){const t=C3(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(qo(n,r.value,t._zod.def));else{const o=n;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=!t._zod.def.abort),r.issues.push(qo(o))}},e(r.value,r)));return t}function Ys(e,t={error:`Input not instance of ${e.name}`}){const r=new dl({type:"custom",check:"custom",fn:n=>n instanceof e,abort:!0,...fe(t)});return r._zod.bag.Class=e,r}function of(e,t){return ul(Xp(e),t)}const sf={custom:"custom"};function af(e){return sb(il,e)}var ze;(function(e){e.assertEqual=o=>{};function t(o){}e.assertIs=t;function r(o){throw new Error}e.assertNever=r,e.arrayToEnum=o=>{const s={};for(const i of o)s[i]=i;return s},e.getValidEnumValues=o=>{const s=e.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(const a of s)i[a]=o[a];return e.objectValues(i)},e.objectValues=o=>e.objectKeys(o).map(function(s){return o[s]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const s=[];for(const i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},e.find=(o,s)=>{for(const i of o)if(s(i))return i},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}e.joinValues=n,e.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(ze||(ze={}));var lf;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(lf||(lf={}));const pe=ze.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),rn=e=>{switch(typeof e){case"undefined":return pe.undefined;case"string":return pe.string;case"number":return Number.isNaN(e)?pe.nan:pe.number;case"boolean":return pe.boolean;case"function":return pe.function;case"bigint":return pe.bigint;case"symbol":return pe.symbol;case"object":return Array.isArray(e)?pe.array:e===null?pe.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?pe.promise:typeof Map<"u"&&e instanceof Map?pe.map:typeof Set<"u"&&e instanceof Set?pe.set:typeof Date<"u"&&e instanceof Date?pe.date:pe.object;default:return pe.unknown}},oe=ze.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Fr extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){const r=t||function(s){return s.message},n={_errors:[]},o=s=>{for(const i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,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(r(i))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return o(this),n}static assert(t){if(!(t instanceof Fr))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ze.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){const r={},n=[];for(const o of this.issues)if(o.path.length>0){const s=o.path[0];r[s]=r[s]||[],r[s].push(t(o))}else n.push(t(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}}Fr.create=e=>new Fr(e);const pl=(e,t)=>{let r;switch(e.code){case oe.invalid_type:e.received===pe.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case oe.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,ze.jsonStringifyReplacer)}`;break;case oe.unrecognized_keys:r=`Unrecognized key(s) in object: ${ze.joinValues(e.keys,", ")}`;break;case oe.invalid_union:r="Invalid input";break;case oe.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ze.joinValues(e.options)}`;break;case oe.invalid_enum_value:r=`Invalid enum value. Expected ${ze.joinValues(e.options)}, received '${e.received}'`;break;case oe.invalid_arguments:r="Invalid function arguments";break;case oe.invalid_return_type:r="Invalid function return type";break;case oe.invalid_date:r="Invalid date";break;case oe.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:ze.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case oe.too_small:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:r="Invalid input";break;case oe.too_big:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:r="Invalid input";break;case oe.custom:r="Invalid input";break;case oe.invalid_intersection_types:r="Intersection results could not be merged";break;case oe.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case oe.not_finite:r="Number must be finite";break;default:r=t.defaultError,ze.assertNever(e)}return{message:r}};let x3=pl;function E3(){return x3}const $3=e=>{const{data:t,path:r,errorMaps:n,issueData:o}=e,s=[...r,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="";const l=n.filter(c=>!!c).slice().reverse();for(const c of l)a=c(i,{data:t,defaultError:a}).message;return{...o,path:s,message:a}};function le(e,t){const r=E3(),n=$3({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===pl?void 0:pl].filter(o=>!!o)});e.common.issues.push(n)}class er{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){const n=[];for(const o of r){if(o.status==="aborted")return xe;o.status==="dirty"&&t.dirty(),n.push(o.value)}return{status:t.value,value:n}}static async mergeObjectAsync(t,r){const n=[];for(const o of r){const s=await o.key,i=await o.value;n.push({key:s,value:i})}return er.mergeObjectSync(t,n)}static mergeObjectSync(t,r){const n={};for(const o of r){const{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return xe;s.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[s.value]=i.value)}return{status:t.value,value:n}}}const xe=Object.freeze({status:"aborted"}),Uo=e=>({status:"dirty",value:e}),ar=e=>({status:"valid",value:e}),cf=e=>e.status==="aborted",uf=e=>e.status==="dirty",Kn=e=>e.status==="valid",Qs=e=>typeof Promise<"u"&&e instanceof Promise;var me;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(me||(me={}));class nn{constructor(t,r,n,o){this._cachedPath=[],this.parent=t,this.data=r,this._path=n,this._key=o}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 df=(e,t)=>{if(Kn(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const r=new Fr(e.common.issues);return this._error=r,this._error}}};function Ae(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:n,description:o}=e;if(t&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(i,a)=>{const{message:l}=e;return i.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:l??r??a.defaultError}},description:o}}class je{get description(){return this._def.description}_getType(t){return rn(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:rn(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new er,ctx:{common:t.parent.common,data:t.data,parsedType:rn(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const r=this._parse(t);if(Qs(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(t){const r=this._parse(t);return Promise.resolve(r)}parse(t,r){const n=this.safeParse(t,r);if(n.success)return n.data;throw n.error}safeParse(t,r){const n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:rn(t)},o=this._parseSync({data:t,path:n.path,parent:n});return df(n,o)}"~validate"(t){const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:rn(t)};if(!this["~standard"].async)try{const n=this._parseSync({data:t,path:[],parent:r});return Kn(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(n=>Kn(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(t,r){const n=await this.safeParseAsync(t,r);if(n.success)return n.data;throw n.error}async safeParseAsync(t,r){const n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:rn(t)},o=this._parse({data:t,path:n.path,parent:n}),s=await(Qs(o)?o:Promise.resolve(o));return df(n,s)}refine(t,r){const n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{const i=t(o),a=()=>s.addIssue({code:oe.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(l=>l?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(t,r){return this._refinement((n,o)=>t(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(t){return new eo({schema:this,typeName:se.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return an.create(this,this._def)}nullable(){return to.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Mr.create(this)}promise(){return ra.create(this,this._def)}or(t){return ea.create([this,t],this._def)}and(t){return ta.create(this,t,this._def)}transform(t){return new eo({...Ae(this._def),schema:this,typeName:se.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const r=typeof t=="function"?t:()=>t;return new ml({...Ae(this._def),innerType:this,defaultValue:r,typeName:se.ZodDefault})}brand(){return new Q3({typeName:se.ZodBranded,type:this,...Ae(this._def)})}catch(t){const r=typeof t=="function"?t:()=>t;return new gl({...Ae(this._def),innerType:this,catchValue:r,typeName:se.ZodCatch})}describe(t){const r=this.constructor;return new r({...this._def,description:t})}pipe(t){return _l.create(this,t)}readonly(){return yl.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const R3=/^c[^\s-]{8,}$/i,P3=/^[0-9a-z]+$/,M3=/^[0-9A-HJKMNP-TV-Z]{26}$/i,N3=/^[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,O3=/^[a-z0-9_-]{21}$/i,A3=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,q3=/^[-+]?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)?)??$/,L3=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,j3="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let fl;const D3=/^(?:(?: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])$/,U3=/^(?:(?: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])$/,z3=/^(([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]))$/,F3=/^(([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])$/,V3=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Z3=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,pf="((\\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])))",B3=new RegExp(`^${pf}$`);function ff(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);const r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function H3(e){return new RegExp(`^${ff(e)}$`)}function J3(e){let t=`${pf}T${ff(e)}`;const r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function G3(e,t){return!!((t==="v4"||!t)&&D3.test(e)||(t==="v6"||!t)&&z3.test(e))}function W3(e,t){if(!A3.test(e))return!1;try{const[r]=e.split(".");if(!r)return!1;const n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||t&&o.alg!==t)}catch{return!1}}function K3(e,t){return!!((t==="v4"||!t)&&U3.test(e)||(t==="v6"||!t)&&F3.test(e))}class on extends je{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==pe.string){const s=this._getOrReturnCtx(t);return le(s,{code:oe.invalid_type,expected:pe.string,received:s.parsedType}),xe}const n=new er;let o;for(const s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(o=this._getOrReturnCtx(t,o),le(o,{code:oe.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")t.data.length>s.value&&(o=this._getOrReturnCtx(t,o),le(o,{code:oe.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){const i=t.data.length>s.value,a=t.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(t,o),i?le(o,{code:oe.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&le(o,{code:oe.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")L3.test(t.data)||(o=this._getOrReturnCtx(t,o),le(o,{validation:"email",code:oe.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")fl||(fl=new RegExp(j3,"u")),fl.test(t.data)||(o=this._getOrReturnCtx(t,o),le(o,{validation:"emoji",code:oe.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")N3.test(t.data)||(o=this._getOrReturnCtx(t,o),le(o,{validation:"uuid",code:oe.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")O3.test(t.data)||(o=this._getOrReturnCtx(t,o),le(o,{validation:"nanoid",code:oe.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")R3.test(t.data)||(o=this._getOrReturnCtx(t,o),le(o,{validation:"cuid",code:oe.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")P3.test(t.data)||(o=this._getOrReturnCtx(t,o),le(o,{validation:"cuid2",code:oe.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")M3.test(t.data)||(o=this._getOrReturnCtx(t,o),le(o,{validation:"ulid",code:oe.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),le(o,{validation:"url",code:oe.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),le(o,{validation:"regex",code:oe.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(t,o),le(o,{code:oe.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(o=this._getOrReturnCtx(t,o),le(o,{code:oe.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(o=this._getOrReturnCtx(t,o),le(o,{code:oe.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?J3(s).test(t.data)||(o=this._getOrReturnCtx(t,o),le(o,{code:oe.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?B3.test(t.data)||(o=this._getOrReturnCtx(t,o),le(o,{code:oe.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?H3(s).test(t.data)||(o=this._getOrReturnCtx(t,o),le(o,{code:oe.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?q3.test(t.data)||(o=this._getOrReturnCtx(t,o),le(o,{validation:"duration",code:oe.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?G3(t.data,s.version)||(o=this._getOrReturnCtx(t,o),le(o,{validation:"ip",code:oe.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?W3(t.data,s.alg)||(o=this._getOrReturnCtx(t,o),le(o,{validation:"jwt",code:oe.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?K3(t.data,s.version)||(o=this._getOrReturnCtx(t,o),le(o,{validation:"cidr",code:oe.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?V3.test(t.data)||(o=this._getOrReturnCtx(t,o),le(o,{validation:"base64",code:oe.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?Z3.test(t.data)||(o=this._getOrReturnCtx(t,o),le(o,{validation:"base64url",code:oe.invalid_string,message:s.message}),n.dirty()):ze.assertNever(s);return{status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(o=>t.test(o),{validation:r,code:oe.invalid_string,...me.errToObj(n)})}_addCheck(t){return new on({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...me.errToObj(t)})}url(t){return this._addCheck({kind:"url",...me.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...me.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...me.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...me.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...me.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...me.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...me.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...me.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...me.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...me.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...me.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...me.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...me.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...me.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...me.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...me.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...me.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...me.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...me.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...me.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...me.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...me.errToObj(r)})}nonempty(t){return this.min(1,me.errToObj(t))}trim(){return new on({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new on({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new on({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}}on.create=e=>new on({checks:[],typeName:se.ZodString,coerce:e?.coerce??!1,...Ae(e)});function Y3(e,t){const r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(e.toFixed(o).replace(".","")),i=Number.parseInt(t.toFixed(o).replace(".",""));return s%i/10**o}class Yn extends je{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==pe.number){const s=this._getOrReturnCtx(t);return le(s,{code:oe.invalid_type,expected:pe.number,received:s.parsedType}),xe}let n;const o=new er;for(const s of this._def.checks)s.kind==="int"?ze.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),le(n,{code:oe.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(n=this._getOrReturnCtx(t,n),le(n,{code:oe.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(n=this._getOrReturnCtx(t,n),le(n,{code:oe.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?Y3(t.data,s.value)!==0&&(n=this._getOrReturnCtx(t,n),le(n,{code:oe.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),le(n,{code:oe.not_finite,message:s.message}),o.dirty()):ze.assertNever(s);return{status:o.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,me.toString(r))}gt(t,r){return this.setLimit("min",t,!1,me.toString(r))}lte(t,r){return this.setLimit("max",t,!0,me.toString(r))}lt(t,r){return this.setLimit("max",t,!1,me.toString(r))}setLimit(t,r,n,o){return new Yn({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:me.toString(o)}]})}_addCheck(t){return new Yn({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:me.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:me.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:me.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:me.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:me.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:me.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:me.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:me.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:me.toString(t)})}get minValue(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&ze.isInteger(t.value))}get isFinite(){let t=null,r=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(t===null||n.value<t)&&(t=n.value)}return Number.isFinite(r)&&Number.isFinite(t)}}Yn.create=e=>new Yn({checks:[],typeName:se.ZodNumber,coerce:e?.coerce||!1,...Ae(e)});class zo extends je{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==pe.bigint)return this._getInvalidInput(t);let n;const o=new er;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(n=this._getOrReturnCtx(t,n),le(n,{code:oe.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(n=this._getOrReturnCtx(t,n),le(n,{code:oe.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),le(n,{code:oe.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):ze.assertNever(s);return{status:o.value,value:t.data}}_getInvalidInput(t){const r=this._getOrReturnCtx(t);return le(r,{code:oe.invalid_type,expected:pe.bigint,received:r.parsedType}),xe}gte(t,r){return this.setLimit("min",t,!0,me.toString(r))}gt(t,r){return this.setLimit("min",t,!1,me.toString(r))}lte(t,r){return this.setLimit("max",t,!0,me.toString(r))}lt(t,r){return this.setLimit("max",t,!1,me.toString(r))}setLimit(t,r,n,o){return new zo({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:me.toString(o)}]})}_addCheck(t){return new zo({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:me.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:me.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:me.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:me.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:me.toString(r)})}get minValue(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}}zo.create=e=>new zo({checks:[],typeName:se.ZodBigInt,coerce:e?.coerce??!1,...Ae(e)});class hf extends je{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==pe.boolean){const n=this._getOrReturnCtx(t);return le(n,{code:oe.invalid_type,expected:pe.boolean,received:n.parsedType}),xe}return ar(t.data)}}hf.create=e=>new hf({typeName:se.ZodBoolean,coerce:e?.coerce||!1,...Ae(e)});class Xs extends je{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==pe.date){const s=this._getOrReturnCtx(t);return le(s,{code:oe.invalid_type,expected:pe.date,received:s.parsedType}),xe}if(Number.isNaN(t.data.getTime())){const s=this._getOrReturnCtx(t);return le(s,{code:oe.invalid_date}),xe}const n=new er;let o;for(const s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(o=this._getOrReturnCtx(t,o),le(o,{code:oe.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(o=this._getOrReturnCtx(t,o),le(o,{code:oe.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):ze.assertNever(s);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new Xs({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:me.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:me.toString(r)})}get minDate(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t!=null?new Date(t):null}}Xs.create=e=>new Xs({checks:[],coerce:e?.coerce||!1,typeName:se.ZodDate,...Ae(e)});class mf extends je{_parse(t){if(this._getType(t)!==pe.symbol){const n=this._getOrReturnCtx(t);return le(n,{code:oe.invalid_type,expected:pe.symbol,received:n.parsedType}),xe}return ar(t.data)}}mf.create=e=>new mf({typeName:se.ZodSymbol,...Ae(e)});class gf extends je{_parse(t){if(this._getType(t)!==pe.undefined){const n=this._getOrReturnCtx(t);return le(n,{code:oe.invalid_type,expected:pe.undefined,received:n.parsedType}),xe}return ar(t.data)}}gf.create=e=>new gf({typeName:se.ZodUndefined,...Ae(e)});class _f extends je{_parse(t){if(this._getType(t)!==pe.null){const n=this._getOrReturnCtx(t);return le(n,{code:oe.invalid_type,expected:pe.null,received:n.parsedType}),xe}return ar(t.data)}}_f.create=e=>new _f({typeName:se.ZodNull,...Ae(e)});class yf extends je{constructor(){super(...arguments),this._any=!0}_parse(t){return ar(t.data)}}yf.create=e=>new yf({typeName:se.ZodAny,...Ae(e)});class vf extends je{constructor(){super(...arguments),this._unknown=!0}_parse(t){return ar(t.data)}}vf.create=e=>new vf({typeName:se.ZodUnknown,...Ae(e)});class sn extends je{_parse(t){const r=this._getOrReturnCtx(t);return le(r,{code:oe.invalid_type,expected:pe.never,received:r.parsedType}),xe}}sn.create=e=>new sn({typeName:se.ZodNever,...Ae(e)});class wf extends je{_parse(t){if(this._getType(t)!==pe.undefined){const n=this._getOrReturnCtx(t);return le(n,{code:oe.invalid_type,expected:pe.void,received:n.parsedType}),xe}return ar(t.data)}}wf.create=e=>new wf({typeName:se.ZodVoid,...Ae(e)});class Mr extends je{_parse(t){const{ctx:r,status:n}=this._processInputParams(t),o=this._def;if(r.parsedType!==pe.array)return le(r,{code:oe.invalid_type,expected:pe.array,received:r.parsedType}),xe;if(o.exactLength!==null){const i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(le(r,{code:i?oe.too_big:oe.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(le(r,{code:oe.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(le(r,{code:oe.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>o.type._parseAsync(new nn(r,i,r.path,a)))).then(i=>er.mergeArray(n,i));const s=[...r.data].map((i,a)=>o.type._parseSync(new nn(r,i,r.path,a)));return er.mergeArray(n,s)}get element(){return this._def.type}min(t,r){return new Mr({...this._def,minLength:{value:t,message:me.toString(r)}})}max(t,r){return new Mr({...this._def,maxLength:{value:t,message:me.toString(r)}})}length(t,r){return new Mr({...this._def,exactLength:{value:t,message:me.toString(r)}})}nonempty(t){return this.min(1,t)}}Mr.create=(e,t)=>new Mr({type:e,minLength:null,maxLength:null,exactLength:null,typeName:se.ZodArray,...Ae(t)});function Qn(e){if(e instanceof _t){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=an.create(Qn(n))}return new _t({...e._def,shape:()=>t})}else return e instanceof Mr?new Mr({...e._def,type:Qn(e.element)}):e instanceof an?an.create(Qn(e.unwrap())):e instanceof to?to.create(Qn(e.unwrap())):e instanceof En?En.create(e.items.map(t=>Qn(t))):e}class _t extends je{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),r=ze.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==pe.object){const c=this._getOrReturnCtx(t);return le(c,{code:oe.invalid_type,expected:pe.object,received:c.parsedType}),xe}const{status:n,ctx:o}=this._processInputParams(t),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof sn&&this._def.unknownKeys==="strip"))for(const c in o.data)i.includes(c)||a.push(c);const l=[];for(const c of i){const u=s[c],f=o.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new nn(o,f,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof sn){const c=this._def.unknownKeys;if(c==="passthrough")for(const u of a)l.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(c==="strict")a.length>0&&(le(o,{code:oe.unrecognized_keys,keys:a}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const u of a){const f=o.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new nn(o,f,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const c=[];for(const u of l){const f=await u.key,p=await u.value;c.push({key:f,value:p,alwaysSet:u.alwaysSet})}return c}).then(c=>er.mergeObjectSync(n,c)):er.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(t){return me.errToObj,new _t({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,n)=>{const o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:me.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new _t({...this._def,unknownKeys:"strip"})}passthrough(){return new _t({...this._def,unknownKeys:"passthrough"})}extend(t){return new _t({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new _t({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:se.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new _t({...this._def,catchall:t})}pick(t){const r={};for(const n of ze.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new _t({...this._def,shape:()=>r})}omit(t){const r={};for(const n of ze.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new _t({...this._def,shape:()=>r})}deepPartial(){return Qn(this)}partial(t){const r={};for(const n of ze.objectKeys(this.shape)){const o=this.shape[n];t&&!t[n]?r[n]=o:r[n]=o.optional()}return new _t({...this._def,shape:()=>r})}required(t){const r={};for(const n of ze.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof an;)s=s._def.innerType;r[n]=s}return new _t({...this._def,shape:()=>r})}keyof(){return Cf(ze.objectKeys(this.shape))}}_t.create=(e,t)=>new _t({shape:()=>e,unknownKeys:"strip",catchall:sn.create(),typeName:se.ZodObject,...Ae(t)}),_t.strictCreate=(e,t)=>new _t({shape:()=>e,unknownKeys:"strict",catchall:sn.create(),typeName:se.ZodObject,...Ae(t)}),_t.lazycreate=(e,t)=>new _t({shape:e,unknownKeys:"strip",catchall:sn.create(),typeName:se.ZodObject,...Ae(t)});class ea extends je{_parse(t){const{ctx:r}=this._processInputParams(t),n=this._def.options;function o(s){for(const a of s)if(a.result.status==="valid")return a.result;for(const a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;const i=s.map(a=>new Fr(a.ctx.common.issues));return le(r,{code:oe.invalid_union,unionErrors:i}),xe}if(r.common.async)return Promise.all(n.map(async s=>{const i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(o);{let s;const i=[];for(const l of n){const c={...r,common:{...r.common,issues:[]},parent:null},u=l._parseSync({data:r.data,path:r.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:c}),c.common.issues.length&&i.push(c.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;const a=i.map(l=>new Fr(l));return le(r,{code:oe.invalid_union,unionErrors:a}),xe}}get options(){return this._def.options}}ea.create=(e,t)=>new ea({options:e,typeName:se.ZodUnion,...Ae(t)});function hl(e,t){const r=rn(e),n=rn(t);if(e===t)return{valid:!0,data:e};if(r===pe.object&&n===pe.object){const o=ze.objectKeys(t),s=ze.objectKeys(e).filter(a=>o.indexOf(a)!==-1),i={...e,...t};for(const a of s){const l=hl(e[a],t[a]);if(!l.valid)return{valid:!1};i[a]=l.data}return{valid:!0,data:i}}else if(r===pe.array&&n===pe.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let s=0;s<e.length;s++){const i=e[s],a=t[s],l=hl(i,a);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return r===pe.date&&n===pe.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class ta extends je{_parse(t){const{status:r,ctx:n}=this._processInputParams(t),o=(s,i)=>{if(cf(s)||cf(i))return xe;const a=hl(s.value,i.value);return a.valid?((uf(s)||uf(i))&&r.dirty(),{status:r.value,value:a.data}):(le(n,{code:oe.invalid_intersection_types}),xe)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}ta.create=(e,t,r)=>new ta({left:e,right:t,typeName:se.ZodIntersection,...Ae(r)});class En extends je{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==pe.array)return le(n,{code:oe.invalid_type,expected:pe.array,received:n.parsedType}),xe;if(n.data.length<this._def.items.length)return le(n,{code:oe.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),xe;!this._def.rest&&n.data.length>this._def.items.length&&(le(n,{code:oe.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const s=[...n.data].map((i,a)=>{const l=this._def.items[a]||this._def.rest;return l?l._parse(new nn(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>er.mergeArray(r,i)):er.mergeArray(r,s)}get items(){return this._def.items}rest(t){return new En({...this._def,rest:t})}}En.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new En({items:e,typeName:se.ZodTuple,rest:null,...Ae(t)})};class bf extends je{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==pe.map)return le(n,{code:oe.invalid_type,expected:pe.map,received:n.parsedType}),xe;const o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,l],c)=>({key:o._parse(new nn(n,a,n.path,[c,"key"])),value:s._parse(new nn(n,l,n.path,[c,"value"]))}));if(n.common.async){const a=new Map;return Promise.resolve().then(async()=>{for(const l of i){const c=await l.key,u=await l.value;if(c.status==="aborted"||u.status==="aborted")return xe;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(c.value,u.value)}return{status:r.value,value:a}})}else{const a=new Map;for(const l of i){const c=l.key,u=l.value;if(c.status==="aborted"||u.status==="aborted")return xe;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(c.value,u.value)}return{status:r.value,value:a}}}}bf.create=(e,t,r)=>new bf({valueType:t,keyType:e,typeName:se.ZodMap,...Ae(r)});class Fo extends je{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==pe.set)return le(n,{code:oe.invalid_type,expected:pe.set,received:n.parsedType}),xe;const o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(le(n,{code:oe.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(le(n,{code:oe.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());const s=this._def.valueType;function i(l){const c=new Set;for(const u of l){if(u.status==="aborted")return xe;u.status==="dirty"&&r.dirty(),c.add(u.value)}return{status:r.value,value:c}}const a=[...n.data.values()].map((l,c)=>s._parse(new nn(n,l,n.path,c)));return n.common.async?Promise.all(a).then(l=>i(l)):i(a)}min(t,r){return new Fo({...this._def,minSize:{value:t,message:me.toString(r)}})}max(t,r){return new Fo({...this._def,maxSize:{value:t,message:me.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}}Fo.create=(e,t)=>new Fo({valueType:e,minSize:null,maxSize:null,typeName:se.ZodSet,...Ae(t)});class kf extends je{get schema(){return this._def.getter()}_parse(t){const{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}}kf.create=(e,t)=>new kf({getter:e,typeName:se.ZodLazy,...Ae(t)});class Tf extends je{_parse(t){if(t.data!==this._def.value){const r=this._getOrReturnCtx(t);return le(r,{received:r.data,code:oe.invalid_literal,expected:this._def.value}),xe}return{status:"valid",value:t.data}}get value(){return this._def.value}}Tf.create=(e,t)=>new Tf({value:e,typeName:se.ZodLiteral,...Ae(t)});function Cf(e,t){return new Xn({values:e,typeName:se.ZodEnum,...Ae(t)})}class Xn extends je{_parse(t){if(typeof t.data!="string"){const r=this._getOrReturnCtx(t),n=this._def.values;return le(r,{expected:ze.joinValues(n),received:r.parsedType,code:oe.invalid_type}),xe}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){const r=this._getOrReturnCtx(t),n=this._def.values;return le(r,{received:r.data,code:oe.invalid_enum_value,options:n}),xe}return ar(t.data)}get options(){return this._def.values}get enum(){const t={};for(const r of this._def.values)t[r]=r;return t}get Values(){const t={};for(const r of this._def.values)t[r]=r;return t}get Enum(){const t={};for(const r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return Xn.create(t,{...this._def,...r})}exclude(t,r=this._def){return Xn.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}}Xn.create=Cf;class Sf extends je{_parse(t){const r=ze.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==pe.string&&n.parsedType!==pe.number){const o=ze.objectValues(r);return le(n,{expected:ze.joinValues(o),received:n.parsedType,code:oe.invalid_type}),xe}if(this._cache||(this._cache=new Set(ze.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const o=ze.objectValues(r);return le(n,{received:n.data,code:oe.invalid_enum_value,options:o}),xe}return ar(t.data)}get enum(){return this._def.values}}Sf.create=(e,t)=>new Sf({values:e,typeName:se.ZodNativeEnum,...Ae(t)});class ra extends je{unwrap(){return this._def.type}_parse(t){const{ctx:r}=this._processInputParams(t);if(r.parsedType!==pe.promise&&r.common.async===!1)return le(r,{code:oe.invalid_type,expected:pe.promise,received:r.parsedType}),xe;const n=r.parsedType===pe.promise?r.data:Promise.resolve(r.data);return ar(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}}ra.create=(e,t)=>new ra({type:e,typeName:se.ZodPromise,...Ae(t)});class eo extends je{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===se.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:r,ctx:n}=this._processInputParams(t),o=this._def.effect||null,s={addIssue:i=>{le(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){const i=o.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return xe;const l=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return l.status==="aborted"?xe:l.status==="dirty"||r.value==="dirty"?Uo(l.value):l});{if(r.value==="aborted")return xe;const a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?xe:a.status==="dirty"||r.value==="dirty"?Uo(a.value):a}}if(o.type==="refinement"){const i=a=>{const l=o.refinement(a,s);if(n.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){const a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?xe:(a.status==="dirty"&&r.dirty(),i(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?xe:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(o.type==="transform")if(n.common.async===!1){const i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Kn(i))return xe;const a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>Kn(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):xe);ze.assertNever(o)}}eo.create=(e,t,r)=>new eo({schema:e,typeName:se.ZodEffects,effect:t,...Ae(r)}),eo.createWithPreprocess=(e,t,r)=>new eo({schema:t,effect:{type:"preprocess",transform:e},typeName:se.ZodEffects,...Ae(r)});class an extends je{_parse(t){return this._getType(t)===pe.undefined?ar(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}an.create=(e,t)=>new an({innerType:e,typeName:se.ZodOptional,...Ae(t)});class to extends je{_parse(t){return this._getType(t)===pe.null?ar(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}to.create=(e,t)=>new to({innerType:e,typeName:se.ZodNullable,...Ae(t)});class ml extends je{_parse(t){const{ctx:r}=this._processInputParams(t);let n=r.data;return r.parsedType===pe.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}ml.create=(e,t)=>new ml({innerType:e,typeName:se.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Ae(t)});class gl extends je{_parse(t){const{ctx:r}=this._processInputParams(t),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Qs(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Fr(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Fr(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}gl.create=(e,t)=>new gl({innerType:e,typeName:se.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Ae(t)});class If extends je{_parse(t){if(this._getType(t)!==pe.nan){const n=this._getOrReturnCtx(t);return le(n,{code:oe.invalid_type,expected:pe.nan,received:n.parsedType}),xe}return{status:"valid",value:t.data}}}If.create=e=>new If({typeName:se.ZodNaN,...Ae(e)});class Q3 extends je{_parse(t){const{ctx:r}=this._processInputParams(t),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}}class _l extends je{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?xe:s.status==="dirty"?(r.dirty(),Uo(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{const o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?xe:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(t,r){return new _l({in:t,out:r,typeName:se.ZodPipeline})}}class yl extends je{_parse(t){const r=this._def.innerType._parse(t),n=o=>(Kn(o)&&(o.value=Object.freeze(o.value)),o);return Qs(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}}yl.create=(e,t)=>new yl({innerType:e,typeName:se.ZodReadonly,...Ae(t)});var se;(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"})(se||(se={}));const Ye=on.create,Nr=Yn.create;sn.create;const ln=Mr.create,gr=_t.create,vl=ea.create;ta.create,En.create;const na=Xn.create;ra.create,an.create,to.create;class xf extends Error{constructor(t,r){super(t),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}}function wl(e){}function Ef(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=wl,onError:r=wl,onRetry:n=wl,onComment:o}=e;let s="",i=!0,a,l="",c="";function u(v){const _=i?v.replace(/^\xEF\xBB\xBF/,""):v,[w,y]=X3(`${s}${_}`);for(const m of w)f(m);s=y,i=!1}function f(v){if(v===""){h();return}if(v.startsWith(":")){o&&o(v.slice(v.startsWith(": ")?2:1));return}const _=v.indexOf(":");if(_!==-1){const w=v.slice(0,_),y=v[_+1]===" "?2:1,m=v.slice(_+y);p(w,m,v);return}p(v,"",v)}function p(v,_,w){switch(v){case"event":c=_;break;case"data":l=`${l}${_}
31
- `;break;case"id":a=_.includes("\0")?void 0:_;break;case"retry":/^\d+$/.test(_)?n(parseInt(_,10)):r(new xf(`Invalid \`retry\` value: "${_}"`,{type:"invalid-retry",value:_,line:w}));break;default:r(new xf(`Unknown field "${v.length>20?`${v.slice(0,20)}…`:v}"`,{type:"unknown-field",field:v,value:_,line:w}));break}}function h(){l.length>0&&t({id:a,event:c||void 0,data:l.endsWith(`
32
- `)?l.slice(0,-1):l}),a=void 0,l="",c=""}function g(v={}){s&&v.consume&&f(s),i=!0,a=void 0,l="",c="",s=""}return{feed:u,reset:g}}function X3(e){const t=[];let r="",n=0;for(;n<e.length;){const o=e.indexOf("\r",n),s=e.indexOf(`
33
- `,n);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){r=e.slice(n);break}else{const a=e.slice(n,i);t.push(a),n=i+1,e[n-1]==="\r"&&e[n]===`
34
- `&&n++}}return[t,r]}class ro extends TransformStream{constructor({onError:t,onRetry:r,onComment:n}={}){let o;super({start(s){o=Ef({onEvent:i=>{s.enqueue(i)},onError(i){t==="terminate"?s.error(i):typeof t=="function"&&t(i)},onRetry:r,onComment:n})},transform(s){o.feed(s)}})}}function xt(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}function e9({tools:e=[],providerToolNames:t,resolveProviderToolName:r}){var n;const o={},s={};for(const i of e)if(i.type==="provider"){const a=(n=r?.(i))!=null?n:i.id in t?t[i.id]:void 0;if(a==null)continue;o[i.name]=a,s[a]=i.name}return{toProviderToolName:i=>{var a;return(a=o[i])!=null?a:i},toCustomToolName:i=>{var a;return(a=s[i])!=null?a:i}}}async function t9(e,t){if(e==null)return Promise.resolve();const r=t?.abortSignal;return new Promise((n,o)=>{if(r?.aborted){o($f());return}const s=setTimeout(()=>{i(),n()},e),i=()=>{clearTimeout(s),r?.removeEventListener("abort",a)},a=()=>{i(),o($f())};r?.addEventListener("abort",a)})}function $f(){return new DOMException("Delay was aborted","AbortError")}var Vo=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))}isResolved(){return this.status.type==="resolved"}isRejected(){return this.status.type==="rejected"}isPending(){return this.status.type==="pending"}};function no(e){return Object.fromEntries([...e.headers])}var{btoa:r9,atob:n9}=globalThis;function oo(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=n9(t);return Uint8Array.from(r,n=>n.codePointAt(0))}function so(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return r9(t)}function ao(e){return e instanceof Uint8Array?so(e):e}function o9(e,t={}){const{useArrayBrackets:r=!0}=t,n=new FormData;for(const[o,s]of Object.entries(e))if(s!=null){if(Array.isArray(s)){if(s.length===1){n.append(o,s[0]);continue}const i=r?`${o}[]`:o;for(const a of s)n.append(i,a);continue}n.append(o,s)}return n}var Rf="AI_DownloadError",Pf=`vercel.ai.error.${Rf}`,s9=Symbol.for(Pf),Mf,Nf,Jt=class extends(Nf=be,Mf=s9,Nf){constructor({url:e,statusCode:t,statusText:r,cause:n,message:o=n==null?`Failed to download ${e}: ${t} ${r}`:`Failed to download ${e}: ${n}`}){super({name:Rf,message:o,cause:n}),this[Mf]=!0,this.url=e,this.statusCode=t,this.statusText=r}static isInstance(e){return be.hasMarker(e,Pf)}},bl=2*1024*1024*1024;async function Of({response:e,url:t,maxBytes:r=bl}){const n=e.headers.get("content-length");if(n!=null){const u=parseInt(n,10);if(!isNaN(u)&&u>r)throw new Jt({url:t,message:`Download of ${t} exceeded maximum size of ${r} bytes (Content-Length: ${u}).`})}const o=e.body;if(o==null)return new Uint8Array(0);const s=o.getReader(),i=[];let a=0;try{for(;;){const{done:u,value:f}=await s.read();if(u)break;if(a+=f.length,a>r)throw new Jt({url:t,message:`Download of ${t} exceeded maximum size of ${r} bytes.`});i.push(f)}}finally{try{await s.cancel()}finally{s.releaseLock()}}const l=new Uint8Array(a);let c=0;for(const u of i)l.set(u,c),c+=u.length;return l}function oa(e){let t;try{t=new URL(e)}catch{throw new Jt({url:e,message:`Invalid URL: ${e}`})}if(t.protocol==="data:")return;if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Jt({url:e,message:`URL scheme must be http, https, or data, got ${t.protocol}`});const r=t.hostname;if(!r)throw new Jt({url:e,message:"URL must have a hostname"});if(r==="localhost"||r.endsWith(".local")||r.endsWith(".localhost"))throw new Jt({url:e,message:`URL with hostname ${r} is not allowed`});if(r.startsWith("[")&&r.endsWith("]")){const n=r.slice(1,-1);if(a9(n))throw new Jt({url:e,message:`URL with IPv6 address ${r} is not allowed`});return}if(Af(r)){if(kl(r))throw new Jt({url:e,message:`URL with IP address ${r} is not allowed`});return}}function Af(e){const t=e.split(".");return t.length!==4?!1:t.every(r=>{const n=Number(r);return Number.isInteger(n)&&n>=0&&n<=255&&String(n)===r})}function kl(e){const t=e.split(".").map(Number),[r,n]=t;return r===0||r===10||r===127||r===169&&n===254||r===172&&n>=16&&n<=31||r===192&&n===168}function a9(e){const t=e.toLowerCase();if(t==="::1"||t==="::")return!0;if(t.startsWith("::ffff:")){const r=t.slice(7);if(Af(r))return kl(r);const n=r.split(":");if(n.length===2){const o=parseInt(n[0],16),s=parseInt(n[1],16);if(!isNaN(o)&&!isNaN(s)){const i=o>>8&255,a=o&255,l=s>>8&255,c=s&255;return kl(`${i}.${a}.${l}.${c}`)}}}return!!(t.startsWith("fc")||t.startsWith("fd")||t.startsWith("fe80"))}async function qf(e,t){var r,n;oa(e);try{const o=await fetch(e,{signal:t?.abortSignal});if(o.redirected&&oa(o.url),!o.ok)throw new Jt({url:e,statusCode:o.status,statusText:o.statusText});const s=await Of({response:o,url:e,maxBytes:(r=t?.maxBytes)!=null?r:bl}),i=(n=o.headers.get("content-type"))!=null?n:void 0;return new Blob([s],i?{type:i}:void 0)}catch(o){throw Jt.isInstance(o)?o:new Jt({url:e,cause:o})}}var Zo=({prefix:e,size:t=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{const o=()=>{const s=r.length,i=new Array(t);for(let a=0;a<t;a++)i[a]=r[Math.random()*s|0];return i.join("")};if(e==null)return o;if(r.includes(n))throw new $d({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${e}${n}${o()}`},Dt=Zo();function Tl(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}function $n(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var i9=["fetch failed","failed to fetch"],l9=["ConnectionRefused","ConnectionClosed","FailedToOpenSocket","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE"];function c9(e){if(!(e instanceof Error))return!1;const t=e.code;return!!(typeof t=="string"&&l9.includes(t))}function Lf({error:e,url:t,requestBodyValues:r}){if($n(e))return e;if(e instanceof TypeError&&i9.includes(e.message.toLowerCase())){const n=e.cause;if(n!=null)return new at({message:`Cannot connect to API: ${n.message}`,cause:n,url:t,requestBodyValues:r,isRetryable:!0})}return c9(e)?new at({message:`Cannot connect to API: ${e.message}`,cause:e,url:t,requestBodyValues:r,isRetryable:!0}):e}function Bo(e=globalThis){var t,r,n;return e.window?"runtime/browser":(t=e.navigator)!=null&&t.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(n=(r=e.process)==null?void 0:r.versions)!=null&&n.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function u9(e){if(e==null)return{};const t={};if(e instanceof Headers)e.forEach((r,n)=>{t[n.toLowerCase()]=r});else{Array.isArray(e)||(e=Object.entries(e));for(const[r,n]of e)n!=null&&(t[r.toLowerCase()]=n)}return t}function cn(e,...t){const r=new Headers(u9(e)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var jf="4.0.23",d9=()=>globalThis.fetch,sa=async({url:e,headers:t={},successfulResponseHandler:r,failedResponseHandler:n,abortSignal:o,fetch:s=d9()})=>{try{const i=await s(e,{method:"GET",headers:cn(t,`ai-sdk/provider-utils/${jf}`,Bo()),signal:o}),a=no(i);if(!i.ok){let l;try{l=await n({response:i,url:e,requestBodyValues:{}})}catch(c){throw $n(c)||at.isInstance(c)?c:new at({message:"Failed to process error response",cause:c,statusCode:i.status,url:e,responseHeaders:a,requestBodyValues:{}})}throw l.value}try{return await r({response:i,url:e,requestBodyValues:{}})}catch(l){throw l instanceof Error&&($n(l)||at.isInstance(l))?l:new at({message:"Failed to process successful response",cause:l,statusCode:i.status,url:e,responseHeaders:a,requestBodyValues:{}})}}catch(i){throw Lf({error:i,url:e,requestBodyValues:{}})}};function Df(e){return e!=null}function p9({mediaType:e,url:t,supportedUrls:r}){return t=t.toLowerCase(),e=e.toLowerCase(),Object.entries(r).map(([n,o])=>{const s=n.toLowerCase();return s==="*"||s==="*/*"?{mediaTypePrefix:"",regexes:o}:{mediaTypePrefix:s.replace(/\*/,""),regexes:o}}).filter(({mediaTypePrefix:n})=>e.startsWith(n)).flatMap(({regexes:n})=>n).some(n=>n.test(t))}function f9({apiKey:e,environmentVariableName:t,apiKeyParameterName:r="apiKey",description:n}){if(typeof e=="string")return e;if(e!=null)throw new Us({message:`${n} API key must be a string.`});if(typeof process>"u")throw new Us({message:`${n} API key is missing. Pass it using the '${r}' parameter. Environment variables are not supported in this environment.`});if(e=process.env[t],e==null)throw new Us({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new Us({message:`${n} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}function io({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 h9(e){var t;const[r,n=""]=e.toLowerCase().split("/");return(t={mpeg:"mp3","x-wav":"wav",opus:"ogg",mp4:"m4a","x-m4a":"m4a"}[n])!=null?t:n}var m9=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,g9=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function Uf(e){const t=JSON.parse(e);return t===null||typeof t!="object"||m9.test(e)===!1&&g9.test(e)===!1?t:_9(t)}function _9(e){let t=[e];for(;t.length;){const r=t;t=[];for(const n of r){if(Object.prototype.hasOwnProperty.call(n,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(n,"constructor")&&n.constructor!==null&&typeof n.constructor=="object"&&Object.prototype.hasOwnProperty.call(n.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const o in n){const s=n[o];s&&typeof s=="object"&&t.push(s)}}}return e}function Cl(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return Uf(e)}try{return Uf(e)}finally{Error.stackTraceLimit=t}}function Sl(e){if(e.type==="object"||Array.isArray(e.type)&&e.type.includes("object")){e.additionalProperties=!1;const{properties:r}=e;if(r!=null)for(const n of Object.keys(r))r[n]=Rn(r[n])}e.items!=null&&(e.items=Array.isArray(e.items)?e.items.map(Rn):Rn(e.items)),e.anyOf!=null&&(e.anyOf=e.anyOf.map(Rn)),e.allOf!=null&&(e.allOf=e.allOf.map(Rn)),e.oneOf!=null&&(e.oneOf=e.oneOf.map(Rn));const{definitions:t}=e;if(t!=null)for(const r of Object.keys(t))t[r]=Rn(t[r]);return e}function Rn(e){return typeof e=="boolean"?e:Sl(e)}var y9=Symbol("Let zodToJsonSchema decide on which parser to use"),zf={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"},v9=e=>typeof e=="string"?{...zf,name:e}:{...zf,...e};function tr(){return{}}function w9(e,t){var r,n,o;const s={type:"array"};return(r=e.type)!=null&&r._def&&((o=(n=e.type)==null?void 0:n._def)==null?void 0:o.typeName)!==se.ZodAny&&(s.items=Be(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 b9(e){const t={type:"integer",format:"int64"};if(!e.checks)return t;for(const r of e.checks)switch(r.kind){case"min":r.inclusive?t.minimum=r.value:t.exclusiveMinimum=r.value;break;case"max":r.inclusive?t.maximum=r.value:t.exclusiveMaximum=r.value;break;case"multipleOf":t.multipleOf=r.value;break}return t}function k9(){return{type:"boolean"}}function Ff(e,t){return Be(e.type._def,t)}var T9=(e,t)=>Be(e.innerType._def,t);function Vf(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Vf(e,t,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return C9(e)}}var C9=e=>{const t={type:"integer",format:"unix-time"};for(const r of e.checks)switch(r.kind){case"min":t.minimum=r.value;break;case"max":t.maximum=r.value;break}return t};function S9(e,t){return{...Be(e.innerType._def,t),default:e.defaultValue()}}function I9(e,t){return t.effectStrategy==="input"?Be(e.schema._def,t):tr()}function x9(e){return{type:"string",enum:Array.from(e.values)}}var E9=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function $9(e,t){const r=[Be(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Be(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(o=>!!o),n=[];return r.forEach(o=>{if(E9(o))n.push(...o.allOf);else{let s=o;if("additionalProperties"in o&&o.additionalProperties===!1){const{additionalProperties:i,...a}=o;s=a}n.push(s)}}),n.length?{allOf:n}:void 0}function R9(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 Il=void 0,_r={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:()=>(Il===void 0&&(Il=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Il),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 Zf(e,t){const r={type:"string"};if(e.checks)for(const n of e.checks)switch(n.kind){case"min":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value;break;case"max":r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value;break;case"email":switch(t.emailStrategy){case"format:email":yr(r,"email",n.message,t);break;case"format:idn-email":yr(r,"idn-email",n.message,t);break;case"pattern:zod":Ut(r,_r.email,n.message,t);break}break;case"url":yr(r,"uri",n.message,t);break;case"uuid":yr(r,"uuid",n.message,t);break;case"regex":Ut(r,n.regex,n.message,t);break;case"cuid":Ut(r,_r.cuid,n.message,t);break;case"cuid2":Ut(r,_r.cuid2,n.message,t);break;case"startsWith":Ut(r,RegExp(`^${xl(n.value,t)}`),n.message,t);break;case"endsWith":Ut(r,RegExp(`${xl(n.value,t)}$`),n.message,t);break;case"datetime":yr(r,"date-time",n.message,t);break;case"date":yr(r,"date",n.message,t);break;case"time":yr(r,"time",n.message,t);break;case"duration":yr(r,"duration",n.message,t);break;case"length":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value;break;case"includes":{Ut(r,RegExp(xl(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&yr(r,"ipv4",n.message,t),n.version!=="v4"&&yr(r,"ipv6",n.message,t);break}case"base64url":Ut(r,_r.base64url,n.message,t);break;case"jwt":Ut(r,_r.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&Ut(r,_r.ipv4Cidr,n.message,t),n.version!=="v4"&&Ut(r,_r.ipv6Cidr,n.message,t);break}case"emoji":Ut(r,_r.emoji(),n.message,t);break;case"ulid":{Ut(r,_r.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{yr(r,"binary",n.message,t);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{Ut(r,_r.base64,n.message,t);break}}break}case"nanoid":Ut(r,_r.nanoid,n.message,t)}return r}function xl(e,t){return t.patternStrategy==="escape"?M9(e):e}var P9=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function M9(e){let t="";for(let r=0;r<e.length;r++)P9.has(e[r])||(t+="\\"),t+=e[r];return t}function yr(e,t,r,n){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,...r&&n.errorMessages&&{errorMessage:{format:r}}})):e.format=t}function Ut(e,t,r,n){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:Bf(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):e.pattern=Bf(t,n)}function Bf(e,t){var r;if(!t.applyRegexFlags||!e.flags)return e.source;const n={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},o=n.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(n.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]==="-"&&((r=o[c+2])!=null&&r.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(n.m){if(o[c]==="^"){s+=`(^|(?<=[\r
35
- ]))`;continue}else if(o[c]==="$"){s+=`($|(?=[\r
36
- ]))`;continue}}if(n.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 Hf(e,t){var r,n,o,s,i,a;const l={type:"object",additionalProperties:(r=Be(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?r:t.allowedAdditionalProperties};if(((n=e.keyType)==null?void 0:n._def.typeName)===se.ZodString&&((o=e.keyType._def.checks)!=null&&o.length)){const{type:c,...u}=Zf(e.keyType._def,t);return{...l,propertyNames:u}}else{if(((s=e.keyType)==null?void 0:s._def.typeName)===se.ZodEnum)return{...l,propertyNames:{enum:e.keyType._def.values}};if(((i=e.keyType)==null?void 0:i._def.typeName)===se.ZodBranded&&e.keyType._def.type._def.typeName===se.ZodString&&((a=e.keyType._def.type._def.checks)!=null&&a.length)){const{type:c,...u}=Ff(e.keyType._def,t);return{...l,propertyNames:u}}}return l}function N9(e,t){if(t.mapStrategy==="record")return Hf(e,t);const r=Be(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||tr(),n=Be(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||tr();return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function O9(e){const t=e.values,n=Object.keys(e.values).filter(s=>typeof t[t[s]]!="number").map(s=>t[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function A9(){return{not:tr()}}function q9(){return{type:"null"}}var El={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function L9(e,t){const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in El&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((o,s)=>{const i=El[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=r.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(n.length===r.length){const o=n.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return j9(e,t)}var j9=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>Be(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!t.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function D9(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[El[e.innerType._def.typeName],"null"]};const r=Be(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function U9(e){const t={type:"number"};if(!e.checks)return t;for(const r of e.checks)switch(r.kind){case"int":t.type="integer";break;case"min":r.inclusive?t.minimum=r.value:t.exclusiveMinimum=r.value;break;case"max":r.inclusive?t.maximum=r.value:t.exclusiveMaximum=r.value;break;case"multipleOf":t.multipleOf=r.value;break}return t}function z9(e,t){const r={type:"object",properties:{}},n=[],o=e.shape();for(const i in o){let a=o[i];if(a===void 0||a._def===void 0)continue;const l=V9(a),c=Be(a._def,{...t,currentPath:[...t.currentPath,"properties",i],propertyPath:[...t.currentPath,"properties",i]});c!==void 0&&(r.properties[i]=c,l||n.push(i))}n.length&&(r.required=n);const s=F9(e,t);return s!==void 0&&(r.additionalProperties=s),r}function F9(e,t){if(e.catchall._def.typeName!=="ZodNever")return Be(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 V9(e){try{return e.isOptional()}catch{return!0}}var Z9=(e,t)=>{var r;if(t.currentPath.toString()===((r=t.propertyPath)==null?void 0:r.toString()))return Be(e.innerType._def,t);const n=Be(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:tr()},n]}:tr()},B9=(e,t)=>{if(t.pipeStrategy==="input")return Be(e.in._def,t);if(t.pipeStrategy==="output")return Be(e.out._def,t);const r=Be(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=Be(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function H9(e,t){return Be(e.type._def,t)}function J9(e,t){const n={type:"array",uniqueItems:!0,items:Be(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&(n.minItems=e.minSize.value),e.maxSize&&(n.maxItems=e.maxSize.value),n}function G9(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>Be(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Be(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>Be(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function W9(){return{not:tr()}}function K9(){return tr()}var Y9=(e,t)=>Be(e.innerType._def,t),Q9=(e,t,r)=>{switch(t){case se.ZodString:return Zf(e,r);case se.ZodNumber:return U9(e);case se.ZodObject:return z9(e,r);case se.ZodBigInt:return b9(e);case se.ZodBoolean:return k9();case se.ZodDate:return Vf(e,r);case se.ZodUndefined:return W9();case se.ZodNull:return q9();case se.ZodArray:return w9(e,r);case se.ZodUnion:case se.ZodDiscriminatedUnion:return L9(e,r);case se.ZodIntersection:return $9(e,r);case se.ZodTuple:return G9(e,r);case se.ZodRecord:return Hf(e,r);case se.ZodLiteral:return R9(e);case se.ZodEnum:return x9(e);case se.ZodNativeEnum:return O9(e);case se.ZodNullable:return D9(e,r);case se.ZodOptional:return Z9(e,r);case se.ZodMap:return N9(e,r);case se.ZodSet:return J9(e,r);case se.ZodLazy:return()=>e.getter()._def;case se.ZodPromise:return H9(e,r);case se.ZodNaN:case se.ZodNever:return A9();case se.ZodEffects:return I9(e,r);case se.ZodAny:return tr();case se.ZodUnknown:return K9();case se.ZodDefault:return S9(e,r);case se.ZodBranded:return Ff(e,r);case se.ZodReadonly:return Y9(e,r);case se.ZodCatch:return T9(e,r);case se.ZodPipeline:return B9(e,r);case se.ZodFunction:case se.ZodVoid:case se.ZodSymbol:return;default:return(n=>{})()}},X9=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")};function Be(e,t,r=!1){var n;const o=t.seen.get(e);if(t.override){const l=(n=t.override)==null?void 0:n.call(t,e,t,o,r);if(l!==y9)return l}if(o&&!r){const l=e4(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=Q9(e,e.typeName,t),a=typeof i=="function"?Be(i(),t):i;if(a&&t4(e,t,a),t.postProcess){const l=t.postProcess(a,e,t);return s.jsonSchema=a,l}return s.jsonSchema=a,a}var e4=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:X9(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,n)=>t.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),tr()):t.$refStrategy==="seen"?tr():void 0}},t4=(e,t,r)=>(e.description&&(r.description=e.description),r),r4=e=>{const t=v9(e),r=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...t.basePath,t.definitionPath,n],jsonSchema:void 0}]))}},n4=(e,t)=>{var r;const n=r4(t);let o=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,f])=>{var p;return{...c,[u]:(p=Be(f._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0))!=null?p:tr()}},{}):void 0;const s=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,i=(r=Be(e._def,s===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,s]},!1))!=null?r:tr(),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,[n.definitionPath]:o}:i:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,s].join("/"),[n.definitionPath]:{...o,[s]:i}};return l.$schema="http://json-schema.org/draft-07/schema#",l},$l=Symbol.for("vercel.ai.schema");function ve(e){let t;return()=>(t==null&&(t=e()),t)}function Pn(e,{validate:t}={}){return{[$l]:!0,_type:void 0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}function o4(e){return typeof e=="object"&&e!==null&&$l in e&&e[$l]===!0&&"jsonSchema"in e&&"validate"in e}function Mn(e){return e==null?Pn({properties:{},additionalProperties:!1}):o4(e)?e:"~standard"in e?e["~standard"].vendor==="zod"?ye(e):s4(e):e()}function s4(e){return Pn(()=>Sl(e["~standard"].jsonSchema.input({target:"draft-07"})),{validate:async t=>{const r=await e["~standard"].validate(t);return"value"in r?{success:!0,value:r.value}:{success:!1,error:new Sn({value:t,cause:r.issues})}}})}function a4(e,t){var r;const n=(r=void 0)!=null?r:!1;return Pn(()=>n4(e,{$refStrategy:n?"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 i4(e,t){var r;const n=(r=void 0)!=null?r:!1;return Pn(()=>Sl(Sb(e,{target:"draft-7",io:"input",reused:n?"ref":"inline"})),{validate:async o=>{const s=await Zp(e,o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function l4(e){return"_zod"in e}function ye(e,t){return l4(e)?i4(e):a4(e)}async function dt({value:e,schema:t,context:r}){const n=await ir({value:e,schema:t,context:r});if(!n.success)throw Sn.wrap({value:e,cause:n.error,context:r});return n.value}async function ir({value:e,schema:t,context:r}){const n=Mn(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};const o=await n.validate(e);return o.success?{success:!0,value:o.value,rawValue:e}:{success:!1,error:Sn.wrap({value:e,cause:o.error,context:r}),rawValue:e}}catch(o){return{success:!1,error:Sn.wrap({value:e,cause:o,context:r}),rawValue:e}}}async function Jf({text:e,schema:t}){try{const r=Cl(e);return t==null?r:dt({value:r,schema:t})}catch(r){throw Ds.isInstance(r)||Sn.isInstance(r)?r:new Ds({text:e,cause:r})}}async function lr({text:e,schema:t}){try{const r=Cl(e);return t==null?{success:!0,value:r,rawValue:r}:await ir({value:r,schema:t})}catch(r){return{success:!1,error:Ds.isInstance(r)?r:new Ds({text:e,cause:r}),rawValue:void 0}}}function Gf(e){try{return Cl(e),!0}catch{return!1}}function Wf({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new ro).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await lr({text:r,schema:t}))}}))}async function Vr({provider:e,providerOptions:t,schema:r}){if(t?.[e]==null)return;const n=await ir({value:t[e],schema:r});if(!n.success)throw new $d({argument:"providerOptions",message:`invalid ${e} provider options`,cause:n.error});return n.value}var c4=()=>globalThis.fetch,zt=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i})=>Yf({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i}),Kf=async({url:e,headers:t,formData:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i})=>Yf({url:e,headers:t,body:{content:r,values:Object.fromEntries(r.entries())},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i}),Yf=async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:s,fetch:i=c4()})=>{try{const a=await i(e,{method:"POST",headers:cn(t,`ai-sdk/provider-utils/${jf}`,Bo()),body:r.content,signal:s}),l=no(a);if(!a.ok){let c;try{c=await o({response:a,url:e,requestBodyValues:r.values})}catch(u){throw $n(u)||at.isInstance(u)?u:new at({message:"Failed to process error response",cause:u,statusCode:a.status,url:e,responseHeaders:l,requestBodyValues:r.values})}throw c.value}try{return await n({response:a,url:e,requestBodyValues:r.values})}catch(c){throw c instanceof Error&&($n(c)||at.isInstance(c))?c:new at({message:"Failed to process successful response",cause:c,statusCode:a.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(a){throw Lf({error:a,url:e,requestBodyValues:r.values})}};function p$(e){return e}function Rl(e){return{...e,type:"dynamic"}}function u4({id:e,inputSchema:t}){return({execute:r,outputSchema:n,needsApproval:o,toModelOutput:s,onInputStart:i,onInputDelta:a,onInputAvailable:l,...c})=>({type:"provider",id:e,args:c,inputSchema:t,outputSchema:n,execute:r,needsApproval:o,toModelOutput:s,onInputStart:i,onInputDelta:a,onInputAvailable:l})}function cr({id:e,inputSchema:t,outputSchema:r,supportsDeferredResults:n}){return({execute:o,needsApproval:s,toModelOutput:i,onInputStart:a,onInputDelta:l,onInputAvailable:c,...u})=>({type:"provider",id:e,args:u,inputSchema:t,outputSchema:r,execute:o,needsApproval:s,toModelOutput:i,onInputStart:a,onInputDelta:l,onInputAvailable:c,supportsDeferredResults:n})}async function Tt(e){return typeof e=="function"&&(e=e()),Promise.resolve(e)}var vr=({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:n,url:o,requestBodyValues:s})=>{const i=await n.text(),a=no(n);if(i.trim()==="")return{responseHeaders:a,value:new at({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:a,responseBody:i,isRetryable:r?.(n)})};try{const l=await Jf({text:i,schema:e});return{responseHeaders:a,value:new at({message:t(l),url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:a,responseBody:i,data:l,isRetryable:r?.(n,l)})}}catch{return{responseHeaders:a,value:new at({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:a,responseBody:i,isRetryable:r?.(n)})}}},aa=e=>async({response:t})=>{const r=no(t);if(t.body==null)throw new Tv({});return{responseHeaders:r,value:Wf({stream:t.body,schema:e})}},Ft=e=>async({response:t,url:r,requestBodyValues:n})=>{const o=await t.text(),s=await lr({text:o,schema:e}),i=no(t);if(!s.success)throw new at({message:"Invalid JSON response",cause:s.error,statusCode:t.status,responseHeaders:i,responseBody:o,url:r,requestBodyValues:n});return{responseHeaders:i,value:s.value,rawValue:s.rawValue}},d4=()=>async({response:e,url:t,requestBodyValues:r})=>{const n=no(e);if(!e.body)throw new at({message:"Response body is empty",url:t,requestBodyValues:r,statusCode:e.status,responseHeaders:n,responseBody:void 0});try{const o=await e.arrayBuffer();return{responseHeaders:n,value:new Uint8Array(o)}}catch(o){throw new at({message:"Failed to read response as array buffer",url:t,requestBodyValues:r,statusCode:e.status,responseHeaders:n,responseBody:void 0,cause:o})}};function Qf(e){return e?.replace(/\/$/,"")}function p4(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*f4({execute:e,input:t,options:r}){const n=e(t,r);if(p4(n)){let o;for await(const s of n)o=s,yield{type:"preliminary",output:s};yield{type:"final",output:o}}else yield{type:"final",output:await n}}function Pl(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ml,Xf;function h4(){if(Xf)return Ml;Xf=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o=(u,f)=>{for(var p in f)e(u,p,{get:f[p],enumerable:!0})},s=(u,f,p,h)=>{if(f&&typeof f=="object"||typeof f=="function")for(let g of r(f))!n.call(u,g)&&g!==p&&e(u,g,{get:()=>f[g],enumerable:!(h=t(f,g))||h.enumerable});return u},i=u=>s(e({},"__esModule",{value:!0}),u),a={};o(a,{SYMBOL_FOR_REQ_CONTEXT:()=>l,getContext:()=>c}),Ml=i(a);const l=Symbol.for("@vercel/request-context");function c(){return globalThis[l]?.get?.()??{}}return Ml}var Nl,eh;function m4(){if(eh)return Nl;eh=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o=(f,p)=>{for(var h in p)e(f,h,{get:p[h],enumerable:!0})},s=(f,p,h,g)=>{if(p&&typeof p=="object"||typeof p=="function")for(let v of r(p))!n.call(f,v)&&v!==h&&e(f,v,{get:()=>p[v],enumerable:!(g=t(p,v))||g.enumerable});return f},i=f=>s(e({},"__esModule",{value:!0}),f),a={};o(a,{getContext:()=>l.getContext,getVercelOidcToken:()=>c,getVercelOidcTokenSync:()=>u}),Nl=i(a);var l=h4();async function c(){return""}function u(){return""}return Nl}var th=m4(),g4="vercel.ai.gateway.error",Ol=Symbol.for(g4),rh,nh,Vt=class gv extends(nh=Error,rh=Ol,nh){constructor({message:t,statusCode:r=500,cause:n,generationId:o}){super(o?`${t} [${o}]`:t),this[rh]=!0,this.statusCode=r,this.cause=n,this.generationId=o}static isInstance(t){return gv.hasMarker(t)}static hasMarker(t){return typeof t=="object"&&t!==null&&Ol in t&&t[Ol]===!0}},oh="GatewayAuthenticationError",_4=`vercel.ai.gateway.error.${oh}`,sh=Symbol.for(_4),ah,ih,Al=class _v extends(ih=Vt,ah=sh,ih){constructor({message:t="Authentication failed",statusCode:r=401,cause:n,generationId:o}={}){super({message:t,statusCode:r,cause:n,generationId:o}),this[ah]=!0,this.name=oh,this.type="authentication_error"}static isInstance(t){return Vt.hasMarker(t)&&sh in t}static createContextualError({apiKeyProvided:t,oidcTokenProvided:r,message:n="Authentication failed",statusCode:o=401,cause:s,generationId:i}){let a;return t?a=`AI Gateway authentication failed: Invalid API key.
39
-
40
- Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
41
-
42
- Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`:r?a=`AI Gateway authentication failed: Invalid OIDC token.
43
-
44
- Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.
45
-
46
- Alternatively, use an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys`:a=`AI Gateway authentication failed: No authentication provided.
47
-
48
- Option 1 - API key:
49
- Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
50
- Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
51
-
52
- Option 2 - OIDC token:
53
- Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new _v({message:a,statusCode:o,cause:s,generationId:i})}},lh="GatewayInvalidRequestError",y4=`vercel.ai.gateway.error.${lh}`,ch=Symbol.for(y4),uh,dh,v4=class extends(dh=Vt,uh=ch,dh){constructor({message:e="Invalid request",statusCode:t=400,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[uh]=!0,this.name=lh,this.type="invalid_request_error"}static isInstance(e){return Vt.hasMarker(e)&&ch in e}},ph="GatewayRateLimitError",w4=`vercel.ai.gateway.error.${ph}`,fh=Symbol.for(w4),hh,mh,b4=class extends(mh=Vt,hh=fh,mh){constructor({message:e="Rate limit exceeded",statusCode:t=429,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[hh]=!0,this.name=ph,this.type="rate_limit_exceeded"}static isInstance(e){return Vt.hasMarker(e)&&fh in e}},gh="GatewayModelNotFoundError",k4=`vercel.ai.gateway.error.${gh}`,_h=Symbol.for(k4),T4=ve(()=>ye(k({modelId:d()}))),yh,vh,C4=class extends(vh=Vt,yh=_h,vh){constructor({message:e="Model not found",statusCode:t=404,modelId:r,cause:n,generationId:o}={}){super({message:e,statusCode:t,cause:n,generationId:o}),this[yh]=!0,this.name=gh,this.type="model_not_found",this.modelId=r}static isInstance(e){return Vt.hasMarker(e)&&_h in e}},wh="GatewayInternalServerError",S4=`vercel.ai.gateway.error.${wh}`,bh=Symbol.for(S4),kh,Th,Ch=class extends(Th=Vt,kh=bh,Th){constructor({message:e="Internal server error",statusCode:t=500,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[kh]=!0,this.name=wh,this.type="internal_server_error"}static isInstance(e){return Vt.hasMarker(e)&&bh in e}},Sh="GatewayResponseError",I4=`vercel.ai.gateway.error.${Sh}`,Ih=Symbol.for(I4),xh,Eh,x4=class extends(Eh=Vt,xh=Ih,Eh){constructor({message:e="Invalid response from Gateway",statusCode:t=502,response:r,validationError:n,cause:o,generationId:s}={}){super({message:e,statusCode:t,cause:o,generationId:s}),this[xh]=!0,this.name=Sh,this.type="response_error",this.response=r,this.validationError=n}static isInstance(e){return Vt.hasMarker(e)&&Ih in e}};async function $h({response:e,statusCode:t,defaultMessage:r="Gateway request failed",cause:n,authMethod:o}){var s;const i=await ir({value:e,schema:E4});if(!i.success){const f=typeof e=="object"&&e!==null&&"generationId"in e?e.generationId:void 0;return new x4({message:`Invalid error response format: ${r}`,statusCode:t,response:e,validationError:i.error,cause:n,generationId:f})}const a=i.value,l=a.error.type,c=a.error.message,u=(s=a.generationId)!=null?s:void 0;switch(l){case"authentication_error":return Al.createContextualError({apiKeyProvided:o==="api-key",oidcTokenProvided:o==="oidc",statusCode:t,cause:n,generationId:u});case"invalid_request_error":return new v4({message:c,statusCode:t,cause:n,generationId:u});case"rate_limit_exceeded":return new b4({message:c,statusCode:t,cause:n,generationId:u});case"model_not_found":{const f=await ir({value:a.error.param,schema:T4});return new C4({message:c,statusCode:t,modelId:f.success?f.value.modelId:void 0,cause:n,generationId:u})}case"internal_server_error":return new Ch({message:c,statusCode:t,cause:n,generationId:u});default:return new Ch({message:c,statusCode:t,cause:n,generationId:u})}}var E4=ve(()=>ye(k({error:k({message:d(),type:d().nullish(),param:Ie().nullish(),code:ae([d(),N()]).nullish()}),generationId:d().nullish()}))),Rh="GatewayTimeoutError",$4=`vercel.ai.gateway.error.${Rh}`,Ph=Symbol.for($4),Mh,Nh,Oh=class yv extends(Nh=Vt,Mh=Ph,Nh){constructor({message:t="Request timed out",statusCode:r=408,cause:n,generationId:o}={}){super({message:t,statusCode:r,cause:n,generationId:o}),this[Mh]=!0,this.name=Rh,this.type="timeout_error"}static isInstance(t){return Vt.hasMarker(t)&&Ph in t}static createTimeoutError({originalMessage:t,statusCode:r=408,cause:n,generationId:o}){const s=`Gateway request timed out: ${t}
54
-
55
- This is a client-side timeout. To resolve this, increase your timeout configuration: https://vercel.com/docs/ai-gateway/capabilities/video-generation#extending-timeouts-for-node.js`;return new yv({message:s,statusCode:r,cause:n,generationId:o})}};function Ah(e){if(!(e instanceof Error))return!1;const t=e.code;return typeof t=="string"?["UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT"].includes(t):!1}async function Gt(e,t){var r;return Vt.isInstance(e)?e:Ah(e)?Oh.createTimeoutError({originalMessage:e instanceof Error?e.message:"Unknown error",cause:e}):at.isInstance(e)?e.cause&&Ah(e.cause)?Oh.createTimeoutError({originalMessage:e.message,cause:e}):await $h({response:R4(e),statusCode:(r=e.statusCode)!=null?r:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):await $h({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}function R4(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 qh="ai-gateway-auth-method";async function Or(e){const t=await ir({value:e[qh],schema:P4});return t.success?t.value:void 0}var P4=ve(()=>ye(ae([P("api-key"),P("oidc")]))),Lh=class{constructor(e){this.config=e}async getAvailableModels(){try{const{value:e}=await sa({url:`${this.config.baseURL}/config`,headers:await Tt(this.config.headers()),successfulResponseHandler:Ft(M4),failedResponseHandler:vr({errorSchema:ht(),errorToMessage:t=>t}),fetch:this.config.fetch});return e}catch(e){throw await Gt(e)}}async getCredits(){try{const e=new URL(this.config.baseURL),{value:t}=await sa({url:`${e.origin}/v1/credits`,headers:await Tt(this.config.headers()),successfulResponseHandler:Ft(N4),failedResponseHandler:vr({errorSchema:ht(),errorToMessage:r=>r}),fetch:this.config.fetch});return t}catch(e){throw await Gt(e)}}},M4=ve(()=>ye(k({models:q(k({id:d(),name:d(),description:d().nullish(),pricing:k({input:d(),output:d(),input_cache_read:d().nullish(),input_cache_write:d().nullish()}).transform(({input:e,output:t,input_cache_read:r,input_cache_write:n})=>({input:e,output:t,...r?{cachedInputTokens:r}:{},...n?{cacheCreationInputTokens:n}:{}})).nullish(),specification:k({specificationVersion:P("v3"),provider:d(),modelId:d()}),modelType:ce(["embedding","image","language","video"]).nullish()}))}))),N4=ve(()=>ye(k({balance:d(),total_used:d()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),O4=class{constructor(e){this.config=e}async getSpendReport(e){try{const t=new URL(this.config.baseURL),r=new URLSearchParams;r.set("start_date",e.startDate),r.set("end_date",e.endDate),e.groupBy&&r.set("group_by",e.groupBy),e.datePart&&r.set("date_part",e.datePart),e.userId&&r.set("user_id",e.userId),e.model&&r.set("model",e.model),e.provider&&r.set("provider",e.provider),e.credentialType&&r.set("credential_type",e.credentialType),e.tags&&e.tags.length>0&&r.set("tags",e.tags.join(","));const{value:n}=await sa({url:`${t.origin}/v1/report?${r.toString()}`,headers:await Tt(this.config.headers()),successfulResponseHandler:Ft(A4),failedResponseHandler:vr({errorSchema:ht(),errorToMessage:o=>o}),fetch:this.config.fetch});return n}catch(t){throw await Gt(t)}}},A4=ve(()=>ye(k({results:q(k({day:d().optional(),hour:d().optional(),user:d().optional(),model:d().optional(),tag:d().optional(),provider:d().optional(),credential_type:ce(["byok","system"]).optional(),total_cost:N(),market_cost:N().optional(),input_tokens:N().optional(),output_tokens:N().optional(),cached_input_tokens:N().optional(),cache_creation_input_tokens:N().optional(),reasoning_tokens:N().optional(),request_count:N().optional()}).transform(({credential_type:e,total_cost:t,market_cost:r,input_tokens:n,output_tokens:o,cached_input_tokens:s,cache_creation_input_tokens:i,reasoning_tokens:a,request_count:l,...c})=>({...c,...e!==void 0?{credentialType:e}:{},totalCost:t,...r!==void 0?{marketCost:r}:{},...n!==void 0?{inputTokens:n}:{},...o!==void 0?{outputTokens:o}:{},...s!==void 0?{cachedInputTokens:s}:{},...i!==void 0?{cacheCreationInputTokens:i}:{},...a!==void 0?{reasoningTokens:a}:{},...l!==void 0?{requestCount:l}:{}})))}))),q4=class{constructor(e){this.config=e}async getGenerationInfo(e){try{const t=new URL(this.config.baseURL),{value:r}=await sa({url:`${t.origin}/v1/generation?id=${encodeURIComponent(e.id)}`,headers:await Tt(this.config.headers()),successfulResponseHandler:Ft(L4),failedResponseHandler:vr({errorSchema:ht(),errorToMessage:n=>n}),fetch:this.config.fetch});return r}catch(t){throw await Gt(t)}}},L4=ve(()=>ye(k({data:k({id:d(),total_cost:N(),upstream_inference_cost:N(),usage:N(),created_at:d(),model:d(),is_byok:ge(),provider_name:d(),streamed:ge(),finish_reason:d(),latency:N(),generation_time:N(),native_tokens_prompt:N(),native_tokens_completion:N(),native_tokens_reasoning:N(),native_tokens_cached:N(),native_tokens_cache_creation:N(),billable_web_search_calls:N()}).transform(({total_cost:e,upstream_inference_cost:t,created_at:r,is_byok:n,provider_name:o,finish_reason:s,generation_time:i,native_tokens_prompt:a,native_tokens_completion:l,native_tokens_reasoning:c,native_tokens_cached:u,native_tokens_cache_creation:f,billable_web_search_calls:p,...h})=>({...h,totalCost:e,upstreamInferenceCost:t,createdAt:r,isByok:n,providerName:o,finishReason:s,generationTime:i,promptTokens:a,completionTokens:l,reasoningTokens:c,cachedTokens:u,cacheCreationTokens:f,billableWebSearchCalls:p}))}).transform(({data:e})=>e))),j4=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(e){const{abortSignal:t,...r}=e;return{args:this.maybeEncodeFileParts(r),warnings:[]}}async doGenerate(e){const{args:t,warnings:r}=await this.getArgs(e),{abortSignal:n}=e,o=await Tt(this.config.headers());try{const{responseHeaders:s,value:i,rawValue:a}=await zt({url:this.getUrl(),headers:xt(o,e.headers,this.getModelConfigHeaders(this.modelId,!1),await Tt(this.config.o11yHeaders)),body:t,successfulResponseHandler:Ft(ht()),failedResponseHandler:vr({errorSchema:ht(),errorToMessage:l=>l}),...n&&{abortSignal:n},fetch:this.config.fetch});return{...i,request:{body:t},response:{headers:s,body:a},warnings:r}}catch(s){throw await Gt(s,await Or(o))}}async doStream(e){const{args:t,warnings:r}=await this.getArgs(e),{abortSignal:n}=e,o=await Tt(this.config.headers());try{const{value:s,responseHeaders:i}=await zt({url:this.getUrl(),headers:xt(o,e.headers,this.getModelConfigHeaders(this.modelId,!0),await Tt(this.config.o11yHeaders)),body:t,successfulResponseHandler:aa(ht()),failedResponseHandler:vr({errorSchema:ht(),errorToMessage:a=>a}),...n&&{abortSignal:n},fetch:this.config.fetch});return{stream:s.pipeThrough(new TransformStream({start(a){r.length>0&&a.enqueue({type:"stream-start",warnings:r})},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 Gt(s,await Or(o))}}isFilePart(e){return e&&typeof e=="object"&&"type"in e&&e.type==="file"}maybeEncodeFileParts(e){for(const t of e.prompt)for(const r of t.content)if(this.isFilePart(r)){const n=r;if(n.data instanceof Uint8Array){const o=Uint8Array.from(n.data),s=Buffer.from(o).toString("base64");n.data=new URL(`data:${n.mediaType||"application/octet-stream"};base64,${s}`)}}return e}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(e,t){return{"ai-language-model-specification-version":"3","ai-language-model-id":e,"ai-language-model-streaming":String(t)}}},D4=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:r,providerOptions:n}){var o;const s=await Tt(this.config.headers());try{const{responseHeaders:i,value:a,rawValue:l}=await zt({url:this.getUrl(),headers:xt(s,t??{},this.getModelConfigHeaders(),await Tt(this.config.o11yHeaders)),body:{values:e,...n?{providerOptions:n}:{}},successfulResponseHandler:Ft(U4),failedResponseHandler:vr({errorSchema:ht(),errorToMessage:c=>c}),...r&&{abortSignal:r},fetch:this.config.fetch});return{embeddings:a.embeddings,usage:(o=a.usage)!=null?o:void 0,providerMetadata:a.providerMetadata,response:{headers:i,body:l},warnings:[]}}catch(i){throw await Gt(i,await Or(s))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"3","ai-model-id":this.modelId}}},U4=ve(()=>ye(k({embeddings:q(q(N())),usage:k({tokens:N()}).nullish(),providerMetadata:he(d(),he(d(),Ie())).optional()}))),z4=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.maxImagesPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:r,aspectRatio:n,seed:o,files:s,mask:i,providerOptions:a,headers:l,abortSignal:c}){var u,f,p,h;const g=await Tt(this.config.headers());try{const{responseHeaders:v,value:_,rawValue:w}=await zt({url:this.getUrl(),headers:xt(g,l??{},this.getModelConfigHeaders(),await Tt(this.config.o11yHeaders)),body:{prompt:e,n:t,...r&&{size:r},...n&&{aspectRatio:n},...o&&{seed:o},...a&&{providerOptions:a},...s&&{files:s.map(y=>jh(y))},...i&&{mask:jh(i)}},successfulResponseHandler:Ft(B4),failedResponseHandler:vr({errorSchema:ht(),errorToMessage:y=>y}),...c&&{abortSignal:c},fetch:this.config.fetch});return{images:_.images,warnings:(u=_.warnings)!=null?u:[],providerMetadata:_.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:v},..._.usage!=null&&{usage:{inputTokens:(f=_.usage.inputTokens)!=null?f:void 0,outputTokens:(p=_.usage.outputTokens)!=null?p:void 0,totalTokens:(h=_.usage.totalTokens)!=null?h:void 0}}}}catch(v){throw await Gt(v,await Or(g))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"3","ai-model-id":this.modelId}}};function jh(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:so(e.data)}:e}var F4=k({images:q(Ie()).optional()}).catchall(Ie()),V4=Ue("type",[k({type:P("unsupported"),feature:d(),details:d().optional()}),k({type:P("compatibility"),feature:d(),details:d().optional()}),k({type:P("other"),message:d()})]),Z4=k({inputTokens:N().nullish(),outputTokens:N().nullish(),totalTokens:N().nullish()}),B4=k({images:q(d()),warnings:q(V4).optional(),providerMetadata:he(d(),F4).optional(),usage:Z4.optional()}),H4=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.maxVideosPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,aspectRatio:r,resolution:n,duration:o,fps:s,seed:i,image:a,providerOptions:l,headers:c,abortSignal:u}){var f;const p=await Tt(this.config.headers());try{const{responseHeaders:h,value:g}=await zt({url:this.getUrl(),headers:xt(p,c??{},this.getModelConfigHeaders(),await Tt(this.config.o11yHeaders),{accept:"text/event-stream"}),body:{prompt:e,n:t,...r&&{aspectRatio:r},...n&&{resolution:n},...o&&{duration:o},...s&&{fps:s},...i&&{seed:i},...l&&{providerOptions:l},...a&&{image:J4(a)}},successfulResponseHandler:async({response:v,url:_,requestBodyValues:w})=>{if(v.body==null)throw new at({message:"SSE response body is empty",url:_,requestBodyValues:w,statusCode:v.status});const m=Wf({stream:v.body,schema:Y4}).getReader(),{done:C,value:b}=await m.read();if(m.releaseLock(),C||!b)throw new at({message:"SSE stream ended without a data event",url:_,requestBodyValues:w,statusCode:v.status});if(!b.success)throw new at({message:"Failed to parse video SSE event",cause:b.error,url:_,requestBodyValues:w,statusCode:v.status});const T=b.value;if(T.type==="error")throw new at({message:T.message,statusCode:T.statusCode,url:_,requestBodyValues:w,responseHeaders:Object.fromEntries([...v.headers]),responseBody:JSON.stringify(T),data:{error:{message:T.message,type:T.errorType,param:T.param}}});return{value:{videos:T.videos,warnings:T.warnings,providerMetadata:T.providerMetadata},responseHeaders:Object.fromEntries([...v.headers])}},failedResponseHandler:vr({errorSchema:ht(),errorToMessage:v=>v}),...u&&{abortSignal:u},fetch:this.config.fetch});return{videos:g.videos,warnings:(f=g.warnings)!=null?f:[],providerMetadata:g.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:h}}}catch(h){throw await Gt(h,await Or(p))}}getUrl(){return`${this.config.baseURL}/video-model`}getModelConfigHeaders(){return{"ai-video-model-specification-version":"3","ai-model-id":this.modelId}}};function J4(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:so(e.data)}:e}var G4=k({videos:q(Ie()).optional()}).catchall(Ie()),W4=ae([k({type:P("url"),url:d(),mediaType:d()}),k({type:P("base64"),data:d(),mediaType:d()})]),K4=Ue("type",[k({type:P("unsupported"),feature:d(),details:d().optional()}),k({type:P("compatibility"),feature:d(),details:d().optional()}),k({type:P("other"),message:d()})]),Y4=Ue("type",[k({type:P("result"),videos:q(W4),warnings:q(K4).optional(),providerMetadata:he(d(),G4).optional()}),k({type:P("error"),message:d(),errorType:d(),statusCode:N(),param:Ie().nullable()})]),Q4=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get provider(){return this.config.provider}async doRerank({documents:e,query:t,topN:r,headers:n,abortSignal:o,providerOptions:s}){const i=await Tt(this.config.headers());try{const{responseHeaders:a,value:l,rawValue:c}=await zt({url:this.getUrl(),headers:xt(i,n??{},this.getModelConfigHeaders(),await Tt(this.config.o11yHeaders)),body:{documents:e,query:t,...r!=null?{topN:r}:{},...s?{providerOptions:s}:{}},successfulResponseHandler:Ft(X4),failedResponseHandler:vr({errorSchema:ht(),errorToMessage:u=>u}),...o&&{abortSignal:o},fetch:this.config.fetch});return{ranking:l.ranking,providerMetadata:l.providerMetadata,response:{headers:a,body:c},warnings:[]}}catch(a){throw await Gt(a,await Or(i))}}getUrl(){return`${this.config.baseURL}/reranking-model`}getModelConfigHeaders(){return{"ai-reranking-model-specification-version":"3","ai-model-id":this.modelId}}},X4=ve(()=>ye(k({ranking:q(k({index:N(),relevanceScore:N()})),providerMetadata:he(d(),he(d(),Ie())).optional()}))),e6=ve(()=>ye(gr({objective:Ye().describe("Natural-language description of the web research goal, including source or freshness guidance and broader context from the task. Maximum 5000 characters."),search_queries:ln(Ye()).optional().describe("Optional search queries to supplement the objective. Maximum 200 characters per query."),mode:na(["one-shot","agentic"]).optional().describe('Mode preset: "one-shot" for comprehensive results with longer excerpts (default), "agentic" for concise, token-efficient results for multi-step workflows.'),max_results:Nr().optional().describe("Maximum number of results to return (1-20). Defaults to 10 if not specified."),source_policy:gr({include_domains:ln(Ye()).optional().describe("List of domains to include in search results."),exclude_domains:ln(Ye()).optional().describe("List of domains to exclude from search results."),after_date:Ye().optional().describe("Only include results published after this date (ISO 8601 format).")}).optional().describe("Source policy for controlling which domains to include/exclude and freshness."),excerpts:gr({max_chars_per_result:Nr().optional().describe("Maximum characters per result."),max_chars_total:Nr().optional().describe("Maximum total characters across all results.")}).optional().describe("Excerpt configuration for controlling result length."),fetch_policy:gr({max_age_seconds:Nr().optional().describe("Maximum age in seconds for cached content. Set to 0 to always fetch fresh content.")}).optional().describe("Fetch policy for controlling content freshness.")}))),t6=ve(()=>ye(vl([gr({searchId:Ye(),results:ln(gr({url:Ye(),title:Ye(),excerpt:Ye(),publishDate:Ye().nullable().optional(),relevanceScore:Nr().optional()}))}),gr({error:na(["api_error","rate_limit","timeout","invalid_input","configuration_error","unknown"]),statusCode:Nr().optional(),message:Ye()})]))),r6=cr({id:"gateway.parallel_search",inputSchema:e6,outputSchema:t6}),n6=(e={})=>r6(e),o6=ve(()=>ye(gr({query:vl([Ye(),ln(Ye())]).describe("Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries."),max_results:Nr().optional().describe("Maximum number of search results to return (1-20, default: 10)"),max_tokens_per_page:Nr().optional().describe("Maximum number of tokens to extract per search result page (256-2048, default: 2048)"),max_tokens:Nr().optional().describe("Maximum total tokens across all search results (default: 25000, max: 1000000)"),country:Ye().optional().describe("Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"),search_domain_filter:ln(Ye()).optional().describe("List of domains to include or exclude from search results (max 20). To include: ['nature.com', 'science.org']. To exclude: ['-example.com', '-spam.net']"),search_language_filter:ln(Ye()).optional().describe("List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"),search_after_date:Ye().optional().describe("Include only results published after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),search_before_date:Ye().optional().describe("Include only results published before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),last_updated_after_filter:Ye().optional().describe("Include only results last updated after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),last_updated_before_filter:Ye().optional().describe("Include only results last updated before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),search_recency_filter:na(["day","week","month","year"]).optional().describe("Filter results by relative time period. Cannot be used with search_after_date or search_before_date.")}))),s6=ve(()=>ye(vl([gr({results:ln(gr({title:Ye(),url:Ye(),snippet:Ye(),date:Ye().optional(),lastUpdated:Ye().optional()})),id:Ye()}),gr({error:na(["api_error","rate_limit","timeout","invalid_input","unknown"]),statusCode:Nr().optional(),message:Ye()})]))),a6=cr({id:"gateway.perplexity_search",inputSchema:o6,outputSchema:s6}),i6=(e={})=>a6(e),l6={parallelSearch:n6,perplexitySearch:i6};async function c6(){var e;return(e=th.getContext().headers)==null?void 0:e["x-vercel-id"]}var u6="3.0.95",d6="0.0.1";function p6(e={}){var t,r;let n=null,o=null;const s=(t=e.metadataCacheRefreshMillis)!=null?t:1e3*60*5;let i=0;const a=(r=Qf(e.baseURL))!=null?r:"https://ai-gateway.vercel.sh/v3/ai",l=async()=>{try{const y=await h6(e);return cn({Authorization:`Bearer ${y.token}`,"ai-gateway-protocol-version":d6,[qh]:y.authMethod,...e.headers},`ai-sdk/gateway/${u6}`)}catch(y){throw Al.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:y})}},c=()=>{const y=io({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),m=io({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),C=io({settingValue:void 0,environmentVariableName:"VERCEL_REGION"}),b=io({settingValue:void 0,environmentVariableName:"VERCEL_PROJECT_ID"});return async()=>{const T=await c6();return{...y&&{"ai-o11y-deployment-id":y},...m&&{"ai-o11y-environment":m},...C&&{"ai-o11y-region":C},...T&&{"ai-o11y-request-id":T},...b&&{"ai-o11y-project-id":b}}}},u=y=>new j4(y,{provider:"gateway",baseURL:a,headers:l,fetch:e.fetch,o11yHeaders:c()}),f=async()=>{var y,m,C;const b=(C=(m=(y=e._internal)==null?void 0:y.currentDate)==null?void 0:m.call(y).getTime())!=null?C:Date.now();return(!n||b-i>s)&&(i=b,n=new Lh({baseURL:a,headers:l,fetch:e.fetch}).getAvailableModels().then(T=>(o=T,T)).catch(async T=>{throw await Gt(T,await Or(await l()))})),o?Promise.resolve(o):n},p=async()=>new Lh({baseURL:a,headers:l,fetch:e.fetch}).getCredits().catch(async y=>{throw await Gt(y,await Or(await l()))}),h=async y=>new O4({baseURL:a,headers:l,fetch:e.fetch}).getSpendReport(y).catch(async m=>{throw await Gt(m,await Or(await l()))}),g=async y=>new q4({baseURL:a,headers:l,fetch:e.fetch}).getGenerationInfo(y).catch(async m=>{throw await Gt(m,await Or(await l()))}),v=function(y){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return u(y)};v.specificationVersion="v3",v.getAvailableModels=f,v.getCredits=p,v.getSpendReport=h,v.getGenerationInfo=g,v.imageModel=y=>new z4(y,{provider:"gateway",baseURL:a,headers:l,fetch:e.fetch,o11yHeaders:c()}),v.languageModel=u;const _=y=>new D4(y,{provider:"gateway",baseURL:a,headers:l,fetch:e.fetch,o11yHeaders:c()});v.embeddingModel=_,v.textEmbeddingModel=_,v.videoModel=y=>new H4(y,{provider:"gateway",baseURL:a,headers:l,fetch:e.fetch,o11yHeaders:c()});const w=y=>new Q4(y,{provider:"gateway",baseURL:a,headers:l,fetch:e.fetch,o11yHeaders:c()});return v.rerankingModel=w,v.reranking=w,v.chat=v.languageModel,v.embedding=v.embeddingModel,v.image=v.imageModel,v.video=v.videoModel,v.tools=l6,v}var f6=p6();async function h6(e){const t=io({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});return t?{token:t,authMethod:"api-key"}:{token:await th.getVercelOidcToken(),authMethod:"oidc"}}var m6=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},Nn="1.9.0",Dh=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function g6(e){var t=new Set([e]),r=new Set,n=e.match(Dh);if(!n)return function(){return!1};var o={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(o.prerelease!=null)return function(l){return l===e};function s(a){return r.add(a),!1}function i(a){return t.add(a),!0}return function(l){if(t.has(l))return!0;if(r.has(l))return!1;var c=l.match(Dh);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 _6=g6(Nn),y6=Nn.split(".")[0],Ho=Symbol.for("opentelemetry.js.api."+y6),Jo=m6;function Go(e,t,r,n){var o;n===void 0&&(n=!1);var s=Jo[Ho]=(o=Jo[Ho])!==null&&o!==void 0?o:{version:Nn};if(!n&&s[e]){var i=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+e);return r.error(i.stack||i.message),!1}if(s.version!==Nn){var i=new Error("@opentelemetry/api: Registration of version v"+s.version+" for "+e+" does not match previously registered API v"+Nn);return r.error(i.stack||i.message),!1}return s[e]=t,r.debug("@opentelemetry/api: Registered a global for "+e+" v"+Nn+"."),!0}function On(e){var t,r,n=(t=Jo[Ho])===null||t===void 0?void 0:t.version;if(!(!n||!_6(n)))return(r=Jo[Ho])===null||r===void 0?void 0:r[e]}function Wo(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+Nn+".");var r=Jo[Ho];r&&delete r[e]}var v6=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],i;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(a){i={error:a}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return s},w6=function(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return e.concat(s||Array.prototype.slice.call(t))},b6=(function(){function e(t){this._namespace=t.namespace||"DiagComponentLogger"}return e.prototype.debug=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Ko("debug",this._namespace,t)},e.prototype.error=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Ko("error",this._namespace,t)},e.prototype.info=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Ko("info",this._namespace,t)},e.prototype.warn=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Ko("warn",this._namespace,t)},e.prototype.verbose=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Ko("verbose",this._namespace,t)},e})();function Ko(e,t,r){var n=On("diag");if(n)return r.unshift(t),n[e].apply(n,w6([],v6(r),!1))}var rr;(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"})(rr||(rr={}));function k6(e,t){e<rr.NONE?e=rr.NONE:e>rr.ALL&&(e=rr.ALL),t=t||{};function r(n,o){var s=t[n];return typeof s=="function"&&e>=o?s.bind(t):function(){}}return{error:r("error",rr.ERROR),warn:r("warn",rr.WARN),info:r("info",rr.INFO),debug:r("debug",rr.DEBUG),verbose:r("verbose",rr.VERBOSE)}}var T6=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],i;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(a){i={error:a}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return s},C6=function(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return e.concat(s||Array.prototype.slice.call(t))},S6="diag",Ar=(function(){function e(){function t(o){return function(){for(var s=[],i=0;i<arguments.length;i++)s[i]=arguments[i];var a=On("diag");if(a)return a[o].apply(a,C6([],T6(s),!1))}}var r=this,n=function(o,s){var i,a,l;if(s===void 0&&(s={logLevel:rr.INFO}),o===r){var c=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return r.error((i=c.stack)!==null&&i!==void 0?i:c.message),!1}typeof s=="number"&&(s={logLevel:s});var u=On("diag"),f=k6((a=s.logLevel)!==null&&a!==void 0?a:rr.INFO,o);if(u&&!s.suppressOverrideMessage){var p=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";u.warn("Current logger will be overwritten from "+p),f.warn("Current logger will overwrite one already registered from "+p)}return Go("diag",f,r,!0)};r.setLogger=n,r.disable=function(){Wo(S6,r)},r.createComponentLogger=function(o){return new b6(o)},r.verbose=t("verbose"),r.debug=t("debug"),r.info=t("info"),r.warn=t("warn"),r.error=t("error")}return e.instance=function(){return this._instance||(this._instance=new e),this._instance},e})(),I6=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],i;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(a){i={error:a}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return s},x6=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},E6=(function(){function e(t){this._entries=t?new Map(t):new Map}return e.prototype.getEntry=function(t){var r=this._entries.get(t);if(r)return Object.assign({},r)},e.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(t){var r=I6(t,2),n=r[0],o=r[1];return[n,o]})},e.prototype.setEntry=function(t,r){var n=new e(this._entries);return n._entries.set(t,r),n},e.prototype.removeEntry=function(t){var r=new e(this._entries);return r._entries.delete(t),r},e.prototype.removeEntries=function(){for(var t,r,n=[],o=0;o<arguments.length;o++)n[o]=arguments[o];var s=new e(this._entries);try{for(var i=x6(n),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&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}return s},e.prototype.clear=function(){return new e},e})();Ar.instance();function $6(e){return e===void 0&&(e={}),new E6(new Map(Object.entries(e)))}function Uh(e){return Symbol.for(e)}var R6=(function(){function e(t){var r=this;r._currentContext=t?new Map(t):new Map,r.getValue=function(n){return r._currentContext.get(n)},r.setValue=function(n,o){var s=new e(r._currentContext);return s._currentContext.set(n,o),s},r.deleteValue=function(n){var o=new e(r._currentContext);return o._currentContext.delete(n),o}}return e})(),P6=new R6,An=(function(){var e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var s in o)Object.prototype.hasOwnProperty.call(o,s)&&(n[s]=o[s])},e(t,r)};return function(t,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");e(t,r);function n(){this.constructor=t}t.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}})(),M6=(function(){function e(){}return e.prototype.createGauge=function(t,r){return F6},e.prototype.createHistogram=function(t,r){return V6},e.prototype.createCounter=function(t,r){return z6},e.prototype.createUpDownCounter=function(t,r){return Z6},e.prototype.createObservableGauge=function(t,r){return H6},e.prototype.createObservableCounter=function(t,r){return B6},e.prototype.createObservableUpDownCounter=function(t,r){return J6},e.prototype.addBatchObservableCallback=function(t,r){},e.prototype.removeBatchObservableCallback=function(t){},e})(),ia=(function(){function e(){}return e})(),N6=(function(e){An(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(r,n){},t})(ia),O6=(function(e){An(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(r,n){},t})(ia),A6=(function(e){An(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(r,n){},t})(ia),q6=(function(e){An(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(r,n){},t})(ia),ql=(function(){function e(){}return e.prototype.addCallback=function(t){},e.prototype.removeCallback=function(t){},e})(),L6=(function(e){An(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(ql),j6=(function(e){An(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(ql),D6=(function(e){An(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(ql),U6=new M6,z6=new N6,F6=new A6,V6=new q6,Z6=new O6,B6=new L6,H6=new j6,J6=new D6,G6={get:function(e,t){if(e!=null)return e[t]},keys:function(e){return e==null?[]:Object.keys(e)}},W6={set:function(e,t,r){e!=null&&(e[t]=r)}},K6=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],i;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(a){i={error:a}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return s},Y6=function(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return e.concat(s||Array.prototype.slice.call(t))},Q6=(function(){function e(){}return e.prototype.active=function(){return P6},e.prototype.with=function(t,r,n){for(var o=[],s=3;s<arguments.length;s++)o[s-3]=arguments[s];return r.call.apply(r,Y6([n],K6(o),!1))},e.prototype.bind=function(t,r){return r},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e})(),X6=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],i;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(a){i={error:a}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return s},ek=function(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return e.concat(s||Array.prototype.slice.call(t))},Ll="context",tk=new Q6,la=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(t){return Go(Ll,t,Ar.instance())},e.prototype.active=function(){return this._getContextManager().active()},e.prototype.with=function(t,r,n){for(var o,s=[],i=3;i<arguments.length;i++)s[i-3]=arguments[i];return(o=this._getContextManager()).with.apply(o,ek([t,r,n],X6(s),!1))},e.prototype.bind=function(t,r){return this._getContextManager().bind(t,r)},e.prototype._getContextManager=function(){return On(Ll)||tk},e.prototype.disable=function(){this._getContextManager().disable(),Wo(Ll,Ar.instance())},e})(),jl;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(jl||(jl={}));var zh="0000000000000000",Fh="00000000000000000000000000000000",rk={traceId:Fh,spanId:zh,traceFlags:jl.NONE},Yo=(function(){function e(t){t===void 0&&(t=rk),this._spanContext=t}return e.prototype.spanContext=function(){return this._spanContext},e.prototype.setAttribute=function(t,r){return this},e.prototype.setAttributes=function(t){return this},e.prototype.addEvent=function(t,r){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,r){},e})(),Dl=Uh("OpenTelemetry Context Key SPAN");function Ul(e){return e.getValue(Dl)||void 0}function nk(){return Ul(la.getInstance().active())}function zl(e,t){return e.setValue(Dl,t)}function ok(e){return e.deleteValue(Dl)}function sk(e,t){return zl(e,new Yo(t))}function Vh(e){var t;return(t=Ul(e))===null||t===void 0?void 0:t.spanContext()}var ak=/^([0-9a-f]{32})$/i,ik=/^[0-9a-f]{16}$/i;function lk(e){return ak.test(e)&&e!==Fh}function ck(e){return ik.test(e)&&e!==zh}function Zh(e){return lk(e.traceId)&&ck(e.spanId)}function uk(e){return new Yo(e)}var Fl=la.getInstance(),Bh=(function(){function e(){}return e.prototype.startSpan=function(t,r,n){n===void 0&&(n=Fl.active());var o=!!r?.root;if(o)return new Yo;var s=n&&Vh(n);return dk(s)&&Zh(s)?new Yo(s):new Yo},e.prototype.startActiveSpan=function(t,r,n,o){var s,i,a;if(!(arguments.length<2)){arguments.length===2?a=r:arguments.length===3?(s=r,a=n):(s=r,i=n,a=o);var l=i??Fl.active(),c=this.startSpan(t,s,l),u=zl(l,c);return Fl.with(u,a,void 0,c)}},e})();function dk(e){return typeof e=="object"&&typeof e.spanId=="string"&&typeof e.traceId=="string"&&typeof e.traceFlags=="number"}var pk=new Bh,fk=(function(){function e(t,r,n,o){this._provider=t,this.name=r,this.version=n,this.options=o}return e.prototype.startSpan=function(t,r,n){return this._getTracer().startSpan(t,r,n)},e.prototype.startActiveSpan=function(t,r,n,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):pk},e})(),hk=(function(){function e(){}return e.prototype.getTracer=function(t,r,n){return new Bh},e})(),mk=new hk,Hh=(function(){function e(){}return e.prototype.getTracer=function(t,r,n){var o;return(o=this.getDelegateTracer(t,r,n))!==null&&o!==void 0?o:new fk(this,t,r,n)},e.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:mk},e.prototype.setDelegate=function(t){this._delegate=t},e.prototype.getDelegateTracer=function(t,r,n){var o;return(o=this._delegate)===null||o===void 0?void 0:o.getTracer(t,r,n)},e})(),ca;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(ca||(ca={}));var Jh=la.getInstance();Ar.instance();var gk=(function(){function e(){}return e.prototype.getMeter=function(t,r,n){return U6},e})(),_k=new gk,Vl="metrics",yk=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalMeterProvider=function(t){return Go(Vl,t,Ar.instance())},e.prototype.getMeterProvider=function(){return On(Vl)||_k},e.prototype.getMeter=function(t,r,n){return this.getMeterProvider().getMeter(t,r,n)},e.prototype.disable=function(){Wo(Vl,Ar.instance())},e})();yk.getInstance();var vk=(function(){function e(){}return e.prototype.inject=function(t,r){},e.prototype.extract=function(t,r){return t},e.prototype.fields=function(){return[]},e})(),Zl=Uh("OpenTelemetry Baggage Key");function Gh(e){return e.getValue(Zl)||void 0}function wk(){return Gh(la.getInstance().active())}function bk(e,t){return e.setValue(Zl,t)}function kk(e){return e.deleteValue(Zl)}var Bl="propagation",Tk=new vk,Ck=(function(){function e(){this.createBaggage=$6,this.getBaggage=Gh,this.getActiveBaggage=wk,this.setBaggage=bk,this.deleteBaggage=kk}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalPropagator=function(t){return Go(Bl,t,Ar.instance())},e.prototype.inject=function(t,r,n){return n===void 0&&(n=W6),this._getGlobalPropagator().inject(t,r,n)},e.prototype.extract=function(t,r,n){return n===void 0&&(n=G6),this._getGlobalPropagator().extract(t,r,n)},e.prototype.fields=function(){return this._getGlobalPropagator().fields()},e.prototype.disable=function(){Wo(Bl,Ar.instance())},e.prototype._getGlobalPropagator=function(){return On(Bl)||Tk},e})();Ck.getInstance();var Hl="trace",Sk=(function(){function e(){this._proxyTracerProvider=new Hh,this.wrapSpanContext=uk,this.isSpanContextValid=Zh,this.deleteSpan=ok,this.getSpan=Ul,this.getActiveSpan=nk,this.getSpanContext=Vh,this.setSpan=zl,this.setSpanContext=sk}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(t){var r=Go(Hl,this._proxyTracerProvider,Ar.instance());return r&&this._proxyTracerProvider.setDelegate(t),r},e.prototype.getTracerProvider=function(){return On(Hl)||this._proxyTracerProvider},e.prototype.getTracer=function(t,r){return this.getTracerProvider().getTracer(t,r)},e.prototype.disable=function(){Wo(Hl,Ar.instance()),this._proxyTracerProvider=new Hh},e})(),Ik=Sk.getInstance(),xk=Object.defineProperty,Ek=(e,t)=>{for(var r in t)xk(e,r,{get:t[r],enumerable:!0})},Wh="AI_InvalidArgumentError",Kh=`vercel.ai.error.${Wh}`,$k=Symbol.for(Kh),Yh,qr=class extends be{constructor({parameter:t,value:r,message:n}){super({name:Wh,message:`Invalid argument for parameter ${t}: ${n}`}),this[Yh]=!0,this.parameter=t,this.value=r}static isInstance(t){return be.hasMarker(t,Kh)}};Yh=$k;var Qh="AI_InvalidToolApprovalError",Xh=`vercel.ai.error.${Qh}`,Rk=Symbol.for(Xh),e0,Pk=class extends be{constructor({approvalId:e}){super({name:Qh,message:`Tool approval response references unknown approvalId: "${e}". No matching tool-approval-request found in message history.`}),this[e0]=!0,this.approvalId=e}static isInstance(e){return be.hasMarker(e,Xh)}};e0=Rk;var t0="AI_InvalidToolInputError",r0=`vercel.ai.error.${t0}`,Mk=Symbol.for(r0),n0,Jl=class extends be{constructor({toolInput:e,toolName:t,cause:r,message:n=`Invalid input for tool ${t}: ${Tn(r)}`}){super({name:t0,message:n,cause:r}),this[n0]=!0,this.toolInput=e,this.toolName=t}static isInstance(e){return be.hasMarker(e,r0)}};n0=Mk;var o0="AI_ToolCallNotFoundForApprovalError",s0=`vercel.ai.error.${o0}`,Nk=Symbol.for(s0),a0,Gl=class extends be{constructor({toolCallId:e,approvalId:t}){super({name:o0,message:`Tool call "${e}" not found for approval request "${t}".`}),this[a0]=!0,this.toolCallId=e,this.approvalId=t}static isInstance(e){return be.hasMarker(e,s0)}};a0=Nk;var i0="AI_MissingToolResultsError",l0=`vercel.ai.error.${i0}`,Ok=Symbol.for(l0),c0,u0=class extends be{constructor({toolCallIds:e}){super({name:i0,message:`Tool result${e.length>1?"s are":" is"} missing for tool call${e.length>1?"s":""} ${e.join(", ")}.`}),this[c0]=!0,this.toolCallIds=e}static isInstance(e){return be.hasMarker(e,l0)}};c0=Ok;var d0="AI_NoObjectGeneratedError",p0=`vercel.ai.error.${d0}`,Ak=Symbol.for(p0),f0,un=class extends be{constructor({message:e="No object generated.",cause:t,text:r,response:n,usage:o,finishReason:s}){super({name:d0,message:e,cause:t}),this[f0]=!0,this.text=r,this.response=n,this.usage=o,this.finishReason=s}static isInstance(e){return be.hasMarker(e,p0)}};f0=Ak;var h0="AI_NoOutputGeneratedError",m0=`vercel.ai.error.${h0}`,qk=Symbol.for(m0),g0,_0=class extends be{constructor({message:e="No output generated.",cause:t}={}){super({name:h0,message:e,cause:t}),this[g0]=!0}static isInstance(e){return be.hasMarker(e,m0)}};g0=qk;var y0="AI_NoSuchToolError",v0=`vercel.ai.error.${y0}`,Lk=Symbol.for(v0),w0,Wl=class extends be{constructor({toolName:e,availableTools:t=void 0,message:r=`Model tried to call unavailable tool '${e}'. ${t===void 0?"No tools are available.":`Available tools: ${t.join(", ")}.`}`}){super({name:y0,message:r}),this[w0]=!0,this.toolName=e,this.availableTools=t}static isInstance(e){return be.hasMarker(e,v0)}};w0=Lk;var b0="AI_ToolCallRepairError",k0=`vercel.ai.error.${b0}`,jk=Symbol.for(k0),T0,Dk=class extends be{constructor({cause:e,originalError:t,message:r=`Error repairing tool call: ${Tn(e)}`}){super({name:b0,message:r,cause:e}),this[T0]=!0,this.originalError=t}static isInstance(e){return be.hasMarker(e,k0)}};T0=jk;var Uk=class extends be{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}},C0="AI_UIMessageStreamError",S0=`vercel.ai.error.${C0}`,zk=Symbol.for(S0),I0,lo=class extends be{constructor({chunkType:e,chunkId:t,message:r}){super({name:C0,message:r}),this[I0]=!0,this.chunkType=e,this.chunkId=t}static isInstance(e){return be.hasMarker(e,S0)}};I0=zk;var x0="AI_InvalidMessageRoleError",E0=`vercel.ai.error.${x0}`,Fk=Symbol.for(E0),$0,Vk=class extends be{constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:x0,message:t}),this[$0]=!0,this.role=e}static isInstance(e){return be.hasMarker(e,E0)}};$0=Fk;var R0="AI_RetryError",P0=`vercel.ai.error.${R0}`,Zk=Symbol.for(P0),M0,N0=class extends be{constructor({message:e,reason:t,errors:r}){super({name:R0,message:e}),this[M0]=!0,this.reason=t,this.errors=r,this.lastError=r[r.length-1]}static isInstance(e){return be.hasMarker(e,P0)}};M0=Zk;function qn(e){return e===void 0?[]:Array.isArray(e)?e:[e]}async function wr(e){for(const t of qn(e.callbacks))if(t!=null)try{await t(e.event)}catch{}}function Bk({warning:e,provider:t,model:r}){const n=`AI SDK Warning (${t} / ${r}):`;switch(e.type){case"unsupported":{let o=`${n} The feature "${e.feature}" is not supported.`;return e.details&&(o+=` ${e.details}`),o}case"compatibility":{let o=`${n} The feature "${e.feature}" is used in a compatibility mode.`;return e.details&&(o+=` ${e.details}`),o}case"other":return`${n} ${e.message}`;default:return`${n} ${JSON.stringify(e,null,2)}`}}var Hk="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",O0=!1,Kl=e=>{if(e.warnings.length===0)return;const t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t=="function"){t(e);return}O0||(O0=!0,console.info(Hk));for(const r of e.warnings)console.warn(Bk({warning:r,provider:e.provider,model:e.model}))}};function Jk({provider:e,modelId:t}){Kl({warnings:[{type:"compatibility",feature:"specificationVersion",details:"Using v2 specification compatibility mode. Some features may not be available."}],provider:e,model:t})}function Gk(e){return e.specificationVersion==="v3"?e:(Jk({provider:e.provider,modelId:e.modelId}),new Proxy(e,{get(t,r){switch(r){case"specificationVersion":return"v3";case"doGenerate":return async(...n)=>{const o=await t.doGenerate(...n);return{...o,finishReason:A0(o.finishReason),usage:q0(o.usage)}};case"doStream":return async(...n)=>{const o=await t.doStream(...n);return{...o,stream:Wk(o.stream)}};default:return t[r]}}}))}function Wk(e){return e.pipeThrough(new TransformStream({transform(t,r){switch(t.type){case"finish":r.enqueue({...t,finishReason:A0(t.finishReason),usage:q0(t.usage)});break;default:r.enqueue(t);break}}}))}function A0(e){return{unified:e==="unknown"?"other":e,raw:void 0}}function q0(e){return{inputTokens:{total:e.inputTokens,noCache:void 0,cacheRead:e.cachedInputTokens,cacheWrite:void 0},outputTokens:{total:e.outputTokens,text:void 0,reasoning:e.reasoningTokens}}}function ua(e){if(typeof e!="string"){if(e.specificationVersion!=="v3"&&e.specificationVersion!=="v2"){const t=e;throw new Uk({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return Gk(e)}return Kk().languageModel(e)}function Kk(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:f6}function Yl(e){if(e!=null)return typeof e=="number"?e:e.totalMs}function L0(e){if(!(e==null||typeof e=="number"))return e.stepMs}function Yk(e){if(!(e==null||typeof e=="number"))return e.chunkMs}var Qk=[{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]}],Xk=e=>{const t=typeof e=="string"?oo(e):e,r=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(r+10)};function e5(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?Xk(e):e}function t5({data:e,signatures:t}){const r=e5(e),n=typeof r=="string"?oo(r.substring(0,Math.min(r.length,24))):r;for(const o of t)if(n.length>=o.bytesPrefix.length&&o.bytesPrefix.every((s,i)=>s===null||n[i]===s))return o.mediaType}var j0="6.0.158",r5=async({url:e,maxBytes:t,abortSignal:r})=>{var n;const o=e.toString();oa(o);try{const s=await fetch(o,{headers:cn({},`ai-sdk/${j0}`,Bo()),signal:r});if(s.redirected&&oa(s.url),!s.ok)throw new Jt({url:o,statusCode:s.status,statusText:s.statusText});return{data:await Of({response:s,url:o,maxBytes:t??bl}),mediaType:(n=s.headers.get("content-type"))!=null?n:void 0}}catch(s){throw Jt.isInstance(s)?s:new Jt({url:o,cause:s})}},n5=(e=r5)=>t=>Promise.all(t.map(async r=>r.isUrlSupportedByModel?null:e(r)));function o5(e){try{const[t,r]=e.split(",");return{mediaType:t.split(";")[0].split(":")[1],base64Content:r}}catch{return{mediaType:void 0,base64Content:void 0}}}var D0=ae([d(),Ys(Uint8Array),Ys(ArrayBuffer),nf(e=>{var t,r;return(r=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?r:!1},{message:"Must be a Buffer"})]);function U0(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:r}=o5(e.toString());if(t==null||r==null)throw new be({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:r,mediaType:t}}return{data:e,mediaType:void 0}}function s5(e){return typeof e=="string"?e:e instanceof ArrayBuffer?so(new Uint8Array(e)):so(e)}async function z0({prompt:e,supportedUrls:t,download:r=n5()}){const n=await i5(e.messages,r,t),o=new Map;for(const c of e.messages)if(c.role==="assistant"&&Array.isArray(c.content))for(const u of c.content)u.type==="tool-approval-request"&&"approvalId"in u&&"toolCallId"in u&&o.set(u.approvalId,u.toolCallId);const s=new Set;for(const c of e.messages)if(c.role==="tool"){for(const u of c.content)if(u.type==="tool-approval-response"){const f=o.get(u.approvalId);f&&s.add(f)}}const i=[...e.system!=null?typeof e.system=="string"?[{role:"system",content:e.system}]:qn(e.system).map(c=>({role:"system",content:c.content,providerOptions:c.providerOptions})):[],...e.messages.map(c=>a5({message:c,downloadedAssets:n}))],a=[];for(const c of i){if(c.role!=="tool"){a.push(c);continue}const u=a.at(-1);u?.role==="tool"?u.content.push(...c.content):a.push(c)}const l=new Set;for(const c of a)switch(c.role){case"assistant":{for(const u of c.content)u.type==="tool-call"&&!u.providerExecuted&&l.add(u.toolCallId);break}case"tool":{for(const u of c.content)u.type==="tool-result"&&l.delete(u.toolCallId);break}case"user":case"system":for(const u of s)l.delete(u);if(l.size>0)throw new u0({toolCallIds:Array.from(l)});break}for(const c of s)l.delete(c);if(l.size>0)throw new u0({toolCallIds:Array.from(l)});return a.filter(c=>c.role!=="tool"||c.content.length>0)}function a5({message:e,downloadedAssets:t}){const r=e.role;switch(r){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(n=>l5(n,t)).filter(n=>n.type!=="text"||n.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(n=>n.type!=="text"||n.text!==""||n.providerOptions!=null).filter(n=>n.type!=="tool-approval-request").map(n=>{const o=n.providerOptions;switch(n.type){case"file":{const{data:s,mediaType:i}=U0(n.data);return{type:"file",data:s,filename:n.filename,mediaType:i??n.mediaType,providerOptions:o}}case"reasoning":return{type:"reasoning",text:n.text,providerOptions:o};case"text":return{type:"text",text:n.text,providerOptions:o};case"tool-call":return{type:"tool-call",toolCallId:n.toolCallId,toolName:n.toolName,input:n.input,providerExecuted:n.providerExecuted,providerOptions:o};case"tool-result":return{type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,output:F0(n.output),providerOptions:o}}}),providerOptions:e.providerOptions};case"tool":return{role:"tool",content:e.content.filter(n=>n.type!=="tool-approval-response"||n.providerExecuted).map(n=>{switch(n.type){case"tool-result":return{type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,output:F0(n.output),providerOptions:n.providerOptions};case"tool-approval-response":return{type:"tool-approval-response",approvalId:n.approvalId,approved:n.approved,reason:n.reason}}}),providerOptions:e.providerOptions};default:{const n=r;throw new Vk({role:n})}}}async function i5(e,t,r){const n=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&&p9({url:s.data.toString(),mediaType:s.mediaType,supportedUrls:r})})),o=await t(n);return Object.fromEntries(o.map((s,i)=>s==null?null:[n[i].url.toString(),{data:s.data,mediaType:s.mediaType}]).filter(s=>s!=null))}function l5(e,t){var r;if(e.type==="text")return{type:"text",text:e.text,providerOptions:e.providerOptions};let n;const o=e.type;switch(o){case"image":n=e.image;break;case"file":n=e.data;break;default:throw new Error(`Unsupported part type: ${o}`)}const{data:s,mediaType:i}=U0(n);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=(r=t5({data:l,signatures:Qk}))!=null?r: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 F0(e){return e.type!=="content"?e:{type:"content",value:e.value.map(t=>t.type!=="media"?t:t.mediaType.startsWith("image/")?{type:"image-data",data:t.data,mediaType:t.mediaType}:{type:"file-data",data:t.data,mediaType:t.mediaType})}}async function Qo({toolCallId:e,input:t,output:r,tool:n,errorMode:o}){return o==="text"?{type:"error-text",value:Tn(r)}:o==="json"?{type:"error-json",value:V0(r)}:n?.toModelOutput?await n.toModelOutput({toolCallId:e,input:t,output:r}):typeof r=="string"?{type:"text",value:r}:{type:"json",value:V0(r)}}function V0(e){return e===void 0?null:e}function Ql({maxOutputTokens:e,temperature:t,topP:r,topK:n,presencePenalty:o,frequencyPenalty:s,seed:i,stopSequences:a}){if(e!=null){if(!Number.isInteger(e))throw new qr({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new qr({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(t!=null&&typeof t!="number")throw new qr({parameter:"temperature",value:t,message:"temperature must be a number"});if(r!=null&&typeof r!="number")throw new qr({parameter:"topP",value:r,message:"topP must be a number"});if(n!=null&&typeof n!="number")throw new qr({parameter:"topK",value:n,message:"topK must be a number"});if(o!=null&&typeof o!="number")throw new qr({parameter:"presencePenalty",value:o,message:"presencePenalty must be a number"});if(s!=null&&typeof s!="number")throw new qr({parameter:"frequencyPenalty",value:s,message:"frequencyPenalty must be a number"});if(i!=null&&!Number.isInteger(i))throw new qr({parameter:"seed",value:i,message:"seed must be an integer"});return{maxOutputTokens:e,temperature:t,topP:r,topK:n,presencePenalty:o,frequencyPenalty:s,stopSequences:a,seed:i}}function c5(e){return e!=null&&Object.keys(e).length>0}async function Z0({tools:e,toolChoice:t,activeTools:r}){if(!c5(e))return{tools:void 0,toolChoice:void 0};const n=r!=null?Object.entries(e).filter(([s])=>r.includes(s)):Object.entries(e),o=[];for(const[s,i]of n){const a=i.type;switch(a){case void 0:case"dynamic":case"function":o.push({type:"function",name:s,description:i.description,inputSchema:await Mn(i.inputSchema).jsonSchema,...i.inputExamples!=null?{inputExamples:i.inputExamples}:{},providerOptions:i.providerOptions,...i.strict!=null?{strict:i.strict}:{}});break;case"provider":o.push({type:"provider",name:s,id:i.id,args:i.args});break;default:{const l=a;throw new Error(`Unsupported tool type: ${l}`)}}}return{tools:o,toolChoice:t==null?{type:"auto"}:typeof t=="string"?{type:t}:{type:"tool",toolName:t.toolName}}}var Xo=Ks(()=>ae([Do(),d(),N(),ge(),he(d(),Xo.optional()),q(Xo)])),ct=he(d(),he(d(),Xo.optional())),B0=k({type:P("text"),text:d(),providerOptions:ct.optional()}),u5=k({type:P("image"),image:ae([D0,Ys(URL)]),mediaType:d().optional(),providerOptions:ct.optional()}),H0=k({type:P("file"),data:ae([D0,Ys(URL)]),filename:d().optional(),mediaType:d(),providerOptions:ct.optional()}),d5=k({type:P("reasoning"),text:d(),providerOptions:ct.optional()}),p5=k({type:P("tool-call"),toolCallId:d(),toolName:d(),input:Ie(),providerOptions:ct.optional(),providerExecuted:ge().optional()}),f5=Ue("type",[k({type:P("text"),value:d(),providerOptions:ct.optional()}),k({type:P("json"),value:Xo,providerOptions:ct.optional()}),k({type:P("execution-denied"),reason:d().optional(),providerOptions:ct.optional()}),k({type:P("error-text"),value:d(),providerOptions:ct.optional()}),k({type:P("error-json"),value:Xo,providerOptions:ct.optional()}),k({type:P("content"),value:q(ae([k({type:P("text"),text:d(),providerOptions:ct.optional()}),k({type:P("media"),data:d(),mediaType:d()}),k({type:P("file-data"),data:d(),mediaType:d(),filename:d().optional(),providerOptions:ct.optional()}),k({type:P("file-url"),url:d(),providerOptions:ct.optional()}),k({type:P("file-id"),fileId:ae([d(),he(d(),d())]),providerOptions:ct.optional()}),k({type:P("image-data"),data:d(),mediaType:d(),providerOptions:ct.optional()}),k({type:P("image-url"),url:d(),providerOptions:ct.optional()}),k({type:P("image-file-id"),fileId:ae([d(),he(d(),d())]),providerOptions:ct.optional()}),k({type:P("custom"),providerOptions:ct.optional()})]))})]),J0=k({type:P("tool-result"),toolCallId:d(),toolName:d(),output:f5,providerOptions:ct.optional()}),h5=k({type:P("tool-approval-request"),approvalId:d(),toolCallId:d()}),m5=k({type:P("tool-approval-response"),approvalId:d(),approved:ge(),reason:d().optional()}),g5=k({role:P("system"),content:d(),providerOptions:ct.optional()}),_5=k({role:P("user"),content:ae([d(),q(ae([B0,u5,H0]))]),providerOptions:ct.optional()}),y5=k({role:P("assistant"),content:ae([d(),q(ae([B0,H0,d5,p5,J0,h5]))]),providerOptions:ct.optional()}),v5=k({role:P("tool"),content:q(ae([J0,m5])),providerOptions:ct.optional()}),w5=ae([g5,_5,y5,v5]);async function G0(e){if(e.prompt==null&&e.messages==null)throw new Cn({prompt:e,message:"prompt or messages must be defined"});if(e.prompt!=null&&e.messages!=null)throw new Cn({prompt:e,message:"prompt and messages cannot be defined at the same time"});if(e.system!=null&&typeof e.system!="string"&&!qn(e.system).every(n=>typeof n=="object"&&n!==null&&"role"in n&&n.role==="system"))throw new Cn({prompt:e,message:"system must be a string, SystemModelMessage, or array of SystemModelMessage"});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 Cn({prompt:e,message:"prompt or messages must be defined"});if(t.length===0)throw new Cn({prompt:e,message:"messages must not be empty"});const r=await ir({value:t,schema:q(w5)});if(!r.success)throw new Cn({prompt:e,message:"The messages do not match the ModelMessage[] schema.",cause:r.error});return{messages:t,system:e.system}}function W0(e){if(!Al.isInstance(e))return e;const t=(process==null?void 0:process.env.NODE_ENV)==="production",r="https://ai-sdk.dev/unauthenticated-ai-gateway";return t?new be({name:"GatewayError",message:`Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${r}`}):Object.assign(new Error(`\x1B[1m\x1B[31mUnauthenticated request to AI Gateway.\x1B[0m
56
-
57
- To authenticate, set the \x1B[33mAI_GATEWAY_API_KEY\x1B[0m environment variable with your API key.
58
-
59
- Alternatively, you can use a provider module instead of the AI Gateway.
60
-
61
- Learn more: \x1B[34m${r}\x1B[0m
62
-
63
- `),{name:"GatewayAuthenticationError"})}function es({operationId:e,telemetry:t}){return{"operation.name":`${e}${t?.functionId!=null?` ${t.functionId}`:""}`,"resource.name":t?.functionId,"ai.operationId":e,"ai.telemetry.functionId":t?.functionId}}function K0({model:e,settings:t,telemetry:r,headers:n}){var o;return{"ai.model.provider":e.provider,"ai.model.id":e.modelId,...Object.entries(t).reduce((s,[i,a])=>{if(i==="timeout"){const l=Yl(a);l!=null&&(s[`ai.settings.${i}`]=l)}else s[`ai.settings.${i}`]=a;return s},{}),...Object.entries((o=r?.metadata)!=null?o:{}).reduce((s,[i,a])=>(s[`ai.telemetry.metadata.${i}`]=a,s),{}),...Object.entries(n??{}).reduce((s,[i,a])=>(a!==void 0&&(s[`ai.request.headers.${i}`]=a),s),{})}}var b5={startSpan(){return da},startActiveSpan(e,t,r,n){if(typeof t=="function")return t(da);if(typeof r=="function")return r(da);if(typeof n=="function")return n(da)}},da={spanContext(){return k5},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}},k5={traceId:"",spanId:"",traceFlags:0};function Y0({isEnabled:e=!1,tracer:t}={}){return e?t||Ik.getTracer("ai"):b5}async function ts({name:e,tracer:t,attributes:r,fn:n,endWhenDone:o=!0}){return t.startActiveSpan(e,{attributes:await r},async s=>{const i=Jh.active();try{const a=await Jh.with(i,()=>n(s));return o&&s.end(),a}catch(a){try{Q0(s,a)}finally{s.end()}throw a}})}function Q0(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:ca.ERROR,message:t.message})):e.setStatus({code:ca.ERROR})}async function ur({telemetry:e,attributes:t}){if(e?.isEnabled!==!0)return{};const r={};for(const[n,o]of Object.entries(t))if(o!=null){if(typeof o=="object"&&"input"in o&&typeof o.input=="function"){if(e?.recordInputs===!1)continue;const s=await o.input();s!=null&&(r[n]=s);continue}if(typeof o=="object"&&"output"in o&&typeof o.output=="function"){if(e?.recordOutputs===!1)continue;const s=await o.output();s!=null&&(r[n]=s);continue}r[n]=o}return r}function X0(e){return JSON.stringify(e.map(t=>({...t,content:typeof t.content=="string"?t.content:t.content.map(r=>r.type==="file"?{...r,data:r.data instanceof Uint8Array?s5(r.data):r.data}:r)})))}function T5(){var e;return(e=globalThis.AI_SDK_TELEMETRY_INTEGRATIONS)!=null?e:[]}function em(){const e=T5();return t=>{const r=qn(t),n=[...e,...r];function o(s){const i=n.map(s).filter(Boolean);return async a=>{for(const l of i)try{await l(a)}catch{}}}return{onStart:o(s=>s.onStart),onStepStart:o(s=>s.onStepStart),onToolCallStart:o(s=>s.onToolCallStart),onToolCallFinish:o(s=>s.onToolCallFinish),onStepFinish:o(s=>s.onStepFinish),onFinish:o(s=>s.onFinish)}}}function Xl(e){return{inputTokens:e.inputTokens.total,inputTokenDetails:{noCacheTokens:e.inputTokens.noCache,cacheReadTokens:e.inputTokens.cacheRead,cacheWriteTokens:e.inputTokens.cacheWrite},outputTokens:e.outputTokens.total,outputTokenDetails:{textTokens:e.outputTokens.text,reasoningTokens:e.outputTokens.reasoning},totalTokens:br(e.inputTokens.total,e.outputTokens.total),raw:e.raw,reasoningTokens:e.outputTokens.reasoning,cachedInputTokens:e.inputTokens.cacheRead}}function ec(){return{inputTokens:void 0,inputTokenDetails:{noCacheTokens:void 0,cacheReadTokens:void 0,cacheWriteTokens:void 0},outputTokens:void 0,outputTokenDetails:{textTokens:void 0,reasoningTokens:void 0},totalTokens:void 0,raw:void 0}}function tm(e,t){var r,n,o,s,i,a,l,c,u,f;return{inputTokens:br(e.inputTokens,t.inputTokens),inputTokenDetails:{noCacheTokens:br((r=e.inputTokenDetails)==null?void 0:r.noCacheTokens,(n=t.inputTokenDetails)==null?void 0:n.noCacheTokens),cacheReadTokens:br((o=e.inputTokenDetails)==null?void 0:o.cacheReadTokens,(s=t.inputTokenDetails)==null?void 0:s.cacheReadTokens),cacheWriteTokens:br((i=e.inputTokenDetails)==null?void 0:i.cacheWriteTokens,(a=t.inputTokenDetails)==null?void 0:a.cacheWriteTokens)},outputTokens:br(e.outputTokens,t.outputTokens),outputTokenDetails:{textTokens:br((l=e.outputTokenDetails)==null?void 0:l.textTokens,(c=t.outputTokenDetails)==null?void 0:c.textTokens),reasoningTokens:br((u=e.outputTokenDetails)==null?void 0:u.reasoningTokens,(f=t.outputTokenDetails)==null?void 0:f.reasoningTokens)},totalTokens:br(e.totalTokens,t.totalTokens),reasoningTokens:br(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:br(e.cachedInputTokens,t.cachedInputTokens)}}function br(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}function pa(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;const r={...e};for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)){const o=t[n];if(o===void 0)continue;const s=n in e?e[n]: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?r[n]=pa(s,o):r[n]=o}return r}function C5({error:e,exponentialBackoffDelay:t}){const r=e.responseHeaders;if(!r)return t;let n;const o=r["retry-after-ms"];if(o){const i=parseFloat(o);Number.isNaN(i)||(n=i)}const s=r["retry-after"];if(s&&n===void 0){const i=parseFloat(s);Number.isNaN(i)?n=Date.parse(s)-Date.now():n=i*1e3}return n!=null&&!Number.isNaN(n)&&0<=n&&(n<60*1e3||n<t)?n:t}var S5=({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:r=2,abortSignal:n}={})=>async o=>rm(o,{maxRetries:e,delayInMs:t,backoffFactor:r,abortSignal:n});async function rm(e,{maxRetries:t,delayInMs:r,backoffFactor:n,abortSignal:o},s=[]){try{return await e()}catch(i){if($n(i)||t===0)throw i;const a=Tl(i),l=[...s,i],c=l.length;if(c>t)throw new N0({message:`Failed after ${c} attempts. Last error: ${a}`,reason:"maxRetriesExceeded",errors:l});if(i instanceof Error&&at.isInstance(i)&&i.isRetryable===!0&&c<=t)return await t9(C5({error:i,exponentialBackoffDelay:r}),{abortSignal:o}),rm(e,{maxRetries:t,delayInMs:n*r,backoffFactor:n,abortSignal:o},l);throw c===1?i:new N0({message:`Failed after ${c} attempts with non-retryable error: '${a}'`,reason:"errorNotRetryable",errors:l})}}function nm({maxRetries:e,abortSignal:t}){if(e!=null){if(!Number.isInteger(e))throw new qr({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});if(e<0)throw new qr({parameter:"maxRetries",value:e,message:"maxRetries must be >= 0"})}const r=e??2;return{maxRetries:r,retry:S5({maxRetries:r,abortSignal:t})}}function om({messages:e}){const t=e.at(-1);if(t?.role!="tool")return{approvedToolApprovals:[],deniedToolApprovals:[]};const r={};for(const l of e)if(l.role==="assistant"&&typeof l.content!="string"){const c=l.content;for(const u of c)u.type==="tool-call"&&(r[u.toolCallId]=u)}const n={};for(const l of e)if(l.role==="assistant"&&typeof l.content!="string"){const c=l.content;for(const u of c)u.type==="tool-approval-request"&&(n[u.approvalId]=u)}const o={};for(const l of t.content)l.type==="tool-result"&&(o[l.toolCallId]=l);const s=[],i=[],a=t.content.filter(l=>l.type==="tool-approval-response");for(const l of a){const c=n[l.approvalId];if(c==null)throw new Pk({approvalId:l.approvalId});if(o[c.toolCallId]!=null)continue;const u=r[c.toolCallId];if(u==null)throw new Gl({toolCallId:c.toolCallId,approvalId:c.approvalId});const f={approvalRequest:c,approvalResponse:l,toolCall:u};l.approved?s.push(f):i.push(f)}return{approvedToolApprovals:s,deniedToolApprovals:i}}function fa(){var e,t;return(t=(e=globalThis?.performance)==null?void 0:e.now())!=null?t:Date.now()}async function tc({toolCall:e,tools:t,tracer:r,telemetry:n,messages:o,abortSignal:s,experimental_context:i,stepNumber:a,model:l,onPreliminaryToolResult:c,onToolCallStart:u,onToolCallFinish:f}){const{toolName:p,toolCallId:h,input:g}=e,v=t?.[p];if(v?.execute==null)return;const _={stepNumber:a,model:l,toolCall:e,messages:o,abortSignal:s,functionId:n?.functionId,metadata:n?.metadata,experimental_context:i};return ts({name:"ai.toolCall",attributes:ur({telemetry:n,attributes:{...es({operationId:"ai.toolCall",telemetry:n}),"ai.toolCall.name":p,"ai.toolCall.id":h,"ai.toolCall.args":{output:()=>JSON.stringify(g)}}}),tracer:r,fn:async w=>{let y;await wr({event:_,callbacks:u});const m=fa();try{const b=f4({execute:v.execute.bind(v),input:g,options:{toolCallId:h,messages:o,abortSignal:s,experimental_context:i}});for await(const T of b)T.type==="preliminary"?c?.({...e,type:"tool-result",output:T.output,preliminary:!0}):y=T.output}catch(b){const T=fa()-m;return await wr({event:{..._,success:!1,error:b,durationMs:T},callbacks:f}),Q0(w,b),{type:"tool-error",toolCallId:h,toolName:p,input:g,error:b,dynamic:v.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{}}}const C=fa()-m;await wr({event:{..._,success:!0,output:y,durationMs:C},callbacks:f});try{w.setAttributes(await ur({telemetry:n,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(y)}}}))}catch{}return{type:"tool-result",toolCallId:h,toolName:p,input:g,output:y,dynamic:v.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{}}}})}function sm(e){const t=e.filter(r=>r.type==="reasoning");return t.length===0?void 0:t.map(r=>r.text).join(`
64
- `)}function am(e){const t=e.filter(r=>r.type==="text");if(t.length!==0)return t.map(r=>r.text).join("")}var im=class{constructor({data:e,mediaType:t}){const r=e instanceof Uint8Array;this.base64Data=r?void 0:e,this.uint8ArrayData=r?e:void 0,this.mediaType=t}get base64(){return this.base64Data==null&&(this.base64Data=so(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=oo(this.base64Data)),this.uint8ArrayData}},I5=class extends im{constructor(e){super(e),this.type="file"}};async function lm({tool:e,toolCall:t,messages:r,experimental_context:n}){return e.needsApproval==null?!1:typeof e.needsApproval=="boolean"?e.needsApproval:await e.needsApproval(t.input,{toolCallId:t.toolCallId,messages:r,experimental_context:n})}var x5={};Ek(x5,{array:()=>R5,choice:()=>P5,json:()=>M5,object:()=>$5,text:()=>ha});function E5(e){const t=["ROOT"];let r=-1,n=null;function o(l,c,u){switch(l){case'"':{r=c,t.pop(),t.push(u),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{r=c,n=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":{r=c,t.pop(),t.push(u),t.push("INSIDE_NUMBER");break}case"{":{r=c,t.pop(),t.push(u),t.push("INSIDE_OBJECT_START");break}case"[":{r=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"}":{r=c,t.pop();break}}}function i(l,c){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=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"}":{r=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(),r=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:r=l}break}case"INSIDE_ARRAY_START":{switch(c){case"]":{r=l,t.pop();break}default:{r=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"]":{r=l,t.pop();break}default:{r=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{o(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),r=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":{r=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 f=e.substring(n,l+1);!"false".startsWith(f)&&!"true".startsWith(f)&&!"null".startsWith(f)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?s(c,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(c,l)):r=l;break}}}let a=e.slice(0,r+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(n,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 rs(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await lr({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await lr({text:E5(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}var ha=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:e}){return e},async parsePartialOutput({text:e}){return{partial:e}},createElementStreamTransform(){}}),$5=({schema:e,name:t,description:r})=>{const n=Mn(e);return{name:"object",responseFormat:Tt(n.jsonSchema).then(o=>({type:"json",schema:o,...t!=null&&{name:t},...r!=null&&{description:r}})),async parseCompleteOutput({text:o},s){const i=await lr({text:o});if(!i.success)throw new un({message:"No object generated: could not parse the response.",cause:i.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});const a=await ir({value:i.value,schema:n});if(!a.success)throw new un({message:"No object generated: response did not match schema.",cause:a.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});return a.value},async parsePartialOutput({text:o}){const s=await rs(o);switch(s.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:s.value}}},createElementStreamTransform(){}}},R5=({element:e,name:t,description:r})=>{const n=Mn(e);return{name:"array",responseFormat:Tt(n.jsonSchema).then(o=>{const{$schema:s,...i}=o;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:i}},required:["elements"],additionalProperties:!1},...t!=null&&{name:t},...r!=null&&{description:r}}}),async parseCompleteOutput({text:o},s){const i=await lr({text:o});if(!i.success)throw new un({message:"No object generated: could not parse the response.",cause:i.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});const a=i.value;if(a==null||typeof a!="object"||!("elements"in a)||!Array.isArray(a.elements))throw new un({message:"No object generated: response did not match schema.",cause:new Sn({value:a,cause:"response must be an object with an elements array"}),text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});for(const l of a.elements){const c=await ir({value:l,schema:n});if(!c.success)throw new un({message:"No object generated: response did not match schema.",cause:c.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason})}return a.elements},async parsePartialOutput({text:o}){const s=await rs(o);switch(s.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{const i=s.value;if(i==null||typeof i!="object"||!("elements"in i)||!Array.isArray(i.elements))return;const a=s.state==="repaired-parse"&&i.elements.length>0?i.elements.slice(0,-1):i.elements,l=[];for(const c of a){const u=await ir({value:c,schema:n});u.success&&l.push(u.value)}return{partial:l}}}},createElementStreamTransform(){let o=0;return new TransformStream({transform({partialOutput:s},i){if(s!=null)for(;o<s.length;o++)i.enqueue(s[o])}})}}},P5=({options:e,name:t,description:r})=>({name:"choice",responseFormat:Promise.resolve({type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:e}},required:["result"],additionalProperties:!1},...t!=null&&{name:t},...r!=null&&{description:r}}),async parseCompleteOutput({text:n},o){const s=await lr({text:n});if(!s.success)throw new un({message:"No object generated: could not parse the response.",cause:s.error,text:n,response:o.response,usage:o.usage,finishReason:o.finishReason});const i=s.value;if(i==null||typeof i!="object"||!("result"in i)||typeof i.result!="string"||!e.includes(i.result))throw new un({message:"No object generated: response did not match schema.",cause:new Sn({value:i,cause:"response must be an object that contains a choice value."}),text:n,response:o.response,usage:o.usage,finishReason:o.finishReason});return i.result},async parsePartialOutput({text:n}){const o=await rs(n);switch(o.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{const s=o.value;if(s==null||typeof s!="object"||!("result"in s)||typeof s.result!="string")return;const i=e.filter(a=>a.startsWith(s.result));return o.state==="successful-parse"?i.includes(s.result)?{partial:s.result}:void 0:i.length===1?{partial:i[0]}:void 0}}},createElementStreamTransform(){}}),M5=({name:e,description:t}={})=>({name:"json",responseFormat:Promise.resolve({type:"json",...e!=null&&{name:e},...t!=null&&{description:t}}),async parseCompleteOutput({text:r},n){const o=await lr({text:r});if(!o.success)throw new un({message:"No object generated: could not parse the response.",cause:o.error,text:r,response:n.response,usage:n.usage,finishReason:n.finishReason});return o.value},async parsePartialOutput({text:r}){const n=await rs(r);switch(n.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return n.value===void 0?void 0:{partial:n.value}}},createElementStreamTransform(){}});async function cm({toolCall:e,tools:t,repairToolCall:r,system:n,messages:o}){var s;try{if(t==null){if(e.providerExecuted&&e.dynamic)return await um(e);throw new Wl({toolName:e.toolName})}try{return await dm({toolCall:e,tools:t})}catch(i){if(r==null||!(Wl.isInstance(i)||Jl.isInstance(i)))throw i;let a=null;try{a=await r({toolCall:e,tools:t,inputSchema:async({toolName:l})=>{const{inputSchema:c}=t[l];return await Mn(c).jsonSchema},system:n,messages:o,error:i})}catch(l){throw new Dk({cause:l,originalError:i})}if(a==null)throw i;return await dm({toolCall:a,tools:t})}}catch(i){const a=await lr({text:e.input}),l=a.success?a.value:e.input;return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:l,dynamic:!0,invalid:!0,error:i,title:(s=t?.[e.toolName])==null?void 0:s.title,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}}}async function um(e){const t=e.input.trim()===""?{success:!0,value:{}}:await lr({text:e.input});if(t.success===!1)throw new Jl({toolName:e.toolName,toolInput:e.input,cause:t.error});return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:t.value,providerExecuted:!0,dynamic:!0,providerMetadata:e.providerMetadata}}async function dm({toolCall:e,tools:t}){const r=e.toolName,n=t[r];if(n==null){if(e.providerExecuted&&e.dynamic)return await um(e);throw new Wl({toolName:e.toolName,availableTools:Object.keys(t)})}const o=Mn(n.inputSchema),s=e.input.trim()===""?await ir({value:{},schema:o}):await lr({text:e.input,schema:o});if(s.success===!1)throw new Jl({toolName:r,toolInput:e.input,cause:s.error});return n.type==="dynamic"?{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:s.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,dynamic:!0,title:n.title}:{type:"tool-call",toolCallId:e.toolCallId,toolName:r,input:s.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:n.title}}var pm=class{constructor({stepNumber:e,model:t,functionId:r,metadata:n,experimental_context:o,content:s,finishReason:i,rawFinishReason:a,usage:l,warnings:c,request:u,response:f,providerMetadata:p}){this.stepNumber=e,this.model=t,this.functionId=r,this.metadata=n,this.experimental_context=o,this.content=s,this.finishReason=i,this.rawFinishReason=a,this.usage=l,this.warnings=c,this.request=u,this.response=f,this.providerMetadata=p}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 rc(e){return({steps:t})=>t.length===e}async function fm({stopConditions:e,steps:t}){return(await Promise.all(e.map(r=>r({steps:t})))).some(r=>r)}async function nc({content:e,tools:t}){const r=[],n=[];for(const s of e)if(s.type!=="source"&&!((s.type==="tool-result"||s.type==="tool-error")&&!s.providerExecuted)&&!(s.type==="text"&&s.text.length===0))switch(s.type){case"text":n.push({type:"text",text:s.text,providerOptions:s.providerMetadata});break;case"reasoning":n.push({type:"reasoning",text:s.text,providerOptions:s.providerMetadata});break;case"file":n.push({type:"file",data:s.file.base64,mediaType:s.file.mediaType,providerOptions:s.providerMetadata});break;case"tool-call":n.push({type:"tool-call",toolCallId:s.toolCallId,toolName:s.toolName,input:s.invalid&&typeof s.input!="object"?{}:s.input,providerExecuted:s.providerExecuted,providerOptions:s.providerMetadata});break;case"tool-result":{const i=await Qo({toolCallId:s.toolCallId,input:s.input,tool:t?.[s.toolName],output:s.output,errorMode:"none"});n.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:i,providerOptions:s.providerMetadata});break}case"tool-error":{const i=await Qo({toolCallId:s.toolCallId,input:s.input,tool:t?.[s.toolName],output:s.error,errorMode:"json"});n.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:i,providerOptions:s.providerMetadata});break}case"tool-approval-request":n.push({type:"tool-approval-request",approvalId:s.approvalId,toolCallId:s.toolCall.toolCallId});break}n.length>0&&r.push({role:"assistant",content:n});const o=[];for(const s of e){if(!(s.type==="tool-result"||s.type==="tool-error")||s.providerExecuted)continue;const i=await Qo({toolCallId:s.toolCallId,input:s.input,tool:t?.[s.toolName],output:s.type==="tool-result"?s.output:s.error,errorMode:s.type==="tool-error"?"text":"none"});o.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:i,...s.providerMetadata!=null?{providerOptions:s.providerMetadata}:{}})}return o.length>0&&r.push({role:"tool",content:o}),r}function hm(...e){const t=e.filter(n=>n!=null);if(t.length===0)return;if(t.length===1)return t[0];const r=new AbortController;for(const n of t){if(n.aborted)return r.abort(n.reason),r.signal;n.addEventListener("abort",()=>{r.abort(n.reason)},{once:!0})}return r.signal}var N5=Zo({prefix:"aitxt",size:24});async function mm({model:e,tools:t,toolChoice:r,system:n,prompt:o,messages:s,maxRetries:i,abortSignal:a,timeout:l,headers:c,stopWhen:u=rc(1),experimental_output:f,output:p=f,experimental_telemetry:h,providerOptions:g,experimental_activeTools:v,activeTools:_=v,experimental_prepareStep:w,prepareStep:y=w,experimental_repairToolCall:m,experimental_download:C,experimental_context:b,experimental_include:T,_internal:{generateId:I=N5}={},experimental_onStart:R,experimental_onStepStart:S,experimental_onToolCallStart:j,experimental_onToolCallFinish:O,onStepFinish:L,onFinish:z,...B}){const X=ua(e),ee=em(),Q=qn(u),Z=Yl(l),ne=L0(l),D=ne!=null?new AbortController:void 0,E=hm(a,Z!=null?AbortSignal.timeout(Z):void 0,D?.signal),{maxRetries:U,retry:F}=nm({maxRetries:i,abortSignal:E}),x=Ql(B),M=cn(c??{},`ai/${j0}`),H=K0({model:X,telemetry:h,headers:M,settings:{...x,maxRetries:U}}),re={provider:X.provider,modelId:X.modelId},te=await G0({system:n,prompt:o,messages:s}),_e=ee(h?.integrations);await wr({event:{model:re,system:n,prompt:o,messages:s,tools:t,toolChoice:r,activeTools:_,maxOutputTokens:x.maxOutputTokens,temperature:x.temperature,topP:x.topP,topK:x.topK,presencePenalty:x.presencePenalty,frequencyPenalty:x.frequencyPenalty,stopSequences:x.stopSequences,seed:x.seed,maxRetries:U,timeout:l,headers:c,providerOptions:g,stopWhen:u,output:p,abortSignal:a,include:T,functionId:h?.functionId,metadata:h?.metadata,experimental_context:b},callbacks:[R,_e.onStart]});const G=Y0(h);try{return await ts({name:"ai.generateText",attributes:ur({telemetry:h,attributes:{...es({operationId:"ai.generateText",telemetry:h}),...H,"ai.model.provider":X.provider,"ai.model.id":X.modelId,"ai.prompt":{input:()=>JSON.stringify({system:n,prompt:o,messages:s})}}}),tracer:G,fn:async A=>{var V,J,Y,ue,Ce,Ze,ot,pt,Qe,et,At,mt,$r,Yt,Je,hr,$,K,Le,Re;const tt=te.messages,bt=[],{approvedToolApprovals:sr,deniedToolApprovals:Rr}=om({messages:tt}),mr=sr.filter(Nt=>!Nt.toolCall.providerExecuted);if(Rr.length>0||mr.length>0){const Nt=await gm({toolCalls:mr.map(Ne=>Ne.toolCall),tools:t,tracer:G,telemetry:h,messages:tt,abortSignal:E,experimental_context:b,stepNumber:0,model:re,onToolCallStart:[j,_e.onToolCallStart],onToolCallFinish:[O,_e.onToolCallFinish]}),Lt=[];for(const Ne of Nt){const Qt=await Qo({toolCallId:Ne.toolCallId,input:Ne.input,tool:t?.[Ne.toolName],output:Ne.type==="tool-result"?Ne.output:Ne.error,errorMode:Ne.type==="tool-error"?"text":"none"});Lt.push({type:"tool-result",toolCallId:Ne.toolCallId,toolName:Ne.toolName,output:Qt})}for(const Ne of Rr)Lt.push({type:"tool-result",toolCallId:Ne.toolCall.toolCallId,toolName:Ne.toolCall.toolName,output:{type:"execution-denied",reason:Ne.approvalResponse.reason,...Ne.toolCall.providerExecuted&&{providerOptions:{openai:{approvalId:Ne.approvalResponse.approvalId}}}}});bt.push({role:"tool",content:Lt})}const ie=Ql(B);let Se,yt=[],ft=[];const we=[],qt=new Map;do{const Nt=ne!=null?setTimeout(()=>D.abort(),ne):void 0;try{const Lt=[...tt,...bt],Ne=await y?.({model:X,steps:we,stepNumber:we.length,messages:Lt,experimental_context:b}),Qt=ua((V=Ne?.model)!=null?V:X),yn={provider:Qt.provider,modelId:Qt.modelId},$s=await z0({prompt:{system:(J=Ne?.system)!=null?J:te.system,messages:(Y=Ne?.messages)!=null?Y:Lt},supportedUrls:await Qt.supportedUrls,download:C});b=(ue=Ne?.experimental_context)!=null?ue:b;const Qr=(Ce=Ne?.activeTools)!=null?Ce:_,{toolChoice:So,tools:Io}=await Z0({tools:t,toolChoice:(Ze=Ne?.toolChoice)!=null?Ze:r,activeTools:Qr}),Ji=(ot=Ne?.messages)!=null?ot:Lt,vn=(pt=Ne?.system)!=null?pt:te.system,gt=pa(g,Ne?.providerOptions);await wr({event:{stepNumber:we.length,model:yn,system:vn,messages:Ji,tools:t,toolChoice:So,activeTools:Qr,steps:[...we],providerOptions:gt,timeout:l,headers:c,stopWhen:u,output:p,abortSignal:a,include:T,functionId:h?.functionId,metadata:h?.metadata,experimental_context:b},callbacks:[S,_e.onStepStart]}),Se=await F(()=>{var Oe;return ts({name:"ai.generateText.doGenerate",attributes:ur({telemetry:h,attributes:{...es({operationId:"ai.generateText.doGenerate",telemetry:h}),...H,"ai.model.provider":Qt.provider,"ai.model.id":Qt.modelId,"ai.prompt.messages":{input:()=>X0($s)},"ai.prompt.tools":{input:()=>Io?.map(Bt=>JSON.stringify(Bt))},"ai.prompt.toolChoice":{input:()=>So!=null?JSON.stringify(So):void 0},"gen_ai.system":Qt.provider,"gen_ai.request.model":Qt.modelId,"gen_ai.request.frequency_penalty":B.frequencyPenalty,"gen_ai.request.max_tokens":B.maxOutputTokens,"gen_ai.request.presence_penalty":B.presencePenalty,"gen_ai.request.stop_sequences":B.stopSequences,"gen_ai.request.temperature":(Oe=B.temperature)!=null?Oe:void 0,"gen_ai.request.top_k":B.topK,"gen_ai.request.top_p":B.topP}}),tracer:G,fn:async Bt=>{var $o,Xr,jr,Ms,Ki,Yi,wn,bn;const We=await Qt.doGenerate({...ie,tools:Io,toolChoice:So,responseFormat:await p?.responseFormat,prompt:$s,providerOptions:gt,abortSignal:E,headers:M}),Dr={id:(Xr=($o=We.response)==null?void 0:$o.id)!=null?Xr:I(),timestamp:(Ms=(jr=We.response)==null?void 0:jr.timestamp)!=null?Ms:new Date,modelId:(Yi=(Ki=We.response)==null?void 0:Ki.modelId)!=null?Yi:Qt.modelId,headers:(wn=We.response)==null?void 0:wn.headers,body:(bn=We.response)==null?void 0:bn.body},kn=Xl(We.usage);return Bt.setAttributes(await ur({telemetry:h,attributes:{"ai.response.finishReason":We.finishReason.unified,"ai.response.text":{output:()=>am(We.content)},"ai.response.reasoning":{output:()=>sm(We.content)},"ai.response.toolCalls":{output:()=>{const Ro=_m(We.content);return Ro==null?void 0:JSON.stringify(Ro)}},"ai.response.id":Dr.id,"ai.response.model":Dr.modelId,"ai.response.timestamp":Dr.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(We.providerMetadata),"ai.usage.inputTokens":We.usage.inputTokens.total,"ai.usage.inputTokenDetails.noCacheTokens":We.usage.inputTokens.noCache,"ai.usage.inputTokenDetails.cacheReadTokens":We.usage.inputTokens.cacheRead,"ai.usage.inputTokenDetails.cacheWriteTokens":We.usage.inputTokens.cacheWrite,"ai.usage.outputTokens":We.usage.outputTokens.total,"ai.usage.outputTokenDetails.textTokens":We.usage.outputTokens.text,"ai.usage.outputTokenDetails.reasoningTokens":We.usage.outputTokens.reasoning,"ai.usage.totalTokens":kn.totalTokens,"ai.usage.reasoningTokens":We.usage.outputTokens.reasoning,"ai.usage.cachedInputTokens":We.usage.inputTokens.cacheRead,"gen_ai.response.finish_reasons":[We.finishReason.unified],"gen_ai.response.id":Dr.id,"gen_ai.response.model":Dr.modelId,"gen_ai.usage.input_tokens":We.usage.inputTokens.total,"gen_ai.usage.output_tokens":We.usage.outputTokens.total}})),{...We,response:Dr}}})});const Xt=await Promise.all(Se.content.filter(Oe=>Oe.type==="tool-call").map(Oe=>cm({toolCall:Oe,tools:t,repairToolCall:m,system:n,messages:Lt}))),xo={};for(const Oe of Xt){if(Oe.invalid)continue;const Bt=t?.[Oe.toolName];Bt!=null&&(Bt?.onInputAvailable!=null&&await Bt.onInputAvailable({input:Oe.input,toolCallId:Oe.toolCallId,messages:Lt,abortSignal:E,experimental_context:b}),await lm({tool:Bt,toolCall:Oe,messages:Lt,experimental_context:b})&&(xo[Oe.toolCallId]={type:"tool-approval-request",approvalId:I(),toolCall:Oe}))}const Gi=Xt.filter(Oe=>Oe.invalid&&Oe.dynamic);ft=[];for(const Oe of Gi)ft.push({type:"tool-error",toolCallId:Oe.toolCallId,toolName:Oe.toolName,input:Oe.input,error:Tl(Oe.error),dynamic:!0});yt=Xt.filter(Oe=>!Oe.providerExecuted),t!=null&&ft.push(...await gm({toolCalls:yt.filter(Oe=>!Oe.invalid&&xo[Oe.toolCallId]==null),tools:t,tracer:G,telemetry:h,messages:Lt,abortSignal:E,experimental_context:b,stepNumber:we.length,model:yn,onToolCallStart:[j,_e.onToolCallStart],onToolCallFinish:[O,_e.onToolCallFinish]}));for(const Oe of Xt){if(!Oe.providerExecuted)continue;const Bt=t?.[Oe.toolName];Bt?.type==="provider"&&Bt.supportsDeferredResults&&(Se.content.some(Xr=>Xr.type==="tool-result"&&Xr.toolCallId===Oe.toolCallId)||qt.set(Oe.toolCallId,{toolName:Oe.toolName}))}for(const Oe of Se.content)Oe.type==="tool-result"&&qt.delete(Oe.toolCallId);const Rs=A5({content:Se.content,toolCalls:Xt,toolOutputs:ft,toolApprovalRequests:Object.values(xo),tools:t});bt.push(...await nc({content:Rs,tools:t}));const Eo=(Qe=T?.requestBody)==null||Qe?(et=Se.request)!=null?et:{}:{...Se.request,body:void 0},Ps={...Se.response,messages:structuredClone(bt),body:(At=T?.responseBody)==null||At?(mt=Se.response)==null?void 0:mt.body:void 0},cd=we.length,Wi=new pm({stepNumber:cd,model:yn,functionId:h?.functionId,metadata:h?.metadata,experimental_context:b,content:Rs,finishReason:Se.finishReason.unified,rawFinishReason:Se.finishReason.raw,usage:Xl(Se.usage),warnings:Se.warnings,providerMetadata:Se.providerMetadata,request:Eo,response:Ps});Kl({warnings:($r=Se.warnings)!=null?$r:[],provider:yn.provider,model:yn.modelId}),we.push(Wi),await wr({event:Wi,callbacks:[L,_e.onStepFinish]})}finally{Nt!=null&&clearTimeout(Nt)}}while((yt.length>0&&ft.length===yt.length||qt.size>0)&&!await fm({stopConditions:Q,steps:we}));A.setAttributes(await ur({telemetry:h,attributes:{"ai.response.finishReason":Se.finishReason.unified,"ai.response.text":{output:()=>am(Se.content)},"ai.response.reasoning":{output:()=>sm(Se.content)},"ai.response.toolCalls":{output:()=>{const Nt=_m(Se.content);return Nt==null?void 0:JSON.stringify(Nt)}},"ai.response.providerMetadata":JSON.stringify(Se.providerMetadata)}}));const Ee=we[we.length-1],st=we.reduce((Nt,Lt)=>tm(Nt,Lt.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0});A.setAttributes(await ur({telemetry:h,attributes:{"ai.usage.inputTokens":st.inputTokens,"ai.usage.inputTokenDetails.noCacheTokens":(Yt=st.inputTokenDetails)==null?void 0:Yt.noCacheTokens,"ai.usage.inputTokenDetails.cacheReadTokens":(Je=st.inputTokenDetails)==null?void 0:Je.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":(hr=st.inputTokenDetails)==null?void 0:hr.cacheWriteTokens,"ai.usage.outputTokens":st.outputTokens,"ai.usage.outputTokenDetails.textTokens":($=st.outputTokenDetails)==null?void 0:$.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":(K=st.outputTokenDetails)==null?void 0:K.reasoningTokens,"ai.usage.totalTokens":st.totalTokens,"ai.usage.reasoningTokens":(Le=st.outputTokenDetails)==null?void 0:Le.reasoningTokens,"ai.usage.cachedInputTokens":(Re=st.inputTokenDetails)==null?void 0:Re.cacheReadTokens}})),await wr({event:{stepNumber:Ee.stepNumber,model:Ee.model,functionId:Ee.functionId,metadata:Ee.metadata,experimental_context:Ee.experimental_context,finishReason:Ee.finishReason,rawFinishReason:Ee.rawFinishReason,usage:Ee.usage,content:Ee.content,text:Ee.text,reasoningText:Ee.reasoningText,reasoning:Ee.reasoning,files:Ee.files,sources:Ee.sources,toolCalls:Ee.toolCalls,staticToolCalls:Ee.staticToolCalls,dynamicToolCalls:Ee.dynamicToolCalls,toolResults:Ee.toolResults,staticToolResults:Ee.staticToolResults,dynamicToolResults:Ee.dynamicToolResults,request:Ee.request,response:Ee.response,warnings:Ee.warnings,providerMetadata:Ee.providerMetadata,steps:we,totalUsage:st},callbacks:[z,_e.onFinish]});let ut;return Ee.finishReason==="stop"&&(ut=await(p??ha()).parseCompleteOutput({text:Ee.text},{response:Ee.response,usage:Ee.usage,finishReason:Ee.finishReason})),new O5({steps:we,totalUsage:st,output:ut})}})}catch(A){throw W0(A)}}async function gm({toolCalls:e,tools:t,tracer:r,telemetry:n,messages:o,abortSignal:s,experimental_context:i,stepNumber:a,model:l,onToolCallStart:c,onToolCallFinish:u}){return(await Promise.all(e.map(async p=>tc({toolCall:p,tools:t,tracer:r,telemetry:n,messages:o,abortSignal:s,experimental_context:i,stepNumber:a,model:l,onToolCallStart:c,onToolCallFinish:u})))).filter(p=>p!=null)}var O5=class{constructor(e){this.steps=e.steps,this._output=e.output,this.totalUsage=e.totalUsage}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 rawFinishReason(){return this.finalStep.rawFinishReason}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 experimental_output(){return this.output}get output(){if(this._output==null)throw new _0;return this._output}};function _m(e){const t=e.filter(r=>r.type==="tool-call");if(t.length!==0)return t.map(r=>({toolCallId:r.toolCallId,toolName:r.toolName,input:r.input}))}function A5({content:e,toolCalls:t,toolOutputs:r,toolApprovalRequests:n,tools:o}){const s=[];for(const i of e)switch(i.type){case"text":case"reasoning":case"source":s.push(i);break;case"file":{s.push({type:"file",file:new im(i),...i.providerMetadata!=null?{providerMetadata:i.providerMetadata}:{}});break}case"tool-call":{s.push(t.find(a=>a.toolCallId===i.toolCallId));break}case"tool-result":{const a=t.find(l=>l.toolCallId===i.toolCallId);if(a==null){const l=o?.[i.toolName];if(!(l?.type==="provider"&&l.supportsDeferredResults))throw new Error(`Tool call ${i.toolCallId} not found.`);i.isError?s.push({type:"tool-error",toolCallId:i.toolCallId,toolName:i.toolName,input:void 0,error:i.result,providerExecuted:!0,dynamic:i.dynamic,...i.providerMetadata!=null?{providerMetadata:i.providerMetadata}:{}}):s.push({type:"tool-result",toolCallId:i.toolCallId,toolName:i.toolName,input:void 0,output:i.result,providerExecuted:!0,dynamic:i.dynamic,...i.providerMetadata!=null?{providerMetadata:i.providerMetadata}:{}});break}i.isError?s.push({type:"tool-error",toolCallId:i.toolCallId,toolName:i.toolName,input:a.input,error:i.result,providerExecuted:!0,dynamic:a.dynamic,...i.providerMetadata!=null?{providerMetadata:i.providerMetadata}:{}}):s.push({type:"tool-result",toolCallId:i.toolCallId,toolName:i.toolName,input:a.input,output:i.result,providerExecuted:!0,dynamic:a.dynamic,...i.providerMetadata!=null?{providerMetadata:i.providerMetadata}:{}});break}case"tool-approval-request":{const a=t.find(l=>l.toolCallId===i.toolCallId);if(a==null)throw new Gl({toolCallId:i.toolCallId,approvalId:i.approvalId});s.push({type:"tool-approval-request",approvalId:i.approvalId,toolCall:a});break}}return[...s,...r,...n]}function ma(e,t){const r=new Headers(e??{});for(const[n,o]of Object.entries(t))r.has(n)||r.set(n,o);return r}function q5({status:e,statusText:t,headers:r,textStream:n}){return new Response(n.pipeThrough(new TextEncoderStream),{status:e??200,statusText:t,headers:ma(r,{"content-type":"text/plain; charset=utf-8"})})}function ym({response:e,status:t,statusText:r,headers:n,stream:o}){const s=t??200;r!==void 0?e.writeHead(s,r,n):e.writeHead(s,n);const i=o.getReader();(async()=>{try{for(;;){const{done:l,value:c}=await i.read();if(l)break;e.write(c)||await new Promise(f=>{e.once("drain",f)})}}catch(l){throw l}finally{e.end()}})()}function L5({response:e,status:t,statusText:r,headers:n,textStream:o}){ym({response:e,status:t,statusText:r,headers:Object.fromEntries(ma(n,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:o.pipeThrough(new TextEncoderStream)})}var vm=class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
65
-
66
- `)},flush(e){e.enqueue(`data: [DONE]
67
-
68
- `)}})}},wm={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function j5({status:e,statusText:t,headers:r,stream:n,consumeSseStream:o}){let s=n.pipeThrough(new vm);if(o){const[i,a]=s.tee();s=i,o({stream:a})}return new Response(s.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:ma(r,wm)})}function D5({originalMessages:e,responseMessageId:t}){if(e==null)return;const r=e[e.length-1];return r?.role==="assistant"?r.id:typeof t=="function"?t():t}function U5(e){return e.type.startsWith("data-")}function oc(e){return e.type.startsWith("tool-")}function z5(e){return e.type==="dynamic-tool"}function bm(e){return oc(e)||z5(e)}function km(e){return e.type.split("-").slice(1).join("-")}function F5({lastMessage:e,messageId:t}){return{message:e?.role==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function V5({stream:e,messageMetadataSchema:t,dataPartSchemas:r,runUpdateMessageJob:n,onError:o,onToolCall:s,onData:i}){return e.pipeThrough(new TransformStream({async transform(a,l){await n(async({state:c,write:u})=>{var f,p,h,g;function v(m){const b=c.message.parts.filter(bm).find(T=>T.toolCallId===m);if(b==null)throw new lo({chunkType:"tool-invocation",chunkId:m,message:`No tool invocation found for tool call ID "${m}".`});return b}function _(m){var C;const b=c.message.parts.find(R=>oc(R)&&R.toolCallId===m.toolCallId),T=m,I=b;if(b!=null){b.state=m.state,I.input=T.input,I.output=T.output,I.errorText=T.errorText,I.rawInput=T.rawInput,I.preliminary=T.preliminary,m.title!==void 0&&(I.title=m.title),I.providerExecuted=(C=T.providerExecuted)!=null?C:b.providerExecuted;const R=T.providerMetadata;if(R!=null)if(m.state==="output-available"||m.state==="output-error"){const S=b;S.resultProviderMetadata=R}else b.callProviderMetadata=R}else c.message.parts.push({type:`tool-${m.toolName}`,toolCallId:m.toolCallId,state:m.state,title:m.title,input:T.input,output:T.output,rawInput:T.rawInput,errorText:T.errorText,providerExecuted:T.providerExecuted,preliminary:T.preliminary,...T.providerMetadata!=null&&(m.state==="output-available"||m.state==="output-error")?{resultProviderMetadata:T.providerMetadata}:{},...T.providerMetadata!=null&&!(m.state==="output-available"||m.state==="output-error")?{callProviderMetadata:T.providerMetadata}:{}})}function w(m){var C,b;const T=c.message.parts.find(S=>S.type==="dynamic-tool"&&S.toolCallId===m.toolCallId),I=m,R=T;if(T!=null){T.state=m.state,R.toolName=m.toolName,R.input=I.input,R.output=I.output,R.errorText=I.errorText,R.rawInput=(C=I.rawInput)!=null?C:R.rawInput,R.preliminary=I.preliminary,m.title!==void 0&&(R.title=m.title),R.providerExecuted=(b=I.providerExecuted)!=null?b:T.providerExecuted;const S=I.providerMetadata;if(S!=null)if(m.state==="output-available"||m.state==="output-error"){const j=T;j.resultProviderMetadata=S}else T.callProviderMetadata=S}else c.message.parts.push({type:"dynamic-tool",toolName:m.toolName,toolCallId:m.toolCallId,state:m.state,input:I.input,output:I.output,errorText:I.errorText,preliminary:I.preliminary,providerExecuted:I.providerExecuted,title:m.title,...I.providerMetadata!=null&&(m.state==="output-available"||m.state==="output-error")?{resultProviderMetadata:I.providerMetadata}:{},...I.providerMetadata!=null&&!(m.state==="output-available"||m.state==="output-error")?{callProviderMetadata:I.providerMetadata}:{}})}async function y(m){if(m!=null){const C=c.message.metadata!=null?pa(c.message.metadata,m):m;t!=null&&await dt({value:C,schema:t,context:{field:"message.metadata",entityId:c.message.id}}),c.message.metadata=C}}switch(a.type){case"text-start":{const m={type:"text",text:"",providerMetadata:a.providerMetadata,state:"streaming"};c.activeTextParts[a.id]=m,c.message.parts.push(m),u();break}case"text-delta":{const m=c.activeTextParts[a.id];if(m==null)throw new lo({chunkType:"text-delta",chunkId:a.id,message:`Received text-delta for missing text part with ID "${a.id}". Ensure a "text-start" chunk is sent before any "text-delta" chunks.`});m.text+=a.delta,m.providerMetadata=(f=a.providerMetadata)!=null?f:m.providerMetadata,u();break}case"text-end":{const m=c.activeTextParts[a.id];if(m==null)throw new lo({chunkType:"text-end",chunkId:a.id,message:`Received text-end for missing text part with ID "${a.id}". Ensure a "text-start" chunk is sent before any "text-end" chunks.`});m.state="done",m.providerMetadata=(p=a.providerMetadata)!=null?p:m.providerMetadata,delete c.activeTextParts[a.id],u();break}case"reasoning-start":{const m={type:"reasoning",text:"",providerMetadata:a.providerMetadata,state:"streaming"};c.activeReasoningParts[a.id]=m,c.message.parts.push(m),u();break}case"reasoning-delta":{const m=c.activeReasoningParts[a.id];if(m==null)throw new lo({chunkType:"reasoning-delta",chunkId:a.id,message:`Received reasoning-delta for missing reasoning part with ID "${a.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-delta" chunks.`});m.text+=a.delta,m.providerMetadata=(h=a.providerMetadata)!=null?h:m.providerMetadata,u();break}case"reasoning-end":{const m=c.activeReasoningParts[a.id];if(m==null)throw new lo({chunkType:"reasoning-end",chunkId:a.id,message:`Received reasoning-end for missing reasoning part with ID "${a.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-end" chunks.`});m.providerMetadata=(g=a.providerMetadata)!=null?g:m.providerMetadata,m.state="done",delete c.activeReasoningParts[a.id],u();break}case"file":{c.message.parts.push({type:"file",mediaType:a.mediaType,url:a.url,...a.providerMetadata!=null?{providerMetadata:a.providerMetadata}:{}}),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 m=c.message.parts.filter(oc);c.partialToolCalls[a.toolCallId]={text:"",toolName:a.toolName,index:m.length,dynamic:a.dynamic,title:a.title},a.dynamic?w({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted,title:a.title,providerMetadata:a.providerMetadata}):_({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted,title:a.title,providerMetadata:a.providerMetadata}),u();break}case"tool-input-delta":{const m=c.partialToolCalls[a.toolCallId];if(m==null)throw new lo({chunkType:"tool-input-delta",chunkId:a.toolCallId,message:`Received tool-input-delta for missing tool call with ID "${a.toolCallId}". Ensure a "tool-input-start" chunk is sent before any "tool-input-delta" chunks.`});m.text+=a.inputTextDelta;const{value:C}=await rs(m.text);m.dynamic?w({toolCallId:a.toolCallId,toolName:m.toolName,state:"input-streaming",input:C,title:m.title}):_({toolCallId:a.toolCallId,toolName:m.toolName,state:"input-streaming",input:C,title:m.title}),u();break}case"tool-input-available":{a.dynamic?w({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata,title:a.title}):_({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata,title:a.title}),u(),s&&!a.providerExecuted&&await s({toolCall:a});break}case"tool-input-error":{const m=c.message.parts.filter(bm).find(b=>b.toolCallId===a.toolCallId);(m!=null?m.type==="dynamic-tool":!!a.dynamic)?w({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:a.input,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}):_({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-approval-request":{const m=v(a.toolCallId);m.state="approval-requested",m.approval={id:a.approvalId},u();break}case"tool-output-denied":{const m=v(a.toolCallId);m.state="output-denied",u();break}case"tool-output-available":{const m=v(a.toolCallId);m.type==="dynamic-tool"?w({toolCallId:a.toolCallId,toolName:m.toolName,state:"output-available",input:m.input,output:a.output,preliminary:a.preliminary,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata,title:m.title}):_({toolCallId:a.toolCallId,toolName:km(m),state:"output-available",input:m.input,output:a.output,providerExecuted:a.providerExecuted,preliminary:a.preliminary,providerMetadata:a.providerMetadata,title:m.title}),u();break}case"tool-output-error":{const m=v(a.toolCallId);m.type==="dynamic-tool"?w({toolCallId:a.toolCallId,toolName:m.toolName,state:"output-error",input:m.input,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata,title:m.title}):_({toolCallId:a.toolCallId,toolName:km(m),state:"output-error",input:m.input,rawInput:m.rawInput,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata,title:m.title}),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":{a.finishReason!=null&&(c.finishReason=a.finishReason),await y(a.messageMetadata),a.messageMetadata!=null&&u();break}case"message-metadata":{await y(a.messageMetadata),a.messageMetadata!=null&&u();break}case"error":{o?.(new Error(a.errorText));break}default:if(U5(a)){if(r?.[a.type]!=null){const b=c.message.parts.findIndex(I=>"id"in I&&"data"in I&&I.id===a.id&&I.type===a.type),T=b>=0?b:c.message.parts.length;await dt({value:a.data,schema:r[a.type],context:{field:`message.parts[${T}].data`,entityName:a.type,entityId:a.id}})}const m=a;if(m.transient){i?.(m);break}const C=m.id!=null?c.message.parts.find(b=>m.type===b.type&&m.id===b.id):void 0;C!=null?C.data=m.data:c.message.parts.push(m),i?.(m),u()}}l.enqueue(a)})}}))}function Z5({messageId:e,originalMessages:t=[],onStepFinish:r,onFinish:n,onError:o,stream:s}){let i=t?.[t.length-1];i?.role!=="assistant"?i=void 0:e=i.id;let a=!1;const l=s.pipeThrough(new TransformStream({transform(g,v){if(g.type==="start"){const _=g;_.messageId==null&&e!=null&&(_.messageId=e)}g.type==="abort"&&(a=!0),v.enqueue(g)}}));if(n==null&&r==null)return l;const c=F5({lastMessage:i?structuredClone(i):void 0,messageId:e??""}),u=async g=>{await g({state:c,write:()=>{}})};let f=!1;const p=async()=>{if(f||!n)return;f=!0;const g=c.message.id===i?.id;await n({isAborted:a,isContinuation:g,responseMessage:c.message,messages:[...g?t.slice(0,-1):t,c.message],finishReason:c.finishReason})},h=async()=>{if(!r)return;const g=c.message.id===i?.id;try{await r({isContinuation:g,responseMessage:structuredClone(c.message),messages:[...g?t.slice(0,-1):t,structuredClone(c.message)]})}catch(v){o(v)}};return V5({stream:l,runUpdateMessageJob:u,onError:o}).pipeThrough(new TransformStream({async transform(g,v){g.type==="finish-step"&&await h(),v.enqueue(g)},async cancel(){await p()},async flush(){await p()}}))}function B5({response:e,status:t,statusText:r,headers:n,stream:o,consumeSseStream:s}){let i=o.pipeThrough(new vm);if(s){const[a,l]=i.tee();i=a,s({stream:l})}ym({response:e,status:t,statusText:r,headers:Object.fromEntries(ma(n,wm).entries()),stream:i.pipeThrough(new TextEncoderStream)})}function ns(e){const t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=function(){const r=this.getReader();let n=!1;async function o(s){var i;if(!n){n=!0;try{s&&await((i=r.cancel)==null?void 0:i.call(r))}finally{try{r.releaseLock()}catch{}}}}return{async next(){if(n)return{done:!0,value:void 0};const{done:s,value:i}=await r.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 H5({stream:e,onError:t}){const r=e.getReader();try{for(;;){const{done:n}=await r.read();if(n)break}}catch(n){t?.(n)}finally{r.releaseLock()}}function Tm(){let e,t;return{promise:new Promise((n,o)=>{e=n,t=o}),resolve:e,reject:t}}function J5(){let e=[],t=null,r=!1,n=Tm();const o=()=>{r=!0,n.resolve(),e.forEach(i=>i.cancel()),e=[],t?.close()},s=async()=>{if(r&&e.length===0){t?.close();return}if(e.length===0)return n=Tm(),await n.promise,s();try{const{value:i,done:a}=await e[0].read();a?(e.shift(),e.length===0&&r?t?.close():await s()):t?.enqueue(i)}catch(i){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=[],r=!0}}),addStream:i=>{if(r)throw new Error("Cannot add inner stream: outer stream is closed");e.push(i.getReader()),n.resolve()},close:()=>{r=!0,n.resolve(),e.length===0&&t?.close()},terminate:o}}function G5({tools:e,generatorStream:t,tracer:r,telemetry:n,system:o,messages:s,abortSignal:i,repairToolCall:a,experimental_context:l,generateId:c,stepNumber:u,model:f,onToolCallStart:p,onToolCallFinish:h}){let g=null;const v=new ReadableStream({start(I){g=I}}),_=new Set,w=new Map,y=new Map;let m=!1,C;function b(){m&&_.size===0&&(C!=null&&g.enqueue(C),g.close())}const T=new TransformStream({async transform(I,R){const S=I.type;switch(S){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":{R.enqueue(I);break}case"file":{R.enqueue({type:"file",file:new I5({data:I.data,mediaType:I.mediaType}),...I.providerMetadata!=null?{providerMetadata:I.providerMetadata}:{}});break}case"finish":{C={type:"finish",finishReason:I.finishReason.unified,rawFinishReason:I.finishReason.raw,usage:Xl(I.usage),providerMetadata:I.providerMetadata};break}case"tool-approval-request":{const j=y.get(I.toolCallId);if(j==null){g.enqueue({type:"error",error:new Gl({toolCallId:I.toolCallId,approvalId:I.approvalId})});break}R.enqueue({type:"tool-approval-request",approvalId:I.approvalId,toolCall:j});break}case"tool-call":{try{const j=await cm({toolCall:I,tools:e,repairToolCall:a,system:o,messages:s});if(y.set(j.toolCallId,j),R.enqueue(j),j.invalid){g.enqueue({type:"tool-error",toolCallId:j.toolCallId,toolName:j.toolName,input:j.input,error:Tl(j.error),dynamic:!0,title:j.title});break}const O=e?.[j.toolName];if(O==null)break;if(O.onInputAvailable!=null&&await O.onInputAvailable({input:j.input,toolCallId:j.toolCallId,messages:s,abortSignal:i,experimental_context:l}),await lm({tool:O,toolCall:j,messages:s,experimental_context:l})){g.enqueue({type:"tool-approval-request",approvalId:c(),toolCall:j});break}if(w.set(j.toolCallId,j.input),O.execute!=null&&j.providerExecuted!==!0){const L=c();_.add(L),tc({toolCall:j,tools:e,tracer:r,telemetry:n,messages:s,abortSignal:i,experimental_context:l,stepNumber:u,model:f,onToolCallStart:p,onToolCallFinish:h,onPreliminaryToolResult:z=>{g.enqueue(z)}}).then(z=>{g.enqueue(z)}).catch(z=>{g.enqueue({type:"error",error:z})}).finally(()=>{_.delete(L),b()})}}catch(j){g.enqueue({type:"error",error:j})}break}case"tool-result":{const j=I.toolName;I.isError?g.enqueue({type:"tool-error",toolCallId:I.toolCallId,toolName:j,input:w.get(I.toolCallId),providerExecuted:!0,error:I.result,dynamic:I.dynamic,...I.providerMetadata!=null?{providerMetadata:I.providerMetadata}:{}}):R.enqueue({type:"tool-result",toolCallId:I.toolCallId,toolName:j,input:w.get(I.toolCallId),output:I.result,providerExecuted:!0,dynamic:I.dynamic,...I.providerMetadata!=null?{providerMetadata:I.providerMetadata}:{}});break}default:{const j=S;throw new Error(`Unhandled chunk type: ${j}`)}}},flush(){m=!0,b()}});return new ReadableStream({async start(I){return Promise.all([t.pipeThrough(T).pipeTo(new WritableStream({write(R){I.enqueue(R)},close(){}})),v.pipeTo(new WritableStream({write(R){I.enqueue(R)},close(){I.close()}}))])}})}var W5=Zo({prefix:"aitxt",size:24});function sc({model:e,tools:t,toolChoice:r,system:n,prompt:o,messages:s,maxRetries:i,abortSignal:a,timeout:l,headers:c,stopWhen:u=rc(1),experimental_output:f,output:p=f,experimental_telemetry:h,prepareStep:g,providerOptions:v,experimental_activeTools:_,activeTools:w=_,experimental_repairToolCall:y,experimental_transform:m,experimental_download:C,includeRawChunks:b=!1,onChunk:T,onError:I=({error:D})=>{console.error(D)},onFinish:R,onAbort:S,onStepFinish:j,experimental_onStart:O,experimental_onStepStart:L,experimental_onToolCallStart:z,experimental_onToolCallFinish:B,experimental_context:X,experimental_include:ee,_internal:{now:Q=fa,generateId:Z=W5}={},...ne}){const D=Yl(l),E=L0(l),U=Yk(l),F=E!=null?new AbortController:void 0,x=U!=null?new AbortController:void 0;return new Y5({model:ua(e),telemetry:h,headers:c,settings:ne,maxRetries:i,abortSignal:hm(a,D!=null?AbortSignal.timeout(D):void 0,F?.signal,x?.signal),stepTimeoutMs:E,stepAbortController:F,chunkTimeoutMs:U,chunkAbortController:x,system:n,prompt:o,messages:s,tools:t,toolChoice:r,transforms:qn(m),activeTools:w,repairToolCall:y,stopConditions:qn(u),output:p,providerOptions:v,prepareStep:g,includeRawChunks:b,timeout:l,stopWhen:u,originalAbortSignal:a,onChunk:T,onError:I,onFinish:R,onAbort:S,onStepFinish:j,onStart:O,onStepStart:L,onToolCallStart:z,onToolCallFinish:B,now:Q,generateId:Z,experimental_context:X,download:C,include:ee})}function K5(e){let t,r="",n="",o,s="";function i({controller:a,partialOutput:l=void 0}){a.enqueue({part:{type:"text-delta",id:t,text:n,providerMetadata:o},partialOutput:l}),n=""}return new TransformStream({async transform(a,l){var c;if(a.type==="finish-step"&&n.length>0&&i({controller:l}),a.type!=="text-delta"&&a.type!=="text-start"&&a.type!=="text-end"){l.enqueue({part:a,partialOutput:void 0});return}if(t==null)t=a.id;else if(a.id!==t){l.enqueue({part:a,partialOutput:void 0});return}if(a.type==="text-start"){l.enqueue({part:a,partialOutput:void 0});return}if(a.type==="text-end"){n.length>0&&i({controller:l}),l.enqueue({part:a,partialOutput:void 0});return}r+=a.text,n+=a.text,o=(c=a.providerMetadata)!=null?c:o;const u=await e.parsePartialOutput({text:r});if(u!==void 0){const f=typeof u.partial=="string"?u.partial:JSON.stringify(u.partial);f!==s&&(i({controller:l,partialOutput:u.partial}),s=f)}}})}var Y5=class{constructor({model:e,telemetry:t,headers:r,settings:n,maxRetries:o,abortSignal:s,stepTimeoutMs:i,stepAbortController:a,chunkTimeoutMs:l,chunkAbortController:c,system:u,prompt:f,messages:p,tools:h,toolChoice:g,transforms:v,activeTools:_,repairToolCall:w,stopConditions:y,output:m,providerOptions:C,prepareStep:b,includeRawChunks:T,now:I,generateId:R,timeout:S,stopWhen:j,originalAbortSignal:O,onChunk:L,onError:z,onFinish:B,onAbort:X,onStepFinish:ee,onStart:Q,onStepStart:Z,onToolCallStart:ne,onToolCallFinish:D,experimental_context:E,download:U,include:F}){this._totalUsage=new Vo,this._finishReason=new Vo,this._rawFinishReason=new Vo,this._steps=new Vo,this.outputSpecification=m,this.includeRawChunks=T,this.tools=h;const M=em()(t?.integrations);let H,re=[];const te=[];let _e,G,A,V={},J=[];const Y=[],ue=new Map;let Ce,Ze={},ot={};const pt=new TransformStream({async transform(Re,tt){var bt,sr,Rr,mr;tt.enqueue(Re);const{part:ie}=Re;if((ie.type==="text-delta"||ie.type==="reasoning-delta"||ie.type==="source"||ie.type==="tool-call"||ie.type==="tool-result"||ie.type==="tool-input-start"||ie.type==="tool-input-delta"||ie.type==="raw")&&await L?.({chunk:ie}),ie.type==="error"&&await z({error:W0(ie.error)}),ie.type==="text-start"&&(Ze[ie.id]={type:"text",text:"",providerMetadata:ie.providerMetadata},re.push(Ze[ie.id])),ie.type==="text-delta"){const Se=Ze[ie.id];if(Se==null){tt.enqueue({part:{type:"error",error:`text part ${ie.id} not found`},partialOutput:void 0});return}Se.text+=ie.text,Se.providerMetadata=(bt=ie.providerMetadata)!=null?bt:Se.providerMetadata}if(ie.type==="text-end"){const Se=Ze[ie.id];if(Se==null){tt.enqueue({part:{type:"error",error:`text part ${ie.id} not found`},partialOutput:void 0});return}Se.providerMetadata=(sr=ie.providerMetadata)!=null?sr:Se.providerMetadata,delete Ze[ie.id]}if(ie.type==="reasoning-start"&&(ot[ie.id]={type:"reasoning",text:"",providerMetadata:ie.providerMetadata},re.push(ot[ie.id])),ie.type==="reasoning-delta"){const Se=ot[ie.id];if(Se==null){tt.enqueue({part:{type:"error",error:`reasoning part ${ie.id} not found`},partialOutput:void 0});return}Se.text+=ie.text,Se.providerMetadata=(Rr=ie.providerMetadata)!=null?Rr:Se.providerMetadata}if(ie.type==="reasoning-end"){const Se=ot[ie.id];if(Se==null){tt.enqueue({part:{type:"error",error:`reasoning part ${ie.id} not found`},partialOutput:void 0});return}Se.providerMetadata=(mr=ie.providerMetadata)!=null?mr:Se.providerMetadata,delete ot[ie.id]}if(ie.type==="file"&&re.push({type:"file",file:ie.file,...ie.providerMetadata!=null?{providerMetadata:ie.providerMetadata}:{}}),ie.type==="source"&&re.push(ie),ie.type==="tool-call"&&re.push(ie),ie.type==="tool-result"&&!ie.preliminary&&re.push(ie),ie.type==="tool-approval-request"&&re.push(ie),ie.type==="tool-error"&&re.push(ie),ie.type==="start-step"&&(re=[],ot={},Ze={},V=ie.request,J=ie.warnings),ie.type==="finish-step"){const Se=await nc({content:re,tools:h}),yt=new pm({stepNumber:Y.length,model:K,...Le,experimental_context:E,content:re,finishReason:ie.finishReason,rawFinishReason:ie.rawFinishReason,usage:ie.usage,warnings:J,request:V,response:{...ie.response,messages:[...te,...Se]},providerMetadata:ie.providerMetadata});await wr({event:yt,callbacks:[ee,M.onStepFinish]}),Kl({warnings:J,provider:K.provider,model:K.modelId}),Y.push(yt),te.push(...Se),H.resolve()}ie.type==="finish"&&(A=ie.totalUsage,_e=ie.finishReason,G=ie.rawFinishReason)},async flush(Re){var tt,bt,sr,Rr,mr,ie,Se;try{if(Y.length===0){const qt=s?.aborted?s.reason:new _0({message:"No output generated. Check the stream for errors."});$._finishReason.reject(qt),$._rawFinishReason.reject(qt),$._totalUsage.reject(qt),$._steps.reject(qt);return}const yt=_e??"other",ft=A??ec();$._finishReason.resolve(yt),$._rawFinishReason.resolve(G),$._totalUsage.resolve(ft),$._steps.resolve(Y);const we=Y[Y.length-1];await wr({event:{stepNumber:we.stepNumber,model:we.model,functionId:we.functionId,metadata:we.metadata,experimental_context:we.experimental_context,finishReason:we.finishReason,rawFinishReason:we.rawFinishReason,totalUsage:ft,usage:we.usage,content:we.content,text:we.text,reasoningText:we.reasoningText,reasoning:we.reasoning,files:we.files,sources:we.sources,toolCalls:we.toolCalls,staticToolCalls:we.staticToolCalls,dynamicToolCalls:we.dynamicToolCalls,toolResults:we.toolResults,staticToolResults:we.staticToolResults,dynamicToolResults:we.dynamicToolResults,request:we.request,response:we.response,warnings:we.warnings,providerMetadata:we.providerMetadata,steps:Y},callbacks:[B,M.onFinish]}),Ce.setAttributes(await ur({telemetry:t,attributes:{"ai.response.finishReason":yt,"ai.response.text":{output:()=>we.text},"ai.response.reasoning":{output:()=>we.reasoningText},"ai.response.toolCalls":{output:()=>{var qt;return(qt=we.toolCalls)!=null&&qt.length?JSON.stringify(we.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(we.providerMetadata),"ai.usage.inputTokens":ft.inputTokens,"ai.usage.inputTokenDetails.noCacheTokens":(tt=ft.inputTokenDetails)==null?void 0:tt.noCacheTokens,"ai.usage.inputTokenDetails.cacheReadTokens":(bt=ft.inputTokenDetails)==null?void 0:bt.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":(sr=ft.inputTokenDetails)==null?void 0:sr.cacheWriteTokens,"ai.usage.outputTokens":ft.outputTokens,"ai.usage.outputTokenDetails.textTokens":(Rr=ft.outputTokenDetails)==null?void 0:Rr.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":(mr=ft.outputTokenDetails)==null?void 0:mr.reasoningTokens,"ai.usage.totalTokens":ft.totalTokens,"ai.usage.reasoningTokens":(ie=ft.outputTokenDetails)==null?void 0:ie.reasoningTokens,"ai.usage.cachedInputTokens":(Se=ft.inputTokenDetails)==null?void 0:Se.cacheReadTokens}}))}catch(yt){Re.error(yt)}finally{Ce.end()}}}),Qe=J5();this.addStream=Qe.addStream,this.closeStream=Qe.close;const et=Qe.stream.getReader();let At=new ReadableStream({async start(Re){Re.enqueue({type:"start"})},async pull(Re){function tt(){X?.({steps:Y}),Re.enqueue({type:"abort",...s?.reason!==void 0?{reason:Tn(s.reason)}:{}}),Re.close()}try{const{done:bt,value:sr}=await et.read();if(bt){Re.close();return}if(s?.aborted){tt();return}Re.enqueue(sr)}catch(bt){$n(bt)&&s?.aborted?tt():Re.error(bt)}},cancel(Re){return Qe.stream.cancel(Re)}});for(const Re of v)At=At.pipeThrough(Re({tools:h,stopStream(){Qe.terminate()}}));this.baseStream=At.pipeThrough(K5(m??ha())).pipeThrough(pt);const{maxRetries:mt,retry:$r}=nm({maxRetries:o,abortSignal:s}),Yt=Y0(t),Je=Ql(n),hr=K0({model:e,telemetry:t,headers:r,settings:{...Je,maxRetries:mt}}),$=this,K={provider:e.provider,modelId:e.modelId},Le={functionId:t?.functionId,metadata:t?.metadata};ts({name:"ai.streamText",attributes:ur({telemetry:t,attributes:{...es({operationId:"ai.streamText",telemetry:t}),...hr,"ai.prompt":{input:()=>JSON.stringify({system:u,prompt:f,messages:p})}}}),tracer:Yt,endWhenDone:!1,fn:async Re=>{Ce=Re;const tt=await G0({system:u,prompt:f,messages:p});await wr({event:{model:K,system:u,prompt:f,messages:p,tools:h,toolChoice:g,activeTools:_,maxOutputTokens:Je.maxOutputTokens,temperature:Je.temperature,topP:Je.topP,topK:Je.topK,presencePenalty:Je.presencePenalty,frequencyPenalty:Je.frequencyPenalty,stopSequences:Je.stopSequences,seed:Je.seed,maxRetries:mt,timeout:S,headers:r,providerOptions:C,stopWhen:j,output:m,abortSignal:O,include:F,...Le,experimental_context:E},callbacks:[Q,M.onStart]});const bt=tt.messages,sr=[],{approvedToolApprovals:Rr,deniedToolApprovals:mr}=om({messages:bt});if(mr.length>0||Rr.length>0){const Se=Rr.filter(Ee=>!Ee.toolCall.providerExecuted),yt=mr.filter(Ee=>!Ee.toolCall.providerExecuted),ft=mr.filter(Ee=>Ee.toolCall.providerExecuted);let we;const qt=new ReadableStream({start(Ee){we=Ee}});$.addStream(qt);try{for(const st of[...yt,...ft])we?.enqueue({type:"tool-output-denied",toolCallId:st.toolCall.toolCallId,toolName:st.toolCall.toolName});const Ee=[];if(await Promise.all(Se.map(async st=>{const ut=await tc({toolCall:st.toolCall,tools:h,tracer:Yt,telemetry:t,messages:bt,abortSignal:s,experimental_context:E,stepNumber:Y.length,model:K,onToolCallStart:[ne,M.onToolCallStart],onToolCallFinish:[D,M.onToolCallFinish],onPreliminaryToolResult:Nt=>{we?.enqueue(Nt)}});ut!=null&&(we?.enqueue(ut),Ee.push(ut))})),Ee.length>0||yt.length>0){const st=[];for(const ut of Ee)st.push({type:"tool-result",toolCallId:ut.toolCallId,toolName:ut.toolName,output:await Qo({toolCallId:ut.toolCallId,input:ut.input,tool:h?.[ut.toolName],output:ut.type==="tool-result"?ut.output:ut.error,errorMode:ut.type==="tool-error"?"text":"none"})});for(const ut of yt)st.push({type:"tool-result",toolCallId:ut.toolCall.toolCallId,toolName:ut.toolCall.toolName,output:{type:"execution-denied",reason:ut.approvalResponse.reason}});sr.push({role:"tool",content:st})}}finally{we?.close()}}te.push(...sr);async function ie({currentStep:Se,responseMessages:yt,usage:ft}){var we,qt,Ee,st,ut,Nt,Lt,Ne,Qt;const yn=$.includeRawChunks,$s=i!=null?setTimeout(()=>a.abort(),i):void 0;let Qr;function So(){l!=null&&(Qr!=null&&clearTimeout(Qr),Qr=setTimeout(()=>c.abort(),l))}function Io(){Qr!=null&&(clearTimeout(Qr),Qr=void 0)}function Ji(){$s!=null&&clearTimeout($s)}try{H=new Vo;const vn=[...bt,...yt],gt=await b?.({model:e,steps:Y,stepNumber:Y.length,messages:vn,experimental_context:E}),Xt=ua((we=gt?.model)!=null?we:e),xo={provider:Xt.provider,modelId:Xt.modelId},Gi=await z0({prompt:{system:(qt=gt?.system)!=null?qt:tt.system,messages:(Ee=gt?.messages)!=null?Ee:vn},supportedUrls:await Xt.supportedUrls,download:U}),Rs=(st=gt?.activeTools)!=null?st:_,{toolChoice:Eo,tools:Ps}=await Z0({tools:h,toolChoice:(ut=gt?.toolChoice)!=null?ut:g,activeTools:Rs});E=(Nt=gt?.experimental_context)!=null?Nt:E;const cd=(Lt=gt?.messages)!=null?Lt:vn,Wi=(Ne=gt?.system)!=null?Ne:tt.system,Oe=pa(C,gt?.providerOptions);await wr({event:{stepNumber:Y.length,model:xo,system:Wi,messages:cd,tools:h,toolChoice:Eo,activeTools:Rs,steps:[...Y],providerOptions:Oe,timeout:S,headers:r,stopWhen:j,output:m,abortSignal:O,include:F,...Le,experimental_context:E},callbacks:[Z,M.onStepStart]});const{result:{stream:Bt,response:$o,request:Xr},doStreamSpan:jr,startTimestampMs:Ms}=await $r(()=>ts({name:"ai.streamText.doStream",attributes:ur({telemetry:t,attributes:{...es({operationId:"ai.streamText.doStream",telemetry:t}),...hr,"ai.model.provider":Xt.provider,"ai.model.id":Xt.modelId,"ai.prompt.messages":{input:()=>X0(Gi)},"ai.prompt.tools":{input:()=>Ps?.map(ke=>JSON.stringify(ke))},"ai.prompt.toolChoice":{input:()=>Eo!=null?JSON.stringify(Eo):void 0},"gen_ai.system":Xt.provider,"gen_ai.request.model":Xt.modelId,"gen_ai.request.frequency_penalty":Je.frequencyPenalty,"gen_ai.request.max_tokens":Je.maxOutputTokens,"gen_ai.request.presence_penalty":Je.presencePenalty,"gen_ai.request.stop_sequences":Je.stopSequences,"gen_ai.request.temperature":Je.temperature,"gen_ai.request.top_k":Je.topK,"gen_ai.request.top_p":Je.topP}}),tracer:Yt,endWhenDone:!1,fn:async ke=>({startTimestampMs:I(),doStreamSpan:ke,result:await Xt.doStream({...Je,tools:Ps,toolChoice:Eo,responseFormat:await m?.responseFormat,prompt:Gi,providerOptions:Oe,abortSignal:s,headers:r,includeRawChunks:yn})})})),Ki=G5({tools:h,generatorStream:Bt,tracer:Yt,telemetry:t,system:u,messages:vn,repairToolCall:w,abortSignal:s,experimental_context:E,generateId:R,stepNumber:Y.length,model:xo,onToolCallStart:[ne,M.onToolCallStart],onToolCallFinish:[D,M.onToolCallFinish]}),Yi=(Qt=F?.requestBody)==null||Qt?Xr??{}:{...Xr,body:void 0},wn=[],bn=[];let We;const Dr={};let kn="other",Ro,jt=ec(),pv,fv=!0,Ur={id:R(),timestamp:new Date,modelId:K.modelId},c$="";$.addStream(Ki.pipeThrough(new TransformStream({async transform(ke,It){var Ns,Os,As,qs,Ls;if(So(),ke.type==="stream-start"){We=ke.warnings;return}if(fv){const kt=I()-Ms;fv=!1,jr.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":kt}),jr.setAttributes({"ai.response.msToFirstChunk":kt}),It.enqueue({type:"start-step",request:Yi,warnings:We??[]})}const js=ke.type;switch(js){case"tool-approval-request":case"text-start":case"text-end":{It.enqueue(ke);break}case"text-delta":{ke.delta.length>0&&(It.enqueue({type:"text-delta",id:ke.id,text:ke.delta,providerMetadata:ke.providerMetadata}),c$+=ke.delta);break}case"reasoning-start":case"reasoning-end":{It.enqueue(ke);break}case"reasoning-delta":{It.enqueue({type:"reasoning-delta",id:ke.id,text:ke.delta,providerMetadata:ke.providerMetadata});break}case"tool-call":{It.enqueue(ke),wn.push(ke);break}case"tool-result":{It.enqueue(ke),ke.preliminary||bn.push(ke);break}case"tool-error":{It.enqueue(ke),bn.push(ke);break}case"response-metadata":{Ur={id:(Ns=ke.id)!=null?Ns:Ur.id,timestamp:(Os=ke.timestamp)!=null?Os:Ur.timestamp,modelId:(As=ke.modelId)!=null?As:Ur.modelId};break}case"finish":{jt=ke.usage,kn=ke.finishReason,Ro=ke.rawFinishReason,pv=ke.providerMetadata;const kt=I()-Ms;jr.addEvent("ai.stream.finish"),jr.setAttributes({"ai.response.msToFinish":kt,"ai.response.avgOutputTokensPerSecond":1e3*((qs=jt.outputTokens)!=null?qs:0)/kt});break}case"file":{It.enqueue(ke);break}case"source":{It.enqueue(ke);break}case"tool-input-start":{Dr[ke.id]=ke.toolName;const kt=h?.[ke.toolName];kt?.onInputStart!=null&&await kt.onInputStart({toolCallId:ke.id,messages:vn,abortSignal:s,experimental_context:E}),It.enqueue({...ke,dynamic:(Ls=ke.dynamic)!=null?Ls:kt?.type==="dynamic",title:kt?.title});break}case"tool-input-end":{delete Dr[ke.id],It.enqueue(ke);break}case"tool-input-delta":{const kt=Dr[ke.id],Po=h?.[kt];Po?.onInputDelta!=null&&await Po.onInputDelta({inputTextDelta:ke.delta,toolCallId:ke.id,messages:vn,abortSignal:s,experimental_context:E}),It.enqueue(ke);break}case"error":{It.enqueue(ke),kn="error";break}case"raw":{yn&&It.enqueue(ke);break}default:{const kt=js;throw new Error(`Unknown chunk type: ${kt}`)}}},async flush(ke){var It,Ns,Os,As,qs,Ls,js;const kt=wn.length>0?JSON.stringify(wn):void 0;try{jr.setAttributes(await ur({telemetry:t,attributes:{"ai.response.finishReason":kn,"ai.response.toolCalls":{output:()=>kt},"ai.response.id":Ur.id,"ai.response.model":Ur.modelId,"ai.response.timestamp":Ur.timestamp.toISOString(),"ai.usage.inputTokens":jt.inputTokens,"ai.usage.inputTokenDetails.noCacheTokens":(It=jt.inputTokenDetails)==null?void 0:It.noCacheTokens,"ai.usage.inputTokenDetails.cacheReadTokens":(Ns=jt.inputTokenDetails)==null?void 0:Ns.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":(Os=jt.inputTokenDetails)==null?void 0:Os.cacheWriteTokens,"ai.usage.outputTokens":jt.outputTokens,"ai.usage.outputTokenDetails.textTokens":(As=jt.outputTokenDetails)==null?void 0:As.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":(qs=jt.outputTokenDetails)==null?void 0:qs.reasoningTokens,"ai.usage.totalTokens":jt.totalTokens,"ai.usage.reasoningTokens":(Ls=jt.outputTokenDetails)==null?void 0:Ls.reasoningTokens,"ai.usage.cachedInputTokens":(js=jt.inputTokenDetails)==null?void 0:js.cacheReadTokens,"gen_ai.response.finish_reasons":[kn],"gen_ai.response.id":Ur.id,"gen_ai.response.model":Ur.modelId,"gen_ai.usage.input_tokens":jt.inputTokens,"gen_ai.usage.output_tokens":jt.outputTokens}}))}catch{}ke.enqueue({type:"finish-step",finishReason:kn,rawFinishReason:Ro,usage:jt,providerMetadata:pv,response:{...Ur,headers:$o?.headers}});const Po=tm(ft,jt);await H.promise;const ud=Y[Y.length-1];try{jr.setAttributes(await ur({telemetry:t,attributes:{"ai.response.text":{output:()=>ud.text},"ai.response.reasoning":{output:()=>ud.reasoningText},"ai.response.providerMetadata":JSON.stringify(ud.providerMetadata)}}))}catch{}finally{jr.end()}const hv=wn.filter(Ot=>Ot.providerExecuted!==!0),u$=bn.filter(Ot=>Ot.providerExecuted!==!0);for(const Ot of wn){if(Ot.providerExecuted!==!0)continue;const dd=h?.[Ot.toolName];dd?.type==="provider"&&dd.supportsDeferredResults&&(bn.some(pd=>(pd.type==="tool-result"||pd.type==="tool-error")&&pd.toolCallId===Ot.toolCallId)||ue.set(Ot.toolCallId,{toolName:Ot.toolName}))}for(const Ot of bn)(Ot.type==="tool-result"||Ot.type==="tool-error")&&ue.delete(Ot.toolCallId);if(Ji(),Io(),(hv.length>0&&u$.length===hv.length||ue.size>0)&&!await fm({stopConditions:y,steps:Y})){yt.push(...await nc({content:Y[Y.length-1].content,tools:h}));try{await ie({currentStep:Se+1,responseMessages:yt,usage:Po})}catch(Ot){ke.enqueue({type:"error",error:Ot}),$.closeStream()}}else ke.enqueue({type:"finish",finishReason:kn,rawFinishReason:Ro,totalUsage:Po}),$.closeStream()}})))}finally{Ji(),Io()}}await ie({currentStep:0,responseMessages:sr,usage:ec()})}}).catch(Re=>{$.addStream(new ReadableStream({start(tt){tt.enqueue({type:"error",error:Re}),tt.close()}})),$.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}get rawFinishReason(){return this.consumeStream(),this._rawFinishReason.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 H5({stream:this.fullStream,onError:e?.onError})}catch(r){(t=e?.onError)==null||t.call(e,r)}}get experimental_partialOutputStream(){return this.partialOutputStream}get partialOutputStream(){return ns(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:e},t){e!=null&&t.enqueue(e)}})))}get elementStream(){var e,t,r;const n=(e=this.outputSpecification)==null?void 0:e.createElementStreamTransform();if(n==null)throw new Pr({functionality:`element streams in ${(r=(t=this.outputSpecification)==null?void 0:t.name)!=null?r:"text"} mode`});return ns(this.teeStream().pipeThrough(n))}get output(){return this.finalStep.then(e=>{var t;return((t=this.outputSpecification)!=null?t:ha()).parseCompleteOutput({text:e.text},{response:e.response,usage:e.usage,finishReason:e.finishReason})})}toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:o=!0,sendSources:s=!1,sendStart:i=!0,sendFinish:a=!0,onError:l=Tn}={}){const c=t!=null?D5({originalMessages:e,responseMessageId:t}):void 0,u=p=>{var h;const g=(h=this.tools)==null?void 0:h[p.toolName];return g==null?p.dynamic:g?.type==="dynamic"?!0:void 0},f=this.fullStream.pipeThrough(new TransformStream({transform:async(p,h)=>{const g=n?.({part:p}),v=p.type;switch(v){case"text-start":{h.enqueue({type:"text-start",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"text-delta":{h.enqueue({type:"text-delta",id:p.id,delta:p.text,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"text-end":{h.enqueue({type:"text-end",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-start":{h.enqueue({type:"reasoning-start",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-delta":{o&&h.enqueue({type:"reasoning-delta",id:p.id,delta:p.text,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-end":{h.enqueue({type:"reasoning-end",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"file":{h.enqueue({type:"file",mediaType:p.file.mediaType,url:`data:${p.file.mediaType};base64,${p.file.base64}`,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"source":{s&&p.sourceType==="url"&&h.enqueue({type:"source-url",sourceId:p.id,url:p.url,title:p.title,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}}),s&&p.sourceType==="document"&&h.enqueue({type:"source-document",sourceId:p.id,mediaType:p.mediaType,title:p.title,filename:p.filename,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"tool-input-start":{const _=u(p);h.enqueue({type:"tool-input-start",toolCallId:p.id,toolName:p.toolName,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},..._!=null?{dynamic:_}:{},...p.title!=null?{title:p.title}:{}});break}case"tool-input-delta":{h.enqueue({type:"tool-input-delta",toolCallId:p.id,inputTextDelta:p.delta});break}case"tool-call":{const _=u(p);p.invalid?h.enqueue({type:"tool-input-error",toolCallId:p.toolCallId,toolName:p.toolName,input:p.input,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},..._!=null?{dynamic:_}:{},errorText:l(p.error),...p.title!=null?{title:p.title}:{}}):h.enqueue({type:"tool-input-available",toolCallId:p.toolCallId,toolName:p.toolName,input:p.input,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},..._!=null?{dynamic:_}:{},...p.title!=null?{title:p.title}:{}});break}case"tool-approval-request":{h.enqueue({type:"tool-approval-request",approvalId:p.approvalId,toolCallId:p.toolCall.toolCallId});break}case"tool-result":{const _=u(p);h.enqueue({type:"tool-output-available",toolCallId:p.toolCallId,output:p.output,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...p.preliminary!=null?{preliminary:p.preliminary}:{},..._!=null?{dynamic:_}:{}});break}case"tool-error":{const _=u(p);h.enqueue({type:"tool-output-error",toolCallId:p.toolCallId,errorText:p.providerExecuted?typeof p.error=="string"?p.error:JSON.stringify(p.error):l(p.error),...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},..._!=null?{dynamic:_}:{}});break}case"tool-output-denied":{h.enqueue({type:"tool-output-denied",toolCallId:p.toolCallId});break}case"error":{h.enqueue({type:"error",errorText:l(p.error)});break}case"start-step":{h.enqueue({type:"start-step"});break}case"finish-step":{h.enqueue({type:"finish-step"});break}case"start":{i&&h.enqueue({type:"start",...g!=null?{messageMetadata:g}:{},...c!=null?{messageId:c}:{}});break}case"finish":{a&&h.enqueue({type:"finish",finishReason:p.finishReason,...g!=null?{messageMetadata:g}:{}});break}case"abort":{h.enqueue(p);break}case"tool-input-end":break;case"raw":break;default:{const _=v;throw new Error(`Unknown chunk type: ${_}`)}}g!=null&&v!=="start"&&v!=="finish"&&h.enqueue({type:"message-metadata",messageMetadata:g})}}));return ns(Z5({stream:f,messageId:c??t?.(),originalMessages:e,onFinish:r,onError:l}))}pipeUIMessageStreamToResponse(e,{originalMessages:t,generateMessageId:r,onFinish:n,messageMetadata:o,sendReasoning:s,sendSources:i,sendFinish:a,sendStart:l,onError:c,...u}={}){B5({response:e,stream:this.toUIMessageStream({originalMessages:t,generateMessageId:r,onFinish:n,messageMetadata:o,sendReasoning:s,sendSources:i,sendFinish:a,sendStart:l,onError:c}),...u})}pipeTextStreamToResponse(e,t){L5({response:e,textStream:this.textStream,...t})}toUIMessageStreamResponse({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:o,sendSources:s,sendFinish:i,sendStart:a,onError:l,...c}={}){return j5({stream:this.toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:o,sendSources:s,sendFinish:i,sendStart:a,onError:l}),...c})}toTextStreamResponse(e){return q5({textStream:this.textStream,...e})}};Zo({prefix:"aiobj",size:24}),Zo({prefix:"aiobj",size:24});let ac;ac=globalThis.crypto;async function Q5(e){return(await ac).getRandomValues(new Uint8Array(e))}async function X5(e){const t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length;let n="";for(;n.length<e;){const o=await Q5(e-n.length);for(const s of o)s<r&&(n+=t[s%t.length])}return n}async function eT(e){return await X5(e)}async function tT(e){const t=await(await ac).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function Cm(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;const t=await eT(e),r=await tT(t);return{code_verifier:t,code_challenge:r}}var rT="AI_MCPClientError",Sm=`vercel.ai.error.${rT}`,nT=Symbol.for(Sm),Im,xm,Fe=class extends(xm=be,Im=nT,xm){constructor({name:e="MCPClientError",message:t,cause:r,data:n,code:o}){super({name:e,message:t,cause:r}),this[Im]=!0,this.data=n,this.code=o}static isInstance(e){return be.hasMarker(e,Sm)}},co="2025-11-25",oT=[co,"2025-06-18","2025-03-26","2024-11-05"],sT=de(he(d(),Ie())),aT=lt({name:d(),version:d(),title:de(d())}),ga=lt({_meta:de(k({}).loose())}),Zr=ga,Em=k({method:d(),params:de(ga)}),$m=k({applyDefaults:de(ge())}).loose(),iT=lt({experimental:de(k({}).loose()),logging:de(k({}).loose()),prompts:de(lt({listChanged:de(ge())})),resources:de(lt({subscribe:de(ge()),listChanged:de(ge())})),tools:de(lt({listChanged:de(ge())})),elicitation:de($m)});k({elicitation:de($m)}).loose();var lT=Zr.extend({protocolVersion:d(),capabilities:iT,serverInfo:aT,instructions:de(d())}),ic=Zr.extend({nextCursor:de(d())}),cT=k({name:d(),title:de(d()),description:de(d()),inputSchema:k({type:P("object"),properties:de(k({}).loose())}).loose(),outputSchema:de(k({}).loose()),annotations:de(k({title:de(d())}).loose()),_meta:sT}).loose(),uT=ic.extend({tools:q(cT)}),Rm=k({type:P("text"),text:d()}).loose(),Pm=k({type:P("image"),data:Wp(),mimeType:d()}).loose(),dT=k({uri:d(),name:d(),title:de(d()),description:de(d()),mimeType:de(d()),size:de(N())}).loose(),pT=ic.extend({resources:q(dT)}),Mm=k({uri:d(),name:de(d()),title:de(d()),mimeType:de(d())}).loose(),Nm=Mm.extend({text:d()}),Om=Mm.extend({blob:Wp()}),Am=k({type:P("resource"),resource:ae([Nm,Om])}).loose(),fT=Zr.extend({content:q(ae([Rm,Pm,Am])),structuredContent:de(Ie()),isError:ge().default(!1).optional()}).or(Zr.extend({toolResult:Ie()})),hT=k({uriTemplate:d(),name:d(),title:de(d()),description:de(d()),mimeType:de(d())}).loose(),mT=Zr.extend({resourceTemplates:q(hT)}),gT=Zr.extend({contents:q(ae([Nm,Om]))}),_T=k({name:d(),description:de(d()),required:de(ge())}).loose(),yT=k({name:d(),title:de(d()),description:de(d()),arguments:de(q(_T))}).loose(),vT=ic.extend({prompts:q(yT)}),wT=k({role:ae([P("user"),P("assistant")]),content:ae([Rm,Pm,Am])}).loose(),bT=Zr.extend({description:de(d()),messages:q(wT)}),kT=ga.extend({message:d(),requestedSchema:Ie()}),qm=Em.extend({method:P("elicitation/create"),params:kT}),TT=Zr.extend({action:ae([P("accept"),P("decline"),P("cancel")]),content:de(he(d(),Ie()))}),_a="2.0",CT=k({jsonrpc:P(_a),id:ae([d(),N().int()])}).merge(Em).strict(),ST=k({jsonrpc:P(_a),id:ae([d(),N().int()]),result:Zr}).strict(),IT=k({jsonrpc:P(_a),id:ae([d(),N().int()]),error:k({code:N().int(),message:d(),data:de(Ie())})}).strict(),xT=k({jsonrpc:P(_a)}).merge(k({method:d(),params:de(ga)})).strict(),os=ae([CT,xT,ST,IT]),Lm=typeof __PACKAGE_VERSION__<"u"?__PACKAGE_VERSION__:"0.0.0-test",jm=k({access_token:d(),id_token:d().optional(),token_type:d(),expires_in:N().optional(),scope:d().optional(),refresh_token:d().optional()}).strip(),Wt=d().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:sf.custom,message:"URL must be parseable",fatal:!0}),op}).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"}),ET=k({resource:d().url(),authorization_servers:q(Wt).optional(),jwks_uri:d().url().optional(),scopes_supported:q(d()).optional(),bearer_methods_supported:q(d()).optional(),resource_signing_alg_values_supported:q(d()).optional(),resource_name:d().optional(),resource_documentation:d().optional(),resource_policy_uri:d().url().optional(),resource_tos_uri:d().url().optional(),tls_client_certificate_bound_access_tokens:ge().optional(),authorization_details_types_supported:q(d()).optional(),dpop_signing_alg_values_supported:q(d()).optional(),dpop_bound_access_tokens_required:ge().optional()}).passthrough(),Dm=k({issuer:d(),authorization_endpoint:Wt,token_endpoint:Wt,registration_endpoint:Wt.optional(),scopes_supported:q(d()).optional(),response_types_supported:q(d()),grant_types_supported:q(d()).optional(),code_challenge_methods_supported:q(d()),token_endpoint_auth_methods_supported:q(d()).optional(),token_endpoint_auth_signing_alg_values_supported:q(d()).optional()}).passthrough(),$T=k({issuer:d(),authorization_endpoint:Wt,token_endpoint:Wt,userinfo_endpoint:Wt.optional(),jwks_uri:Wt,registration_endpoint:Wt.optional(),scopes_supported:q(d()).optional(),response_types_supported:q(d()),grant_types_supported:q(d()).optional(),subject_types_supported:q(d()),id_token_signing_alg_values_supported:q(d()),claims_supported:q(d()).optional(),token_endpoint_auth_methods_supported:q(d()).optional()}).passthrough(),RT=$T.merge(Dm.pick({code_challenge_methods_supported:!0})),PT=k({client_id:d(),client_secret:d().optional(),client_id_issued_at:N().optional(),client_secret_expires_at:N().optional()}).strip(),MT=k({redirect_uris:q(Wt),token_endpoint_auth_method:d().optional(),grant_types:q(d()).optional(),response_types:q(d()).optional(),client_name:d().optional(),client_uri:Wt.optional(),logo_uri:Wt.optional(),scope:d().optional(),contacts:q(d()).optional(),tos_uri:Wt.optional(),policy_uri:d().optional(),jwks_uri:Wt.optional(),jwks:ht().optional(),software_id:d().optional(),software_version:d().optional(),software_statement:d().optional()}).strip(),NT=k({error:d(),error_description:d().optional(),error_uri:d().optional()}),OT=MT.merge(PT),AT="AI_MCPClientOAuthError",Um=`vercel.ai.error.${AT}`,qT=Symbol.for(Um),zm,Fm,ss=class extends(Fm=be,zm=qT,Fm){constructor({name:e="MCPClientOAuthError",message:t,cause:r}){super({name:e,message:t,cause:r}),this[zm]=!0}static isInstance(e){return be.hasMarker(e,Um)}},uo=class extends ss{};uo.errorCode="server_error";var ya=class extends ss{};ya.errorCode="invalid_client";var va=class extends ss{};va.errorCode="invalid_grant";var wa=class extends ss{};wa.errorCode="unauthorized_client";var LT={[uo.errorCode]:uo,[ya.errorCode]:ya,[va.errorCode]:va,[wa.errorCode]:wa};function jT(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function lc(e){const t=e.href;return e.pathname==="/"&&t.endsWith("/")?t.slice(0,-1):t}function DT({requestedResource:e,configuredResource:t}){const r=typeof e=="string"?new URL(e):new URL(e.href),n=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;const o=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return o.startsWith(s)}var ba=class extends Error{constructor(t="Unauthorized"){super(t),this.name="UnauthorizedError"}};function ka(e){var t;const r=(t=e.headers.get("www-authenticate"))!=null?t:e.headers.get("WWW-Authenticate");if(!r)return;const[n,o]=r.split(" ");if(n.toLowerCase()!=="bearer"||!o)return;const s=/resource_metadata="([^"]*)"/,i=r.match(s);if(i)try{return new URL(i[1])}catch{return}}function UT(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function cc(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?cc(e,void 0,r):void 0;throw n}}async function Vm(e,t,r=fetch){return await cc(e,{"MCP-Protocol-Version":t},r)}function zT(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function FT(e,t,r,n){var o,s;const i=new URL(e),a=(o=n?.protocolVersion)!=null?o:co;let l;if(n?.metadataUrl)l=new URL(n.metadataUrl);else{const u=UT(t,i.pathname);l=new URL(u,(s=n?.metadataServerUrl)!=null?s:i),l.search=i.search}let c=await Vm(l,a,r);if(!n?.metadataUrl&&zT(c,i.pathname)){const u=new URL(`/.well-known/${t}`,i);c=await Vm(u,a,r)}return c}async function VT(e,t,r=fetch){const n=await FT(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!n||n.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return ET.parse(await n.json())}function ZT(e){const t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),n;let o=t.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,t.origin),type:"oauth"}),n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${o}`,t.origin),type:"oidc"}),n.push({url:new URL(`${o}/.well-known/openid-configuration`,t.origin),type:"oidc"}),n}async function BT(e,{fetchFn:t=fetch,protocolVersion:r=co}={}){var n;const o={"MCP-Protocol-Version":r},s=ZT(e);for(const{url:i,type:a}of s){const l=await cc(i,o,t);if(l){if(!l.ok){if(l.status>=400&&l.status<500)continue;throw new Error(`HTTP ${l.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${i}`)}if(a==="oauth")return Dm.parse(await l.json());{const c=RT.parse(await l.json());if(!((n=c.code_challenge_methods_supported)!=null&&n.includes("S256")))throw new Error(`Incompatible OIDC provider at ${i}: does not support S256 code challenge method required by MCP specification`);return c}}}}async function HT(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:o,state:s,resource:i}){const a="code",l="S256";let c;if(t){if(c=new URL(t.authorization_endpoint),!t.response_types_supported.includes(a))throw new Error(`Incompatible auth server: does not support response type ${a}`);if(!t.code_challenge_methods_supported||!t.code_challenge_methods_supported.includes(l))throw new Error(`Incompatible auth server: does not support code challenge method ${l}`)}else c=new URL("/authorize",e);const u=await Cm(),f=u.code_verifier,p=u.code_challenge;return c.searchParams.set("response_type",a),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",p),c.searchParams.set("code_challenge_method",l),c.searchParams.set("redirect_uri",String(n)),s&&c.searchParams.set("state",s),o&&c.searchParams.set("scope",o),o?.includes("offline_access")&&c.searchParams.append("prompt","consent"),i&&c.searchParams.set("resource",lc(i)),{authorizationUrl:c,codeVerifier:f}}function Zm(e,t){const r=e.client_secret!==void 0;return t.length===0?r?"client_secret_post":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}function Bm(e,t,r,n){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":JT(o,s,r);return;case"client_secret_post":GT(o,s,n);return;case"none":WT(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function JT(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const n=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${n}`)}function GT(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function WT(e,t){t.set("client_id",e)}async function uc(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=NT.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:i}=n,a=LT[o]||uo;return new a({message:s||"",cause:i})}catch(n){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new uo({message:o})}}async function KT(e,{metadata:t,clientInformation:r,authorizationCode:n,codeVerifier:o,redirectUri:s,resource:i,addClientAuthentication:a,fetchFn:l}){var c;const u="authorization_code",f=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e);if(t?.grant_types_supported&&!t.grant_types_supported.includes(u))throw new Error(`Incompatible auth server: does not support grant type ${u}`);const p=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),h=new URLSearchParams({grant_type:u,code:n,code_verifier:o,redirect_uri:String(s)});if(a)a(p,h,e,t);else{const v=(c=t?.token_endpoint_auth_methods_supported)!=null?c:[],_=Zm(r,v);Bm(_,r,p,h)}i&&h.set("resource",lc(i));const g=await(l??fetch)(f,{method:"POST",headers:p,body:h});if(!g.ok)throw await uc(g);return jm.parse(await g.json())}async function YT(e,{metadata:t,clientInformation:r,refreshToken:n,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",Accept:"application/json"}),f=new URLSearchParams({grant_type:l,refresh_token:n});if(s)s(u,f,e,t);else{const h=(a=t?.token_endpoint_auth_methods_supported)!=null?a:[],g=Zm(r,h);Bm(g,r,u,f)}o&&f.set("resource",lc(o));const p=await(i??fetch)(c,{method:"POST",headers:u,body:f});if(!p.ok)throw await uc(p);return jm.parse({refresh_token:n,...await p.json()})}async function QT(e,{metadata:t,clientMetadata:r,fetchFn:n}){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(n??fetch)(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok)throw await uc(s);return OT.parse(await s.json())}async function Ta(e,t){var r,n;try{return await dc(e,t)}catch(o){if(o instanceof ya||o instanceof wa)return await((r=e.invalidateCredentials)==null?void 0:r.call(e,"all")),await dc(e,t);if(o instanceof va)return await((n=e.invalidateCredentials)==null?void 0:n.call(e,"tokens")),await dc(e,t);throw o}}async function XT(e,t,r){const n=jT(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!DT({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}async function dc(e,{serverUrl:t,authorizationCode:r,callbackState:n,scope:o,resourceMetadataUrl:s,fetchFn:i}){let a,l;try{a=await VT(t,{resourceMetadataUrl:s},i),a.authorization_servers&&a.authorization_servers.length>0&&(l=a.authorization_servers[0])}catch{}l||(l=t);const c=await XT(t,e,a),u=await BT(l,{fetchFn:i});let f=await Promise.resolve(e.clientInformation());if(!f){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const _=await QT(l,{metadata:u,clientMetadata:e.clientMetadata,fetchFn:i});await e.saveClientInformation(_),f=_}if(r!==void 0){if(e.storedState){const y=await e.storedState();if(y!==void 0&&y!==n)throw new Error("OAuth state parameter mismatch - possible CSRF attack")}const _=await e.codeVerifier(),w=await KT(l,{metadata:u,clientInformation:f,authorizationCode:r,codeVerifier:_,redirectUri:e.redirectUrl,resource:c,addClientAuthentication:e.addClientAuthentication,fetchFn:i});return await e.saveTokens(w),"AUTHORIZED"}const p=await e.tokens();if(p?.refresh_token)try{const _=await YT(l,{metadata:u,clientInformation:f,refreshToken:p.refresh_token,resource:c,addClientAuthentication:e.addClientAuthentication,fetchFn:i});return await e.saveTokens(_),"AUTHORIZED"}catch(_){if(!(!(_ instanceof ss)||_ instanceof uo))throw _}const h=e.state?await e.state():void 0;h&&e.saveState&&await e.saveState(h);const{authorizationUrl:g,codeVerifier:v}=await HT(l,{metadata:u,clientInformation:f,state:h,redirectUrl:e.redirectUrl,scope:o||e.clientMetadata.scope,resource:c});return await e.saveCodeVerifier(v),await e.redirectToAuthorization(g),"REDIRECT"}var eC=class{constructor({url:e,headers:t,authProvider:r,redirect:n="follow",fetch:o}){this.connected=!1,this.url=new URL(e),this.headers=t,this.authProvider=r,this.redirectMode=n,this.fetchFn=o??globalThis.fetch}async commonHeaders(e){const t={...this.headers,...e,"mcp-protocol-version":co};if(this.authProvider){const r=await this.authProvider.tokens();r?.access_token&&(t.Authorization=`Bearer ${r.access_token}`)}return cn(t,`ai-sdk/${Lm}`,Bo())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;const r=async(n=!1)=>{var o,s,i,a,l;try{const c=await this.commonHeaders({Accept:"text/event-stream"}),u=await this.fetchFn(this.url.href,{headers:c,signal:(o=this.abortController)==null?void 0:o.signal,redirect:this.redirectMode});if(u.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=ka(u);try{if(await Ta(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!=="AUTHORIZED"){const v=new ba;return(s=this.onerror)==null||s.call(this,v),t(v)}}catch(g){return(i=this.onerror)==null||i.call(this,g),t(g)}return r(!0)}if(!u.ok||!u.body){let g=`MCP SSE Transport Error: ${u.status} ${u.statusText}`;u.status===405&&(g+=". This server does not support SSE transport. Try using `http` transport instead");const v=new Fe({message:g});return(a=this.onerror)==null||a.call(this,v),t(v)}const p=u.body.pipeThrough(new TextDecoderStream).pipeThrough(new ro).getReader(),h=async()=>{var g,v,_;try{for(;;){const{done:w,value:y}=await p.read();if(w){if(this.connected)throw this.connected=!1,new Fe({message:"MCP SSE Transport Error: Connection closed unexpectedly"});return}const{event:m,data:C}=y;if(m==="endpoint"){if(this.endpoint=new URL(C,this.url),this.endpoint.origin!==this.url.origin)throw new Fe({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 b=os.parse(JSON.parse(C));(g=this.onmessage)==null||g.call(this,b)}catch(b){const T=new Fe({message:"MCP SSE Transport Error: Failed to parse message",cause:b});(v=this.onerror)==null||v.call(this,T)}}}catch(w){if(w instanceof Error&&w.name==="AbortError")return;(_=this.onerror)==null||_.call(this,w),t(w)}};this.sseConnection={close:()=>p.cancel()},h()}catch(c){if(c instanceof Error&&c.name==="AbortError")return;(l=this.onerror)==null||l.call(this,c),t(c)}};r()})}async close(){var e,t,r;this.connected=!1,(e=this.sseConnection)==null||e.close(),(t=this.abortController)==null||t.abort(),(r=this.onclose)==null||r.call(this)}async send(e){if(!this.endpoint||!this.connected)throw new Fe({message:"MCP SSE Transport Error: Not connected"});const t=this.endpoint,r=async(n=!1)=>{var o,s,i,a,l;try{const u={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json"}),body:JSON.stringify(e),signal:(o=this.abortController)==null?void 0:o.signal,redirect:this.redirectMode},f=await this.fetchFn(t.href,u);if(f.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=ka(f);try{if(await Ta(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!=="AUTHORIZED"){const h=new ba;(s=this.onerror)==null||s.call(this,h);return}}catch(p){(i=this.onerror)==null||i.call(this,p);return}return r(!0)}if(!f.ok){const p=await f.text().catch(()=>null),h=new Fe({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${f.status}): ${p}`});(a=this.onerror)==null||a.call(this,h);return}}catch(c){(l=this.onerror)==null||l.call(this,c);return}};await r()}},tC=class{constructor({url:e,headers:t,authProvider:r,redirect:n="follow",fetch:o}){this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(e),this.headers=t,this.authProvider=r,this.redirectMode=n,this.fetchFn=o??globalThis.fetch}async commonHeaders(e){const t={...this.headers,...e,"mcp-protocol-version":co};if(this.sessionId&&(t["mcp-session-id"]=this.sessionId),this.authProvider){const r=await this.authProvider.tokens();r?.access_token&&(t.Authorization=`Bearer ${r.access_token}`)}return cn(t,`ai-sdk/${Lm}`,Bo())}async start(){if(this.abortController)throw new Fe({message:"MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically."});this.abortController=new AbortController,this.openInboundSse()}async close(){var e,t,r;(e=this.inboundSseConnection)==null||e.close();try{if(this.sessionId&&this.abortController&&!this.abortController.signal.aborted){const n=await this.commonHeaders({});await this.fetchFn(this.url.href,{method:"DELETE",headers:n,signal:this.abortController.signal,redirect:this.redirectMode}).catch(()=>{})}}catch{}(t=this.abortController)==null||t.abort(),(r=this.onclose)==null||r.call(this)}async send(e){const t=async(r=!1)=>{var n,o,s,i,a,l,c;try{const f={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),body:JSON.stringify(e),signal:(n=this.abortController)==null?void 0:n.signal,redirect:this.redirectMode},p=await this.fetchFn(this.url.href,f),h=p.headers.get("mcp-session-id");if(h&&(this.sessionId=h),p.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=ka(p);try{if(await Ta(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!=="AUTHORIZED")throw new ba}catch(w){throw(o=this.onerror)==null||o.call(this,w),w}return t(!0)}if(p.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!p.ok){const w=await p.text().catch(()=>null);let y=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${p.status}): ${w}`;p.status===404&&(y+=". This server does not support HTTP transport. Try using `sse` transport instead");const m=new Fe({message:y});throw(s=this.onerror)==null||s.call(this,m),m}if(!("id"in e))return;const v=p.headers.get("content-type")||"";if(v.includes("application/json")){const w=await p.json(),y=Array.isArray(w)?w.map(m=>os.parse(m)):[os.parse(w)];for(const m of y)(i=this.onmessage)==null||i.call(this,m);return}if(v.includes("text/event-stream")){if(!p.body){const C=new Fe({message:"MCP HTTP Transport Error: text/event-stream response without body"});throw(a=this.onerror)==null||a.call(this,C),C}const y=p.body.pipeThrough(new TextDecoderStream).pipeThrough(new ro).getReader();(async()=>{var C,b,T;try{for(;;){const{done:I,value:R}=await y.read();if(I)return;const{event:S,data:j}=R;if(S==="message")try{const O=os.parse(JSON.parse(j));(C=this.onmessage)==null||C.call(this,O)}catch(O){const L=new Fe({message:"MCP HTTP Transport Error: Failed to parse message",cause:O});(b=this.onerror)==null||b.call(this,L)}}}catch(I){if(I instanceof Error&&I.name==="AbortError")return;(T=this.onerror)==null||T.call(this,I)}})();return}const _=new Fe({message:`MCP HTTP Transport Error: Unexpected content type: ${v}`});throw(l=this.onerror)==null||l.call(this,_),_}catch(u){throw(c=this.onerror)==null||c.call(this,u),u}};await t()}getNextReconnectionDelay(e){const{initialReconnectionDelay:t,reconnectionDelayGrowFactor:r,maxReconnectionDelay:n}=this.reconnectionOptions;return Math.min(t*Math.pow(r,e),n)}scheduleInboundSseReconnection(){var e;const{maxRetries:t}=this.reconnectionOptions;if(t>0&&this.inboundReconnectAttempts>=t){(e=this.onerror)==null||e.call(this,new Fe({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${t}) exceeded.`}));return}const r=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(async()=>{var n;(n=this.abortController)!=null&&n.signal.aborted||await this.openInboundSse(!1,this.lastInboundEventId)},r)}async openInboundSse(e=!1,t){var r,n,o,s,i,a;try{const l=await this.commonHeaders({Accept:"text/event-stream"});t&&(l["last-event-id"]=t);const c=await this.fetchFn(this.url.href,{method:"GET",headers:l,signal:(r=this.abortController)==null?void 0:r.signal,redirect:this.redirectMode}),u=c.headers.get("mcp-session-id");if(u&&(this.sessionId=u),c.status===401&&this.authProvider&&!e){this.resourceMetadataUrl=ka(c);try{if(await Ta(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!=="AUTHORIZED"){const v=new ba;(n=this.onerror)==null||n.call(this,v);return}}catch(g){(o=this.onerror)==null||o.call(this,g);return}return this.openInboundSse(!0,t)}if(c.status===405)return;if(!c.ok||!c.body){const g=new Fe({message:`MCP HTTP Transport Error: GET SSE failed: ${c.status} ${c.statusText}`});(s=this.onerror)==null||s.call(this,g);return}const p=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new ro).getReader(),h=async()=>{var g,v,_,w;try{for(;;){const{done:y,value:m}=await p.read();if(y)return;const{event:C,data:b,id:T}=m;if(T&&(this.lastInboundEventId=T),C==="message")try{const I=os.parse(JSON.parse(b));(g=this.onmessage)==null||g.call(this,I)}catch(I){const R=new Fe({message:"MCP HTTP Transport Error: Failed to parse message",cause:I});(v=this.onerror)==null||v.call(this,R)}}}catch(y){if(y instanceof Error&&y.name==="AbortError")return;(_=this.onerror)==null||_.call(this,y),(w=this.abortController)!=null&&w.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>p.cancel()},this.inboundReconnectAttempts=0,h()}catch(l){if(l instanceof Error&&l.name==="AbortError")return;(i=this.onerror)==null||i.call(this,l),(a=this.abortController)!=null&&a.signal.aborted||this.scheduleInboundSseReconnection()}}};function rC(e){switch(e.type){case"sse":return new eC(e);case"http":return new tC(e);default:throw new Fe({message:"Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface."})}}function nC(e){return"start"in e&&typeof e.start=="function"&&"send"in e&&typeof e.send=="function"&&"close"in e&&typeof e.close=="function"}var oC="1.0.0";function Hm({output:e}){const t=e;return!("content"in t)||!Array.isArray(t.content)?{type:"json",value:t}:{type:"content",value:t.content.map(n=>n.type==="text"&&"text"in n?{type:"text",text:n.text}:n.type==="image"&&"data"in n&&"mimeType"in n?{type:"image-data",data:n.data,mediaType:n.mimeType}:{type:"text",text:JSON.stringify(n)})}}async function sC(e){const t=new aC(e);return await t.init(),t}var aC=class{constructor({transport:e,name:t="ai-sdk-mcp-client",version:r=oC,onUncaughtError:n,capabilities:o}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this._serverInfo={name:"",version:""},this.isClosed=!0,this.onUncaughtError=n,this.clientCapabilities=o??{},nC(e)?this.transport=e:this.transport=rC(e),this.transport.onclose=()=>this.onClose(),this.transport.onerror=s=>this.onError(s),this.transport.onmessage=s=>{if("method"in s){"id"in s?this.onRequestMessage(s):this.onError(new Fe({message:"Unsupported message type"}));return}this.onResponse(s)},this.clientInfo={name:t,version:r}}get serverInfo(){return this._serverInfo}async init(){try{await this.transport.start(),this.isClosed=!1;const e=await this.request({request:{method:"initialize",params:{protocolVersion:co,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:lT});if(e===void 0)throw new Fe({message:"Server sent invalid initialize result"});if(!oT.includes(e.protocolVersion))throw new Fe({message:`Server's protocol version is not supported: ${e.protocolVersion}`});return this.serverCapabilities=e.capabilities,this._serverInfo=e.serverInfo,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 Fe({message:"Server does not support tools"});break;case"resources/list":case"resources/read":case"resources/templates/list":if(!this.serverCapabilities.resources)throw new Fe({message:"Server does not support resources"});break;case"prompts/list":case"prompts/get":if(!this.serverCapabilities.prompts)throw new Fe({message:"Server does not support prompts"});break;default:throw new Fe({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:r}){return new Promise((n,o)=>{if(this.isClosed)return o(new Fe({message:"Attempted to send a request from a closed client"}));this.assertCapability(e.method);const s=r?.signal;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?.aborted)return o(new Fe({message:"Request was aborted",cause:s.reason}));if(c instanceof Error)return o(c);try{const u=t.parse(c.result);n(u)}catch(u){const f=new Fe({message:"Failed to parse server response",cause:u});o(f)}}),this.transport.send(a).catch(c=>{l(),o(c)})})}async listTools({params:e,options:t}={}){return this.request({request:{method:"tools/list",params:e},resultSchema:uT,options:t})}async callTool({name:e,args:t,options:r}){try{return this.request({request:{method:"tools/call",params:{name:e,arguments:t}},resultSchema:fT,options:{signal:r?.abortSignal}})}catch(n){throw n}}async listResourcesInternal({params:e,options:t}={}){try{return this.request({request:{method:"resources/list",params:e},resultSchema:pT,options:t})}catch(r){throw r}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:"resources/read",params:{uri:e}},resultSchema:gT,options:t})}catch(r){throw r}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:"resources/templates/list"},resultSchema:mT,options:e})}catch(t){throw t}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:"prompts/list",params:e},resultSchema:vT,options:t})}catch(r){throw r}}async getPromptInternal({name:e,args:t,options:r}){try{return this.request({request:{method:"prompts/get",params:{name:e,arguments:t}},resultSchema:bT,options:r})}catch(n){throw n}}async notification(e){const t={...e,jsonrpc:"2.0"};await this.transport.send(t)}async tools({schemas:e="automatic"}={}){const t=await this.listTools();return this.toolsFromDefinitions(t,{schemas:e})}toolsFromDefinitions(e,{schemas:t="automatic"}={}){var r,n;const o={};for(const{name:s,title:i,description:a,inputSchema:l,annotations:c,_meta:u}of e.tools){const f=i??c?.title;if(t!=="automatic"&&!(s in t))continue;const p=this,h=t!=="automatic"?(r=t[s])==null?void 0:r.outputSchema:void 0,g=async(_,w)=>{var y;(y=w?.abortSignal)==null||y.throwIfAborted();const m=await p.callTool({name:s,args:_,options:w});return m.isError?m:h!=null?p.extractStructuredContent(m,h,s):m},v=t==="automatic"?Rl({description:a,title:f,inputSchema:Pn({...l,properties:(n=l.properties)!=null?n:{},additionalProperties:!1}),execute:g,toModelOutput:Hm}):{description:a,title:f,inputSchema:t[s].inputSchema,...h!=null?{outputSchema:h}:{},execute:g,toModelOutput:Hm};o[s]={...v,_meta:u}}return o}async extractStructuredContent(e,t,r){if("structuredContent"in e&&e.structuredContent!=null){const n=await ir({value:e.structuredContent,schema:Mn(t)});if(!n.success)throw new Fe({message:`Tool "${r}" returned structuredContent that does not match the expected outputSchema`,cause:n.error});return n.value}if("content"in e&&Array.isArray(e.content)){const n=e.content.find(o=>o.type==="text");if(n&&"text"in n){const o=await lr({text:n.text,schema:t});if(!o.success)throw new Fe({message:`Tool "${r}" returned content that does not match the expected outputSchema`,cause:o.error});return o.value}}throw new Fe({message:`Tool "${r}" did not return structuredContent or parseable text content`})}listResources({params:e,options:t}={}){return this.listResourcesInternal({params:e,options:t})}readResource({uri:e,options:t}){return this.readResourceInternal({uri:e,options:t})}listResourceTemplates({options:e}={}){return this.listResourceTemplatesInternal({options:e})}experimental_listPrompts({params:e,options:t}={}){return this.listPromptsInternal({params:e,options:t})}experimental_getPrompt({name:e,arguments:t,options:r}){return this.getPromptInternal({name:e,args:t,options:r})}onElicitationRequest(e,t){if(e!==qm)throw new Fe({message:"Unsupported request schema. Only ElicitationRequestSchema is supported."});this.elicitationRequestHandler=t}async onRequestMessage(e){try{if(e.method!=="elicitation/create"){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32601,message:`Unsupported request method: ${e.method}`}});return}if(!this.elicitationRequestHandler){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32601,message:"No elicitation handler registered on client"}});return}const t=qm.safeParse({method:e.method,params:e.params});if(!t.success){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32602,message:`Invalid elicitation request: ${t.error.message}`,data:t.error.issues}});return}try{const r=await this.elicitationRequestHandler(t.data),n=TT.parse(r);await this.transport.send({jsonrpc:"2.0",id:e.id,result:n})}catch(r){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32603,message:r instanceof Error?r.message:"Failed to handle elicitation request"}}),this.onError(r)}}catch(t){this.onError(t)}}onClose(){if(this.isClosed)return;this.isClosed=!0;const e=new Fe({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),r=this.responseHandlers.get(t);if(r===void 0)throw new Fe({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),r("result"in e?e:new Fe({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}};function Ca(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function Jm(e=fetch,t){return t?async(r,n)=>{const o={...t,...n,headers:n?.headers?{...Ca(t.headers),...Ca(n.headers)}:t.headers};return e(r,o)}:e}const Sa="2025-11-25",iC=[Sa,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Ln="io.modelcontextprotocol/related-task",Ia="2.0",Et=nf(e=>e!==null&&(typeof e=="object"||typeof e=="function")),Gm=ae([d(),N().int()]),Wm=d();lt({ttl:ae([N(),Do()]).optional(),pollInterval:N().optional()});const lC=k({ttl:N().optional()}),cC=k({taskId:d()}),pc=lt({progressToken:Gm.optional(),[Ln]:cC.optional()}),nr=k({_meta:pc.optional()}),as=nr.extend({task:lC.optional()}),uC=e=>as.safeParse(e).success,$t=k({method:d(),params:nr.loose().optional()}),dr=k({_meta:pc.optional()}),pr=k({method:d(),params:dr.loose().optional()}),Rt=lt({_meta:pc.optional()}),xa=ae([d(),N().int()]),Km=k({jsonrpc:P(Ia),id:xa,...$t.shape}).strict(),fc=e=>Km.safeParse(e).success,Ym=k({jsonrpc:P(Ia),...pr.shape}).strict(),dC=e=>Ym.safeParse(e).success,hc=k({jsonrpc:P(Ia),id:xa,result:Rt}).strict(),is=e=>hc.safeParse(e).success;var $e;(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"})($e||($e={}));const mc=k({jsonrpc:P(Ia),id:xa.optional(),error:k({code:N().int(),message:d(),data:Ie().optional()})}).strict(),pC=e=>mc.safeParse(e).success,jn=ae([Km,Ym,hc,mc]);ae([hc,mc]);const Dn=Rt.strict(),fC=dr.extend({requestId:xa.optional(),reason:d().optional()}),gc=pr.extend({method:P("notifications/cancelled"),params:fC}),hC=k({src:d(),mimeType:d().optional(),sizes:q(d()).optional(),theme:ce(["light","dark"]).optional()}),ls=k({icons:q(hC).optional()}),po=k({name:d(),title:d().optional()}),Qm=po.extend({...po.shape,...ls.shape,version:d(),websiteUrl:d().optional(),description:d().optional()}),mC=ll(k({applyDefaults:ge().optional()}),he(d(),Ie())),gC=of(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,ll(k({form:mC.optional(),url:Et.optional()}),he(d(),Ie()).optional())),_C=lt({list:Et.optional(),cancel:Et.optional(),requests:lt({sampling:lt({createMessage:Et.optional()}).optional(),elicitation:lt({create:Et.optional()}).optional()}).optional()}),yC=lt({list:Et.optional(),cancel:Et.optional(),requests:lt({tools:lt({call:Et.optional()}).optional()}).optional()}),vC=k({experimental:he(d(),Et).optional(),sampling:k({context:Et.optional(),tools:Et.optional()}).optional(),elicitation:gC.optional(),roots:k({listChanged:ge().optional()}).optional(),tasks:_C.optional()}),wC=nr.extend({protocolVersion:d(),capabilities:vC,clientInfo:Qm}),bC=$t.extend({method:P("initialize"),params:wC}),kC=k({experimental:he(d(),Et).optional(),logging:Et.optional(),completions:Et.optional(),prompts:k({listChanged:ge().optional()}).optional(),resources:k({subscribe:ge().optional(),listChanged:ge().optional()}).optional(),tools:k({listChanged:ge().optional()}).optional(),tasks:yC.optional()}),Xm=Rt.extend({protocolVersion:d(),capabilities:kC,serverInfo:Qm,instructions:d().optional()}),e2=pr.extend({method:P("notifications/initialized"),params:dr.optional()}),TC=e=>e2.safeParse(e).success,_c=$t.extend({method:P("ping"),params:nr.optional()}),CC=k({progress:N(),total:de(N()),message:de(d())}),SC=k({...dr.shape,...CC.shape,progressToken:Gm}),yc=pr.extend({method:P("notifications/progress"),params:SC}),IC=nr.extend({cursor:Wm.optional()}),cs=$t.extend({params:IC.optional()}),us=Rt.extend({nextCursor:Wm.optional()}),xC=ce(["working","input_required","completed","failed","cancelled"]),ds=k({taskId:d(),status:xC,ttl:ae([N(),Do()]),createdAt:d(),lastUpdatedAt:d(),pollInterval:de(N()),statusMessage:de(d())}),ps=Rt.extend({task:ds}),EC=dr.merge(ds),Ea=pr.extend({method:P("notifications/tasks/status"),params:EC}),vc=$t.extend({method:P("tasks/get"),params:nr.extend({taskId:d()})}),wc=Rt.merge(ds),bc=$t.extend({method:P("tasks/result"),params:nr.extend({taskId:d()})});Rt.loose();const kc=cs.extend({method:P("tasks/list")}),Tc=us.extend({tasks:q(ds)}),Cc=$t.extend({method:P("tasks/cancel"),params:nr.extend({taskId:d()})}),$C=Rt.merge(ds),t2=k({uri:d(),mimeType:de(d()),_meta:he(d(),Ie()).optional()}),r2=t2.extend({text:d()}),Sc=d().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),n2=t2.extend({blob:Sc}),fs=ce(["user","assistant"]),fo=k({audience:q(fs).optional(),priority:N().min(0).max(1).optional(),lastModified:Vp({offset:!0}).optional()}),o2=k({...po.shape,...ls.shape,uri:d(),description:de(d()),mimeType:de(d()),annotations:fo.optional(),_meta:de(lt({}))}),RC=k({...po.shape,...ls.shape,uriTemplate:d(),description:de(d()),mimeType:de(d()),annotations:fo.optional(),_meta:de(lt({}))}),PC=cs.extend({method:P("resources/list")}),s2=us.extend({resources:q(o2)}),MC=cs.extend({method:P("resources/templates/list")}),a2=us.extend({resourceTemplates:q(RC)}),Ic=nr.extend({uri:d()}),NC=Ic,OC=$t.extend({method:P("resources/read"),params:NC}),i2=Rt.extend({contents:q(ae([r2,n2]))}),xc=pr.extend({method:P("notifications/resources/list_changed"),params:dr.optional()}),AC=Ic,qC=$t.extend({method:P("resources/subscribe"),params:AC}),LC=Ic,jC=$t.extend({method:P("resources/unsubscribe"),params:LC}),DC=dr.extend({uri:d()}),l2=pr.extend({method:P("notifications/resources/updated"),params:DC}),UC=k({name:d(),description:de(d()),required:de(ge())}),zC=k({...po.shape,...ls.shape,description:de(d()),arguments:de(q(UC)),_meta:de(lt({}))}),FC=cs.extend({method:P("prompts/list")}),c2=us.extend({prompts:q(zC)}),VC=nr.extend({name:d(),arguments:he(d(),d()).optional()}),ZC=$t.extend({method:P("prompts/get"),params:VC}),Ec=k({type:P("text"),text:d(),annotations:fo.optional(),_meta:he(d(),Ie()).optional()}),$c=k({type:P("image"),data:Sc,mimeType:d(),annotations:fo.optional(),_meta:he(d(),Ie()).optional()}),Rc=k({type:P("audio"),data:Sc,mimeType:d(),annotations:fo.optional(),_meta:he(d(),Ie()).optional()}),BC=k({type:P("tool_use"),name:d(),id:d(),input:he(d(),Ie()),_meta:he(d(),Ie()).optional()}),HC=k({type:P("resource"),resource:ae([r2,n2]),annotations:fo.optional(),_meta:he(d(),Ie()).optional()}),JC=o2.extend({type:P("resource_link")}),Pc=ae([Ec,$c,Rc,JC,HC]),GC=k({role:fs,content:Pc}),u2=Rt.extend({description:d().optional(),messages:q(GC)}),Mc=pr.extend({method:P("notifications/prompts/list_changed"),params:dr.optional()}),WC=k({title:d().optional(),readOnlyHint:ge().optional(),destructiveHint:ge().optional(),idempotentHint:ge().optional(),openWorldHint:ge().optional()}),KC=k({taskSupport:ce(["required","optional","forbidden"]).optional()}),d2=k({...po.shape,...ls.shape,description:d().optional(),inputSchema:k({type:P("object"),properties:he(d(),Et).optional(),required:q(d()).optional()}).catchall(Ie()),outputSchema:k({type:P("object"),properties:he(d(),Et).optional(),required:q(d()).optional()}).catchall(Ie()).optional(),annotations:WC.optional(),execution:KC.optional(),_meta:he(d(),Ie()).optional()}),YC=cs.extend({method:P("tools/list")}),p2=us.extend({tools:q(d2)}),hs=Rt.extend({content:q(Pc).default([]),structuredContent:he(d(),Ie()).optional(),isError:ge().optional()});hs.or(Rt.extend({toolResult:Ie()}));const QC=as.extend({name:d(),arguments:he(d(),Ie()).optional()}),XC=$t.extend({method:P("tools/call"),params:QC}),Nc=pr.extend({method:P("notifications/tools/list_changed"),params:dr.optional()}),eS=k({autoRefresh:ge().default(!0),debounceMs:N().int().nonnegative().default(300)}),f2=ce(["debug","info","notice","warning","error","critical","alert","emergency"]),tS=nr.extend({level:f2}),rS=$t.extend({method:P("logging/setLevel"),params:tS}),nS=dr.extend({level:f2,logger:d().optional(),data:Ie()}),h2=pr.extend({method:P("notifications/message"),params:nS}),oS=k({name:d().optional()}),sS=k({hints:q(oS).optional(),costPriority:N().min(0).max(1).optional(),speedPriority:N().min(0).max(1).optional(),intelligencePriority:N().min(0).max(1).optional()}),aS=k({mode:ce(["auto","required","none"]).optional()}),iS=k({type:P("tool_result"),toolUseId:d().describe("The unique identifier for the corresponding tool call."),content:q(Pc).default([]),structuredContent:k({}).loose().optional(),isError:ge().optional(),_meta:he(d(),Ie()).optional()}),lS=Ue("type",[Ec,$c,Rc]),$a=Ue("type",[Ec,$c,Rc,BC,iS]),cS=k({role:fs,content:ae([$a,q($a)]),_meta:he(d(),Ie()).optional()}),uS=as.extend({messages:q(cS),modelPreferences:sS.optional(),systemPrompt:d().optional(),includeContext:ce(["none","thisServer","allServers"]).optional(),temperature:N().optional(),maxTokens:N().int(),stopSequences:q(d()).optional(),metadata:Et.optional(),tools:q(d2).optional(),toolChoice:aS.optional()}),Oc=$t.extend({method:P("sampling/createMessage"),params:uS}),Ac=Rt.extend({model:d(),stopReason:de(ce(["endTurn","stopSequence","maxTokens"]).or(d())),role:fs,content:lS}),m2=Rt.extend({model:d(),stopReason:de(ce(["endTurn","stopSequence","maxTokens","toolUse"]).or(d())),role:fs,content:ae([$a,q($a)])}),dS=k({type:P("boolean"),title:d().optional(),description:d().optional(),default:ge().optional()}),pS=k({type:P("string"),title:d().optional(),description:d().optional(),minLength:N().optional(),maxLength:N().optional(),format:ce(["email","uri","date","date-time"]).optional(),default:d().optional()}),fS=k({type:ce(["number","integer"]),title:d().optional(),description:d().optional(),minimum:N().optional(),maximum:N().optional(),default:N().optional()}),hS=k({type:P("string"),title:d().optional(),description:d().optional(),enum:q(d()),default:d().optional()}),mS=k({type:P("string"),title:d().optional(),description:d().optional(),oneOf:q(k({const:d(),title:d()})),default:d().optional()}),gS=k({type:P("string"),title:d().optional(),description:d().optional(),enum:q(d()),enumNames:q(d()).optional(),default:d().optional()}),_S=ae([hS,mS]),yS=k({type:P("array"),title:d().optional(),description:d().optional(),minItems:N().optional(),maxItems:N().optional(),items:k({type:P("string"),enum:q(d())}),default:q(d()).optional()}),vS=k({type:P("array"),title:d().optional(),description:d().optional(),minItems:N().optional(),maxItems:N().optional(),items:k({anyOf:q(k({const:d(),title:d()}))}),default:q(d()).optional()}),wS=ae([yS,vS]),bS=ae([gS,_S,wS]),kS=ae([bS,dS,pS,fS]),TS=as.extend({mode:P("form").optional(),message:d(),requestedSchema:k({type:P("object"),properties:he(d(),kS),required:q(d()).optional()})}),CS=as.extend({mode:P("url"),message:d(),elicitationId:d(),url:d().url()}),SS=ae([TS,CS]),qc=$t.extend({method:P("elicitation/create"),params:SS}),IS=dr.extend({elicitationId:d()}),xS=pr.extend({method:P("notifications/elicitation/complete"),params:IS}),Lc=Rt.extend({action:ce(["accept","decline","cancel"]),content:of(e=>e===null?void 0:e,he(d(),ae([d(),N(),ge(),q(d())])).optional())}),ES=k({type:P("ref/resource"),uri:d()}),$S=k({type:P("ref/prompt"),name:d()}),RS=nr.extend({ref:ae([$S,ES]),argument:k({name:d(),value:d()}),context:k({arguments:he(d(),d()).optional()}).optional()}),PS=$t.extend({method:P("completion/complete"),params:RS}),g2=Rt.extend({completion:lt({values:q(d()).max(100),total:de(N().int()),hasMore:de(ge())})}),MS=k({uri:d().startsWith("file://"),name:d().optional(),_meta:he(d(),Ie()).optional()}),_2=$t.extend({method:P("roots/list"),params:nr.optional()}),y2=Rt.extend({roots:q(MS)}),NS=pr.extend({method:P("notifications/roots/list_changed"),params:dr.optional()});ae([_c,bC,PS,rS,ZC,FC,PC,MC,OC,qC,jC,XC,YC,vc,bc,kc,Cc]),ae([gc,yc,e2,NS,Ea]),ae([Dn,Ac,m2,Lc,y2,wc,Tc,ps]),ae([_c,Oc,qc,_2,vc,bc,kc,Cc]),ae([gc,yc,h2,l2,xc,Nc,Mc,Ea,xS]),ae([Dn,Xm,g2,u2,c2,s2,a2,i2,hs,p2,wc,Tc,ps]);class Te extends Error{constructor(t,r,n){super(`MCP error ${t}: ${r}`),this.code=t,this.data=n,this.name="McpError"}static fromError(t,r,n){if(t===$e.UrlElicitationRequired&&n){const o=n;if(o.elicitations)return new OS(o.elicitations,r)}return new Te(t,r,n)}}class OS extends Te{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super($e.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}}const Pt=jb().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:sf.custom,message:"URL must be parseable",fatal:!0}),op}).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"}),AS=lt({resource:d().url(),authorization_servers:q(Pt).optional(),jwks_uri:d().url().optional(),scopes_supported:q(d()).optional(),bearer_methods_supported:q(d()).optional(),resource_signing_alg_values_supported:q(d()).optional(),resource_name:d().optional(),resource_documentation:d().optional(),resource_policy_uri:d().url().optional(),resource_tos_uri:d().url().optional(),tls_client_certificate_bound_access_tokens:ge().optional(),authorization_details_types_supported:q(d()).optional(),dpop_signing_alg_values_supported:q(d()).optional(),dpop_bound_access_tokens_required:ge().optional()}),v2=lt({issuer:d(),authorization_endpoint:Pt,token_endpoint:Pt,registration_endpoint:Pt.optional(),scopes_supported:q(d()).optional(),response_types_supported:q(d()),response_modes_supported:q(d()).optional(),grant_types_supported:q(d()).optional(),token_endpoint_auth_methods_supported:q(d()).optional(),token_endpoint_auth_signing_alg_values_supported:q(d()).optional(),service_documentation:Pt.optional(),revocation_endpoint:Pt.optional(),revocation_endpoint_auth_methods_supported:q(d()).optional(),revocation_endpoint_auth_signing_alg_values_supported:q(d()).optional(),introspection_endpoint:d().optional(),introspection_endpoint_auth_methods_supported:q(d()).optional(),introspection_endpoint_auth_signing_alg_values_supported:q(d()).optional(),code_challenge_methods_supported:q(d()).optional(),client_id_metadata_document_supported:ge().optional()}),qS=lt({issuer:d(),authorization_endpoint:Pt,token_endpoint:Pt,userinfo_endpoint:Pt.optional(),jwks_uri:Pt,registration_endpoint:Pt.optional(),scopes_supported:q(d()).optional(),response_types_supported:q(d()),response_modes_supported:q(d()).optional(),grant_types_supported:q(d()).optional(),acr_values_supported:q(d()).optional(),subject_types_supported:q(d()),id_token_signing_alg_values_supported:q(d()),id_token_encryption_alg_values_supported:q(d()).optional(),id_token_encryption_enc_values_supported:q(d()).optional(),userinfo_signing_alg_values_supported:q(d()).optional(),userinfo_encryption_alg_values_supported:q(d()).optional(),userinfo_encryption_enc_values_supported:q(d()).optional(),request_object_signing_alg_values_supported:q(d()).optional(),request_object_encryption_alg_values_supported:q(d()).optional(),request_object_encryption_enc_values_supported:q(d()).optional(),token_endpoint_auth_methods_supported:q(d()).optional(),token_endpoint_auth_signing_alg_values_supported:q(d()).optional(),display_values_supported:q(d()).optional(),claim_types_supported:q(d()).optional(),claims_supported:q(d()).optional(),service_documentation:d().optional(),claims_locales_supported:q(d()).optional(),ui_locales_supported:q(d()).optional(),claims_parameter_supported:ge().optional(),request_parameter_supported:ge().optional(),request_uri_parameter_supported:ge().optional(),require_request_uri_registration:ge().optional(),op_policy_uri:Pt.optional(),op_tos_uri:Pt.optional(),client_id_metadata_document_supported:ge().optional()}),LS=k({...qS.shape,...v2.pick({code_challenge_methods_supported:!0}).shape}),jS=k({access_token:d(),id_token:d().optional(),token_type:d(),expires_in:af().optional(),scope:d().optional(),refresh_token:d().optional()}).strip(),DS=k({error:d(),error_description:d().optional(),error_uri:d().optional()}),w2=Pt.optional().or(P("").transform(()=>{})),US=k({redirect_uris:q(Pt),token_endpoint_auth_method:d().optional(),grant_types:q(d()).optional(),response_types:q(d()).optional(),client_name:d().optional(),client_uri:Pt.optional(),logo_uri:w2,scope:d().optional(),contacts:q(d()).optional(),tos_uri:w2,policy_uri:d().optional(),jwks_uri:Pt.optional(),jwks:ht().optional(),software_id:d().optional(),software_version:d().optional(),software_statement:d().optional()}).strip(),zS=k({client_id:d(),client_secret:d().optional(),client_id_issued_at:N().optional(),client_secret_expires_at:N().optional()}).strip(),FS=US.merge(zS);k({error:d(),error_description:d().optional()}).strip(),k({token:d(),token_type_hint:d().optional()}).strip();function VS(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function ZS({requestedResource:e,configuredResource:t}){const r=typeof e=="string"?new URL(e):new URL(e.href),n=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;const o=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return o.startsWith(s)}class Ct extends Error{constructor(t,r){super(t),this.errorUri=r,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 jc extends Ct{}jc.errorCode="invalid_request";class Ra extends Ct{}Ra.errorCode="invalid_client";class Pa extends Ct{}Pa.errorCode="invalid_grant";class Ma extends Ct{}Ma.errorCode="unauthorized_client";class Dc extends Ct{}Dc.errorCode="unsupported_grant_type";class Uc extends Ct{}Uc.errorCode="invalid_scope";class zc extends Ct{}zc.errorCode="access_denied";class ho extends Ct{}ho.errorCode="server_error";class Fc extends Ct{}Fc.errorCode="temporarily_unavailable";class Vc extends Ct{}Vc.errorCode="unsupported_response_type";class Zc extends Ct{}Zc.errorCode="unsupported_token_type";class Bc extends Ct{}Bc.errorCode="invalid_token";class Hc extends Ct{}Hc.errorCode="method_not_allowed";class Jc extends Ct{}Jc.errorCode="too_many_requests";class Na extends Ct{}Na.errorCode="invalid_client_metadata";class Gc extends Ct{}Gc.errorCode="insufficient_scope";class Wc extends Ct{}Wc.errorCode="invalid_target";const BS={[jc.errorCode]:jc,[Ra.errorCode]:Ra,[Pa.errorCode]:Pa,[Ma.errorCode]:Ma,[Dc.errorCode]:Dc,[Uc.errorCode]:Uc,[zc.errorCode]:zc,[ho.errorCode]:ho,[Fc.errorCode]:Fc,[Vc.errorCode]:Vc,[Zc.errorCode]:Zc,[Bc.errorCode]:Bc,[Hc.errorCode]:Hc,[Jc.errorCode]:Jc,[Na.errorCode]:Na,[Gc.errorCode]:Gc,[Wc.errorCode]:Wc};class fr extends Error{constructor(t){super(t??"Unauthorized")}}function HS(e){return["client_secret_basic","client_secret_post","none"].includes(e)}const Kc="code",Yc="S256";function JS(e,t){const r=e.client_secret!==void 0;return t.length===0?r?"client_secret_post":"none":"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&HS(e.token_endpoint_auth_method)&&t.includes(e.token_endpoint_auth_method)?e.token_endpoint_auth_method:r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}function GS(e,t,r,n){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":WS(o,s,r);return;case"client_secret_post":KS(o,s,n);return;case"none":YS(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function WS(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const n=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${n}`)}function KS(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function YS(e,t){t.set("client_id",e)}async function b2(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=DS.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:i}=n,a=BS[o]||ho;return new a(s||"",i)}catch(n){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new ho(o)}}async function Un(e,t){try{return await Qc(e,t)}catch(r){if(r instanceof Ra||r instanceof Ma)return await e.invalidateCredentials?.("all"),await Qc(e,t);if(r instanceof Pa)return await e.invalidateCredentials?.("tokens"),await Qc(e,t);throw r}}async function Qc(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){let i,a;try{i=await e8(t,{resourceMetadataUrl:o},s),i.authorization_servers&&i.authorization_servers.length>0&&(a=i.authorization_servers[0])}catch{}a||(a=new URL("/",t));const l=await XS(t,e,i),c=await s8(a,{fetchFn:s});let u=await Promise.resolve(e.clientInformation());if(!u){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");const _=c?.client_id_metadata_document_supported===!0,w=e.clientMetadataUrl;if(w&&!QS(w))throw new Na(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${w}`);if(_&&w)u={client_id:w},await e.saveClientInformation?.(u);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const m=await u8(a,{metadata:c,clientMetadata:e.clientMetadata,fetchFn:s});await e.saveClientInformation(m),u=m}}const f=!e.redirectUrl;if(r!==void 0||f){const _=await c8(e,a,{metadata:c,resource:l,authorizationCode:r,fetchFn:s});return await e.saveTokens(_),"AUTHORIZED"}const p=await e.tokens();if(p?.refresh_token)try{const _=await l8(a,{metadata:c,clientInformation:u,refreshToken:p.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(_),"AUTHORIZED"}catch(_){if(!(!(_ instanceof Ct)||_ instanceof ho))throw _}const h=e.state?await e.state():void 0,{authorizationUrl:g,codeVerifier:v}=await a8(a,{metadata:c,clientInformation:u,state:h,redirectUrl:e.redirectUrl,scope:n||i?.scopes_supported?.join(" ")||e.clientMetadata.scope,resource:l});return await e.saveCodeVerifier(v),await e.redirectToAuthorization(g),"REDIRECT"}function QS(e){if(!e)return!1;try{const t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function XS(e,t,r){const n=VS(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!ZS({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}function Oa(e){const t=e.headers.get("WWW-Authenticate");if(!t)return{};const[r,n]=t.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};const o=Xc(e,"resource_metadata")||void 0;let s;if(o)try{s=new URL(o)}catch{}const i=Xc(e,"scope")||void 0,a=Xc(e,"error")||void 0;return{resourceMetadataUrl:s,scope:i,error:a}}function Xc(e,t){const r=e.headers.get("WWW-Authenticate");if(!r)return null;const n=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),o=r.match(n);return o?o[1]||o[2]:null}async function e8(e,t,r=fetch){const n=await n8(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!n||n.status===404)throw await n?.body?.cancel(),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw await n.body?.cancel(),new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return AS.parse(await n.json())}async function eu(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?eu(e,void 0,r):void 0;throw n}}function t8(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function k2(e,t,r=fetch){return await eu(e,{"MCP-Protocol-Version":t},r)}function r8(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function n8(e,t,r,n){const o=new URL(e),s=n?.protocolVersion??Sa;let i;if(n?.metadataUrl)i=new URL(n.metadataUrl);else{const l=t8(t,o.pathname);i=new URL(l,n?.metadataServerUrl??o),i.search=o.search}let a=await k2(i,s,r);if(!n?.metadataUrl&&r8(a,o.pathname)){const l=new URL(`/.well-known/${t}`,o);a=await k2(l,s,r)}return a}function o8(e){const t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),n;let o=t.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,t.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${o}`,t.origin),type:"oidc"}),n.push({url:new URL(`${o}/.well-known/openid-configuration`,t.origin),type:"oidc"}),n}async function s8(e,{fetchFn:t=fetch,protocolVersion:r=Sa}={}){const n={"MCP-Protocol-Version":r,Accept:"application/json"},o=o8(e);for(const{url:s,type:i}of o){const a=await eu(s,n,t);if(a){if(!a.ok){if(await a.body?.cancel(),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"?v2.parse(await a.json()):LS.parse(await a.json())}}}async function a8(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:o,state:s,resource:i}){let a;if(t){if(a=new URL(t.authorization_endpoint),!t.response_types_supported.includes(Kc))throw new Error(`Incompatible auth server: does not support response type ${Kc}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Yc))throw new Error(`Incompatible auth server: does not support code challenge method ${Yc}`)}else a=new URL("/authorize",e);const l=await Cm(),c=l.code_verifier,u=l.code_challenge;return a.searchParams.set("response_type",Kc),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",u),a.searchParams.set("code_challenge_method",Yc),a.searchParams.set("redirect_uri",String(n)),s&&a.searchParams.set("state",s),o&&a.searchParams.set("scope",o),o?.includes("offline_access")&&a.searchParams.append("prompt","consent"),i&&a.searchParams.set("resource",i.href),{authorizationUrl:a,codeVerifier:c}}function i8(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function T2(e,{metadata:t,tokenRequestParams:r,clientInformation:n,addClientAuthentication:o,resource:s,fetchFn:i}){const a=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),l=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(s&&r.set("resource",s.href),o)await o(l,r,a,t);else if(n){const u=t?.token_endpoint_auth_methods_supported??[],f=JS(n,u);GS(f,n,l,r)}const c=await(i??fetch)(a,{method:"POST",headers:l,body:r});if(!c.ok)throw await b2(c);return jS.parse(await c.json())}async function l8(e,{metadata:t,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:s,fetchFn:i}){const a=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),l=await T2(e,{metadata:t,tokenRequestParams:a,clientInformation:r,addClientAuthentication:s,resource:o,fetchFn:i});return{refresh_token:n,...l}}async function c8(e,t,{metadata:r,resource:n,authorizationCode:o,fetchFn:s}={}){const i=e.clientMetadata.scope;let a;if(e.prepareTokenRequest&&(a=await e.prepareTokenRequest(i)),!a){if(!o)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");const c=await e.codeVerifier();a=i8(o,c,e.redirectUrl)}const l=await e.clientInformation();return T2(t,{metadata:r,tokenRequestParams:a,clientInformation:l??void 0,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:s})}async function u8(e,{metadata:t,clientMetadata:r,fetchFn:n}){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(n??fetch)(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok)throw await b2(s);return FS.parse(await s.json())}const d8={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class mo extends Error{constructor(t,r){super(`Streamable HTTP error: ${r}`),this.code=t}}class Aa{constructor(t,r){this._hasCompletedAuthFlow=!1,this._url=t,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=Jm(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??d8}async _authThenStart(){if(!this._authProvider)throw new fr("No auth provider");let t;try{t=await Un(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(t!=="AUTHORIZED")throw new fr;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){const t={};if(this._authProvider){const n=await this._authProvider.tokens();n&&(t.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(t["mcp-session-id"]=this._sessionId),this._protocolVersion&&(t["mcp-protocol-version"]=this._protocolVersion);const r=Ca(this._requestInit?.headers);return new Headers({...t,...r})}async _startOrAuthSse(t){const{resumptionToken:r}=t;try{const n=await this._commonHeaders();n.set("Accept","text/event-stream"),r&&n.set("last-event-id",r);const o=await(this._fetch??fetch)(this._url,{method:"GET",headers:n,signal:this._abortController?.signal});if(!o.ok){if(await o.body?.cancel(),o.status===401&&this._authProvider)return await this._authThenStart();if(o.status===405)return;throw new mo(o.status,`Failed to open SSE stream: ${o.statusText}`)}this._handleSseStream(o.body,t,!0)}catch(n){throw this.onerror?.(n),n}}_getNextReconnectionDelay(t){if(this._serverRetryMs!==void 0)return this._serverRetryMs;const r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,t),o)}_scheduleReconnection(t,r=0){const n=this._reconnectionOptions.maxRetries;if(r>=n){this.onerror?.(new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}const o=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(t).catch(s=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`)),this._scheduleReconnection(t,r+1)})},o)}_handleSseStream(t,r,n){if(!t)return;const{onresumptiontoken:o,replayMessageId:s}=r;let i,a=!1,l=!1;(async()=>{try{const u=t.pipeThrough(new TextDecoderStream).pipeThrough(new ro({onRetry:h=>{this._serverRetryMs=h}})).getReader();for(;;){const{value:h,done:g}=await u.read();if(g)break;if(h.id&&(i=h.id,a=!0,o?.(h.id)),!!h.data&&(!h.event||h.event==="message"))try{const v=jn.parse(JSON.parse(h.data));is(v)&&(l=!0,s!==void 0&&(v.id=s)),this.onmessage?.(v)}catch(v){this.onerror?.(v)}}(n||a)&&!l&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:i,onresumptiontoken:o,replayMessageId:s},0)}catch(u){if(this.onerror?.(new Error(`SSE stream disconnected: ${u}`)),(n||a)&&!l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:i,onresumptiontoken:o,replayMessageId:s},0)}catch(h){this.onerror?.(new Error(`Failed to reconnect: ${h instanceof Error?h.message:String(h)}`))}}})()}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 fr("No auth provider");if(await Un(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new fr("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(t,r){try{const{resumptionToken:n,onresumptiontoken:o}=r||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:fc(t)?t.id:void 0}).catch(p=>this.onerror?.(p));return}const s=await this._commonHeaders();s.set("content-type","application/json"),s.set("accept","application/json, text/event-stream");const i={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(t),signal:this._abortController?.signal},a=await(this._fetch??fetch)(this._url,i),l=a.headers.get("mcp-session-id");if(l&&(this._sessionId=l),!a.ok){const p=await a.text().catch(()=>null);if(a.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new mo(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:h,scope:g}=Oa(a);if(this._resourceMetadataUrl=h,this._scope=g,await Un(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new fr;return this._hasCompletedAuthFlow=!0,this.send(t)}if(a.status===403&&this._authProvider){const{resourceMetadataUrl:h,scope:g,error:v}=Oa(a);if(v==="insufficient_scope"){const _=a.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===_)throw new mo(403,"Server returned 403 after trying upscoping");if(g&&(this._scope=g),h&&(this._resourceMetadataUrl=h),this._lastUpscopingHeader=_??void 0,await Un(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new fr;return this.send(t)}}throw new mo(a.status,`Error POSTing to endpoint: ${p}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,a.status===202){await a.body?.cancel(),TC(t)&&this._startOrAuthSse({resumptionToken:void 0}).catch(p=>this.onerror?.(p));return}const u=(Array.isArray(t)?t:[t]).filter(p=>"method"in p&&"id"in p&&p.id!==void 0).length>0,f=a.headers.get("content-type");if(u)if(f?.includes("text/event-stream"))this._handleSseStream(a.body,{onresumptiontoken:o},!1);else if(f?.includes("application/json")){const p=await a.json(),h=Array.isArray(p)?p.map(g=>jn.parse(g)):[jn.parse(p)];for(const g of h)this.onmessage?.(g)}else throw await a.body?.cancel(),new mo(-1,`Unexpected content type: ${f}`);else await a.body?.cancel()}catch(n){throw this.onerror?.(n),n}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{const t=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:t,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,r);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new mo(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(t){throw this.onerror?.(t),t}}setProtocolVersion(t){this._protocolVersion=t}get protocolVersion(){return this._protocolVersion}async resumeStream(t,r){await this._startOrAuthSse({resumptionToken:t,onresumptiontoken:r?.onresumptiontoken})}}class C2 extends Event{constructor(t,r){var n,o;super(t),this.code=(n=r?.code)!=null?n:void 0,this.message=(o=r?.message)!=null?o:void 0}[Symbol.for("nodejs.util.inspect.custom")](t,r,n){return n(S2(this),r)}[Symbol.for("Deno.customInspect")](t,r){return t(S2(this),r)}}function p8(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function tu(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(tu).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${tu(e.cause)}`:e.message:`${e}`}function S2(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var I2=e=>{throw TypeError(e)},ru=(e,t,r)=>t.has(e)||I2("Cannot "+r),qe=(e,t,r)=>(ru(e,t,"read from private field"),r?r.call(e):t.get(e)),wt=(e,t,r)=>t.has(e)?I2("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),nt=(e,t,r,n)=>(ru(e,t,"write to private field"),t.set(e,r),r),Br=(e,t,r)=>(ru(e,t,"access private method"),r),Kt,zn,go,qa,La,ms,_o,gs,dn,yo,vo,wo,_s,kr,nu,ou,su,x2,au,iu,ys,lu,cu;class ja extends EventTarget{constructor(t,r){var n,o;super(),wt(this,kr),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,wt(this,Kt),wt(this,zn),wt(this,go),wt(this,qa),wt(this,La),wt(this,ms),wt(this,_o),wt(this,gs,null),wt(this,dn),wt(this,yo),wt(this,vo,null),wt(this,wo,null),wt(this,_s,null),wt(this,ou,async s=>{var i;qe(this,yo).reset();const{body:a,redirected:l,status:c,headers:u}=s;if(c===204){Br(this,kr,ys).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?nt(this,go,new URL(s.url)):nt(this,go,void 0),c!==200){Br(this,kr,ys).call(this,`Non-200 status code (${c})`,c);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){Br(this,kr,ys).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(qe(this,Kt)===this.CLOSED)return;nt(this,Kt,this.OPEN);const f=new Event("open");if((i=qe(this,_s))==null||i.call(this,f),this.dispatchEvent(f),typeof a!="object"||!a||!("getReader"in a)){Br(this,kr,ys).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}const p=new TextDecoder,h=a.getReader();let g=!0;do{const{done:v,value:_}=await h.read();_&&qe(this,yo).feed(p.decode(_,{stream:!v})),v&&(g=!1,qe(this,yo).reset(),Br(this,kr,lu).call(this))}while(g)}),wt(this,su,s=>{nt(this,dn,void 0),!(s.name==="AbortError"||s.type==="aborted")&&Br(this,kr,lu).call(this,tu(s))}),wt(this,au,s=>{typeof s.id=="string"&&nt(this,gs,s.id);const i=new MessageEvent(s.event||"message",{data:s.data,origin:qe(this,go)?qe(this,go).origin:qe(this,zn).origin,lastEventId:s.id||""});qe(this,wo)&&(!s.event||s.event==="message")&&qe(this,wo).call(this,i),this.dispatchEvent(i)}),wt(this,iu,s=>{nt(this,ms,s)}),wt(this,cu,()=>{nt(this,_o,void 0),qe(this,Kt)===this.CONNECTING&&Br(this,kr,nu).call(this)});try{if(t instanceof URL)nt(this,zn,t);else if(typeof t=="string")nt(this,zn,new URL(t,f8()));else throw new Error("Invalid URL")}catch{throw p8("An invalid or illegal string was specified")}nt(this,yo,Ef({onEvent:qe(this,au),onRetry:qe(this,iu)})),nt(this,Kt,this.CONNECTING),nt(this,ms,3e3),nt(this,La,(n=r?.fetch)!=null?n:globalThis.fetch),nt(this,qa,(o=r?.withCredentials)!=null?o:!1),Br(this,kr,nu).call(this)}get readyState(){return qe(this,Kt)}get url(){return qe(this,zn).href}get withCredentials(){return qe(this,qa)}get onerror(){return qe(this,vo)}set onerror(t){nt(this,vo,t)}get onmessage(){return qe(this,wo)}set onmessage(t){nt(this,wo,t)}get onopen(){return qe(this,_s)}set onopen(t){nt(this,_s,t)}addEventListener(t,r,n){const o=r;super.addEventListener(t,o,n)}removeEventListener(t,r,n){const o=r;super.removeEventListener(t,o,n)}close(){qe(this,_o)&&clearTimeout(qe(this,_o)),qe(this,Kt)!==this.CLOSED&&(qe(this,dn)&&qe(this,dn).abort(),nt(this,Kt,this.CLOSED),nt(this,dn,void 0))}}Kt=new WeakMap,zn=new WeakMap,go=new WeakMap,qa=new WeakMap,La=new WeakMap,ms=new WeakMap,_o=new WeakMap,gs=new WeakMap,dn=new WeakMap,yo=new WeakMap,vo=new WeakMap,wo=new WeakMap,_s=new WeakMap,kr=new WeakSet,nu=function(){nt(this,Kt,this.CONNECTING),nt(this,dn,new AbortController),qe(this,La)(qe(this,zn),Br(this,kr,x2).call(this)).then(qe(this,ou)).catch(qe(this,su))},ou=new WeakMap,su=new WeakMap,x2=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...qe(this,gs)?{"Last-Event-ID":qe(this,gs)}:void 0},cache:"no-store",signal:(e=qe(this,dn))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},au=new WeakMap,iu=new WeakMap,ys=function(e,t){var r;qe(this,Kt)!==this.CLOSED&&nt(this,Kt,this.CLOSED);const n=new C2("error",{code:t,message:e});(r=qe(this,vo))==null||r.call(this,n),this.dispatchEvent(n)},lu=function(e,t){var r;if(qe(this,Kt)===this.CLOSED)return;nt(this,Kt,this.CONNECTING);const n=new C2("error",{code:t,message:e});(r=qe(this,vo))==null||r.call(this,n),this.dispatchEvent(n),nt(this,_o,setTimeout(qe(this,cu),qe(this,ms)))},cu=new WeakMap,ja.CONNECTING=0,ja.OPEN=1,ja.CLOSED=2;function f8(){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 h8 extends Error{constructor(t,r,n){super(`SSE error: ${r}`),this.code=t,this.event=n}}class Da{constructor(t,r){this._url=t,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=r?.eventSourceInit,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=Jm(r?.fetch,r?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new fr("No auth provider");let t;try{t=await Un(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(t!=="AUTHORIZED")throw new fr;return await this._startOrAuth()}async _commonHeaders(){const t={};if(this._authProvider){const n=await this._authProvider.tokens();n&&(t.Authorization=`Bearer ${n.access_token}`)}this._protocolVersion&&(t["mcp-protocol-version"]=this._protocolVersion);const r=Ca(this._requestInit?.headers);return new Headers({...t,...r})}_startOrAuth(){const t=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((r,n)=>{this._eventSource=new ja(this._url.href,{...this._eventSourceInit,fetch:async(o,s)=>{const i=await this._commonHeaders();i.set("Accept","text/event-stream");const a=await t(o,{...s,headers:i});if(a.status===401&&a.headers.has("www-authenticate")){const{resourceMetadataUrl:l,scope:c}=Oa(a);this._resourceMetadataUrl=l,this._scope=c}return a}}),this._abortController=new AbortController,this._eventSource.onerror=o=>{if(o.code===401&&this._authProvider){this._authThenStart().then(r,n);return}const s=new h8(o.code,o.message,o);n(s),this.onerror?.(s)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",o=>{const s=o;try{if(this._endpoint=new URL(s.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(i){n(i),this.onerror?.(i),this.close();return}r()}),this._eventSource.onmessage=o=>{const s=o;let i;try{i=jn.parse(JSON.parse(s.data))}catch(a){this.onerror?.(a);return}this.onmessage?.(i)}})}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 fr("No auth provider");if(await Un(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new fr("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(t){if(!this._endpoint)throw new Error("Not connected");try{const r=await this._commonHeaders();r.set("content-type","application/json");const n={...this._requestInit,method:"POST",headers:r,body:JSON.stringify(t),signal:this._abortController?.signal},o=await(this._fetch??fetch)(this._endpoint,n);if(!o.ok){const s=await o.text().catch(()=>null);if(o.status===401&&this._authProvider){const{resourceMetadataUrl:i,scope:a}=Oa(o);if(this._resourceMetadataUrl=i,this._scope=a,await Un(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new fr;return this.send(t)}throw new Error(`Error POSTing to endpoint (HTTP ${o.status}): ${s}`)}await o.body?.cancel()}catch(r){throw this.onerror?.(r),r}}setProtocolVersion(t){this._protocolVersion=t}}class Ua{constructor(){this._messageQueue=[]}static createLinkedPair(){const t=new Ua,r=new Ua;return t._otherTransport=r,r._otherTransport=t,[t,r]}async start(){for(;this._messageQueue.length>0;){const t=this._messageQueue.shift();this.onmessage?.(t.message,t.extra)}}async close(){const t=this._otherTransport;this._otherTransport=void 0,await t?.close(),this.onclose?.()}async send(t,r){if(!this._otherTransport)throw new Error("Not connected");this._otherTransport.onmessage?this._otherTransport.onmessage(t,{authInfo:r?.authInfo}):this._otherTransport._messageQueue.push({message:t,extra:{authInfo:r?.authInfo}})}}var uu=k({error:k({message:d(),type:d().nullish(),param:ht().nullish(),code:ae([d(),N()]).nullish()})}),Tr=vr({errorSchema:uu,errorToMessage:e=>e.error.message});function E2(e){const t=e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat"),r=e.startsWith("gpt-4")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-nano")&&!e.startsWith("gpt-5-chat")&&!e.startsWith("gpt-5.4-nano")||e.startsWith("o3")||e.startsWith("o4-mini"),n=e.startsWith("o1")||e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat"),o=e.startsWith("gpt-5.1")||e.startsWith("gpt-5.2")||e.startsWith("gpt-5.3")||e.startsWith("gpt-5.4");return{supportsFlexProcessing:t,supportsPriorityProcessing:r,isReasoningModel:n,systemMessageMode:n?"developer":"system",supportsNonReasoningParameters:o}}function $2(e){var t,r,n,o,s,i;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const a=(t=e.prompt_tokens)!=null?t:0,l=(r=e.completion_tokens)!=null?r:0,c=(o=(n=e.prompt_tokens_details)==null?void 0:n.cached_tokens)!=null?o:0,u=(i=(s=e.completion_tokens_details)==null?void 0:s.reasoning_tokens)!=null?i:0;return{inputTokens:{total:a,noCache:a-c,cacheRead:c,cacheWrite:void 0},outputTokens:{total:l,text:l-u,reasoning:u},raw:e}}function m8({prompt:e,systemMessageMode:t="system"}){var r;const n=[],o=[];for(const{role:s,content:i}of e)switch(s){case"system":{switch(t){case"system":{n.push({role:"system",content:i});break}case"developer":{n.push({role:"developer",content:i});break}case"remove":{o.push({type:"other",message:"system messages are removed for this model"});break}default:{const a=t;throw new Error(`Unsupported system message mode: ${a}`)}}break}case"user":{if(i.length===1&&i[0].type==="text"){n.push({role:"user",content:i[0].text});break}n.push({role:"user",content:i.map((a,l)=>{var c,u,f;switch(a.type){case"text":return{type:"text",text:a.text};case"file":if(a.mediaType.startsWith("image/")){const p=a.mediaType==="image/*"?"image/jpeg":a.mediaType;return{type:"image_url",image_url:{url:a.data instanceof URL?a.data.toString():`data:${p};base64,${ao(a.data)}`,detail:(u=(c=a.providerOptions)==null?void 0:c.openai)==null?void 0:u.imageDetail}}}else if(a.mediaType.startsWith("audio/")){if(a.data instanceof URL)throw new Pr({functionality:"audio file parts with URLs"});switch(a.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:ao(a.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:ao(a.data),format:"mp3"}};default:throw new Pr({functionality:`audio content parts with media type ${a.mediaType}`})}}else if(a.mediaType==="application/pdf"){if(a.data instanceof URL)throw new Pr({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof a.data=="string"&&a.data.startsWith("file-")?{file_id:a.data}:{filename:(f=a.filename)!=null?f:`part-${l}.pdf`,file_data:`data:application/pdf;base64,${ao(a.data)}`}}}else throw new Pr({functionality:`file part media type ${a.mediaType}`})}})});break}case"assistant":{let a="";const l=[];for(const c of i)switch(c.type){case"text":{a+=c.text;break}case"tool-call":{l.push({id:c.toolCallId,type:"function",function:{name:c.toolName,arguments:JSON.stringify(c.input)}});break}}n.push({role:"assistant",content:a,tool_calls:l.length>0?l:void 0});break}case"tool":{for(const a of i){if(a.type==="tool-approval-response")continue;const l=a.output;let c;switch(l.type){case"text":case"error-text":c=l.value;break;case"execution-denied":c=(r=l.reason)!=null?r:"Tool execution denied.";break;case"content":case"json":case"error-json":c=JSON.stringify(l.value);break}n.push({role:"tool",tool_call_id:a.toolCallId,content:c})}break}default:{const a=s;throw new Error(`Unsupported role: ${a}`)}}return{messages:n,warnings:o}}function du({id:e,model:t,created:r}){return{id:e??void 0,modelId:t??void 0,timestamp:r?new Date(r*1e3):void 0}}function R2(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"other"}}var g8=ve(()=>ye(k({id:d().nullish(),created:N().nullish(),model:d().nullish(),choices:q(k({message:k({role:P("assistant").nullish(),content:d().nullish(),tool_calls:q(k({id:d().nullish(),type:P("function"),function:k({name:d(),arguments:d()})})).nullish(),annotations:q(k({type:P("url_citation"),url_citation:k({start_index:N(),end_index:N(),url:d(),title:d()})})).nullish()}),index:N(),logprobs:k({content:q(k({token:d(),logprob:N(),top_logprobs:q(k({token:d(),logprob:N()}))})).nullish()}).nullish(),finish_reason:d().nullish()})),usage:k({prompt_tokens:N().nullish(),completion_tokens:N().nullish(),total_tokens:N().nullish(),prompt_tokens_details:k({cached_tokens:N().nullish()}).nullish(),completion_tokens_details:k({reasoning_tokens:N().nullish(),accepted_prediction_tokens:N().nullish(),rejected_prediction_tokens:N().nullish()}).nullish()}).nullish()}))),_8=ve(()=>ye(ae([k({id:d().nullish(),created:N().nullish(),model:d().nullish(),choices:q(k({delta:k({role:ce(["assistant"]).nullish(),content:d().nullish(),tool_calls:q(k({index:N(),id:d().nullish(),type:P("function").nullish(),function:k({name:d().nullish(),arguments:d().nullish()})})).nullish(),annotations:q(k({type:P("url_citation"),url_citation:k({start_index:N(),end_index:N(),url:d(),title:d()})})).nullish()}).nullish(),logprobs:k({content:q(k({token:d(),logprob:N(),top_logprobs:q(k({token:d(),logprob:N()}))})).nullish()}).nullish(),finish_reason:d().nullish(),index:N()})),usage:k({prompt_tokens:N().nullish(),completion_tokens:N().nullish(),total_tokens:N().nullish(),prompt_tokens_details:k({cached_tokens:N().nullish()}).nullish(),completion_tokens_details:k({reasoning_tokens:N().nullish(),accepted_prediction_tokens:N().nullish(),rejected_prediction_tokens:N().nullish()}).nullish()}).nullish()}),uu]))),y8=ve(()=>ye(k({logitBias:he(af(),N()).optional(),logprobs:ae([ge(),N()]).optional(),parallelToolCalls:ge().optional(),user:d().optional(),reasoningEffort:ce(["none","minimal","low","medium","high","xhigh"]).optional(),maxCompletionTokens:N().optional(),store:ge().optional(),metadata:he(d().max(64),d().max(512)).optional(),prediction:he(d(),ht()).optional(),serviceTier:ce(["auto","flex","priority","default"]).optional(),strictJsonSchema:ge().optional(),textVerbosity:ce(["low","medium","high"]).optional(),promptCacheKey:d().optional(),promptCacheRetention:ce(["in_memory","24h"]).optional(),safetyIdentifier:d().optional(),systemMessageMode:ce(["system","developer","remove"]).optional(),forceReasoning:ge().optional()})));function v8({tools:e,toolChoice:t}){e=e?.length?e:void 0;const r=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};const n=[];for(const s of e)switch(s.type){case"function":n.push({type:"function",function:{name:s.name,description:s.description,parameters:s.inputSchema,...s.strict!=null?{strict:s.strict}:{}}});break;default:r.push({type:"unsupported",feature:`tool type: ${s.type}`});break}if(t==null)return{tools:n,toolChoice:void 0,toolWarnings:r};const o=t.type;switch(o){case"auto":case"none":case"required":return{tools:n,toolChoice:o,toolWarnings:r};case"tool":return{tools:n,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:r};default:{const s=o;throw new Pr({functionality:`tool choice type: ${s}`})}}}var w8=class{constructor(e,t){this.specificationVersion="v3",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:r,topP:n,topK:o,frequencyPenalty:s,presencePenalty:i,stopSequences:a,responseFormat:l,seed:c,tools:u,toolChoice:f,providerOptions:p}){var h,g,v,_,w;const y=[],m=(h=await Vr({provider:"openai",providerOptions:p,schema:y8}))!=null?h:{},C=E2(this.modelId),b=(g=m.forceReasoning)!=null?g:C.isReasoningModel;o!=null&&y.push({type:"unsupported",feature:"topK"});const{messages:T,warnings:I}=m8({prompt:e,systemMessageMode:(v=m.systemMessageMode)!=null?v:b?"developer":C.systemMessageMode});y.push(...I);const R=(_=m.strictJsonSchema)!=null?_:!0,S={model:this.modelId,logit_bias:m.logitBias,logprobs:m.logprobs===!0||typeof m.logprobs=="number"?!0:void 0,top_logprobs:typeof m.logprobs=="number"?m.logprobs:typeof m.logprobs=="boolean"&&m.logprobs?0:void 0,user:m.user,parallel_tool_calls:m.parallelToolCalls,max_tokens:t,temperature:r,top_p:n,frequency_penalty:s,presence_penalty:i,response_format:l?.type==="json"?l.schema!=null?{type:"json_schema",json_schema:{schema:l.schema,strict:R,name:(w=l.name)!=null?w:"response",description:l.description}}:{type:"json_object"}:void 0,stop:a,seed:c,verbosity:m.textVerbosity,max_completion_tokens:m.maxCompletionTokens,store:m.store,metadata:m.metadata,prediction:m.prediction,reasoning_effort:m.reasoningEffort,service_tier:m.serviceTier,prompt_cache_key:m.promptCacheKey,prompt_cache_retention:m.promptCacheRetention,safety_identifier:m.safetyIdentifier,messages:T};b?((m.reasoningEffort!=="none"||!C.supportsNonReasoningParameters)&&(S.temperature!=null&&(S.temperature=void 0,y.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),S.top_p!=null&&(S.top_p=void 0,y.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"})),S.logprobs!=null&&(S.logprobs=void 0,y.push({type:"other",message:"logprobs is not supported for reasoning models"}))),S.frequency_penalty!=null&&(S.frequency_penalty=void 0,y.push({type:"unsupported",feature:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),S.presence_penalty!=null&&(S.presence_penalty=void 0,y.push({type:"unsupported",feature:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),S.logit_bias!=null&&(S.logit_bias=void 0,y.push({type:"other",message:"logitBias is not supported for reasoning models"})),S.top_logprobs!=null&&(S.top_logprobs=void 0,y.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),S.max_tokens!=null&&(S.max_completion_tokens==null&&(S.max_completion_tokens=S.max_tokens),S.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&S.temperature!=null&&(S.temperature=void 0,y.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),m.serviceTier==="flex"&&!C.supportsFlexProcessing&&(y.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),S.service_tier=void 0),m.serviceTier==="priority"&&!C.supportsPriorityProcessing&&(y.push({type:"unsupported",feature:"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"}),S.service_tier=void 0);const{tools:j,toolChoice:O,toolWarnings:L}=v8({tools:u,toolChoice:f});return{args:{...S,tools:j,tool_choice:O},warnings:[...y,...L]}}async doGenerate(e){var t,r,n,o,s,i,a;const{args:l,warnings:c}=await this.getArgs(e),{responseHeaders:u,value:f,rawValue:p}=await zt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:xt(this.config.headers(),e.headers),body:l,failedResponseHandler:Tr,successfulResponseHandler:Ft(g8),abortSignal:e.abortSignal,fetch:this.config.fetch}),h=f.choices[0],g=[],v=h.message.content;v!=null&&v.length>0&&g.push({type:"text",text:v});for(const y of(t=h.message.tool_calls)!=null?t:[])g.push({type:"tool-call",toolCallId:(r=y.id)!=null?r:Dt(),toolName:y.function.name,input:y.function.arguments});for(const y of(n=h.message.annotations)!=null?n:[])g.push({type:"source",sourceType:"url",id:Dt(),url:y.url_citation.url,title:y.url_citation.title});const _=(o=f.usage)==null?void 0:o.completion_tokens_details;(s=f.usage)==null||s.prompt_tokens_details;const w={openai:{}};return _?.accepted_prediction_tokens!=null&&(w.openai.acceptedPredictionTokens=_?.accepted_prediction_tokens),_?.rejected_prediction_tokens!=null&&(w.openai.rejectedPredictionTokens=_?.rejected_prediction_tokens),((i=h.logprobs)==null?void 0:i.content)!=null&&(w.openai.logprobs=h.logprobs.content),{content:g,finishReason:{unified:R2(h.finish_reason),raw:(a=h.finish_reason)!=null?a:void 0},usage:$2(f.usage),request:{body:l},response:{...du(f),headers:u,body:p},warnings:c,providerMetadata:w}}async doStream(e){const{args:t,warnings:r}=await this.getArgs(e),n={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:o,value:s}=await zt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:xt(this.config.headers(),e.headers),body:n,failedResponseHandler:Tr,successfulResponseHandler:aa(_8),abortSignal:e.abortSignal,fetch:this.config.fetch}),i=[];let a={unified:"other",raw:void 0},l,c=!1,u=!1;const f={openai:{}};return{stream:s.pipeThrough(new TransformStream({start(p){p.enqueue({type:"stream-start",warnings:r})},transform(p,h){var g,v,_,w,y,m,C,b,T,I,R,S,j,O,L,z,B;if(e.includeRawChunks&&h.enqueue({type:"raw",rawValue:p.rawValue}),!p.success){a={unified:"error",raw:void 0},h.enqueue({type:"error",error:p.error});return}const X=p.value;if("error"in X){a={unified:"error",raw:void 0},h.enqueue({type:"error",error:X.error});return}if(!c){const Z=du(X);Object.values(Z).some(Boolean)&&(c=!0,h.enqueue({type:"response-metadata",...du(X)}))}X.usage!=null&&(l=X.usage,((g=X.usage.completion_tokens_details)==null?void 0:g.accepted_prediction_tokens)!=null&&(f.openai.acceptedPredictionTokens=(v=X.usage.completion_tokens_details)==null?void 0:v.accepted_prediction_tokens),((_=X.usage.completion_tokens_details)==null?void 0:_.rejected_prediction_tokens)!=null&&(f.openai.rejectedPredictionTokens=(w=X.usage.completion_tokens_details)==null?void 0:w.rejected_prediction_tokens));const ee=X.choices[0];if(ee?.finish_reason!=null&&(a={unified:R2(ee.finish_reason),raw:ee.finish_reason}),((y=ee?.logprobs)==null?void 0:y.content)!=null&&(f.openai.logprobs=ee.logprobs.content),ee?.delta==null)return;const Q=ee.delta;if(Q.content!=null&&(u||(h.enqueue({type:"text-start",id:"0"}),u=!0),h.enqueue({type:"text-delta",id:"0",delta:Q.content})),Q.tool_calls!=null)for(const Z of Q.tool_calls){const ne=Z.index;if(i[ne]==null){if(Z.type!=null&&Z.type!=="function")throw new Qi({data:Z,message:"Expected 'function' type."});if(Z.id==null)throw new Qi({data:Z,message:"Expected 'id' to be a string."});if(((m=Z.function)==null?void 0:m.name)==null)throw new Qi({data:Z,message:"Expected 'function.name' to be a string."});h.enqueue({type:"tool-input-start",id:Z.id,toolName:Z.function.name}),i[ne]={id:Z.id,type:"function",function:{name:Z.function.name,arguments:(C=Z.function.arguments)!=null?C:""},hasFinished:!1};const E=i[ne];((b=E.function)==null?void 0:b.name)!=null&&((T=E.function)==null?void 0:T.arguments)!=null&&(E.function.arguments.length>0&&h.enqueue({type:"tool-input-delta",id:E.id,delta:E.function.arguments}),Gf(E.function.arguments)&&(h.enqueue({type:"tool-input-end",id:E.id}),h.enqueue({type:"tool-call",toolCallId:(I=E.id)!=null?I:Dt(),toolName:E.function.name,input:E.function.arguments}),E.hasFinished=!0));continue}const D=i[ne];D.hasFinished||(((R=Z.function)==null?void 0:R.arguments)!=null&&(D.function.arguments+=(j=(S=Z.function)==null?void 0:S.arguments)!=null?j:""),h.enqueue({type:"tool-input-delta",id:D.id,delta:(O=Z.function.arguments)!=null?O:""}),((L=D.function)==null?void 0:L.name)!=null&&((z=D.function)==null?void 0:z.arguments)!=null&&Gf(D.function.arguments)&&(h.enqueue({type:"tool-input-end",id:D.id}),h.enqueue({type:"tool-call",toolCallId:(B=D.id)!=null?B:Dt(),toolName:D.function.name,input:D.function.arguments}),D.hasFinished=!0))}if(Q.annotations!=null)for(const Z of Q.annotations)h.enqueue({type:"source",sourceType:"url",id:Dt(),url:Z.url_citation.url,title:Z.url_citation.title})},flush(p){u&&p.enqueue({type:"text-end",id:"0"}),p.enqueue({type:"finish",finishReason:a,usage:$2(l),...f!=null?{providerMetadata:f}:{}})}})),request:{body:n},response:{headers:o}}}};function P2(e){var t,r,n,o;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const s=(t=e.prompt_tokens)!=null?t:0,i=(r=e.completion_tokens)!=null?r:0;return{inputTokens:{total:(n=e.prompt_tokens)!=null?n:void 0,noCache:s,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:(o=e.completion_tokens)!=null?o:void 0,text:i,reasoning:void 0},raw:e}}function b8({prompt:e,user:t="user",assistant:r="assistant"}){let n="";e[0].role==="system"&&(n+=`${e[0].content}
69
-
70
- `,e=e.slice(1));for(const{role:o,content:s}of e)switch(o){case"system":throw new Cn({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("");n+=`${t}:
71
- ${i}
72
-
73
- `;break}case"assistant":{const i=s.map(a=>{switch(a.type){case"text":return a.text;case"tool-call":throw new Pr({functionality:"tool-call messages"})}}).join("");n+=`${r}:
74
- ${i}
75
-
76
- `;break}case"tool":throw new Pr({functionality:"tool messages"});default:{const i=o;throw new Error(`Unsupported role: ${i}`)}}return n+=`${r}:
77
- `,{prompt:n,stopSequences:[`
78
- ${t}:`]}}function M2({id:e,model:t,created:r}){return{id:e??void 0,modelId:t??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function N2(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"other"}}var k8=ve(()=>ye(k({id:d().nullish(),created:N().nullish(),model:d().nullish(),choices:q(k({text:d(),finish_reason:d(),logprobs:k({tokens:q(d()),token_logprobs:q(N()),top_logprobs:q(he(d(),N())).nullish()}).nullish()})),usage:k({prompt_tokens:N(),completion_tokens:N(),total_tokens:N()}).nullish()}))),T8=ve(()=>ye(ae([k({id:d().nullish(),created:N().nullish(),model:d().nullish(),choices:q(k({text:d(),finish_reason:d().nullish(),index:N(),logprobs:k({tokens:q(d()),token_logprobs:q(N()),top_logprobs:q(he(d(),N())).nullish()}).nullish()})),usage:k({prompt_tokens:N(),completion_tokens:N(),total_tokens:N()}).nullish()}),uu]))),O2=ve(()=>ye(k({echo:ge().optional(),logitBias:he(d(),N()).optional(),suffix:d().optional(),user:d().optional(),logprobs:ae([ge(),N()]).optional()}))),C8=class{constructor(e,t){this.specificationVersion="v3",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:r,topP:n,topK:o,frequencyPenalty:s,presencePenalty:i,stopSequences:a,responseFormat:l,tools:c,toolChoice:u,seed:f,providerOptions:p}){const h=[],g={...await Vr({provider:"openai",providerOptions:p,schema:O2}),...await Vr({provider:this.providerOptionsName,providerOptions:p,schema:O2})};o!=null&&h.push({type:"unsupported",feature:"topK"}),c?.length&&h.push({type:"unsupported",feature:"tools"}),u!=null&&h.push({type:"unsupported",feature:"toolChoice"}),l!=null&&l.type!=="text"&&h.push({type:"unsupported",feature:"responseFormat",details:"JSON response format is not supported."});const{prompt:v,stopSequences:_}=b8({prompt:e}),w=[..._??[],...a??[]];return{args:{model:this.modelId,echo:g.echo,logit_bias:g.logitBias,logprobs:g?.logprobs===!0?0:g?.logprobs===!1?void 0:g?.logprobs,suffix:g.suffix,user:g.user,max_tokens:t,temperature:r,top_p:n,frequency_penalty:s,presence_penalty:i,seed:f,prompt:v,stop:w.length>0?w:void 0},warnings:h}}async doGenerate(e){var t;const{args:r,warnings:n}=await this.getArgs(e),{responseHeaders:o,value:s,rawValue:i}=await zt({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:xt(this.config.headers(),e.headers),body:r,failedResponseHandler:Tr,successfulResponseHandler:Ft(k8),abortSignal:e.abortSignal,fetch:this.config.fetch}),a=s.choices[0],l={openai:{}};return a.logprobs!=null&&(l.openai.logprobs=a.logprobs),{content:[{type:"text",text:a.text}],usage:P2(s.usage),finishReason:{unified:N2(a.finish_reason),raw:(t=a.finish_reason)!=null?t:void 0},request:{body:r},response:{...M2(s),headers:o,body:i},providerMetadata:l,warnings:n}}async doStream(e){const{args:t,warnings:r}=await this.getArgs(e),n={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:o,value:s}=await zt({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:xt(this.config.headers(),e.headers),body:n,failedResponseHandler:Tr,successfulResponseHandler:aa(T8),abortSignal:e.abortSignal,fetch:this.config.fetch});let i={unified:"other",raw:void 0};const a={openai:{}};let l,c=!0;return{stream:s.pipeThrough(new TransformStream({start(u){u.enqueue({type:"stream-start",warnings:r})},transform(u,f){if(e.includeRawChunks&&f.enqueue({type:"raw",rawValue:u.rawValue}),!u.success){i={unified:"error",raw:void 0},f.enqueue({type:"error",error:u.error});return}const p=u.value;if("error"in p){i={unified:"error",raw:void 0},f.enqueue({type:"error",error:p.error});return}c&&(c=!1,f.enqueue({type:"response-metadata",...M2(p)}),f.enqueue({type:"text-start",id:"0"})),p.usage!=null&&(l=p.usage);const h=p.choices[0];h?.finish_reason!=null&&(i={unified:N2(h.finish_reason),raw:h.finish_reason}),h?.logprobs!=null&&(a.openai.logprobs=h.logprobs),h?.text!=null&&h.text.length>0&&f.enqueue({type:"text-delta",id:"0",delta:h.text})},flush(u){c||u.enqueue({type:"text-end",id:"0"}),u.enqueue({type:"finish",finishReason:i,providerMetadata:a,usage:P2(l)})}})),request:{body:n},response:{headers:o}}}},S8=ve(()=>ye(k({dimensions:N().optional(),user:d().optional()}))),I8=ve(()=>ye(k({data:q(k({embedding:q(N())})),usage:k({prompt_tokens:N()}).nullish()}))),x8=class{constructor(e,t){this.specificationVersion="v3",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:r,providerOptions:n}){var o;if(e.length>this.maxEmbeddingsPerCall)throw new Rv({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const s=(o=await Vr({provider:"openai",providerOptions:n,schema:S8}))!=null?o:{},{responseHeaders:i,value:a,rawValue:l}=await zt({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:Tr,successfulResponseHandler:Ft(I8),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:a.data.map(c=>c.embedding),usage:a.usage?{tokens:a.usage.prompt_tokens}:void 0,response:{headers:i,body:l}}}},A2=ve(()=>ye(k({created:N().nullish(),data:q(k({b64_json:d(),revised_prompt:d().nullish()})),background:d().nullish(),output_format:d().nullish(),size:d().nullish(),quality:d().nullish(),usage:k({input_tokens:N().nullish(),output_tokens:N().nullish(),total_tokens:N().nullish(),input_tokens_details:k({image_tokens:N().nullish(),text_tokens:N().nullish()}).nullish()}).nullish()}))),E8={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10,"chatgpt-image-latest":10},$8=["chatgpt-image-","gpt-image-1-mini","gpt-image-1.5","gpt-image-1"];function R8(e){return $8.some(t=>e.startsWith(t))}var P8=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get maxImagesPerCall(){var e;return(e=E8[this.modelId])!=null?e:1}get provider(){return this.config.provider}async doGenerate({prompt:e,files:t,mask:r,n,size:o,aspectRatio:s,seed:i,providerOptions:a,headers:l,abortSignal:c}){var u,f,p,h,g,v,_,w,y,m,C;const b=[];s!=null&&b.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),i!=null&&b.push({type:"unsupported",feature:"seed"});const T=(p=(f=(u=this.config._internal)==null?void 0:u.currentDate)==null?void 0:f.call(u))!=null?p:new Date;if(t!=null){const{value:S,responseHeaders:j}=await Kf({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:xt(this.config.headers(),l),formData:o9({model:this.modelId,prompt:e,image:await Promise.all(t.map(O=>O.type==="file"?new Blob([O.data instanceof Uint8Array?new Blob([O.data],{type:O.mediaType}):new Blob([oo(O.data)],{type:O.mediaType})],{type:O.mediaType}):qf(O.url))),mask:r!=null?await M8(r):void 0,n,size:o,...(h=a.openai)!=null?h:{}}),failedResponseHandler:Tr,successfulResponseHandler:Ft(A2),abortSignal:c,fetch:this.config.fetch});return{images:S.data.map(O=>O.b64_json),warnings:b,usage:S.usage!=null?{inputTokens:(g=S.usage.input_tokens)!=null?g:void 0,outputTokens:(v=S.usage.output_tokens)!=null?v:void 0,totalTokens:(_=S.usage.total_tokens)!=null?_:void 0}:void 0,response:{timestamp:T,modelId:this.modelId,headers:j},providerMetadata:{openai:{images:S.data.map((O,L)=>{var z,B,X,ee,Q,Z;return{...O.revised_prompt?{revisedPrompt:O.revised_prompt}:{},created:(z=S.created)!=null?z:void 0,size:(B=S.size)!=null?B:void 0,quality:(X=S.quality)!=null?X:void 0,background:(ee=S.background)!=null?ee:void 0,outputFormat:(Q=S.output_format)!=null?Q:void 0,...q2((Z=S.usage)==null?void 0:Z.input_tokens_details,L,S.data.length)}})}}}}const{value:I,responseHeaders:R}=await zt({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:xt(this.config.headers(),l),body:{model:this.modelId,prompt:e,n,size:o,...(w=a.openai)!=null?w:{},...R8(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:Tr,successfulResponseHandler:Ft(A2),abortSignal:c,fetch:this.config.fetch});return{images:I.data.map(S=>S.b64_json),warnings:b,usage:I.usage!=null?{inputTokens:(y=I.usage.input_tokens)!=null?y:void 0,outputTokens:(m=I.usage.output_tokens)!=null?m:void 0,totalTokens:(C=I.usage.total_tokens)!=null?C:void 0}:void 0,response:{timestamp:T,modelId:this.modelId,headers:R},providerMetadata:{openai:{images:I.data.map((S,j)=>{var O,L,z,B,X,ee;return{...S.revised_prompt?{revisedPrompt:S.revised_prompt}:{},created:(O=I.created)!=null?O:void 0,size:(L=I.size)!=null?L:void 0,quality:(z=I.quality)!=null?z:void 0,background:(B=I.background)!=null?B:void 0,outputFormat:(X=I.output_format)!=null?X:void 0,...q2((ee=I.usage)==null?void 0:ee.input_tokens_details,j,I.data.length)}})}}}}};function q2(e,t,r){if(e==null)return{};const n={};if(e.image_tokens!=null){const o=Math.floor(e.image_tokens/r),s=e.image_tokens-o*(r-1);n.imageTokens=t===r-1?s:o}if(e.text_tokens!=null){const o=Math.floor(e.text_tokens/r),s=e.text_tokens-o*(r-1);n.textTokens=t===r-1?s:o}return n}async function M8(e){if(!e)return;if(e.type==="url")return qf(e.url);const t=e.data instanceof Uint8Array?e.data:oo(e.data);return new Blob([t],{type:e.mediaType})}var L2=ve(()=>ye(k({callId:d(),operation:Ue("type",[k({type:P("create_file"),path:d(),diff:d()}),k({type:P("delete_file"),path:d()}),k({type:P("update_file"),path:d(),diff:d()})])}))),j2=ve(()=>ye(k({status:ce(["completed","failed"]),output:d().optional()}))),N8=cr({id:"openai.apply_patch",inputSchema:L2,outputSchema:j2}),O8=N8,A8=ve(()=>ye(k({code:d().nullish(),containerId:d()}))),q8=ve(()=>ye(k({outputs:q(Ue("type",[k({type:P("logs"),logs:d()}),k({type:P("image"),url:d()})])).nullish()}))),L8=ve(()=>ye(k({container:ae([d(),k({fileIds:q(d()).optional()})]).optional()}))),j8=cr({id:"openai.code_interpreter",inputSchema:A8,outputSchema:q8}),D8=(e={})=>j8(e),U8=ve(()=>ye(k({name:d(),description:d().optional(),format:ae([k({type:P("grammar"),syntax:ce(["regex","lark"]),definition:d()}),k({type:P("text")})]).optional()}))),z8=ve(()=>ye(d())),F8=u4({id:"openai.custom",inputSchema:z8}),V8=e=>F8(e),D2=k({key:d(),type:ce(["eq","ne","gt","gte","lt","lte","in","nin"]),value:ae([d(),N(),ge(),q(d())])}),U2=k({type:ce(["and","or"]),filters:q(ae([D2,Ks(()=>U2)]))}),Z8=ve(()=>ye(k({vectorStoreIds:q(d()),maxNumResults:N().optional(),ranking:k({ranker:d().optional(),scoreThreshold:N().optional()}).optional(),filters:ae([D2,U2]).optional()}))),B8=ve(()=>ye(k({queries:q(d()),results:q(k({attributes:he(d(),Ie()),fileId:d(),filename:d(),score:N(),text:d()})).nullable()}))),H8=cr({id:"openai.file_search",inputSchema:k({}),outputSchema:B8}),J8=ve(()=>ye(k({background:ce(["auto","opaque","transparent"]).optional(),inputFidelity:ce(["low","high"]).optional(),inputImageMask:k({fileId:d().optional(),imageUrl:d().optional()}).optional(),model:d().optional(),moderation:ce(["auto"]).optional(),outputCompression:N().int().min(0).max(100).optional(),outputFormat:ce(["png","jpeg","webp"]).optional(),partialImages:N().int().min(0).max(3).optional(),quality:ce(["auto","low","medium","high"]).optional(),size:ce(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),G8=ve(()=>ye(k({}))),W8=ve(()=>ye(k({result:d()}))),K8=cr({id:"openai.image_generation",inputSchema:G8,outputSchema:W8}),Y8=(e={})=>K8(e),z2=ve(()=>ye(k({action:k({type:P("exec"),command:q(d()),timeoutMs:N().optional(),user:d().optional(),workingDirectory:d().optional(),env:he(d(),d()).optional()})}))),F2=ve(()=>ye(k({output:d()}))),Q8=cr({id:"openai.local_shell",inputSchema:z2,outputSchema:F2}),V2=ve(()=>ye(k({action:k({commands:q(d()),timeoutMs:N().optional(),maxOutputLength:N().optional()})}))),pu=ve(()=>ye(k({output:q(k({stdout:d(),stderr:d(),outcome:Ue("type",[k({type:P("timeout")}),k({type:P("exit"),exitCode:N()})])}))}))),X8=q(Ue("type",[k({type:P("skillReference"),skillId:d(),version:d().optional()}),k({type:P("inline"),name:d(),description:d(),source:k({type:P("base64"),mediaType:P("application/zip"),data:d()})})])).optional(),eI=ve(()=>ye(k({environment:ae([k({type:P("containerAuto"),fileIds:q(d()).optional(),memoryLimit:ce(["1g","4g","16g","64g"]).optional(),networkPolicy:Ue("type",[k({type:P("disabled")}),k({type:P("allowlist"),allowedDomains:q(d()),domainSecrets:q(k({domain:d(),name:d(),value:d()})).optional()})]).optional(),skills:X8}),k({type:P("containerReference"),containerId:d()}),k({type:P("local").optional(),skills:q(k({name:d(),description:d(),path:d()})).optional()})]).optional()}))),tI=cr({id:"openai.shell",inputSchema:V2,outputSchema:pu}),rI=ve(()=>ye(k({execution:ce(["server","client"]).optional(),description:d().optional(),parameters:he(d(),Ie()).optional()}))),fu=ve(()=>ye(k({arguments:Ie().optional(),call_id:d().nullish()}))),hu=ve(()=>ye(k({tools:q(he(d(),Ie()))}))),nI=cr({id:"openai.tool_search",inputSchema:fu,outputSchema:hu}),oI=(e={})=>nI(e),sI=ve(()=>ye(k({externalWebAccess:ge().optional(),filters:k({allowedDomains:q(d()).optional()}).optional(),searchContextSize:ce(["low","medium","high"]).optional(),userLocation:k({type:P("approximate"),country:d().optional(),city:d().optional(),region:d().optional(),timezone:d().optional()}).optional()}))),aI=ve(()=>ye(k({}))),iI=ve(()=>ye(k({action:Ue("type",[k({type:P("search"),query:d().optional()}),k({type:P("openPage"),url:d().nullish()}),k({type:P("findInPage"),url:d().nullish(),pattern:d().nullish()})]).optional(),sources:q(Ue("type",[k({type:P("url"),url:d()}),k({type:P("api"),name:d()})])).optional()}))),lI=cr({id:"openai.web_search",inputSchema:aI,outputSchema:iI}),cI=(e={})=>lI(e),uI=ve(()=>ye(k({searchContextSize:ce(["low","medium","high"]).optional(),userLocation:k({type:P("approximate"),country:d().optional(),city:d().optional(),region:d().optional(),timezone:d().optional()}).optional()}))),dI=ve(()=>ye(k({}))),pI=ve(()=>ye(k({action:Ue("type",[k({type:P("search"),query:d().optional()}),k({type:P("openPage"),url:d().nullish()}),k({type:P("findInPage"),url:d().nullish(),pattern:d().nullish()})]).optional()}))),fI=cr({id:"openai.web_search_preview",inputSchema:dI,outputSchema:pI}),mu=Ks(()=>ae([d(),N(),ge(),Do(),q(mu),he(d(),mu)])),hI=ve(()=>ye(k({serverLabel:d(),allowedTools:ae([q(d()),k({readOnly:ge().optional(),toolNames:q(d()).optional()})]).optional(),authorization:d().optional(),connectorId:d().optional(),headers:he(d(),d()).optional(),requireApproval:ae([ce(["always","never"]),k({never:k({toolNames:q(d()).optional()}).optional()})]).optional(),serverDescription:d().optional(),serverUrl:d().optional()}).refine(e=>e.serverUrl!=null||e.connectorId!=null,"One of serverUrl or connectorId must be provided."))),mI=ve(()=>ye(k({}))),gI=ve(()=>ye(k({type:P("call"),serverLabel:d(),name:d(),arguments:d(),output:d().nullish(),error:ae([d(),mu]).optional()}))),_I=cr({id:"openai.mcp",inputSchema:mI,outputSchema:gI}),yI=e=>_I(e),vI={applyPatch:O8,customTool:V8,codeInterpreter:D8,fileSearch:H8,imageGeneration:Y8,localShell:Q8,shell:tI,webSearchPreview:fI,webSearch:cI,mcp:yI,toolSearch:oI};function Z2(e){var t,r,n,o;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const s=e.input_tokens,i=e.output_tokens,a=(r=(t=e.input_tokens_details)==null?void 0:t.cached_tokens)!=null?r:0,l=(o=(n=e.output_tokens_details)==null?void 0:n.reasoning_tokens)!=null?o:0;return{inputTokens:{total:s,noCache:s-a,cacheRead:a,cacheWrite:void 0},outputTokens:{total:i,text:i-l,reasoning:l},raw:e}}function B2(e,t){return t?t.some(r=>e.startsWith(r)):!1}async function wI({prompt:e,toolNameMapping:t,systemMessageMode:r,providerOptionsName:n,fileIdPrefixes:o,store:s,hasConversation:i=!1,hasLocalShellTool:a=!1,hasShellTool:l=!1,hasApplyPatchTool:c=!1,customProviderToolNames:u}){var f,p,h,g,v,_,w,y,m,C,b,T,I,R,S,j,O;let L=[];const z=[],B=new Set;for(const{role:X,content:ee}of e)switch(X){case"system":{switch(r){case"system":{L.push({role:"system",content:ee});break}case"developer":{L.push({role:"developer",content:ee});break}case"remove":{z.push({type:"other",message:"system messages are removed for this model"});break}default:{const Q=r;throw new Error(`Unsupported system message mode: ${Q}`)}}break}case"user":{L.push({role:"user",content:ee.map((Q,Z)=>{var ne,D,E;switch(Q.type){case"text":return{type:"input_text",text:Q.text};case"file":if(Q.mediaType.startsWith("image/")){const U=Q.mediaType==="image/*"?"image/jpeg":Q.mediaType;return{type:"input_image",...Q.data instanceof URL?{image_url:Q.data.toString()}:typeof Q.data=="string"&&B2(Q.data,o)?{file_id:Q.data}:{image_url:`data:${U};base64,${ao(Q.data)}`},detail:(D=(ne=Q.providerOptions)==null?void 0:ne[n])==null?void 0:D.imageDetail}}else{if(Q.mediaType==="application/pdf")return Q.data instanceof URL?{type:"input_file",file_url:Q.data.toString()}:{type:"input_file",...typeof Q.data=="string"&&B2(Q.data,o)?{file_id:Q.data}:{filename:(E=Q.filename)!=null?E:`part-${Z}.pdf`,file_data:`data:application/pdf;base64,${ao(Q.data)}`}};throw new Pr({functionality:`file part media type ${Q.mediaType}`})}}})});break}case"assistant":{const Q={};for(const Z of ee)switch(Z.type){case"text":{const ne=(f=Z.providerOptions)==null?void 0:f[n],D=ne?.itemId,E=ne?.phase;if(i&&D!=null)break;if(s&&D!=null){L.push({type:"item_reference",id:D});break}L.push({role:"assistant",content:[{type:"output_text",text:Z.text}],id:D,...E!=null&&{phase:E}});break}case"tool-call":{const ne=(_=(h=(p=Z.providerOptions)==null?void 0:p[n])==null?void 0:h.itemId)!=null?_:(v=(g=Z.providerMetadata)==null?void 0:g[n])==null?void 0:v.itemId;if(i&&ne!=null)break;const D=t.toProviderToolName(Z.toolName);if(D==="tool_search"){if(s&&ne!=null){L.push({type:"item_reference",id:ne});break}const E=typeof Z.input=="string"?await Jf({text:Z.input,schema:fu}):await dt({value:Z.input,schema:fu}),U=E.call_id!=null?"client":"server";L.push({type:"tool_search_call",id:ne??Z.toolCallId,execution:U,call_id:(w=E.call_id)!=null?w:null,status:"completed",arguments:E.arguments});break}if(Z.providerExecuted){s&&ne!=null&&L.push({type:"item_reference",id:ne});break}if(s&&ne!=null){L.push({type:"item_reference",id:ne});break}if(a&&D==="local_shell"){const E=await dt({value:Z.input,schema:z2});L.push({type:"local_shell_call",call_id:Z.toolCallId,id:ne,action:{type:"exec",command:E.action.command,timeout_ms:E.action.timeoutMs,user:E.action.user,working_directory:E.action.workingDirectory,env:E.action.env}});break}if(l&&D==="shell"){const E=await dt({value:Z.input,schema:V2});L.push({type:"shell_call",call_id:Z.toolCallId,id:ne,status:"completed",action:{commands:E.action.commands,timeout_ms:E.action.timeoutMs,max_output_length:E.action.maxOutputLength}});break}if(c&&D==="apply_patch"){const E=await dt({value:Z.input,schema:L2});L.push({type:"apply_patch_call",call_id:E.callId,id:ne,status:"completed",operation:E.operation});break}if(u?.has(D)){L.push({type:"custom_tool_call",call_id:Z.toolCallId,name:D,input:typeof Z.input=="string"?Z.input:JSON.stringify(Z.input),id:ne});break}L.push({type:"function_call",call_id:Z.toolCallId,name:D,arguments:JSON.stringify(Z.input),id:ne});break}case"tool-result":{if(Z.output.type==="execution-denied"||Z.output.type==="json"&&typeof Z.output.value=="object"&&Z.output.value!=null&&"type"in Z.output.value&&Z.output.value.type==="execution-denied"||i)break;const ne=t.toProviderToolName(Z.toolName);if(ne==="tool_search"){const D=(C=(m=(y=Z.providerOptions)==null?void 0:y[n])==null?void 0:m.itemId)!=null?C:Z.toolCallId;if(s)L.push({type:"item_reference",id:D});else if(Z.output.type==="json"){const E=await dt({value:Z.output.value,schema:hu});L.push({type:"tool_search_output",id:D,execution:"server",call_id:null,status:"completed",tools:E.tools})}break}if(l&&ne==="shell"){if(Z.output.type==="json"){const D=await dt({value:Z.output.value,schema:pu});L.push({type:"shell_call_output",call_id:Z.toolCallId,output:D.output.map(E=>({stdout:E.stdout,stderr:E.stderr,outcome:E.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:E.outcome.exitCode}}))})}break}if(s){const D=(I=(T=(b=Z.providerOptions)==null?void 0:b[n])==null?void 0:T.itemId)!=null?I:Z.toolCallId;L.push({type:"item_reference",id:D})}else z.push({type:"other",message:`Results for OpenAI tool ${Z.toolName} are not sent to the API when store is false`});break}case"reasoning":{const ne=await Vr({provider:n,providerOptions:Z.providerOptions,schema:bI}),D=ne?.itemId;if(i&&D!=null)break;if(D!=null){const E=Q[D];if(s)E===void 0&&(L.push({type:"item_reference",id:D}),Q[D]={type:"reasoning",id:D,summary:[]});else{const U=[];Z.text.length>0?U.push({type:"summary_text",text:Z.text}):E!==void 0&&z.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(Z)}.`}),E===void 0?(Q[D]={type:"reasoning",id:D,encrypted_content:ne?.reasoningEncryptedContent,summary:U},L.push(Q[D])):(E.summary.push(...U),ne?.reasoningEncryptedContent!=null&&(E.encrypted_content=ne.reasoningEncryptedContent))}}else{const E=ne?.reasoningEncryptedContent;if(E!=null){const U=[];Z.text.length>0&&U.push({type:"summary_text",text:Z.text}),L.push({type:"reasoning",encrypted_content:E,summary:U})}else z.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(Z)}.`})}break}}break}case"tool":{for(const Q of ee){if(Q.type==="tool-approval-response"){const E=Q;if(B.has(E.approvalId))continue;B.add(E.approvalId),s&&L.push({type:"item_reference",id:E.approvalId}),L.push({type:"mcp_approval_response",approval_request_id:E.approvalId,approve:E.approved});continue}const Z=Q.output;if(Z.type==="execution-denied"&&((S=(R=Z.providerOptions)==null?void 0:R.openai)==null?void 0:S.approvalId))continue;const ne=t.toProviderToolName(Q.toolName);if(ne==="tool_search"&&Z.type==="json"){const E=await dt({value:Z.value,schema:hu});L.push({type:"tool_search_output",execution:"client",call_id:Q.toolCallId,status:"completed",tools:E.tools});continue}if(a&&ne==="local_shell"&&Z.type==="json"){const E=await dt({value:Z.value,schema:F2});L.push({type:"local_shell_call_output",call_id:Q.toolCallId,output:E.output});continue}if(l&&ne==="shell"&&Z.type==="json"){const E=await dt({value:Z.value,schema:pu});L.push({type:"shell_call_output",call_id:Q.toolCallId,output:E.output.map(U=>({stdout:U.stdout,stderr:U.stderr,outcome:U.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:U.outcome.exitCode}}))});continue}if(c&&Q.toolName==="apply_patch"&&Z.type==="json"){const E=await dt({value:Z.value,schema:j2});L.push({type:"apply_patch_call_output",call_id:Q.toolCallId,status:E.status,output:E.output});continue}if(u?.has(ne)){let E;switch(Z.type){case"text":case"error-text":E=Z.value;break;case"execution-denied":E=(j=Z.reason)!=null?j:"Tool execution denied.";break;case"json":case"error-json":E=JSON.stringify(Z.value);break;case"content":E=Z.value.map(U=>{var F;switch(U.type){case"text":return{type:"input_text",text:U.text};case"image-data":return{type:"input_image",image_url:`data:${U.mediaType};base64,${U.data}`};case"image-url":return{type:"input_image",image_url:U.url};case"file-data":return{type:"input_file",filename:(F=U.filename)!=null?F:"data",file_data:`data:${U.mediaType};base64,${U.data}`};case"file-url":return{type:"input_file",file_url:U.url};default:z.push({type:"other",message:`unsupported custom tool content part type: ${U.type}`});return}}).filter(Df);break;default:E=""}L.push({type:"custom_tool_call_output",call_id:Q.toolCallId,output:E});continue}let D;switch(Z.type){case"text":case"error-text":D=Z.value;break;case"execution-denied":D=(O=Z.reason)!=null?O:"Tool execution denied.";break;case"json":case"error-json":D=JSON.stringify(Z.value);break;case"content":D=Z.value.map(E=>{var U;switch(E.type){case"text":return{type:"input_text",text:E.text};case"image-data":return{type:"input_image",image_url:`data:${E.mediaType};base64,${E.data}`};case"image-url":return{type:"input_image",image_url:E.url};case"file-data":return{type:"input_file",filename:(U=E.filename)!=null?U:"data",file_data:`data:${E.mediaType};base64,${E.data}`};case"file-url":return{type:"input_file",file_url:E.url};default:{z.push({type:"other",message:`unsupported tool content part type: ${E.type}`});return}}}).filter(Df);break}L.push({type:"function_call_output",call_id:Q.toolCallId,output:D})}break}default:{const Q=X;throw new Error(`Unsupported role: ${Q}`)}}return!s&&L.some(X=>"type"in X&&X.type==="reasoning"&&X.encrypted_content==null)&&(z.push({type:"other",message:"Reasoning parts without encrypted content are not supported when store is false. Skipping reasoning parts."}),L=L.filter(X=>!("type"in X)||X.type!=="reasoning"||X.encrypted_content!=null)),{input:L,warnings:z}}var bI=k({itemId:d().nullish(),reasoningEncryptedContent:d().nullish()});function gu({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":"other"}}var vs=Ks(()=>ae([d(),N(),ge(),Do(),q(vs),he(d(),vs.optional())])),kI=ve(()=>ye(ae([k({type:P("response.output_text.delta"),item_id:d(),delta:d(),logprobs:q(k({token:d(),logprob:N(),top_logprobs:q(k({token:d(),logprob:N()}))})).nullish()}),k({type:ce(["response.completed","response.incomplete"]),response:k({incomplete_details:k({reason:d()}).nullish(),usage:k({input_tokens:N(),input_tokens_details:k({cached_tokens:N().nullish()}).nullish(),output_tokens:N(),output_tokens_details:k({reasoning_tokens:N().nullish()}).nullish()}),service_tier:d().nullish()})}),k({type:P("response.failed"),response:k({error:k({code:d().nullish(),message:d()}).nullish(),incomplete_details:k({reason:d()}).nullish(),usage:k({input_tokens:N(),input_tokens_details:k({cached_tokens:N().nullish()}).nullish(),output_tokens:N(),output_tokens_details:k({reasoning_tokens:N().nullish()}).nullish()}).nullish(),service_tier:d().nullish()})}),k({type:P("response.created"),response:k({id:d(),created_at:N(),model:d(),service_tier:d().nullish()})}),k({type:P("response.output_item.added"),output_index:N(),item:Ue("type",[k({type:P("message"),id:d(),phase:ce(["commentary","final_answer"]).nullish()}),k({type:P("reasoning"),id:d(),encrypted_content:d().nullish()}),k({type:P("function_call"),id:d(),call_id:d(),name:d(),arguments:d()}),k({type:P("web_search_call"),id:d(),status:d()}),k({type:P("computer_call"),id:d(),status:d()}),k({type:P("file_search_call"),id:d()}),k({type:P("image_generation_call"),id:d()}),k({type:P("code_interpreter_call"),id:d(),container_id:d(),code:d().nullable(),outputs:q(Ue("type",[k({type:P("logs"),logs:d()}),k({type:P("image"),url:d()})])).nullable(),status:d()}),k({type:P("mcp_call"),id:d(),status:d(),approval_request_id:d().nullish()}),k({type:P("mcp_list_tools"),id:d()}),k({type:P("mcp_approval_request"),id:d()}),k({type:P("apply_patch_call"),id:d(),call_id:d(),status:ce(["in_progress","completed"]),operation:Ue("type",[k({type:P("create_file"),path:d(),diff:d()}),k({type:P("delete_file"),path:d()}),k({type:P("update_file"),path:d(),diff:d()})])}),k({type:P("custom_tool_call"),id:d(),call_id:d(),name:d(),input:d()}),k({type:P("shell_call"),id:d(),call_id:d(),status:ce(["in_progress","completed","incomplete"]),action:k({commands:q(d())})}),k({type:P("shell_call_output"),id:d(),call_id:d(),status:ce(["in_progress","completed","incomplete"]),output:q(k({stdout:d(),stderr:d(),outcome:Ue("type",[k({type:P("timeout")}),k({type:P("exit"),exit_code:N()})])}))}),k({type:P("tool_search_call"),id:d(),execution:ce(["server","client"]),call_id:d().nullable(),status:ce(["in_progress","completed","incomplete"]),arguments:Ie()}),k({type:P("tool_search_output"),id:d(),execution:ce(["server","client"]),call_id:d().nullable(),status:ce(["in_progress","completed","incomplete"]),tools:q(he(d(),vs.optional()))})])}),k({type:P("response.output_item.done"),output_index:N(),item:Ue("type",[k({type:P("message"),id:d(),phase:ce(["commentary","final_answer"]).nullish()}),k({type:P("reasoning"),id:d(),encrypted_content:d().nullish()}),k({type:P("function_call"),id:d(),call_id:d(),name:d(),arguments:d(),status:P("completed")}),k({type:P("custom_tool_call"),id:d(),call_id:d(),name:d(),input:d(),status:P("completed")}),k({type:P("code_interpreter_call"),id:d(),code:d().nullable(),container_id:d(),outputs:q(Ue("type",[k({type:P("logs"),logs:d()}),k({type:P("image"),url:d()})])).nullable()}),k({type:P("image_generation_call"),id:d(),result:d()}),k({type:P("web_search_call"),id:d(),status:d(),action:Ue("type",[k({type:P("search"),query:d().nullish(),sources:q(Ue("type",[k({type:P("url"),url:d()}),k({type:P("api"),name:d()})])).nullish()}),k({type:P("open_page"),url:d().nullish()}),k({type:P("find_in_page"),url:d().nullish(),pattern:d().nullish()})]).nullish()}),k({type:P("file_search_call"),id:d(),queries:q(d()),results:q(k({attributes:he(d(),ae([d(),N(),ge()])),file_id:d(),filename:d(),score:N(),text:d()})).nullish()}),k({type:P("local_shell_call"),id:d(),call_id:d(),action:k({type:P("exec"),command:q(d()),timeout_ms:N().optional(),user:d().optional(),working_directory:d().optional(),env:he(d(),d()).optional()})}),k({type:P("computer_call"),id:d(),status:P("completed")}),k({type:P("mcp_call"),id:d(),status:d(),arguments:d(),name:d(),server_label:d(),output:d().nullish(),error:ae([d(),k({type:d().optional(),code:ae([N(),d()]).optional(),message:d().optional()}).loose()]).nullish(),approval_request_id:d().nullish()}),k({type:P("mcp_list_tools"),id:d(),server_label:d(),tools:q(k({name:d(),description:d().optional(),input_schema:ht(),annotations:he(d(),Ie()).optional()})),error:ae([d(),k({type:d().optional(),code:ae([N(),d()]).optional(),message:d().optional()}).loose()]).optional()}),k({type:P("mcp_approval_request"),id:d(),server_label:d(),name:d(),arguments:d(),approval_request_id:d().optional()}),k({type:P("apply_patch_call"),id:d(),call_id:d(),status:ce(["in_progress","completed"]),operation:Ue("type",[k({type:P("create_file"),path:d(),diff:d()}),k({type:P("delete_file"),path:d()}),k({type:P("update_file"),path:d(),diff:d()})])}),k({type:P("shell_call"),id:d(),call_id:d(),status:ce(["in_progress","completed","incomplete"]),action:k({commands:q(d())})}),k({type:P("shell_call_output"),id:d(),call_id:d(),status:ce(["in_progress","completed","incomplete"]),output:q(k({stdout:d(),stderr:d(),outcome:Ue("type",[k({type:P("timeout")}),k({type:P("exit"),exit_code:N()})])}))}),k({type:P("tool_search_call"),id:d(),execution:ce(["server","client"]),call_id:d().nullable(),status:ce(["in_progress","completed","incomplete"]),arguments:Ie()}),k({type:P("tool_search_output"),id:d(),execution:ce(["server","client"]),call_id:d().nullable(),status:ce(["in_progress","completed","incomplete"]),tools:q(he(d(),vs.optional()))})])}),k({type:P("response.function_call_arguments.delta"),item_id:d(),output_index:N(),delta:d()}),k({type:P("response.custom_tool_call_input.delta"),item_id:d(),output_index:N(),delta:d()}),k({type:P("response.image_generation_call.partial_image"),item_id:d(),output_index:N(),partial_image_b64:d()}),k({type:P("response.code_interpreter_call_code.delta"),item_id:d(),output_index:N(),delta:d()}),k({type:P("response.code_interpreter_call_code.done"),item_id:d(),output_index:N(),code:d()}),k({type:P("response.output_text.annotation.added"),annotation:Ue("type",[k({type:P("url_citation"),start_index:N(),end_index:N(),url:d(),title:d()}),k({type:P("file_citation"),file_id:d(),filename:d(),index:N()}),k({type:P("container_file_citation"),container_id:d(),file_id:d(),filename:d(),start_index:N(),end_index:N()}),k({type:P("file_path"),file_id:d(),index:N()})])}),k({type:P("response.reasoning_summary_part.added"),item_id:d(),summary_index:N()}),k({type:P("response.reasoning_summary_text.delta"),item_id:d(),summary_index:N(),delta:d()}),k({type:P("response.reasoning_summary_part.done"),item_id:d(),summary_index:N()}),k({type:P("response.apply_patch_call_operation_diff.delta"),item_id:d(),output_index:N(),delta:d(),obfuscation:d().nullish()}),k({type:P("response.apply_patch_call_operation_diff.done"),item_id:d(),output_index:N(),diff:d()}),k({type:P("error"),sequence_number:N(),error:k({type:d(),code:d(),message:d(),param:d().nullish()})}),k({type:d()}).loose().transform(e=>({type:"unknown_chunk",message:e.type}))]))),TI=ve(()=>ye(k({id:d().optional(),created_at:N().optional(),error:k({message:d(),type:d(),param:d().nullish(),code:d()}).nullish(),model:d().optional(),output:q(Ue("type",[k({type:P("message"),role:P("assistant"),id:d(),phase:ce(["commentary","final_answer"]).nullish(),content:q(k({type:P("output_text"),text:d(),logprobs:q(k({token:d(),logprob:N(),top_logprobs:q(k({token:d(),logprob:N()}))})).nullish(),annotations:q(Ue("type",[k({type:P("url_citation"),start_index:N(),end_index:N(),url:d(),title:d()}),k({type:P("file_citation"),file_id:d(),filename:d(),index:N()}),k({type:P("container_file_citation"),container_id:d(),file_id:d(),filename:d(),start_index:N(),end_index:N()}),k({type:P("file_path"),file_id:d(),index:N()})]))}))}),k({type:P("web_search_call"),id:d(),status:d(),action:Ue("type",[k({type:P("search"),query:d().nullish(),sources:q(Ue("type",[k({type:P("url"),url:d()}),k({type:P("api"),name:d()})])).nullish()}),k({type:P("open_page"),url:d().nullish()}),k({type:P("find_in_page"),url:d().nullish(),pattern:d().nullish()})]).nullish()}),k({type:P("file_search_call"),id:d(),queries:q(d()),results:q(k({attributes:he(d(),ae([d(),N(),ge()])),file_id:d(),filename:d(),score:N(),text:d()})).nullish()}),k({type:P("code_interpreter_call"),id:d(),code:d().nullable(),container_id:d(),outputs:q(Ue("type",[k({type:P("logs"),logs:d()}),k({type:P("image"),url:d()})])).nullable()}),k({type:P("image_generation_call"),id:d(),result:d()}),k({type:P("local_shell_call"),id:d(),call_id:d(),action:k({type:P("exec"),command:q(d()),timeout_ms:N().optional(),user:d().optional(),working_directory:d().optional(),env:he(d(),d()).optional()})}),k({type:P("function_call"),call_id:d(),name:d(),arguments:d(),id:d()}),k({type:P("custom_tool_call"),call_id:d(),name:d(),input:d(),id:d()}),k({type:P("computer_call"),id:d(),status:d().optional()}),k({type:P("reasoning"),id:d(),encrypted_content:d().nullish(),summary:q(k({type:P("summary_text"),text:d()}))}),k({type:P("mcp_call"),id:d(),status:d(),arguments:d(),name:d(),server_label:d(),output:d().nullish(),error:ae([d(),k({type:d().optional(),code:ae([N(),d()]).optional(),message:d().optional()}).loose()]).nullish(),approval_request_id:d().nullish()}),k({type:P("mcp_list_tools"),id:d(),server_label:d(),tools:q(k({name:d(),description:d().optional(),input_schema:ht(),annotations:he(d(),Ie()).optional()})),error:ae([d(),k({type:d().optional(),code:ae([N(),d()]).optional(),message:d().optional()}).loose()]).optional()}),k({type:P("mcp_approval_request"),id:d(),server_label:d(),name:d(),arguments:d(),approval_request_id:d().optional()}),k({type:P("apply_patch_call"),id:d(),call_id:d(),status:ce(["in_progress","completed"]),operation:Ue("type",[k({type:P("create_file"),path:d(),diff:d()}),k({type:P("delete_file"),path:d()}),k({type:P("update_file"),path:d(),diff:d()})])}),k({type:P("shell_call"),id:d(),call_id:d(),status:ce(["in_progress","completed","incomplete"]),action:k({commands:q(d())})}),k({type:P("shell_call_output"),id:d(),call_id:d(),status:ce(["in_progress","completed","incomplete"]),output:q(k({stdout:d(),stderr:d(),outcome:Ue("type",[k({type:P("timeout")}),k({type:P("exit"),exit_code:N()})])}))}),k({type:P("tool_search_call"),id:d(),execution:ce(["server","client"]),call_id:d().nullable(),status:ce(["in_progress","completed","incomplete"]),arguments:Ie()}),k({type:P("tool_search_output"),id:d(),execution:ce(["server","client"]),call_id:d().nullable(),status:ce(["in_progress","completed","incomplete"]),tools:q(he(d(),vs.optional()))})])).optional(),service_tier:d().nullish(),incomplete_details:k({reason:d()}).nullish(),usage:k({input_tokens:N(),input_tokens_details:k({cached_tokens:N().nullish()}).nullish(),output_tokens:N(),output_tokens_details:k({reasoning_tokens:N().nullish()}).nullish()}).optional()}))),H2=20,J2=ve(()=>ye(k({conversation:d().nullish(),include:q(ce(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:d().nullish(),logprobs:ae([ge(),N().min(1).max(H2)]).optional(),maxToolCalls:N().nullish(),metadata:ht().nullish(),parallelToolCalls:ge().nullish(),previousResponseId:d().nullish(),promptCacheKey:d().nullish(),promptCacheRetention:ce(["in_memory","24h"]).nullish(),reasoningEffort:d().nullish(),reasoningSummary:d().nullish(),safetyIdentifier:d().nullish(),serviceTier:ce(["auto","flex","priority","default"]).nullish(),store:ge().nullish(),strictJsonSchema:ge().nullish(),textVerbosity:ce(["low","medium","high"]).nullish(),truncation:ce(["auto","disabled"]).nullish(),user:d().nullish(),systemMessageMode:ce(["system","developer","remove"]).optional(),forceReasoning:ge().optional()})));async function CI({tools:e,toolChoice:t,toolNameMapping:r,customProviderToolNames:n}){var o,s;e=e?.length?e:void 0;const i=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:i};const a=[],l=n??new Set;for(const u of e)switch(u.type){case"function":{const f=(o=u.providerOptions)==null?void 0:o.openai,p=f?.deferLoading;a.push({type:"function",name:u.name,description:u.description,parameters:u.inputSchema,...u.strict!=null?{strict:u.strict}:{},...p!=null?{defer_loading:p}:{}});break}case"provider":{switch(u.id){case"openai.file_search":{const f=await dt({value:u.args,schema:Z8});a.push({type:"file_search",vector_store_ids:f.vectorStoreIds,max_num_results:f.maxNumResults,ranking_options:f.ranking?{ranker:f.ranking.ranker,score_threshold:f.ranking.scoreThreshold}:void 0,filters:f.filters});break}case"openai.local_shell":{a.push({type:"local_shell"});break}case"openai.shell":{const f=await dt({value:u.args,schema:eI});a.push({type:"shell",...f.environment&&{environment:SI(f.environment)}});break}case"openai.apply_patch":{a.push({type:"apply_patch"});break}case"openai.web_search_preview":{const f=await dt({value:u.args,schema:uI});a.push({type:"web_search_preview",search_context_size:f.searchContextSize,user_location:f.userLocation});break}case"openai.web_search":{const f=await dt({value:u.args,schema:sI});a.push({type:"web_search",filters:f.filters!=null?{allowed_domains:f.filters.allowedDomains}:void 0,external_web_access:f.externalWebAccess,search_context_size:f.searchContextSize,user_location:f.userLocation});break}case"openai.code_interpreter":{const f=await dt({value:u.args,schema:L8});a.push({type:"code_interpreter",container:f.container==null?{type:"auto",file_ids:void 0}:typeof f.container=="string"?f.container:{type:"auto",file_ids:f.container.fileIds}});break}case"openai.image_generation":{const f=await dt({value:u.args,schema:J8});a.push({type:"image_generation",background:f.background,input_fidelity:f.inputFidelity,input_image_mask:f.inputImageMask?{file_id:f.inputImageMask.fileId,image_url:f.inputImageMask.imageUrl}:void 0,model:f.model,moderation:f.moderation,partial_images:f.partialImages,quality:f.quality,output_compression:f.outputCompression,output_format:f.outputFormat,size:f.size});break}case"openai.mcp":{const f=await dt({value:u.args,schema:hI}),p=v=>({tool_names:v.toolNames}),h=f.requireApproval,g=h==null?void 0:typeof h=="string"?h:h.never!=null?{never:p(h.never)}:void 0;a.push({type:"mcp",server_label:f.serverLabel,allowed_tools:Array.isArray(f.allowedTools)?f.allowedTools:f.allowedTools?{read_only:f.allowedTools.readOnly,tool_names:f.allowedTools.toolNames}:void 0,authorization:f.authorization,connector_id:f.connectorId,headers:f.headers,require_approval:g??"never",server_description:f.serverDescription,server_url:f.serverUrl});break}case"openai.custom":{const f=await dt({value:u.args,schema:U8});a.push({type:"custom",name:f.name,description:f.description,format:f.format}),l.add(f.name);break}case"openai.tool_search":{const f=await dt({value:u.args,schema:rI});a.push({type:"tool_search",...f.execution!=null?{execution:f.execution}:{},...f.description!=null?{description:f.description}:{},...f.parameters!=null?{parameters:f.parameters}:{}});break}}break}default:i.push({type:"unsupported",feature:`function tool ${u}`});break}if(t==null)return{tools:a,toolChoice:void 0,toolWarnings:i};const c=t.type;switch(c){case"auto":case"none":case"required":return{tools:a,toolChoice:c,toolWarnings:i};case"tool":{const u=(s=r?.toProviderToolName(t.toolName))!=null?s:t.toolName;return{tools:a,toolChoice:u==="code_interpreter"||u==="file_search"||u==="image_generation"||u==="web_search_preview"||u==="web_search"||u==="mcp"||u==="apply_patch"?{type:u}:l.has(u)?{type:"custom",name:u}:{type:"function",name:u},toolWarnings:i}}default:{const u=c;throw new Pr({functionality:`tool choice type: ${u}`})}}}function SI(e){if(e.type==="containerReference")return{type:"container_reference",container_id:e.containerId};if(e.type==="containerAuto"){const r=e;return{type:"container_auto",file_ids:r.fileIds,memory_limit:r.memoryLimit,network_policy:r.networkPolicy==null?void 0:r.networkPolicy.type==="disabled"?{type:"disabled"}:{type:"allowlist",allowed_domains:r.networkPolicy.allowedDomains,domain_secrets:r.networkPolicy.domainSecrets},skills:II(r.skills)}}return{type:"local",skills:e.skills}}function II(e){return e?.map(t=>t.type==="skillReference"?{type:"skill_reference",skill_id:t.skillId,version:t.version}:{type:"inline",name:t.name,description:t.description,source:{type:"base64",media_type:t.source.mediaType,data:t.source.data}})}function G2(e){var t,r;const n={};for(const o of e)if(o.role==="assistant")for(const s of o.content){if(s.type!=="tool-call")continue;const i=(r=(t=s.providerOptions)==null?void 0:t.openai)==null?void 0:r.approvalRequestId;i!=null&&(n[i]=s.toolCallId)}return n}var xI=class{constructor(e,t){this.specificationVersion="v3",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:r,topP:n,topK:o,presencePenalty:s,frequencyPenalty:i,seed:a,prompt:l,providerOptions:c,tools:u,toolChoice:f,responseFormat:p}){var h,g,v,_,w,y,m,C,b;const T=[],I=E2(this.modelId);o!=null&&T.push({type:"unsupported",feature:"topK"}),a!=null&&T.push({type:"unsupported",feature:"seed"}),s!=null&&T.push({type:"unsupported",feature:"presencePenalty"}),i!=null&&T.push({type:"unsupported",feature:"frequencyPenalty"}),r!=null&&T.push({type:"unsupported",feature:"stopSequences"});const R=this.config.provider.includes("azure")?"azure":"openai";let S=await Vr({provider:R,providerOptions:c,schema:J2});S==null&&R!=="openai"&&(S=await Vr({provider:"openai",providerOptions:c,schema:J2}));const j=(h=S?.forceReasoning)!=null?h:I.isReasoningModel;S?.conversation&&S?.previousResponseId&&T.push({type:"unsupported",feature:"conversation",details:"conversation and previousResponseId cannot be used together"});const O=e9({tools:u,providerToolNames:{"openai.code_interpreter":"code_interpreter","openai.file_search":"file_search","openai.image_generation":"image_generation","openai.local_shell":"local_shell","openai.shell":"shell","openai.web_search":"web_search","openai.web_search_preview":"web_search_preview","openai.mcp":"mcp","openai.apply_patch":"apply_patch","openai.tool_search":"tool_search"},resolveProviderToolName:te=>te.id==="openai.custom"?te.args.name:void 0}),L=new Set,{tools:z,toolChoice:B,toolWarnings:X}=await CI({tools:u,toolChoice:f,toolNameMapping:O,customProviderToolNames:L}),{input:ee,warnings:Q}=await wI({prompt:l,toolNameMapping:O,systemMessageMode:(g=S?.systemMessageMode)!=null?g:j?"developer":I.systemMessageMode,providerOptionsName:R,fileIdPrefixes:this.config.fileIdPrefixes,store:(v=S?.store)!=null?v:!0,hasConversation:S?.conversation!=null,hasLocalShellTool:E("openai.local_shell"),hasShellTool:E("openai.shell"),hasApplyPatchTool:E("openai.apply_patch"),customProviderToolNames:L.size>0?L:void 0});T.push(...Q);const Z=(_=S?.strictJsonSchema)!=null?_:!0;let ne=S?.include;function D(te){ne==null?ne=[te]:ne.includes(te)||(ne=[...ne,te])}function E(te){return u?.find(_e=>_e.type==="provider"&&_e.id===te)!=null}const U=typeof S?.logprobs=="number"?S?.logprobs:S?.logprobs===!0?H2:void 0;U&&D("message.output_text.logprobs");const F=(w=u?.find(te=>te.type==="provider"&&(te.id==="openai.web_search"||te.id==="openai.web_search_preview")))==null?void 0:w.name;F&&D("web_search_call.action.sources"),E("openai.code_interpreter")&&D("code_interpreter_call.outputs");const x=S?.store;x===!1&&j&&D("reasoning.encrypted_content");const M={model:this.modelId,input:ee,temperature:t,top_p:n,max_output_tokens:e,...(p?.type==="json"||S?.textVerbosity)&&{text:{...p?.type==="json"&&{format:p.schema!=null?{type:"json_schema",strict:Z,name:(y=p.name)!=null?y:"response",description:p.description,schema:p.schema}:{type:"json_object"}},...S?.textVerbosity&&{verbosity:S.textVerbosity}}},conversation:S?.conversation,max_tool_calls:S?.maxToolCalls,metadata:S?.metadata,parallel_tool_calls:S?.parallelToolCalls,previous_response_id:S?.previousResponseId,store:x,user:S?.user,instructions:S?.instructions,service_tier:S?.serviceTier,include:ne,prompt_cache_key:S?.promptCacheKey,prompt_cache_retention:S?.promptCacheRetention,safety_identifier:S?.safetyIdentifier,top_logprobs:U,truncation:S?.truncation,...j&&(S?.reasoningEffort!=null||S?.reasoningSummary!=null)&&{reasoning:{...S?.reasoningEffort!=null&&{effort:S.reasoningEffort},...S?.reasoningSummary!=null&&{summary:S.reasoningSummary}}}};j?S?.reasoningEffort==="none"&&I.supportsNonReasoningParameters||(M.temperature!=null&&(M.temperature=void 0,T.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),M.top_p!=null&&(M.top_p=void 0,T.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"}))):(S?.reasoningEffort!=null&&T.push({type:"unsupported",feature:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),S?.reasoningSummary!=null&&T.push({type:"unsupported",feature:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),S?.serviceTier==="flex"&&!I.supportsFlexProcessing&&(T.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete M.service_tier),S?.serviceTier==="priority"&&!I.supportsPriorityProcessing&&(T.push({type:"unsupported",feature:"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 H=(b=(C=(m=u?.find(te=>te.type==="provider"&&te.id==="openai.shell"))==null?void 0:m.args)==null?void 0:C.environment)==null?void 0:b.type,re=H==="containerAuto"||H==="containerReference";return{webSearchToolName:F,args:{...M,tools:z,tool_choice:B},warnings:[...T,...X],store:x,toolNameMapping:O,providerOptionsName:R,isShellProviderExecuted:re}}async doGenerate(e){var t,r,n,o,s,i,a,l,c,u,f,p,h,g,v,_,w,y,m,C,b,T,I,R,S,j,O,L;const{args:z,warnings:B,webSearchToolName:X,toolNameMapping:ee,providerOptionsName:Q,isShellProviderExecuted:Z}=await this.getArgs(e),ne=this.config.url({path:"/responses",modelId:this.modelId}),D=G2(e.prompt),{responseHeaders:E,value:U,rawValue:F}=await zt({url:ne,headers:xt(this.config.headers(),e.headers),body:z,failedResponseHandler:Tr,successfulResponseHandler:Ft(TI),abortSignal:e.abortSignal,fetch:this.config.fetch});if(U.error)throw new at({message:U.error.message,url:ne,requestBodyValues:z,statusCode:400,responseHeaders:E,responseBody:F,isRetryable:!1});const x=[],M=[];let H=!1;const re=[];for(const G of U.output)switch(G.type){case"reasoning":{G.summary.length===0&&G.summary.push({type:"summary_text",text:""});for(const A of G.summary)x.push({type:"reasoning",text:A.text,providerMetadata:{[Q]:{itemId:G.id,reasoningEncryptedContent:(t=G.encrypted_content)!=null?t:null}}});break}case"image_generation_call":{x.push({type:"tool-call",toolCallId:G.id,toolName:ee.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),x.push({type:"tool-result",toolCallId:G.id,toolName:ee.toCustomToolName("image_generation"),result:{result:G.result}});break}case"tool_search_call":{const A=(r=G.call_id)!=null?r:G.id,V=G.execution==="server";V&&re.push(A),x.push({type:"tool-call",toolCallId:A,toolName:ee.toCustomToolName("tool_search"),input:JSON.stringify({arguments:G.arguments,call_id:G.call_id}),...V?{providerExecuted:!0}:{},providerMetadata:{[Q]:{itemId:G.id}}});break}case"tool_search_output":{const A=(o=(n=G.call_id)!=null?n:re.shift())!=null?o:G.id;x.push({type:"tool-result",toolCallId:A,toolName:ee.toCustomToolName("tool_search"),result:{tools:G.tools},providerMetadata:{[Q]:{itemId:G.id}}});break}case"local_shell_call":{x.push({type:"tool-call",toolCallId:G.call_id,toolName:ee.toCustomToolName("local_shell"),input:JSON.stringify({action:G.action}),providerMetadata:{[Q]:{itemId:G.id}}});break}case"shell_call":{x.push({type:"tool-call",toolCallId:G.call_id,toolName:ee.toCustomToolName("shell"),input:JSON.stringify({action:{commands:G.action.commands}}),...Z&&{providerExecuted:!0},providerMetadata:{[Q]:{itemId:G.id}}});break}case"shell_call_output":{x.push({type:"tool-result",toolCallId:G.call_id,toolName:ee.toCustomToolName("shell"),result:{output:G.output.map(A=>({stdout:A.stdout,stderr:A.stderr,outcome:A.outcome.type==="exit"?{type:"exit",exitCode:A.outcome.exit_code}:{type:"timeout"}}))}});break}case"message":{for(const A of G.content){(i=(s=e.providerOptions)==null?void 0:s[Q])!=null&&i.logprobs&&A.logprobs&&M.push(A.logprobs);const V={itemId:G.id,...G.phase!=null&&{phase:G.phase},...A.annotations.length>0&&{annotations:A.annotations}};x.push({type:"text",text:A.text,providerMetadata:{[Q]:V}});for(const J of A.annotations)J.type==="url_citation"?x.push({type:"source",sourceType:"url",id:(c=(l=(a=this.config).generateId)==null?void 0:l.call(a))!=null?c:Dt(),url:J.url,title:J.title}):J.type==="file_citation"?x.push({type:"source",sourceType:"document",id:(p=(f=(u=this.config).generateId)==null?void 0:f.call(u))!=null?p:Dt(),mediaType:"text/plain",title:J.filename,filename:J.filename,providerMetadata:{[Q]:{type:J.type,fileId:J.file_id,index:J.index}}}):J.type==="container_file_citation"?x.push({type:"source",sourceType:"document",id:(v=(g=(h=this.config).generateId)==null?void 0:g.call(h))!=null?v:Dt(),mediaType:"text/plain",title:J.filename,filename:J.filename,providerMetadata:{[Q]:{type:J.type,fileId:J.file_id,containerId:J.container_id}}}):J.type==="file_path"&&x.push({type:"source",sourceType:"document",id:(y=(w=(_=this.config).generateId)==null?void 0:w.call(_))!=null?y:Dt(),mediaType:"application/octet-stream",title:J.file_id,filename:J.file_id,providerMetadata:{[Q]:{type:J.type,fileId:J.file_id,index:J.index}}})}break}case"function_call":{H=!0,x.push({type:"tool-call",toolCallId:G.call_id,toolName:G.name,input:G.arguments,providerMetadata:{[Q]:{itemId:G.id}}});break}case"custom_tool_call":{H=!0;const A=ee.toCustomToolName(G.name);x.push({type:"tool-call",toolCallId:G.call_id,toolName:A,input:JSON.stringify(G.input),providerMetadata:{[Q]:{itemId:G.id}}});break}case"web_search_call":{x.push({type:"tool-call",toolCallId:G.id,toolName:ee.toCustomToolName(X??"web_search"),input:JSON.stringify({}),providerExecuted:!0}),x.push({type:"tool-result",toolCallId:G.id,toolName:ee.toCustomToolName(X??"web_search"),result:K2(G.action)});break}case"mcp_call":{const A=G.approval_request_id!=null&&(m=D[G.approval_request_id])!=null?m:G.id,V=`mcp.${G.name}`;x.push({type:"tool-call",toolCallId:A,toolName:V,input:G.arguments,providerExecuted:!0,dynamic:!0}),x.push({type:"tool-result",toolCallId:A,toolName:V,result:{type:"call",serverLabel:G.server_label,name:G.name,arguments:G.arguments,...G.output!=null?{output:G.output}:{},...G.error!=null?{error:G.error}:{}},providerMetadata:{[Q]:{itemId:G.id}}});break}case"mcp_list_tools":break;case"mcp_approval_request":{const A=(C=G.approval_request_id)!=null?C:G.id,V=(I=(T=(b=this.config).generateId)==null?void 0:T.call(b))!=null?I:Dt(),J=`mcp.${G.name}`;x.push({type:"tool-call",toolCallId:V,toolName:J,input:G.arguments,providerExecuted:!0,dynamic:!0}),x.push({type:"tool-approval-request",approvalId:A,toolCallId:V});break}case"computer_call":{x.push({type:"tool-call",toolCallId:G.id,toolName:ee.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),x.push({type:"tool-result",toolCallId:G.id,toolName:ee.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:G.status||"completed"}});break}case"file_search_call":{x.push({type:"tool-call",toolCallId:G.id,toolName:ee.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),x.push({type:"tool-result",toolCallId:G.id,toolName:ee.toCustomToolName("file_search"),result:{queries:G.queries,results:(S=(R=G.results)==null?void 0:R.map(A=>({attributes:A.attributes,fileId:A.file_id,filename:A.filename,score:A.score,text:A.text})))!=null?S:null}});break}case"code_interpreter_call":{x.push({type:"tool-call",toolCallId:G.id,toolName:ee.toCustomToolName("code_interpreter"),input:JSON.stringify({code:G.code,containerId:G.container_id}),providerExecuted:!0}),x.push({type:"tool-result",toolCallId:G.id,toolName:ee.toCustomToolName("code_interpreter"),result:{outputs:G.outputs}});break}case"apply_patch_call":{x.push({type:"tool-call",toolCallId:G.call_id,toolName:ee.toCustomToolName("apply_patch"),input:JSON.stringify({callId:G.call_id,operation:G.operation}),providerMetadata:{[Q]:{itemId:G.id}}});break}}const te={[Q]:{responseId:U.id,...M.length>0?{logprobs:M}:{},...typeof U.service_tier=="string"?{serviceTier:U.service_tier}:{}}},_e=U.usage;return{content:x,finishReason:{unified:gu({finishReason:(j=U.incomplete_details)==null?void 0:j.reason,hasFunctionCall:H}),raw:(L=(O=U.incomplete_details)==null?void 0:O.reason)!=null?L:void 0},usage:Z2(_e),request:{body:z},response:{id:U.id,timestamp:new Date(U.created_at*1e3),modelId:U.model,headers:E,body:F},providerMetadata:te,warnings:B}}async doStream(e){const{args:t,warnings:r,webSearchToolName:n,toolNameMapping:o,store:s,providerOptionsName:i,isShellProviderExecuted:a}=await this.getArgs(e),{responseHeaders:l,value:c}=await zt({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:xt(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:Tr,successfulResponseHandler:aa(kI),abortSignal:e.abortSignal,fetch:this.config.fetch}),u=this,f=G2(e.prompt),p=new Map;let h={unified:"other",raw:void 0},g;const v=[];let _=null;const w={},y=[];let m,C=!1;const b={};let T;const I=[];return{stream:c.pipeThrough(new TransformStream({start(R){R.enqueue({type:"stream-start",warnings:r})},transform(R,S){var j,O,L,z,B,X,ee,Q,Z,ne,D,E,U,F,x,M,H,re,te,_e,G,A,V,J,Y,ue,Ce,Ze,ot,pt,Qe,et,At,mt,$r,Yt,Je,hr;if(e.includeRawChunks&&S.enqueue({type:"raw",rawValue:R.rawValue}),!R.success){h={unified:"error",raw:void 0},S.enqueue({type:"error",error:R.error});return}const $=R.value;if(W2($)){if($.item.type==="function_call")w[$.output_index]={toolName:$.item.name,toolCallId:$.item.call_id},S.enqueue({type:"tool-input-start",id:$.item.call_id,toolName:$.item.name});else if($.item.type==="custom_tool_call"){const K=o.toCustomToolName($.item.name);w[$.output_index]={toolName:K,toolCallId:$.item.call_id},S.enqueue({type:"tool-input-start",id:$.item.call_id,toolName:K})}else if($.item.type==="web_search_call")w[$.output_index]={toolName:o.toCustomToolName(n??"web_search"),toolCallId:$.item.id},S.enqueue({type:"tool-input-start",id:$.item.id,toolName:o.toCustomToolName(n??"web_search"),providerExecuted:!0}),S.enqueue({type:"tool-input-end",id:$.item.id}),S.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:o.toCustomToolName(n??"web_search"),input:JSON.stringify({}),providerExecuted:!0});else if($.item.type==="computer_call")w[$.output_index]={toolName:o.toCustomToolName("computer_use"),toolCallId:$.item.id},S.enqueue({type:"tool-input-start",id:$.item.id,toolName:o.toCustomToolName("computer_use"),providerExecuted:!0});else if($.item.type==="code_interpreter_call")w[$.output_index]={toolName:o.toCustomToolName("code_interpreter"),toolCallId:$.item.id,codeInterpreter:{containerId:$.item.container_id}},S.enqueue({type:"tool-input-start",id:$.item.id,toolName:o.toCustomToolName("code_interpreter"),providerExecuted:!0}),S.enqueue({type:"tool-input-delta",id:$.item.id,delta:`{"containerId":"${$.item.container_id}","code":"`});else if($.item.type==="file_search_call")S.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:o.toCustomToolName("file_search"),input:"{}",providerExecuted:!0});else if($.item.type==="image_generation_call")S.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:o.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0});else if($.item.type==="tool_search_call"){const K=$.item.id,Le=o.toCustomToolName("tool_search"),Re=$.item.execution==="server";w[$.output_index]={toolName:Le,toolCallId:K,toolSearchExecution:(j=$.item.execution)!=null?j:"server"},Re&&S.enqueue({type:"tool-input-start",id:K,toolName:Le,providerExecuted:!0})}else if($.item.type!=="tool_search_output"){if(!($.item.type==="mcp_call"||$.item.type==="mcp_list_tools"||$.item.type==="mcp_approval_request"))if($.item.type==="apply_patch_call"){const{call_id:K,operation:Le}=$.item;if(w[$.output_index]={toolName:o.toCustomToolName("apply_patch"),toolCallId:K,applyPatch:{hasDiff:Le.type==="delete_file",endEmitted:Le.type==="delete_file"}},S.enqueue({type:"tool-input-start",id:K,toolName:o.toCustomToolName("apply_patch")}),Le.type==="delete_file"){const Re=JSON.stringify({callId:K,operation:Le});S.enqueue({type:"tool-input-delta",id:K,delta:Re}),S.enqueue({type:"tool-input-end",id:K})}else S.enqueue({type:"tool-input-delta",id:K,delta:`{"callId":"${Fn(K)}","operation":{"type":"${Fn(Le.type)}","path":"${Fn(Le.path)}","diff":"`})}else $.item.type==="shell_call"?w[$.output_index]={toolName:o.toCustomToolName("shell"),toolCallId:$.item.call_id}:$.item.type==="shell_call_output"||($.item.type==="message"?(y.splice(0,y.length),m=(O=$.item.phase)!=null?O:void 0,S.enqueue({type:"text-start",id:$.item.id,providerMetadata:{[i]:{itemId:$.item.id,...$.item.phase!=null&&{phase:$.item.phase}}}})):W2($)&&$.item.type==="reasoning"&&(b[$.item.id]={encryptedContent:$.item.encrypted_content,summaryParts:{0:"active"}},S.enqueue({type:"reasoning-start",id:`${$.item.id}:0`,providerMetadata:{[i]:{itemId:$.item.id,reasoningEncryptedContent:(L=$.item.encrypted_content)!=null?L:null}}})))}}else if($I($)){if($.item.type==="message"){const K=(z=$.item.phase)!=null?z:m;m=void 0,S.enqueue({type:"text-end",id:$.item.id,providerMetadata:{[i]:{itemId:$.item.id,...K!=null&&{phase:K},...y.length>0&&{annotations:y}}}})}else if($.item.type==="function_call")w[$.output_index]=void 0,C=!0,S.enqueue({type:"tool-input-end",id:$.item.call_id}),S.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:$.item.name,input:$.item.arguments,providerMetadata:{[i]:{itemId:$.item.id}}});else if($.item.type==="custom_tool_call"){w[$.output_index]=void 0,C=!0;const K=o.toCustomToolName($.item.name);S.enqueue({type:"tool-input-end",id:$.item.call_id}),S.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:K,input:JSON.stringify($.item.input),providerMetadata:{[i]:{itemId:$.item.id}}})}else if($.item.type==="web_search_call")w[$.output_index]=void 0,S.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:o.toCustomToolName(n??"web_search"),result:K2($.item.action)});else if($.item.type==="computer_call")w[$.output_index]=void 0,S.enqueue({type:"tool-input-end",id:$.item.id}),S.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:o.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),S.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:o.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:$.item.status||"completed"}});else if($.item.type==="file_search_call")w[$.output_index]=void 0,S.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:o.toCustomToolName("file_search"),result:{queries:$.item.queries,results:(X=(B=$.item.results)==null?void 0:B.map(K=>({attributes:K.attributes,fileId:K.file_id,filename:K.filename,score:K.score,text:K.text})))!=null?X:null}});else if($.item.type==="code_interpreter_call")w[$.output_index]=void 0,S.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:o.toCustomToolName("code_interpreter"),result:{outputs:$.item.outputs}});else if($.item.type==="image_generation_call")S.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:o.toCustomToolName("image_generation"),result:{result:$.item.result}});else if($.item.type==="tool_search_call"){const K=w[$.output_index],Le=$.item.execution==="server";if(K!=null){const Re=Le?K.toolCallId:(ee=$.item.call_id)!=null?ee:$.item.id;Le?I.push(Re):S.enqueue({type:"tool-input-start",id:Re,toolName:K.toolName}),S.enqueue({type:"tool-input-end",id:Re}),S.enqueue({type:"tool-call",toolCallId:Re,toolName:K.toolName,input:JSON.stringify({arguments:$.item.arguments,call_id:Le?null:Re}),...Le?{providerExecuted:!0}:{},providerMetadata:{[i]:{itemId:$.item.id}}})}w[$.output_index]=void 0}else if($.item.type==="tool_search_output"){const K=(Z=(Q=$.item.call_id)!=null?Q:I.shift())!=null?Z:$.item.id;S.enqueue({type:"tool-result",toolCallId:K,toolName:o.toCustomToolName("tool_search"),result:{tools:$.item.tools},providerMetadata:{[i]:{itemId:$.item.id}}})}else if($.item.type==="mcp_call"){w[$.output_index]=void 0;const K=(ne=$.item.approval_request_id)!=null?ne:void 0,Le=K!=null&&(E=(D=p.get(K))!=null?D:f[K])!=null?E:$.item.id,Re=`mcp.${$.item.name}`;S.enqueue({type:"tool-call",toolCallId:Le,toolName:Re,input:$.item.arguments,providerExecuted:!0,dynamic:!0}),S.enqueue({type:"tool-result",toolCallId:Le,toolName:Re,result:{type:"call",serverLabel:$.item.server_label,name:$.item.name,arguments:$.item.arguments,...$.item.output!=null?{output:$.item.output}:{},...$.item.error!=null?{error:$.item.error}:{}},providerMetadata:{[i]:{itemId:$.item.id}}})}else if($.item.type==="mcp_list_tools")w[$.output_index]=void 0;else if($.item.type==="apply_patch_call"){const K=w[$.output_index];K?.applyPatch&&!K.applyPatch.endEmitted&&$.item.operation.type!=="delete_file"&&(K.applyPatch.hasDiff||S.enqueue({type:"tool-input-delta",id:K.toolCallId,delta:Fn($.item.operation.diff)}),S.enqueue({type:"tool-input-delta",id:K.toolCallId,delta:'"}}'}),S.enqueue({type:"tool-input-end",id:K.toolCallId}),K.applyPatch.endEmitted=!0),K&&$.item.status==="completed"&&S.enqueue({type:"tool-call",toolCallId:K.toolCallId,toolName:o.toCustomToolName("apply_patch"),input:JSON.stringify({callId:$.item.call_id,operation:$.item.operation}),providerMetadata:{[i]:{itemId:$.item.id}}}),w[$.output_index]=void 0}else if($.item.type==="mcp_approval_request"){w[$.output_index]=void 0;const K=(x=(F=(U=u.config).generateId)==null?void 0:F.call(U))!=null?x:Dt(),Le=(M=$.item.approval_request_id)!=null?M:$.item.id;p.set(Le,K);const Re=`mcp.${$.item.name}`;S.enqueue({type:"tool-call",toolCallId:K,toolName:Re,input:$.item.arguments,providerExecuted:!0,dynamic:!0}),S.enqueue({type:"tool-approval-request",approvalId:Le,toolCallId:K})}else if($.item.type==="local_shell_call")w[$.output_index]=void 0,S.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:o.toCustomToolName("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:{[i]:{itemId:$.item.id}}});else if($.item.type==="shell_call")w[$.output_index]=void 0,S.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:o.toCustomToolName("shell"),input:JSON.stringify({action:{commands:$.item.action.commands}}),...a&&{providerExecuted:!0},providerMetadata:{[i]:{itemId:$.item.id}}});else if($.item.type==="shell_call_output")S.enqueue({type:"tool-result",toolCallId:$.item.call_id,toolName:o.toCustomToolName("shell"),result:{output:$.item.output.map(K=>({stdout:K.stdout,stderr:K.stderr,outcome:K.outcome.type==="exit"?{type:"exit",exitCode:K.outcome.exit_code}:{type:"timeout"}}))}});else if($.item.type==="reasoning"){const K=b[$.item.id],Le=Object.entries(K.summaryParts).filter(([Re,tt])=>tt==="active"||tt==="can-conclude").map(([Re])=>Re);for(const Re of Le)S.enqueue({type:"reasoning-end",id:`${$.item.id}:${Re}`,providerMetadata:{[i]:{itemId:$.item.id,reasoningEncryptedContent:(H=$.item.encrypted_content)!=null?H:null}}});delete b[$.item.id]}}else if(NI($)){const K=w[$.output_index];K!=null&&S.enqueue({type:"tool-input-delta",id:K.toolCallId,delta:$.delta})}else if(OI($)){const K=w[$.output_index];K!=null&&S.enqueue({type:"tool-input-delta",id:K.toolCallId,delta:$.delta})}else if(jI($)){const K=w[$.output_index];K?.applyPatch&&(S.enqueue({type:"tool-input-delta",id:K.toolCallId,delta:Fn($.delta)}),K.applyPatch.hasDiff=!0)}else if(DI($)){const K=w[$.output_index];K?.applyPatch&&!K.applyPatch.endEmitted&&(K.applyPatch.hasDiff||(S.enqueue({type:"tool-input-delta",id:K.toolCallId,delta:Fn($.diff)}),K.applyPatch.hasDiff=!0),S.enqueue({type:"tool-input-delta",id:K.toolCallId,delta:'"}}'}),S.enqueue({type:"tool-input-end",id:K.toolCallId}),K.applyPatch.endEmitted=!0)}else if(AI($))S.enqueue({type:"tool-result",toolCallId:$.item_id,toolName:o.toCustomToolName("image_generation"),result:{result:$.partial_image_b64},preliminary:!0});else if(qI($)){const K=w[$.output_index];K!=null&&S.enqueue({type:"tool-input-delta",id:K.toolCallId,delta:Fn($.delta)})}else if(LI($)){const K=w[$.output_index];K!=null&&(S.enqueue({type:"tool-input-delta",id:K.toolCallId,delta:'"}'}),S.enqueue({type:"tool-input-end",id:K.toolCallId}),S.enqueue({type:"tool-call",toolCallId:K.toolCallId,toolName:o.toCustomToolName("code_interpreter"),input:JSON.stringify({code:$.code,containerId:K.codeInterpreter.containerId}),providerExecuted:!0}))}else if(MI($))_=$.response.id,S.enqueue({type:"response-metadata",id:$.response.id,timestamp:new Date($.response.created_at*1e3),modelId:$.response.model});else if(EI($))S.enqueue({type:"text-delta",id:$.item_id,delta:$.delta}),(te=(re=e.providerOptions)==null?void 0:re[i])!=null&&te.logprobs&&$.logprobs&&v.push($.logprobs);else if($.type==="response.reasoning_summary_part.added"){if($.summary_index>0){const K=b[$.item_id];K.summaryParts[$.summary_index]="active";for(const Le of Object.keys(K.summaryParts))K.summaryParts[Le]==="can-conclude"&&(S.enqueue({type:"reasoning-end",id:`${$.item_id}:${Le}`,providerMetadata:{[i]:{itemId:$.item_id}}}),K.summaryParts[Le]="concluded");S.enqueue({type:"reasoning-start",id:`${$.item_id}:${$.summary_index}`,providerMetadata:{[i]:{itemId:$.item_id,reasoningEncryptedContent:(G=(_e=b[$.item_id])==null?void 0:_e.encryptedContent)!=null?G:null}}})}}else if($.type==="response.reasoning_summary_text.delta")S.enqueue({type:"reasoning-delta",id:`${$.item_id}:${$.summary_index}`,delta:$.delta,providerMetadata:{[i]:{itemId:$.item_id}}});else if($.type==="response.reasoning_summary_part.done")s?(S.enqueue({type:"reasoning-end",id:`${$.item_id}:${$.summary_index}`,providerMetadata:{[i]:{itemId:$.item_id}}}),b[$.item_id].summaryParts[$.summary_index]="concluded"):b[$.item_id].summaryParts[$.summary_index]="can-conclude";else if(RI($))h={unified:gu({finishReason:(A=$.response.incomplete_details)==null?void 0:A.reason,hasFunctionCall:C}),raw:(J=(V=$.response.incomplete_details)==null?void 0:V.reason)!=null?J:void 0},g=$.response.usage,typeof $.response.service_tier=="string"&&(T=$.response.service_tier);else if(PI($)){const K=(Y=$.response.incomplete_details)==null?void 0:Y.reason;h={unified:K?gu({finishReason:K,hasFunctionCall:C}):"error",raw:K??"error"},g=(ue=$.response.usage)!=null?ue:void 0}else UI($)?(y.push($.annotation),$.annotation.type==="url_citation"?S.enqueue({type:"source",sourceType:"url",id:(ot=(Ze=(Ce=u.config).generateId)==null?void 0:Ze.call(Ce))!=null?ot:Dt(),url:$.annotation.url,title:$.annotation.title}):$.annotation.type==="file_citation"?S.enqueue({type:"source",sourceType:"document",id:(et=(Qe=(pt=u.config).generateId)==null?void 0:Qe.call(pt))!=null?et:Dt(),mediaType:"text/plain",title:$.annotation.filename,filename:$.annotation.filename,providerMetadata:{[i]:{type:$.annotation.type,fileId:$.annotation.file_id,index:$.annotation.index}}}):$.annotation.type==="container_file_citation"?S.enqueue({type:"source",sourceType:"document",id:($r=(mt=(At=u.config).generateId)==null?void 0:mt.call(At))!=null?$r:Dt(),mediaType:"text/plain",title:$.annotation.filename,filename:$.annotation.filename,providerMetadata:{[i]:{type:$.annotation.type,fileId:$.annotation.file_id,containerId:$.annotation.container_id}}}):$.annotation.type==="file_path"&&S.enqueue({type:"source",sourceType:"document",id:(hr=(Je=(Yt=u.config).generateId)==null?void 0:Je.call(Yt))!=null?hr:Dt(),mediaType:"application/octet-stream",title:$.annotation.file_id,filename:$.annotation.file_id,providerMetadata:{[i]:{type:$.annotation.type,fileId:$.annotation.file_id,index:$.annotation.index}}})):zI($)&&S.enqueue({type:"error",error:$})},flush(R){const S={[i]:{responseId:_,...v.length>0?{logprobs:v}:{},...T!==void 0?{serviceTier:T}:{}}};R.enqueue({type:"finish",finishReason:h,usage:Z2(g),providerMetadata:S})}})),request:{body:t},response:{headers:l}}}};function EI(e){return e.type==="response.output_text.delta"}function $I(e){return e.type==="response.output_item.done"}function RI(e){return e.type==="response.completed"||e.type==="response.incomplete"}function PI(e){return e.type==="response.failed"}function MI(e){return e.type==="response.created"}function NI(e){return e.type==="response.function_call_arguments.delta"}function OI(e){return e.type==="response.custom_tool_call_input.delta"}function AI(e){return e.type==="response.image_generation_call.partial_image"}function qI(e){return e.type==="response.code_interpreter_call_code.delta"}function LI(e){return e.type==="response.code_interpreter_call_code.done"}function jI(e){return e.type==="response.apply_patch_call_operation_diff.delta"}function DI(e){return e.type==="response.apply_patch_call_operation_diff.done"}function W2(e){return e.type==="response.output_item.added"}function UI(e){return e.type==="response.output_text.annotation.added"}function zI(e){return e.type==="error"}function K2(e){var t;if(e==null)return{};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_in_page":return{action:{type:"findInPage",url:e.url,pattern:e.pattern}}}}function Fn(e){return JSON.stringify(e).slice(1,-1)}var FI=ve(()=>ye(k({instructions:d().nullish(),speed:N().min(.25).max(4).default(1).nullish()}))),VI=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get provider(){return this.config.provider}async getArgs({text:e,voice:t="alloy",outputFormat:r="mp3",speed:n,instructions:o,language:s,providerOptions:i}){const a=[],l=await Vr({provider:"openai",providerOptions:i,schema:FI}),c={model:this.modelId,input:e,voice:t,response_format:"mp3",speed:n,instructions:o};if(r&&(["mp3","opus","aac","flac","wav","pcm"].includes(r)?c.response_format=r:a.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${r}. Using mp3 instead.`})),l){const u={};for(const f in u){const p=u[f];p!==void 0&&(c[f]=p)}}return s&&a.push({type:"unsupported",feature:"language",details:`OpenAI speech models do not support language selection. Language parameter "${s}" was ignored.`}),{requestBody:c,warnings:a}}async doGenerate(e){var t,r,n;const o=(n=(r=(t=this.config._internal)==null?void 0:t.currentDate)==null?void 0:r.call(t))!=null?n:new Date,{requestBody:s,warnings:i}=await this.getArgs(e),{value:a,responseHeaders:l,rawValue:c}=await zt({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:xt(this.config.headers(),e.headers),body:s,failedResponseHandler:Tr,successfulResponseHandler:d4(),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}}}},ZI=ve(()=>ye(k({text:d(),language:d().nullish(),duration:N().nullish(),words:q(k({word:d(),start:N(),end:N()})).nullish(),segments:q(k({id:N(),seek:N(),start:N(),end:N(),text:d(),tokens:q(N()),temperature:N(),avg_logprob:N(),compression_ratio:N(),no_speech_prob:N()})).nullish()}))),BI=ve(()=>ye(k({include:q(d()).optional(),language:d().optional(),prompt:d().optional(),temperature:N().min(0).max(1).default(0).optional(),timestampGranularities:q(ce(["word","segment"])).default(["segment"]).optional()}))),Y2={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"},HI=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get provider(){return this.config.provider}async getArgs({audio:e,mediaType:t,providerOptions:r}){const n=[],o=await Vr({provider:"openai",providerOptions:r,schema:BI}),s=new FormData,i=e instanceof Uint8Array?new Blob([e]):new Blob([oo(e)]);s.append("model",this.modelId);const a=h9(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 f of u)s.append(`${c}[]`,String(f));else s.append(c,String(u))}return{formData:s,warnings:n}}async doGenerate(e){var t,r,n,o,s,i,a,l;const c=(n=(r=(t=this.config._internal)==null?void 0:t.currentDate)==null?void 0:r.call(t))!=null?n:new Date,{formData:u,warnings:f}=await this.getArgs(e),{value:p,responseHeaders:h,rawValue:g}=await Kf({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:xt(this.config.headers(),e.headers),formData:u,failedResponseHandler:Tr,successfulResponseHandler:Ft(ZI),abortSignal:e.abortSignal,fetch:this.config.fetch}),v=p.language!=null&&p.language in Y2?Y2[p.language]:void 0;return{text:p.text,segments:(a=(i=(o=p.segments)==null?void 0:o.map(_=>({text:_.text,startSecond:_.start,endSecond:_.end})))!=null?i:(s=p.words)==null?void 0:s.map(_=>({text:_.word,startSecond:_.start,endSecond:_.end})))!=null?a:[],language:v,durationInSeconds:(l=p.duration)!=null?l:void 0,warnings:f,response:{timestamp:c,modelId:this.modelId,headers:h,body:g}}}},JI="3.0.52";function Q2(e={}){var t,r;const n=(t=Qf(io({settingValue:e.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?t:"https://api.openai.com/v1",o=(r=e.name)!=null?r:"openai",s=()=>cn({Authorization:`Bearer ${f9({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${JI}`),i=v=>new w8(v,{provider:`${o}.chat`,url:({path:_})=>`${n}${_}`,headers:s,fetch:e.fetch}),a=v=>new C8(v,{provider:`${o}.completion`,url:({path:_})=>`${n}${_}`,headers:s,fetch:e.fetch}),l=v=>new x8(v,{provider:`${o}.embedding`,url:({path:_})=>`${n}${_}`,headers:s,fetch:e.fetch}),c=v=>new P8(v,{provider:`${o}.image`,url:({path:_})=>`${n}${_}`,headers:s,fetch:e.fetch}),u=v=>new HI(v,{provider:`${o}.transcription`,url:({path:_})=>`${n}${_}`,headers:s,fetch:e.fetch}),f=v=>new VI(v,{provider:`${o}.speech`,url:({path:_})=>`${n}${_}`,headers:s,fetch:e.fetch}),p=v=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return h(v)},h=v=>new xI(v,{provider:`${o}.responses`,url:({path:_})=>`${n}${_}`,headers:s,fetch:e.fetch,fileIdPrefixes:["file-"]}),g=function(v){return p(v)};return g.specificationVersion="v3",g.languageModel=p,g.chat=i,g.completion=a,g.responses=h,g.embedding=l,g.embeddingModel=l,g.textEmbedding=l,g.textEmbeddingModel=l,g.image=c,g.imageModel=c,g.transcription=u,g.transcriptionModel=u,g.speech=f,g.speechModel=f,g.tools=vI,g}Q2();var X2="vercel.ai.error",GI=Symbol.for(X2),eg,WI=class vv extends Error{constructor({name:t,message:r,cause:n}){super(r),this[eg]=!0,this.name=t,this.cause=n}static isInstance(t){return vv.hasMarker(t,X2)}static hasMarker(t,r){const n=Symbol.for(r);return t!=null&&typeof t=="object"&&n in t&&typeof t[n]=="boolean"&&t[n]===!0}};eg=GI;var St=WI,tg="AI_APICallError",rg=`vercel.ai.error.${tg}`,KI=Symbol.for(rg),ng,Hr=class extends St{constructor({message:e,url:t,requestBodyValues:r,statusCode:n,responseHeaders:o,responseBody:s,cause:i,isRetryable:a=n!=null&&(n===408||n===409||n===429||n>=500),data:l}){super({name:tg,message:e,cause:i}),this[ng]=!0,this.url=t,this.requestBodyValues=r,this.statusCode=n,this.responseHeaders=o,this.responseBody=s,this.isRetryable=a,this.data=l}static isInstance(e){return St.hasMarker(e,rg)}};ng=KI;var og="AI_EmptyResponseBodyError",sg=`vercel.ai.error.${og}`,YI=Symbol.for(sg),ag,QI=class extends St{constructor({message:e="Empty response body"}={}){super({name:og,message:e}),this[ag]=!0}static isInstance(e){return St.hasMarker(e,sg)}};ag=YI;function ig(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var lg="AI_InvalidArgumentError",cg=`vercel.ai.error.${lg}`,XI=Symbol.for(cg),ug,dg=class extends St{constructor({message:e,cause:t,argument:r}){super({name:lg,message:e,cause:t}),this[ug]=!0,this.argument=r}static isInstance(e){return St.hasMarker(e,cg)}};ug=XI;var pg="AI_InvalidResponseDataError",fg=`vercel.ai.error.${pg}`,ex=Symbol.for(fg),hg,mg=class extends St{constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:pg,message:t}),this[hg]=!0,this.data=e}static isInstance(e){return St.hasMarker(e,fg)}};hg=ex;var gg="AI_JSONParseError",_g=`vercel.ai.error.${gg}`,tx=Symbol.for(_g),yg,za=class extends St{constructor({text:e,cause:t}){super({name:gg,message:`JSON parsing failed: Text: ${e}.
79
- Error message: ${ig(t)}`,cause:t}),this[yg]=!0,this.text=e}static isInstance(e){return St.hasMarker(e,_g)}};yg=tx;var vg="AI_LoadAPIKeyError",wg=`vercel.ai.error.${vg}`,rx=Symbol.for(wg),bg,Fa=class extends St{constructor({message:e}){super({name:vg,message:e}),this[bg]=!0}static isInstance(e){return St.hasMarker(e,wg)}};bg=rx;var kg="AI_NoSuchModelError",Tg=`vercel.ai.error.${kg}`,nx=Symbol.for(Tg),Cg,Sg=class extends St{constructor({errorName:e=kg,modelId:t,modelType:r,message:n=`No such ${r}: ${t}`}){super({name:e,message:n}),this[Cg]=!0,this.modelId=t,this.modelType=r}static isInstance(e){return St.hasMarker(e,Tg)}};Cg=nx;var Ig="AI_TypeValidationError",xg=`vercel.ai.error.${Ig}`,ox=Symbol.for(xg),Eg,sx=class hd extends St{constructor({value:t,cause:r}){super({name:Ig,message:`Type validation failed: Value: ${JSON.stringify(t)}.
80
- Error message: ${ig(r)}`,cause:r}),this[Eg]=!0,this.value=t}static isInstance(t){return St.hasMarker(t,xg)}static wrap({value:t,cause:r}){return hd.isInstance(r)&&r.value===t?r:new hd({value:t,cause:r})}};Eg=ox;var ws=sx,$g="AI_UnsupportedFunctionalityError",Rg=`vercel.ai.error.${$g}`,ax=Symbol.for(Rg),Pg,Mg=class extends St{constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:$g,message:t}),this[Pg]=!0,this.functionality=e}static isInstance(e){return St.hasMarker(e,Rg)}};Pg=ax;function Ng(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}function Va(e){return Object.fromEntries([...e.headers])}var ix=({prefix:e,size:t=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{const o=()=>{const s=r.length,i=new Array(t);for(let a=0;a<t;a++)i[a]=r[Math.random()*s|0];return i.join("")};if(e==null)return o;if(r.includes(n))throw new dg({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${e}${n}${o()}`},Za=ix();function _u(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var lx=["fetch failed","failed to fetch"];function cx({error:e,url:t,requestBodyValues:r}){if(_u(e))return e;if(e instanceof TypeError&&lx.includes(e.message.toLowerCase())){const n=e.cause;if(n!=null)return new Hr({message:`Cannot connect to API: ${n.message}`,cause:n,url:t,requestBodyValues:r,isRetryable:!0})}return e}function ux(e=globalThis){var t,r,n;return e.window?"runtime/browser":(t=e.navigator)!=null&&t.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(n=(r=e.process)==null?void 0:r.versions)!=null&&n.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function dx(e){if(e==null)return{};const t={};if(e instanceof Headers)e.forEach((r,n)=>{t[n.toLowerCase()]=r});else{Array.isArray(e)||(e=Object.entries(e));for(const[r,n]of e)n!=null&&(t[r.toLowerCase()]=n)}return t}function Og(e,...t){const r=new Headers(dx(e)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var px="3.0.18";function fx({apiKey:e,environmentVariableName:t,apiKeyParameterName:r="apiKey",description:n}){if(typeof e=="string")return e;if(e!=null)throw new Fa({message:`${n} API key must be a string.`});if(typeof process>"u")throw new Fa({message:`${n} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new Fa({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new Fa({message:`${n} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}var hx=/"__proto__"\s*:/,mx=/"constructor"\s*:/;function Ag(e){const t=JSON.parse(e);return t===null||typeof t!="object"||hx.test(e)===!1&&mx.test(e)===!1?t:gx(t)}function gx(e){let t=[e];for(;t.length;){const r=t;t=[];for(const n of r){if(Object.prototype.hasOwnProperty.call(n,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(n,"constructor")&&Object.prototype.hasOwnProperty.call(n.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const o in n){const s=n[o];s&&typeof s=="object"&&t.push(s)}}}return e}function yu(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return Ag(e)}try{return Ag(e)}finally{Error.stackTraceLimit=t}}var vu=Symbol.for("vercel.ai.validator");function _x(e){return{[vu]:!0,validate:e}}function yx(e){return typeof e=="object"&&e!==null&&vu in e&&e[vu]===!0&&"validate"in e}function vx(e){return yx(e)?e:typeof e=="function"?e():wx(e)}function wx(e){return _x(async t=>{const r=await e["~standard"].validate(t);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new ws({value:t,cause:r.issues})}})}async function bx({value:e,schema:t}){const r=await bs({value:e,schema:t});if(!r.success)throw ws.wrap({value:e,cause:r.error});return r.value}async function bs({value:e,schema:t}){const r=vx(t);try{if(r.validate==null)return{success:!0,value:e,rawValue:e};const n=await r.validate(e);return n.success?{success:!0,value:n.value,rawValue:e}:{success:!1,error:ws.wrap({value:e,cause:n.error}),rawValue:e}}catch(n){return{success:!1,error:ws.wrap({value:e,cause:n}),rawValue:e}}}async function kx({text:e,schema:t}){try{const r=yu(e);return t==null?r:bx({value:r,schema:t})}catch(r){throw za.isInstance(r)||ws.isInstance(r)?r:new za({text:e,cause:r})}}async function qg({text:e,schema:t}){try{const r=yu(e);return t==null?{success:!0,value:r,rawValue:r}:await bs({value:r,schema:t})}catch(r){return{success:!1,error:za.isInstance(r)?r:new za({text:e,cause:r}),rawValue:void 0}}}function Lg(e){try{return yu(e),!0}catch{return!1}}function Tx({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new ro).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await qg({text:r,schema:t}))}}))}async function jg({provider:e,providerOptions:t,schema:r}){if(t?.[e]==null)return;const n=await bs({value:t[e],schema:r});if(!n.success)throw new dg({argument:"providerOptions",message:`invalid ${e} provider options`,cause:n.error});return n.value}var Cx=()=>globalThis.fetch,Dg=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i})=>Sx({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i}),Sx=async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:s,fetch:i=Cx()})=>{try{const a=await i(e,{method:"POST",headers:Og(t,`ai-sdk/provider-utils/${px}`,ux()),body:r.content,signal:s}),l=Va(a);if(!a.ok){let c;try{c=await o({response:a,url:e,requestBodyValues:r.values})}catch(u){throw _u(u)||Hr.isInstance(u)?u:new Hr({message:"Failed to process error response",cause:u,statusCode:a.status,url:e,responseHeaders:l,requestBodyValues:r.values})}throw c.value}try{return await n({response:a,url:e,requestBodyValues:r.values})}catch(c){throw c instanceof Error&&(_u(c)||Hr.isInstance(c))?c:new Hr({message:"Failed to process successful response",cause:c,statusCode:a.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(a){throw cx({error:a,url:e,requestBodyValues:r.values})}},Ix=({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:n,url:o,requestBodyValues:s})=>{const i=await n.text(),a=Va(n);if(i.trim()==="")return{responseHeaders:a,value:new Hr({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:a,responseBody:i,isRetryable:r?.(n)})};try{const l=await kx({text:i,schema:e});return{responseHeaders:a,value:new Hr({message:t(l),url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:a,responseBody:i,data:l,isRetryable:r?.(n,l)})}}catch{return{responseHeaders:a,value:new Hr({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:a,responseBody:i,isRetryable:r?.(n)})}}},xx=e=>async({response:t})=>{const r=Va(t);if(t.body==null)throw new QI({});return{responseHeaders:r,value:Tx({stream:t.body,schema:e})}},Ex=e=>async({response:t,url:r,requestBodyValues:n})=>{const o=await t.text(),s=await qg({text:o,schema:e}),i=Va(t);if(!s.success)throw new Hr({message:"Invalid JSON response",cause:s.error,statusCode:t.status,responseHeaders:i,responseBody:o,url:r,requestBodyValues:n});return{responseHeaders:i,value:s.value,rawValue:s.rawValue}};new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");var{btoa:$x}=globalThis;function Rx(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return $x(t)}function Px(e){return e instanceof Uint8Array?Rx(e):e}function Mx(e){return e?.replace(/\/$/,"")}function ks(e){var t,r;return(r=(t=e?.providerOptions)==null?void 0:t.openaiCompatible)!=null?r:{}}function Nx(e){const t=[];for(const{role:r,content:n,...o}of e){const s=ks({...o});switch(r){case"system":{t.push({role:"system",content:n,...s});break}case"user":{if(n.length===1&&n[0].type==="text"){t.push({role:"user",content:n[0].text,...ks(n[0])});break}t.push({role:"user",content:n.map(i=>{const a=ks(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,${Px(i.data)}`},...a}}else throw new Mg({functionality:`file part media type ${i.mediaType}`})}}),...s});break}case"assistant":{let i="";const a=[];for(const l of n){const c=ks(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 n){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=ks(i);t.push({role:"tool",tool_call_id:i.toolCallId,content:l,...c})}break}default:{const i=r;throw new Error(`Unsupported role: ${i}`)}}}return t}function Ug({id:e,model:t,created:r}){return{id:e??void 0,modelId:t??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function zg(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 wu=k({user:d().optional(),reasoningEffort:d().optional(),textVerbosity:d().optional()}),Ox=k({error:k({message:d(),type:d().nullish(),param:ht().nullish(),code:ae([d(),N()]).nullish()})}),Ax={errorSchema:Ox,errorToMessage:e=>e.error.message};function qx({tools:e,toolChoice:t}){e=e?.length?e:void 0;const r=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};const n=[];for(const s of e)s.type==="provider-defined"?r.push({type:"unsupported-tool",tool:s}):n.push({type:"function",function:{name:s.name,description:s.description,parameters:s.inputSchema}});if(t==null)return{tools:n,toolChoice:void 0,toolWarnings:r};const o=t.type;switch(o){case"auto":case"none":case"required":return{tools:n,toolChoice:o,toolWarnings:r};case"tool":return{tools:n,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:r};default:{const s=o;throw new Mg({functionality:`tool choice type: ${s}`})}}}var Lx=class{constructor(e,t){this.specificationVersion="v2";var r,n;this.modelId=e,this.config=t;const o=(r=t.errorStructure)!=null?r:Ax;this.chunkSchema=Dx(o.errorSchema),this.failedResponseHandler=Ix(o),this.supportsStructuredOutputs=(n=t.supportsStructuredOutputs)!=null?n:!1}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var e,t,r;return(r=(t=(e=this.config).supportedUrls)==null?void 0:t.call(e))!=null?r:{}}async getArgs({prompt:e,maxOutputTokens:t,temperature:r,topP:n,topK:o,frequencyPenalty:s,presencePenalty:i,providerOptions:a,stopSequences:l,responseFormat:c,seed:u,toolChoice:f,tools:p}){var h,g,v,_;const w=[],y=Object.assign((h=await jg({provider:"openai-compatible",providerOptions:a,schema:wu}))!=null?h:{},(g=await jg({provider:this.providerOptionsName,providerOptions:a,schema:wu}))!=null?g:{});o!=null&&w.push({type:"unsupported-setting",setting:"topK"}),c?.type==="json"&&c.schema!=null&&!this.supportsStructuredOutputs&&w.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:m,toolChoice:C,toolWarnings:b}=qx({tools:p,toolChoice:f});return{args:{model:this.modelId,user:y.user,max_tokens:t,temperature:r,top_p:n,frequency_penalty:s,presence_penalty:i,response_format: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((_=a?.[this.providerOptionsName])!=null?_:{}).filter(([T])=>!Object.keys(wu.shape).includes(T))),reasoning_effort:y.reasoningEffort,verbosity:y.textVerbosity,messages:Nx(e),tools:m,tool_choice:C},warnings:[...w,...b]}}async doGenerate(e){var t,r,n,o,s,i,a,l,c,u,f,p,h,g,v,_,w;const{args:y,warnings:m}=await this.getArgs({...e}),C=JSON.stringify(y),{responseHeaders:b,value:T,rawValue:I}=await Dg({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Ng(this.config.headers(),e.headers),body:y,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:Ex(jx),abortSignal:e.abortSignal,fetch:this.config.fetch}),R=T.choices[0],S=[],j=R.message.content;j!=null&&j.length>0&&S.push({type:"text",text:j});const O=(t=R.message.reasoning_content)!=null?t:R.message.reasoning;if(O!=null&&O.length>0&&S.push({type:"reasoning",text:O}),R.message.tool_calls!=null)for(const B of R.message.tool_calls)S.push({type:"tool-call",toolCallId:(r=B.id)!=null?r:Za(),toolName:B.function.name,input:B.function.arguments});const L={[this.providerOptionsName]:{},...await((o=(n=this.config.metadataExtractor)==null?void 0:n.extractMetadata)==null?void 0:o.call(n,{parsedBody:I}))},z=(s=T.usage)==null?void 0:s.completion_tokens_details;return z?.accepted_prediction_tokens!=null&&(L[this.providerOptionsName].acceptedPredictionTokens=z?.accepted_prediction_tokens),z?.rejected_prediction_tokens!=null&&(L[this.providerOptionsName].rejectedPredictionTokens=z?.rejected_prediction_tokens),{content:S,finishReason:zg(R.finish_reason),usage:{inputTokens:(a=(i=T.usage)==null?void 0:i.prompt_tokens)!=null?a:void 0,outputTokens:(c=(l=T.usage)==null?void 0:l.completion_tokens)!=null?c:void 0,totalTokens:(f=(u=T.usage)==null?void 0:u.total_tokens)!=null?f:void 0,reasoningTokens:(g=(h=(p=T.usage)==null?void 0:p.completion_tokens_details)==null?void 0:h.reasoning_tokens)!=null?g:void 0,cachedInputTokens:(w=(_=(v=T.usage)==null?void 0:v.prompt_tokens_details)==null?void 0:_.cached_tokens)!=null?w:void 0},providerMetadata:L,request:{body:C},response:{...Ug(T),headers:b,body:I},warnings:m}}async doStream(e){var t;const{args:r,warnings:n}=await this.getArgs({...e}),o={...r,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 Dg({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Ng(this.config.headers(),e.headers),body:o,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:xx(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 f=!0;const p=this.providerOptionsName;let h=!1,g=!1;return{stream:a.pipeThrough(new TransformStream({start(v){v.enqueue({type:"stream-start",warnings:n})},transform(v,_){var w,y,m,C,b,T,I,R,S,j,O,L,z;if(e.includeRawChunks&&_.enqueue({type:"raw",rawValue:v.rawValue}),!v.success){c="error",_.enqueue({type:"error",error:v.error});return}const B=v.value;if(s?.processChunk(v.rawValue),"error"in B){c="error",_.enqueue({type:"error",error:B.error.message});return}if(f&&(f=!1,_.enqueue({type:"response-metadata",...Ug(B)})),B.usage!=null){const{prompt_tokens:Z,completion_tokens:ne,total_tokens:D,prompt_tokens_details:E,completion_tokens_details:U}=B.usage;u.promptTokens=Z??void 0,u.completionTokens=ne??void 0,u.totalTokens=D??void 0,U?.reasoning_tokens!=null&&(u.completionTokensDetails.reasoningTokens=U?.reasoning_tokens),U?.accepted_prediction_tokens!=null&&(u.completionTokensDetails.acceptedPredictionTokens=U?.accepted_prediction_tokens),U?.rejected_prediction_tokens!=null&&(u.completionTokensDetails.rejectedPredictionTokens=U?.rejected_prediction_tokens),E?.cached_tokens!=null&&(u.promptTokensDetails.cachedTokens=E?.cached_tokens)}const X=B.choices[0];if(X?.finish_reason!=null&&(c=zg(X.finish_reason)),X?.delta==null)return;const ee=X.delta,Q=(w=ee.reasoning_content)!=null?w:ee.reasoning;if(Q&&(h||(_.enqueue({type:"reasoning-start",id:"reasoning-0"}),h=!0),_.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:Q})),ee.content&&(g||(_.enqueue({type:"text-start",id:"txt-0"}),g=!0),_.enqueue({type:"text-delta",id:"txt-0",delta:ee.content})),ee.tool_calls!=null)for(const Z of ee.tool_calls){const ne=Z.index;if(l[ne]==null){if(Z.id==null)throw new mg({data:Z,message:"Expected 'id' to be a string."});if(((y=Z.function)==null?void 0:y.name)==null)throw new mg({data:Z,message:"Expected 'function.name' to be a string."});_.enqueue({type:"tool-input-start",id:Z.id,toolName:Z.function.name}),l[ne]={id:Z.id,type:"function",function:{name:Z.function.name,arguments:(m=Z.function.arguments)!=null?m:""},hasFinished:!1};const E=l[ne];((C=E.function)==null?void 0:C.name)!=null&&((b=E.function)==null?void 0:b.arguments)!=null&&(E.function.arguments.length>0&&_.enqueue({type:"tool-input-delta",id:E.id,delta:E.function.arguments}),Lg(E.function.arguments)&&(_.enqueue({type:"tool-input-end",id:E.id}),_.enqueue({type:"tool-call",toolCallId:(T=E.id)!=null?T:Za(),toolName:E.function.name,input:E.function.arguments}),E.hasFinished=!0));continue}const D=l[ne];D.hasFinished||(((I=Z.function)==null?void 0:I.arguments)!=null&&(D.function.arguments+=(S=(R=Z.function)==null?void 0:R.arguments)!=null?S:""),_.enqueue({type:"tool-input-delta",id:D.id,delta:(j=Z.function.arguments)!=null?j:""}),((O=D.function)==null?void 0:O.name)!=null&&((L=D.function)==null?void 0:L.arguments)!=null&&Lg(D.function.arguments)&&(_.enqueue({type:"tool-input-end",id:D.id}),_.enqueue({type:"tool-call",toolCallId:(z=D.id)!=null?z:Za(),toolName:D.function.name,input:D.function.arguments}),D.hasFinished=!0))}},flush(v){var _,w,y,m,C,b;h&&v.enqueue({type:"reasoning-end",id:"reasoning-0"}),g&&v.enqueue({type:"text-end",id:"txt-0"});for(const I of l.filter(R=>!R.hasFinished))v.enqueue({type:"tool-input-end",id:I.id}),v.enqueue({type:"tool-call",toolCallId:(_=I.id)!=null?_:Za(),toolName:I.function.name,input:I.function.arguments});const T={[p]:{},...s?.buildMetadata()};u.completionTokensDetails.acceptedPredictionTokens!=null&&(T[p].acceptedPredictionTokens=u.completionTokensDetails.acceptedPredictionTokens),u.completionTokensDetails.rejectedPredictionTokens!=null&&(T[p].rejectedPredictionTokens=u.completionTokensDetails.rejectedPredictionTokens),v.enqueue({type:"finish",finishReason:c,usage:{inputTokens:(w=u.promptTokens)!=null?w:void 0,outputTokens:(y=u.completionTokens)!=null?y:void 0,totalTokens:(m=u.totalTokens)!=null?m:void 0,reasoningTokens:(C=u.completionTokensDetails.reasoningTokens)!=null?C:void 0,cachedInputTokens:(b=u.promptTokensDetails.cachedTokens)!=null?b:void 0},providerMetadata:T})}})),request:{body:o},response:{headers:i}}}},Fg=k({prompt_tokens:N().nullish(),completion_tokens:N().nullish(),total_tokens:N().nullish(),prompt_tokens_details:k({cached_tokens:N().nullish()}).nullish(),completion_tokens_details:k({reasoning_tokens:N().nullish(),accepted_prediction_tokens:N().nullish(),rejected_prediction_tokens:N().nullish()}).nullish()}).nullish(),jx=k({id:d().nullish(),created:N().nullish(),model:d().nullish(),choices:q(k({message:k({role:P("assistant").nullish(),content:d().nullish(),reasoning_content:d().nullish(),reasoning:d().nullish(),tool_calls:q(k({id:d().nullish(),function:k({name:d(),arguments:d()})})).nullish()}),finish_reason:d().nullish()})),usage:Fg}),Dx=e=>ae([k({id:d().nullish(),created:N().nullish(),model:d().nullish(),choices:q(k({delta:k({role:ce(["assistant"]).nullish(),content:d().nullish(),reasoning_content:d().nullish(),reasoning:d().nullish(),tool_calls:q(k({index:N(),id:d().nullish(),function:k({name:d().nullish(),arguments:d().nullish()})})).nullish()}).nullish(),finish_reason:d().nullish()})),usage:Fg}),e]);k({echo:ge().optional(),logitBias:he(d(),N()).optional(),suffix:d().optional(),user:d().optional()});var Ux=k({prompt_tokens:N(),completion_tokens:N(),total_tokens:N()});k({id:d().nullish(),created:N().nullish(),model:d().nullish(),choices:q(k({text:d(),finish_reason:d()})),usage:Ux.nullish()}),k({dimensions:N().optional(),user:d().optional()}),k({data:q(k({embedding:q(N())})),usage:k({prompt_tokens:N()}).nullish(),providerMetadata:he(d(),he(d(),ht())).optional()}),k({data:q(k({b64_json:d()}))});var Vg=e=>{var t,r;return e==null?void 0:{deepseek:{promptCacheHitTokens:(t=e.prompt_cache_hit_tokens)!=null?t:NaN,promptCacheMissTokens:(r=e.prompt_cache_miss_tokens)!=null?r:NaN}}},zx={extractMetadata:async({parsedBody:e})=>{const t=await bs({value:e,schema:Fx});return!t.success||t.value.usage==null?void 0:Vg(t.value.usage)},createStreamExtractor:()=>{let e;return{processChunk:async t=>{var r,n;const o=await bs({value:t,schema:Vx});o.success&&((n=(r=o.value.choices)==null?void 0:r[0])==null?void 0:n.finish_reason)==="stop"&&o.value.usage&&(e=o.value.usage)},buildMetadata:()=>Vg(e)}}},Zg=k({prompt_cache_hit_tokens:N().nullish(),prompt_cache_miss_tokens:N().nullish()}),Fx=k({usage:Zg.nullish()}),Vx=k({choices:q(k({finish_reason:d().nullish()})).nullish(),usage:Zg.nullish()}),Zx="1.0.30";function Bg(e={}){var t;const r=Mx((t=e.baseURL)!=null?t:"https://api.deepseek.com/v1"),n=()=>Og({Authorization:`Bearer ${fx({apiKey:e.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...e.headers},`ai-sdk/deepseek/${Zx}`);class o extends Lx{addJsonInstruction(l){var c;if(((c=l.responseFormat)==null?void 0:c.type)!=="json")return l;const p=[...Array.isArray(l.prompt)?l.prompt:[],{role:"user",content:[{type:"text",text:"Return ONLY a valid JSON object."}]}];return{...l,prompt:p}}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})=>`${r}${l}`,headers:n,fetch:e.fetch,metadataExtractor:zx}),i=a=>s(a);return i.languageModel=s,i.chat=s,i.textEmbeddingModel=a=>{throw new Sg({modelId:a,modelType:"textEmbeddingModel"})},i.imageModel=a=>{throw new Sg({modelId:a,modelType:"imageModel"})},i}Bg();const Bx=(e,t,r)=>{if(r.endsWith("content"))chrome.tabs.query({},n=>{n.forEach(o=>{chrome.tabs.sendMessage(o.id,{type:e,data:t,direction:r,tabId:o.id})})});else return chrome.runtime.sendMessage({direction:r,type:e,data:t})},Hx=(e,t,r,n)=>{const o=(s,i,a)=>{if(s.type===e&&s.direction===r){const{data:l}=s;t(l,i,a),a(i)}};return chrome.runtime.onMessage.addListener(o),()=>chrome.runtime.onMessage.removeListener(o)};class Jx{constructor(t){this._isStarted=!1,this._isClosed=!1,this.targetSessionId=t,this._messageListener=Hx("mcp-server-to-client",r=>{try{if(r.sessionId!==this.targetSessionId)return;const n=jn.parse(r.mcpMessage);this.onmessage?.(n)}catch(n){console.log("【Client Transport】处理server消息错误:",n)}},"content->bg")}_throwError(t,r){if(t()){const n=new Error(r);throw console.log(r,n),this.onerror&&this.onerror(n),n}}async start(){this._throwError(()=>this._isClosed,"【Client Transport】 未启动,无法重新启动"),this._isStarted=!0}async send(t,r){this._throwError(()=>!this._isStarted,"【Client Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Client Transport】 已关闭,无法发送消息");let n;if(chrome.sessionRegistry){const o=chrome.sessionRegistry.get(this.targetSessionId);o&&o.tabIds.length>0&&(n=o.tabIds[o.tabIds.length-1])}n==null&&(n=await chrome.runtime.sendMessage({type:"get-session-tab-id",sessionId:this.targetSessionId})),this._throwError(()=>n==null,`【Client Transport】后台未找到活动的tabId用于${this.targetSessionId}`),Bx("mcp-client-to-server",{sessionId:this.targetSessionId,tabId:n,mcpMessage:t},"bg->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 Ba(e){return!!e._zod}function pn(e,t){return Ba(e)?pp(e,t):e.safeParse(t)}function Hg(e){if(!e)return;let t;if(Ba(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function Gx(e){if(Ba(e)){const s=e._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.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 n=e.value;if(n!==void 0)return n}function Vn(e){return e==="completed"||e==="failed"||e==="cancelled"}new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Jg(e){const r=Hg(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const n=Gx(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Gg(e,t){const r=pn(e,t);if(!r.success)throw r.error;return r.data}const Wx=6e4;class Kx{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._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(gc,r=>{this._oncancel(r)}),this.setNotificationHandler(yc,r=>{this._onprogress(r)}),this.setRequestHandler(_c,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(vc,async(r,n)=>{const o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new Te($e.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(bc,async(r,n)=>{const o=async()=>{const s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){const l=a.message,c=l.id,u=this._requestResolvers.get(c);if(u)if(this._requestResolvers.delete(c),a.type==="response")u(l);else{const f=l,p=new Te(f.error.code,f.error.message,f.error.data);u(p)}else{const f=a.type==="response"?"Response":"Error";this._onerror(new Error(`${f} handler missing for request ${c}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}const i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new Te($e.InvalidParams,`Task not found: ${s}`);if(!Vn(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Vn(i.status)){const a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Ln]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(kc,async(r,n)=>{try{const{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new Te($e.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Cc,async(r,n)=>{try{const o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new Te($e.InvalidParams,`Task not found: ${r.params.taskId}`);if(Vn(o.status))throw new Te($e.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);const s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new Te($e.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof Te?o:new Te($e.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,n,o,s=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(t){const r=this._timeoutInfo.get(t);if(!r)return!1;const n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),Te.fromError($e.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){const r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){this._transport=t;const r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};const n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};const o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),is(s)||pC(s)?this._onresponse(s):fc(s)?this._onrequest(s,i):dC(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){const t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();const r=Te.fromError($e.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const n of t.values())n(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){const r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(t,r){const n=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,o=this._transport,s=t.params?._meta?.[Ln]?.taskId;if(n===void 0){const u={jsonrpc:"2.0",id:t.id,error:{code:$e.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch(f=>this._onerror(new Error(`Failed to enqueue error response: ${f}`))):o?.send(u).catch(f=>this._onerror(new Error(`Failed to send an error response: ${f}`)));return}const i=new AbortController;this._requestHandlerAbortControllers.set(t.id,i);const a=uC(t.params)?t.params.task:void 0,l=this._taskStore?this.requestTaskStore(t,o?.sessionId):void 0,c={signal:i.signal,sessionId:o?.sessionId,_meta:t.params?._meta,sendNotification:async u=>{const f={relatedRequestId:t.id};s&&(f.relatedTask={taskId:s}),await this.notification(u,f)},sendRequest:async(u,f,p)=>{const h={...p,relatedRequestId:t.id};s&&!h.relatedTask&&(h.relatedTask={taskId:s});const g=h.relatedTask?.taskId??s;return g&&l&&await l.updateTaskStatus(g,"input_required"),await this.request(u,f,h)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:s,taskStore:l,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,c)).then(async u=>{if(i.signal.aborted)return;const f={result:u,jsonrpc:"2.0",id:t.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:f,timestamp:Date.now()},o?.sessionId):await o?.send(f)},async u=>{if(i.signal.aborted)return;const f={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(u.code)?u.code:$e.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:f,timestamp:Date.now()},o?.sessionId):await o?.send(f)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){const{progressToken:r,...n}=t.params,o=Number(r),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){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(l);return}s(n)}_onresponse(t){const r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),is(t))n(t);else{const i=new Te(t.error.code,t.error.message,t.error.data);n(i)}return}const o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(is(t)&&t.result&&typeof t.result=="object"){const i=t.result;if(i.task&&typeof i.task=="object"){const a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),is(t))o(t);else{const i=Te.fromError(t.error.code,t.error.message,t.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,r,n){const{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(t,r,n)}}catch(i){yield{type:"error",error:i instanceof Te?i:new Te($e.InternalError,String(i))}}return}let s;try{const i=await this.request(t,ps,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new Te($e.InternalError,"Task creation did not return a task");for(;;){const a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},Vn(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new Te($e.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new Te($e.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}const l=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(c=>setTimeout(c,l)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof Te?i:new Te($e.InternalError,String(i))}}}request(t,r,n){const{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:l}=n??{};return new Promise((c,u)=>{const f=y=>{u(y)};if(!this._transport){f(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),a&&this.assertTaskCapability(t.method)}catch(y){f(y);return}n?.signal?.throwIfAborted();const p=this._requestMessageId++,h={...t,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.onprogress),h.params={...t.params,_meta:{...t.params?._meta||{},progressToken:p}}),a&&(h.params={...h.params,task:a}),l&&(h.params={...h.params,_meta:{...h.params?._meta||{},[Ln]:l}});const g=y=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(y)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(C=>this._onerror(new Error(`Failed to send cancellation: ${C}`)));const m=y instanceof Te?y:new Te($e.RequestTimeout,String(y));u(m)};this._responseHandlers.set(p,y=>{if(!n?.signal?.aborted){if(y instanceof Error)return u(y);try{const m=pn(r,y.result);m.success?c(m.data):u(m.error)}catch(m){u(m)}}}),n?.signal?.addEventListener("abort",()=>{g(n?.signal?.reason)});const v=n?.timeout??Wx,_=()=>g(Te.fromError($e.RequestTimeout,"Request timed out",{timeout:v}));this._setupTimeout(p,v,n?.maxTotalTimeout,_,n?.resetTimeoutOnProgress??!1);const w=l?.taskId;if(w){const y=m=>{const C=this._responseHandlers.get(p);C?C(m):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,y),this._enqueueTaskMessage(w,{type:"request",message:h,timestamp:Date.now()}).catch(m=>{this._cleanupTimeout(p),u(m)})}else this._transport.send(h,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(y=>{this._cleanupTimeout(p),u(y)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},wc,r)}async getTaskResult(t,r,n){return this.request({method:"tasks/result",params:t},r,n)}async listTasks(t,r){return this.request({method:"tasks/list",params:t},Tc,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},$C,r)}async notification(t,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);const n=r?.relatedTask?.taskId;if(n){const a={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[Ln]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let a={...t,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Ln]:r.relatedTask}}}),this._transport?.send(a,r).catch(l=>this._onerror(l))});return}let i={...t,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Ln]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(t,r){const n=Jg(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{const i=Gg(t,o);return Promise.resolve(r(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,r){const n=Jg(t);this._notificationHandlers.set(n,o=>{const s=Gg(t,o);return Promise.resolve(r(s))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){const r=this._taskProgressTokens.get(t);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,r,n,o)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){const n=await this._taskMessageQueue.dequeueAll(t,r);for(const o of n)if(o.type==="request"&&fc(o.message)){const s=o.message.id,i=this._requestResolvers.get(s);i?(i(new Te($e.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let n=this._options?.defaultTaskPollInterval??1e3;try{const o=await this._taskStore?.getTask(t);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new Te($e.InvalidRequest,"Request cancelled"));return}const i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new Te($e.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){const n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!t)throw new Error("No request provided");return await n.createTask(o,t.id,{method:t.method,params:t.params},r)},getTask:async o=>{const s=await n.getTask(o,r);if(!s)throw new Te($e.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);const a=await n.getTask(o,r);if(a){const l=Ea.parse({method:"notifications/tasks/status",params:a});await this.notification(l),Vn(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{const a=await n.getTask(o,r);if(!a)throw new Te($e.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Vn(a.status))throw new Te($e.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);const l=await n.getTask(o,r);if(l){const c=Ea.parse({method:"notifications/tasks/status",params:l});await this.notification(c),Vn(l.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}function Wg(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Yx(e,t){const r={...e};for(const n in t){const o=n,s=t[o];if(s===void 0)continue;const i=r[o];Wg(i)&&Wg(s)?r[o]={...i,...s}:r[o]=s}return r}var Ha={exports:{}},bu={},Jr={},Zn={},ku={},Tu={},Cu={},Kg;function Ja(){return Kg||(Kg=1,(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 r extends t{constructor(y){if(super(),!e.IDENTIFIER.test(y))throw new Error("CodeGen: name must be a valid identifier");this.str=y}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=r;class n extends t{constructor(y){super(),this._items=typeof y=="string"?[y]:y}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const y=this._items[0];return y===""||y==='""'}get str(){var y;return(y=this._str)!==null&&y!==void 0?y:this._str=this._items.reduce((m,C)=>`${m}${C}`,"")}get names(){var y;return(y=this._names)!==null&&y!==void 0?y:this._names=this._items.reduce((m,C)=>(C instanceof r&&(m[C.str]=(m[C.str]||0)+1),m),{})}}e._Code=n,e.nil=new n("");function o(w,...y){const m=[w[0]];let C=0;for(;C<y.length;)a(m,y[C]),m.push(w[++C]);return new n(m)}e._=o;const s=new n("+");function i(w,...y){const m=[h(w[0])];let C=0;for(;C<y.length;)m.push(s),a(m,y[C]),m.push(s,h(w[++C]));return l(m),new n(m)}e.str=i;function a(w,y){y instanceof n?w.push(...y._items):y instanceof r?w.push(y):w.push(f(y))}e.addCodeArg=a;function l(w){let y=1;for(;y<w.length-1;){if(w[y]===s){const m=c(w[y-1],w[y+1]);if(m!==void 0){w.splice(y-1,3,m);continue}w[y++]="+"}y++}}function c(w,y){if(y==='""')return w;if(w==='""')return y;if(typeof w=="string")return y instanceof r||w[w.length-1]!=='"'?void 0:typeof y!="string"?`${w.slice(0,-1)}${y}"`:y[0]==='"'?w.slice(0,-1)+y.slice(1):void 0;if(typeof y=="string"&&y[0]==='"'&&!(w instanceof r))return`"${w}${y.slice(1)}`}function u(w,y){return y.emptyStr()?w:w.emptyStr()?y:i`${w}${y}`}e.strConcat=u;function f(w){return typeof w=="number"||typeof w=="boolean"||w===null?w:h(Array.isArray(w)?w.join(","):w)}function p(w){return new n(h(w))}e.stringify=p;function h(w){return JSON.stringify(w).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.safeStringify=h;function g(w){return typeof w=="string"&&e.IDENTIFIER.test(w)?new n(`.${w}`):o`[${w}]`}e.getProperty=g;function v(w){if(typeof w=="string"&&e.IDENTIFIER.test(w))return new n(`${w}`);throw new Error(`CodeGen: invalid export name: ${w}, use explicit $id name mapping`)}e.getEsmExportName=v;function _(w){return new n(w.toString())}e.regexpCode=_})(Cu)),Cu}var Su={},Yg;function Qg(){return Yg||(Yg=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=Ja();class r extends Error{constructor(c){super(`CodeGen: "code" for ${c} not defined`),this.value=c.value}}var n;(function(l){l[l.Started=0]="Started",l[l.Completed=1]="Completed"})(n||(e.UsedValueState=n={})),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,f;if(!((f=(u=this._parent)===null||u===void 0?void 0:u._prefixes)===null||f===void 0)&&f.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:f}){this.value=c,this.scopePath=(0,t._)`.${new t.Name(u)}[${f}]`}}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 f;if(u.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const p=this.toName(c),{prefix:h}=p,g=(f=u.key)!==null&&f!==void 0?f:u.ref;let v=this._values[h];if(v){const y=v.get(g);if(y)return y}else v=this._values[h]=new Map;v.set(g,p);const _=this._scope[h]||(this._scope[h]=[]),w=_.length;return _[w]=u.ref,p.setValue(u,{property:h,itemIndex:w}),p}getValue(c,u){const f=this._values[c];if(f)return f.get(u)}scopeRefs(c,u=this._values){return this._reduceValues(u,f=>{if(f.scopePath===void 0)throw new Error(`CodeGen: name "${f}" has no value`);return(0,t._)`${c}${f.scopePath}`})}scopeCode(c=this._values,u,f){return this._reduceValues(c,p=>{if(p.value===void 0)throw new Error(`CodeGen: name "${p}" has no value`);return p.value.code},u,f)}_reduceValues(c,u,f={},p){let h=t.nil;for(const g in c){const v=c[g];if(!v)continue;const _=f[g]=f[g]||new Map;v.forEach(w=>{if(_.has(w))return;_.set(w,n.Started);let y=u(w);if(y){const m=this.opts.es5?e.varKinds.var:e.varKinds.const;h=(0,t._)`${h}${m} ${w} = ${y};${this.opts._n}`}else if(y=p?.(w))h=(0,t._)`${h}${y}${this.opts._n}`;else throw new r(w);_.set(w,n.Completed)})}return h}}e.ValueScope=a})(Su)),Su}var Xg;function Pe(){return Xg||(Xg=1,(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=Ja(),r=Qg();var n=Ja();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return n.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return n.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return n.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}});var o=Qg();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(x,M){return this}}class i extends s{constructor(x,M,H){super(),this.varKind=x,this.name=M,this.rhs=H}render({es5:x,_n:M}){const H=x?r.varKinds.var:this.varKind,re=this.rhs===void 0?"":` = ${this.rhs}`;return`${H} ${this.name}${re};`+M}optimizeNames(x,M){if(x[this.name.str])return this.rhs&&(this.rhs=B(this.rhs,x,M)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class a extends s{constructor(x,M,H){super(),this.lhs=x,this.rhs=M,this.sideEffects=H}render({_n:x}){return`${this.lhs} = ${this.rhs};`+x}optimizeNames(x,M){if(!(this.lhs instanceof t.Name&&!x[this.lhs.str]&&!this.sideEffects))return this.rhs=B(this.rhs,x,M),this}get names(){const x=this.lhs instanceof t.Name?{}:{...this.lhs.names};return z(x,this.rhs)}}class l extends a{constructor(x,M,H,re){super(x,H,re),this.op=M}render({_n:x}){return`${this.lhs} ${this.op}= ${this.rhs};`+x}}class c extends s{constructor(x){super(),this.label=x,this.names={}}render({_n:x}){return`${this.label}:`+x}}class u extends s{constructor(x){super(),this.label=x,this.names={}}render({_n:x}){return`break${this.label?` ${this.label}`:""};`+x}}class f extends s{constructor(x){super(),this.error=x}render({_n:x}){return`throw ${this.error};`+x}get names(){return this.error.names}}class p extends s{constructor(x){super(),this.code=x}render({_n:x}){return`${this.code};`+x}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(x,M){return this.code=B(this.code,x,M),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class h extends s{constructor(x=[]){super(),this.nodes=x}render(x){return this.nodes.reduce((M,H)=>M+H.render(x),"")}optimizeNodes(){const{nodes:x}=this;let M=x.length;for(;M--;){const H=x[M].optimizeNodes();Array.isArray(H)?x.splice(M,1,...H):H?x[M]=H:x.splice(M,1)}return x.length>0?this:void 0}optimizeNames(x,M){const{nodes:H}=this;let re=H.length;for(;re--;){const te=H[re];te.optimizeNames(x,M)||(X(x,te.names),H.splice(re,1))}return H.length>0?this:void 0}get names(){return this.nodes.reduce((x,M)=>L(x,M.names),{})}}class g extends h{render(x){return"{"+x._n+super.render(x)+"}"+x._n}}class v extends h{}class _ extends g{}_.kind="else";class w extends g{constructor(x,M){super(M),this.condition=x}render(x){let M=`if(${this.condition})`+super.render(x);return this.else&&(M+="else "+this.else.render(x)),M}optimizeNodes(){super.optimizeNodes();const x=this.condition;if(x===!0)return this.nodes;let M=this.else;if(M){const H=M.optimizeNodes();M=this.else=Array.isArray(H)?new _(H):H}if(M)return x===!1?M instanceof w?M:M.nodes:this.nodes.length?this:new w(ee(x),M instanceof w?[M]:M.nodes);if(!(x===!1||!this.nodes.length))return this}optimizeNames(x,M){var H;if(this.else=(H=this.else)===null||H===void 0?void 0:H.optimizeNames(x,M),!!(super.optimizeNames(x,M)||this.else))return this.condition=B(this.condition,x,M),this}get names(){const x=super.names;return z(x,this.condition),this.else&&L(x,this.else.names),x}}w.kind="if";class y extends g{}y.kind="for";class m extends y{constructor(x){super(),this.iteration=x}render(x){return`for(${this.iteration})`+super.render(x)}optimizeNames(x,M){if(super.optimizeNames(x,M))return this.iteration=B(this.iteration,x,M),this}get names(){return L(super.names,this.iteration.names)}}class C extends y{constructor(x,M,H,re){super(),this.varKind=x,this.name=M,this.from=H,this.to=re}render(x){const M=x.es5?r.varKinds.var:this.varKind,{name:H,from:re,to:te}=this;return`for(${M} ${H}=${re}; ${H}<${te}; ${H}++)`+super.render(x)}get names(){const x=z(super.names,this.from);return z(x,this.to)}}class b extends y{constructor(x,M,H,re){super(),this.loop=x,this.varKind=M,this.name=H,this.iterable=re}render(x){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(x)}optimizeNames(x,M){if(super.optimizeNames(x,M))return this.iterable=B(this.iterable,x,M),this}get names(){return L(super.names,this.iterable.names)}}class T extends g{constructor(x,M,H){super(),this.name=x,this.args=M,this.async=H}render(x){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(x)}}T.kind="func";class I extends h{render(x){return"return "+super.render(x)}}I.kind="return";class R extends g{render(x){let M="try"+super.render(x);return this.catch&&(M+=this.catch.render(x)),this.finally&&(M+=this.finally.render(x)),M}optimizeNodes(){var x,M;return super.optimizeNodes(),(x=this.catch)===null||x===void 0||x.optimizeNodes(),(M=this.finally)===null||M===void 0||M.optimizeNodes(),this}optimizeNames(x,M){var H,re;return super.optimizeNames(x,M),(H=this.catch)===null||H===void 0||H.optimizeNames(x,M),(re=this.finally)===null||re===void 0||re.optimizeNames(x,M),this}get names(){const x=super.names;return this.catch&&L(x,this.catch.names),this.finally&&L(x,this.finally.names),x}}class S extends g{constructor(x){super(),this.error=x}render(x){return`catch(${this.error})`+super.render(x)}}S.kind="catch";class j extends g{render(x){return"finally"+super.render(x)}}j.kind="finally";class O{constructor(x,M={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...M,_n:M.lines?`
81
- `:""},this._extScope=x,this._scope=new r.Scope({parent:x}),this._nodes=[new v]}toString(){return this._root.render(this.opts)}name(x){return this._scope.name(x)}scopeName(x){return this._extScope.name(x)}scopeValue(x,M){const H=this._extScope.value(x,M);return(this._values[H.prefix]||(this._values[H.prefix]=new Set)).add(H),H}getScopeValue(x,M){return this._extScope.getValue(x,M)}scopeRefs(x){return this._extScope.scopeRefs(x,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(x,M,H,re){const te=this._scope.toName(M);return H!==void 0&&re&&(this._constants[te.str]=H),this._leafNode(new i(x,te,H)),te}const(x,M,H){return this._def(r.varKinds.const,x,M,H)}let(x,M,H){return this._def(r.varKinds.let,x,M,H)}var(x,M,H){return this._def(r.varKinds.var,x,M,H)}assign(x,M,H){return this._leafNode(new a(x,M,H))}add(x,M){return this._leafNode(new l(x,e.operators.ADD,M))}code(x){return typeof x=="function"?x():x!==t.nil&&this._leafNode(new p(x)),this}object(...x){const M=["{"];for(const[H,re]of x)M.length>1&&M.push(","),M.push(H),(H!==re||this.opts.es5)&&(M.push(":"),(0,t.addCodeArg)(M,re));return M.push("}"),new t._Code(M)}if(x,M,H){if(this._blockNode(new w(x)),M&&H)this.code(M).else().code(H).endIf();else if(M)this.code(M).endIf();else if(H)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(x){return this._elseNode(new w(x))}else(){return this._elseNode(new _)}endIf(){return this._endBlockNode(w,_)}_for(x,M){return this._blockNode(x),M&&this.code(M).endFor(),this}for(x,M){return this._for(new m(x),M)}forRange(x,M,H,re,te=this.opts.es5?r.varKinds.var:r.varKinds.let){const _e=this._scope.toName(x);return this._for(new C(te,_e,M,H),()=>re(_e))}forOf(x,M,H,re=r.varKinds.const){const te=this._scope.toName(x);if(this.opts.es5){const _e=M instanceof t.Name?M:this.var("_arr",M);return this.forRange("_i",0,(0,t._)`${_e}.length`,G=>{this.var(te,(0,t._)`${_e}[${G}]`),H(te)})}return this._for(new b("of",re,te,M),()=>H(te))}forIn(x,M,H,re=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(x,(0,t._)`Object.keys(${M})`,H);const te=this._scope.toName(x);return this._for(new b("in",re,te,M),()=>H(te))}endFor(){return this._endBlockNode(y)}label(x){return this._leafNode(new c(x))}break(x){return this._leafNode(new u(x))}return(x){const M=new I;if(this._blockNode(M),this.code(x),M.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(I)}try(x,M,H){if(!M&&!H)throw new Error('CodeGen: "try" without "catch" and "finally"');const re=new R;if(this._blockNode(re),this.code(x),M){const te=this.name("e");this._currNode=re.catch=new S(te),M(te)}return H&&(this._currNode=re.finally=new j,this.code(H)),this._endBlockNode(S,j)}throw(x){return this._leafNode(new f(x))}block(x,M){return this._blockStarts.push(this._nodes.length),x&&this.code(x).endBlock(M),this}endBlock(x){const M=this._blockStarts.pop();if(M===void 0)throw new Error("CodeGen: not in self-balancing block");const H=this._nodes.length-M;if(H<0||x!==void 0&&H!==x)throw new Error(`CodeGen: wrong number of nodes: ${H} vs ${x} expected`);return this._nodes.length=M,this}func(x,M=t.nil,H,re){return this._blockNode(new T(x,M,H)),re&&this.code(re).endFunc(),this}endFunc(){return this._endBlockNode(T)}optimize(x=1){for(;x-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(x){return this._currNode.nodes.push(x),this}_blockNode(x){this._currNode.nodes.push(x),this._nodes.push(x)}_endBlockNode(x,M){const H=this._currNode;if(H instanceof x||M&&H instanceof M)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${M?`${x.kind}/${M.kind}`:x.kind}"`)}_elseNode(x){const M=this._currNode;if(!(M instanceof w))throw new Error('CodeGen: "else" without "if"');return this._currNode=M.else=x,this}get _root(){return this._nodes[0]}get _currNode(){const x=this._nodes;return x[x.length-1]}set _currNode(x){const M=this._nodes;M[M.length-1]=x}}e.CodeGen=O;function L(F,x){for(const M in x)F[M]=(F[M]||0)+(x[M]||0);return F}function z(F,x){return x instanceof t._CodeOrName?L(F,x.names):F}function B(F,x,M){if(F instanceof t.Name)return H(F);if(!re(F))return F;return new t._Code(F._items.reduce((te,_e)=>(_e instanceof t.Name&&(_e=H(_e)),_e instanceof t._Code?te.push(..._e._items):te.push(_e),te),[]));function H(te){const _e=M[te.str];return _e===void 0||x[te.str]!==1?te:(delete x[te.str],_e)}function re(te){return te instanceof t._Code&&te._items.some(_e=>_e instanceof t.Name&&x[_e.str]===1&&M[_e.str]!==void 0)}}function X(F,x){for(const M in x)F[M]=(F[M]||0)-(x[M]||0)}function ee(F){return typeof F=="boolean"||typeof F=="number"||F===null?!F:(0,t._)`!${U(F)}`}e.not=ee;const Q=E(e.operators.AND);function Z(...F){return F.reduce(Q)}e.and=Z;const ne=E(e.operators.OR);function D(...F){return F.reduce(ne)}e.or=D;function E(F){return(x,M)=>x===t.nil?M:M===t.nil?x:(0,t._)`${U(x)} ${F} ${U(M)}`}function U(F){return F instanceof t.Name?F:(0,t._)`(${F})`}})(Tu)),Tu}var Me={},e_;function De(){if(e_)return Me;e_=1,Object.defineProperty(Me,"__esModule",{value:!0}),Me.checkStrictMode=Me.getErrorPath=Me.Type=Me.useFunc=Me.setEvaluated=Me.evaluatedPropsToName=Me.mergeEvaluated=Me.eachItem=Me.unescapeJsonPointer=Me.escapeJsonPointer=Me.escapeFragment=Me.unescapeFragment=Me.schemaRefOrVal=Me.schemaHasRulesButRef=Me.schemaHasRules=Me.checkUnknownRules=Me.alwaysValidSchema=Me.toHash=void 0;const e=Pe(),t=Ja();function r(b){const T={};for(const I of b)T[I]=!0;return T}Me.toHash=r;function n(b,T){return typeof T=="boolean"?T:Object.keys(T).length===0?!0:(o(b,T),!s(T,b.self.RULES.all))}Me.alwaysValidSchema=n;function o(b,T=b.schema){const{opts:I,self:R}=b;if(!I.strictSchema||typeof T=="boolean")return;const S=R.RULES.keywords;for(const j in T)S[j]||C(b,`unknown keyword: "${j}"`)}Me.checkUnknownRules=o;function s(b,T){if(typeof b=="boolean")return!b;for(const I in b)if(T[I])return!0;return!1}Me.schemaHasRules=s;function i(b,T){if(typeof b=="boolean")return!b;for(const I in b)if(I!=="$ref"&&T.all[I])return!0;return!1}Me.schemaHasRulesButRef=i;function a({topSchemaRef:b,schemaPath:T},I,R,S){if(!S){if(typeof I=="number"||typeof I=="boolean")return I;if(typeof I=="string")return(0,e._)`${I}`}return(0,e._)`${b}${T}${(0,e.getProperty)(R)}`}Me.schemaRefOrVal=a;function l(b){return f(decodeURIComponent(b))}Me.unescapeFragment=l;function c(b){return encodeURIComponent(u(b))}Me.escapeFragment=c;function u(b){return typeof b=="number"?`${b}`:b.replace(/~/g,"~0").replace(/\//g,"~1")}Me.escapeJsonPointer=u;function f(b){return b.replace(/~1/g,"/").replace(/~0/g,"~")}Me.unescapeJsonPointer=f;function p(b,T){if(Array.isArray(b))for(const I of b)T(I);else T(b)}Me.eachItem=p;function h({mergeNames:b,mergeToName:T,mergeValues:I,resultToName:R}){return(S,j,O,L)=>{const z=O===void 0?j:O instanceof e.Name?(j instanceof e.Name?b(S,j,O):T(S,j,O),O):j instanceof e.Name?(T(S,O,j),j):I(j,O);return L===e.Name&&!(z instanceof e.Name)?R(S,z):z}}Me.mergeEvaluated={props:h({mergeNames:(b,T,I)=>b.if((0,e._)`${I} !== true && ${T} !== undefined`,()=>{b.if((0,e._)`${T} === true`,()=>b.assign(I,!0),()=>b.assign(I,(0,e._)`${I} || {}`).code((0,e._)`Object.assign(${I}, ${T})`))}),mergeToName:(b,T,I)=>b.if((0,e._)`${I} !== true`,()=>{T===!0?b.assign(I,!0):(b.assign(I,(0,e._)`${I} || {}`),v(b,I,T))}),mergeValues:(b,T)=>b===!0?!0:{...b,...T},resultToName:g}),items:h({mergeNames:(b,T,I)=>b.if((0,e._)`${I} !== true && ${T} !== undefined`,()=>b.assign(I,(0,e._)`${T} === true ? true : ${I} > ${T} ? ${I} : ${T}`)),mergeToName:(b,T,I)=>b.if((0,e._)`${I} !== true`,()=>b.assign(I,T===!0?!0:(0,e._)`${I} > ${T} ? ${I} : ${T}`)),mergeValues:(b,T)=>b===!0?!0:Math.max(b,T),resultToName:(b,T)=>b.var("items",T)})};function g(b,T){if(T===!0)return b.var("props",!0);const I=b.var("props",(0,e._)`{}`);return T!==void 0&&v(b,I,T),I}Me.evaluatedPropsToName=g;function v(b,T,I){Object.keys(I).forEach(R=>b.assign((0,e._)`${T}${(0,e.getProperty)(R)}`,!0))}Me.setEvaluated=v;const _={};function w(b,T){return b.scopeValue("func",{ref:T,code:_[T.code]||(_[T.code]=new t._Code(T.code))})}Me.useFunc=w;var y;(function(b){b[b.Num=0]="Num",b[b.Str=1]="Str"})(y||(Me.Type=y={}));function m(b,T,I){if(b instanceof e.Name){const R=T===y.Num;return I?R?(0,e._)`"[" + ${b} + "]"`:(0,e._)`"['" + ${b} + "']"`:R?(0,e._)`"/" + ${b}`:(0,e._)`"/" + ${b}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return I?(0,e.getProperty)(b).toString():"/"+u(b)}Me.getErrorPath=m;function C(b,T,I=b.opts.strictSchema){if(I){if(T=`strict mode: ${T}`,I===!0)throw new Error(T);b.self.logger.warn(T)}}return Me.checkStrictMode=C,Me}var Ga={},t_;function fn(){if(t_)return Ga;t_=1,Object.defineProperty(Ga,"__esModule",{value:!0});const e=Pe(),t={data:new e.Name("data"),valCxt:new e.Name("valCxt"),instancePath:new e.Name("instancePath"),parentData:new e.Name("parentData"),parentDataProperty:new e.Name("parentDataProperty"),rootData:new e.Name("rootData"),dynamicAnchors:new e.Name("dynamicAnchors"),vErrors:new e.Name("vErrors"),errors:new e.Name("errors"),this:new e.Name("this"),self:new e.Name("self"),scope:new e.Name("scope"),json:new e.Name("json"),jsonPos:new e.Name("jsonPos"),jsonLen:new e.Name("jsonLen"),jsonPart:new e.Name("jsonPart")};return Ga.default=t,Ga}var r_;function Wa(){return r_||(r_=1,(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=Pe(),r=De(),n=fn();e.keywordError={message:({keyword:_})=>(0,t.str)`must pass "${_}" keyword validation`},e.keyword$DataError={message:({keyword:_,schemaType:w})=>w?(0,t.str)`"${_}" keyword must be ${w} ($data)`:(0,t.str)`"${_}" keyword is invalid ($data)`};function o(_,w=e.keywordError,y,m){const{it:C}=_,{gen:b,compositeRule:T,allErrors:I}=C,R=f(_,w,y);m??(T||I)?l(b,R):c(C,(0,t._)`[${R}]`)}e.reportError=o;function s(_,w=e.keywordError,y){const{it:m}=_,{gen:C,compositeRule:b,allErrors:T}=m,I=f(_,w,y);l(C,I),b||T||c(m,n.default.vErrors)}e.reportExtraError=s;function i(_,w){_.assign(n.default.errors,w),_.if((0,t._)`${n.default.vErrors} !== null`,()=>_.if(w,()=>_.assign((0,t._)`${n.default.vErrors}.length`,w),()=>_.assign(n.default.vErrors,null)))}e.resetErrorsCount=i;function a({gen:_,keyword:w,schemaValue:y,data:m,errsCount:C,it:b}){if(C===void 0)throw new Error("ajv implementation error");const T=_.name("err");_.forRange("i",C,n.default.errors,I=>{_.const(T,(0,t._)`${n.default.vErrors}[${I}]`),_.if((0,t._)`${T}.instancePath === undefined`,()=>_.assign((0,t._)`${T}.instancePath`,(0,t.strConcat)(n.default.instancePath,b.errorPath))),_.assign((0,t._)`${T}.schemaPath`,(0,t.str)`${b.errSchemaPath}/${w}`),b.opts.verbose&&(_.assign((0,t._)`${T}.schema`,y),_.assign((0,t._)`${T}.data`,m))})}e.extendErrors=a;function l(_,w){const y=_.const("err",w);_.if((0,t._)`${n.default.vErrors} === null`,()=>_.assign(n.default.vErrors,(0,t._)`[${y}]`),(0,t._)`${n.default.vErrors}.push(${y})`),_.code((0,t._)`${n.default.errors}++`)}function c(_,w){const{gen:y,validateName:m,schemaEnv:C}=_;C.$async?y.throw((0,t._)`new ${_.ValidationError}(${w})`):(y.assign((0,t._)`${m}.errors`,w),y.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 f(_,w,y){const{createErrors:m}=_.it;return m===!1?(0,t._)`{}`:p(_,w,y)}function p(_,w,y={}){const{gen:m,it:C}=_,b=[h(C,y),g(_,y)];return v(_,w,b),m.object(...b)}function h({errorPath:_},{instancePath:w}){const y=w?(0,t.str)`${_}${(0,r.getErrorPath)(w,r.Type.Str)}`:_;return[n.default.instancePath,(0,t.strConcat)(n.default.instancePath,y)]}function g({keyword:_,it:{errSchemaPath:w}},{schemaPath:y,parentSchema:m}){let C=m?w:(0,t.str)`${w}/${_}`;return y&&(C=(0,t.str)`${C}${(0,r.getErrorPath)(y,r.Type.Str)}`),[u.schemaPath,C]}function v(_,{params:w,message:y},m){const{keyword:C,data:b,schemaValue:T,it:I}=_,{opts:R,propertyName:S,topSchemaRef:j,schemaPath:O}=I;m.push([u.keyword,C],[u.params,typeof w=="function"?w(_):w||(0,t._)`{}`]),R.messages&&m.push([u.message,typeof y=="function"?y(_):y]),R.verbose&&m.push([u.schema,T],[u.parentSchema,(0,t._)`${j}${O}`],[n.default.data,b]),S&&m.push([u.propertyName,S])}})(ku)),ku}var n_;function Qx(){if(n_)return Zn;n_=1,Object.defineProperty(Zn,"__esModule",{value:!0}),Zn.boolOrEmptySchema=Zn.topBoolOrEmptySchema=void 0;const e=Wa(),t=Pe(),r=fn(),n={message:"boolean schema is false"};function o(a){const{gen:l,schema:c,validateName:u}=a;c===!1?i(a,!1):typeof c=="object"&&c.$async===!0?l.return(r.default.data):(l.assign((0,t._)`${u}.errors`,null),l.return(!0))}Zn.topBoolOrEmptySchema=o;function s(a,l){const{gen:c,schema:u}=a;u===!1?(c.var(l,!1),i(a)):c.var(l,!0)}Zn.boolOrEmptySchema=s;function i(a,l){const{gen:c,data:u}=a,f={gen:c,keyword:"false schema",data:u,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:a};(0,e.reportError)(f,n,void 0,l)}return Zn}var Mt={},Bn={},o_;function s_(){if(o_)return Bn;o_=1,Object.defineProperty(Bn,"__esModule",{value:!0}),Bn.getRules=Bn.isJSONType=void 0;const e=["string","number","integer","boolean","null","object","array"],t=new Set(e);function r(o){return typeof o=="string"&&t.has(o)}Bn.isJSONType=r;function n(){const o={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...o,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},o.number,o.string,o.array,o.object],post:{rules:[]},all:{},keywords:{}}}return Bn.getRules=n,Bn}var Gr={},a_;function i_(){if(a_)return Gr;a_=1,Object.defineProperty(Gr,"__esModule",{value:!0}),Gr.shouldUseRule=Gr.shouldUseGroup=Gr.schemaHasRulesForType=void 0;function e({schema:n,self:o},s){const i=o.RULES.types[s];return i&&i!==!0&&t(n,i)}Gr.schemaHasRulesForType=e;function t(n,o){return o.rules.some(s=>r(n,s))}Gr.shouldUseGroup=t;function r(n,o){var s;return n[o.keyword]!==void 0||((s=o.definition.implements)===null||s===void 0?void 0:s.some(i=>n[i]!==void 0))}return Gr.shouldUseRule=r,Gr}var l_;function Ka(){if(l_)return Mt;l_=1,Object.defineProperty(Mt,"__esModule",{value:!0}),Mt.reportTypeError=Mt.checkDataTypes=Mt.checkDataType=Mt.coerceAndCheckDataType=Mt.getJSONTypes=Mt.getSchemaTypes=Mt.DataType=void 0;const e=s_(),t=i_(),r=Wa(),n=Pe(),o=De();var s;(function(y){y[y.Correct=0]="Correct",y[y.Wrong=1]="Wrong"})(s||(Mt.DataType=s={}));function i(y){const m=a(y.type);if(m.includes("null")){if(y.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!m.length&&y.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');y.nullable===!0&&m.push("null")}return m}Mt.getSchemaTypes=i;function a(y){const m=Array.isArray(y)?y:y?[y]:[];if(m.every(e.isJSONType))return m;throw new Error("type must be JSONType or JSONType[]: "+m.join(","))}Mt.getJSONTypes=a;function l(y,m){const{gen:C,data:b,opts:T}=y,I=u(m,T.coerceTypes),R=m.length>0&&!(I.length===0&&m.length===1&&(0,t.schemaHasRulesForType)(y,m[0]));if(R){const S=g(m,b,T.strictNumbers,s.Wrong);C.if(S,()=>{I.length?f(y,m,I):_(y)})}return R}Mt.coerceAndCheckDataType=l;const c=new Set(["string","number","integer","boolean","null"]);function u(y,m){return m?y.filter(C=>c.has(C)||m==="array"&&C==="array"):[]}function f(y,m,C){const{gen:b,data:T,opts:I}=y,R=b.let("dataType",(0,n._)`typeof ${T}`),S=b.let("coerced",(0,n._)`undefined`);I.coerceTypes==="array"&&b.if((0,n._)`${R} == 'object' && Array.isArray(${T}) && ${T}.length == 1`,()=>b.assign(T,(0,n._)`${T}[0]`).assign(R,(0,n._)`typeof ${T}`).if(g(m,T,I.strictNumbers),()=>b.assign(S,T))),b.if((0,n._)`${S} !== undefined`);for(const O of C)(c.has(O)||O==="array"&&I.coerceTypes==="array")&&j(O);b.else(),_(y),b.endIf(),b.if((0,n._)`${S} !== undefined`,()=>{b.assign(T,S),p(y,S)});function j(O){switch(O){case"string":b.elseIf((0,n._)`${R} == "number" || ${R} == "boolean"`).assign(S,(0,n._)`"" + ${T}`).elseIf((0,n._)`${T} === null`).assign(S,(0,n._)`""`);return;case"number":b.elseIf((0,n._)`${R} == "boolean" || ${T} === null
82
- || (${R} == "string" && ${T} && ${T} == +${T})`).assign(S,(0,n._)`+${T}`);return;case"integer":b.elseIf((0,n._)`${R} === "boolean" || ${T} === null
83
- || (${R} === "string" && ${T} && ${T} == +${T} && !(${T} % 1))`).assign(S,(0,n._)`+${T}`);return;case"boolean":b.elseIf((0,n._)`${T} === "false" || ${T} === 0 || ${T} === null`).assign(S,!1).elseIf((0,n._)`${T} === "true" || ${T} === 1`).assign(S,!0);return;case"null":b.elseIf((0,n._)`${T} === "" || ${T} === 0 || ${T} === false`),b.assign(S,null);return;case"array":b.elseIf((0,n._)`${R} === "string" || ${R} === "number"
84
- || ${R} === "boolean" || ${T} === null`).assign(S,(0,n._)`[${T}]`)}}}function p({gen:y,parentData:m,parentDataProperty:C},b){y.if((0,n._)`${m} !== undefined`,()=>y.assign((0,n._)`${m}[${C}]`,b))}function h(y,m,C,b=s.Correct){const T=b===s.Correct?n.operators.EQ:n.operators.NEQ;let I;switch(y){case"null":return(0,n._)`${m} ${T} null`;case"array":I=(0,n._)`Array.isArray(${m})`;break;case"object":I=(0,n._)`${m} && typeof ${m} == "object" && !Array.isArray(${m})`;break;case"integer":I=R((0,n._)`!(${m} % 1) && !isNaN(${m})`);break;case"number":I=R();break;default:return(0,n._)`typeof ${m} ${T} ${y}`}return b===s.Correct?I:(0,n.not)(I);function R(S=n.nil){return(0,n.and)((0,n._)`typeof ${m} == "number"`,S,C?(0,n._)`isFinite(${m})`:n.nil)}}Mt.checkDataType=h;function g(y,m,C,b){if(y.length===1)return h(y[0],m,C,b);let T;const I=(0,o.toHash)(y);if(I.array&&I.object){const R=(0,n._)`typeof ${m} != "object"`;T=I.null?R:(0,n._)`!${m} || ${R}`,delete I.null,delete I.array,delete I.object}else T=n.nil;I.number&&delete I.integer;for(const R in I)T=(0,n.and)(T,h(R,m,C,b));return T}Mt.checkDataTypes=g;const v={message:({schema:y})=>`must be ${y}`,params:({schema:y,schemaValue:m})=>typeof y=="string"?(0,n._)`{type: ${y}}`:(0,n._)`{type: ${m}}`};function _(y){const m=w(y);(0,r.reportError)(m,v)}Mt.reportTypeError=_;function w(y){const{gen:m,data:C,schema:b}=y,T=(0,o.schemaRefOrVal)(y,b,"type");return{gen:m,keyword:"type",data:C,schema:b.type,schemaCode:T,schemaValue:T,parentSchema:b,params:{},it:y}}return Mt}var Ts={},c_;function Xx(){if(c_)return Ts;c_=1,Object.defineProperty(Ts,"__esModule",{value:!0}),Ts.assignDefaults=void 0;const e=Pe(),t=De();function r(o,s){const{properties:i,items:a}=o.schema;if(s==="object"&&i)for(const l in i)n(o,l,i[l].default);else s==="array"&&Array.isArray(a)&&a.forEach((l,c)=>n(o,c,l.default))}Ts.assignDefaults=r;function n(o,s,i){const{gen:a,compositeRule:l,data:c,opts:u}=o;if(i===void 0)return;const f=(0,e._)`${c}${(0,e.getProperty)(s)}`;if(l){(0,t.checkStrictMode)(o,`default is ignored for: ${f}`);return}let p=(0,e._)`${f} === undefined`;u.useDefaults==="empty"&&(p=(0,e._)`${p} || ${f} === null || ${f} === ""`),a.if(p,(0,e._)`${f} = ${(0,e.stringify)(i)}`)}return Ts}var Cr={},He={},u_;function Sr(){if(u_)return He;u_=1,Object.defineProperty(He,"__esModule",{value:!0}),He.validateUnion=He.validateArray=He.usePattern=He.callValidateCode=He.schemaProperties=He.allSchemaProperties=He.noPropertyInData=He.propertyInData=He.isOwnProperty=He.hasPropFunc=He.reportMissingProp=He.checkMissingProp=He.checkReportMissingProp=void 0;const e=Pe(),t=De(),r=fn(),n=De();function o(y,m){const{gen:C,data:b,it:T}=y;C.if(u(C,b,m,T.opts.ownProperties),()=>{y.setParams({missingProperty:(0,e._)`${m}`},!0),y.error()})}He.checkReportMissingProp=o;function s({gen:y,data:m,it:{opts:C}},b,T){return(0,e.or)(...b.map(I=>(0,e.and)(u(y,m,I,C.ownProperties),(0,e._)`${T} = ${I}`)))}He.checkMissingProp=s;function i(y,m){y.setParams({missingProperty:m},!0),y.error()}He.reportMissingProp=i;function a(y){return y.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,e._)`Object.prototype.hasOwnProperty`})}He.hasPropFunc=a;function l(y,m,C){return(0,e._)`${a(y)}.call(${m}, ${C})`}He.isOwnProperty=l;function c(y,m,C,b){const T=(0,e._)`${m}${(0,e.getProperty)(C)} !== undefined`;return b?(0,e._)`${T} && ${l(y,m,C)}`:T}He.propertyInData=c;function u(y,m,C,b){const T=(0,e._)`${m}${(0,e.getProperty)(C)} === undefined`;return b?(0,e.or)(T,(0,e.not)(l(y,m,C))):T}He.noPropertyInData=u;function f(y){return y?Object.keys(y).filter(m=>m!=="__proto__"):[]}He.allSchemaProperties=f;function p(y,m){return f(m).filter(C=>!(0,t.alwaysValidSchema)(y,m[C]))}He.schemaProperties=p;function h({schemaCode:y,data:m,it:{gen:C,topSchemaRef:b,schemaPath:T,errorPath:I},it:R},S,j,O){const L=O?(0,e._)`${y}, ${m}, ${b}${T}`:m,z=[[r.default.instancePath,(0,e.strConcat)(r.default.instancePath,I)],[r.default.parentData,R.parentData],[r.default.parentDataProperty,R.parentDataProperty],[r.default.rootData,r.default.rootData]];R.opts.dynamicRef&&z.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);const B=(0,e._)`${L}, ${C.object(...z)}`;return j!==e.nil?(0,e._)`${S}.call(${j}, ${B})`:(0,e._)`${S}(${B})`}He.callValidateCode=h;const g=(0,e._)`new RegExp`;function v({gen:y,it:{opts:m}},C){const b=m.unicodeRegExp?"u":"",{regExp:T}=m.code,I=T(C,b);return y.scopeValue("pattern",{key:I.toString(),ref:I,code:(0,e._)`${T.code==="new RegExp"?g:(0,n.useFunc)(y,T)}(${C}, ${b})`})}He.usePattern=v;function _(y){const{gen:m,data:C,keyword:b,it:T}=y,I=m.name("valid");if(T.allErrors){const S=m.let("valid",!0);return R(()=>m.assign(S,!1)),S}return m.var(I,!0),R(()=>m.break()),I;function R(S){const j=m.const("len",(0,e._)`${C}.length`);m.forRange("i",0,j,O=>{y.subschema({keyword:b,dataProp:O,dataPropType:t.Type.Num},I),m.if((0,e.not)(I),S)})}}He.validateArray=_;function w(y){const{gen:m,schema:C,keyword:b,it:T}=y;if(!Array.isArray(C))throw new Error("ajv implementation error");if(C.some(j=>(0,t.alwaysValidSchema)(T,j))&&!T.opts.unevaluated)return;const R=m.let("valid",!1),S=m.name("_valid");m.block(()=>C.forEach((j,O)=>{const L=y.subschema({keyword:b,schemaProp:O,compositeRule:!0},S);m.assign(R,(0,e._)`${R} || ${S}`),y.mergeValidEvaluated(L,S)||m.if((0,e.not)(R))})),y.result(R,()=>y.reset(),()=>y.error(!0))}return He.validateUnion=w,He}var d_;function e7(){if(d_)return Cr;d_=1,Object.defineProperty(Cr,"__esModule",{value:!0}),Cr.validateKeywordUsage=Cr.validSchemaType=Cr.funcKeywordCode=Cr.macroKeywordCode=void 0;const e=Pe(),t=fn(),r=Sr(),n=Wa();function o(p,h){const{gen:g,keyword:v,schema:_,parentSchema:w,it:y}=p,m=h.macro.call(y.self,_,w,y),C=c(g,v,m);y.opts.validateSchema!==!1&&y.self.validateSchema(m,!0);const b=g.name("valid");p.subschema({schema:m,schemaPath:e.nil,errSchemaPath:`${y.errSchemaPath}/${v}`,topSchemaRef:C,compositeRule:!0},b),p.pass(b,()=>p.error(!0))}Cr.macroKeywordCode=o;function s(p,h){var g;const{gen:v,keyword:_,schema:w,parentSchema:y,$data:m,it:C}=p;l(C,h);const b=!m&&h.compile?h.compile.call(C.self,w,y,C):h.validate,T=c(v,_,b),I=v.let("valid");p.block$data(I,R),p.ok((g=h.valid)!==null&&g!==void 0?g:I);function R(){if(h.errors===!1)O(),h.modifying&&i(p),L(()=>p.error());else{const z=h.async?S():j();h.modifying&&i(p),L(()=>a(p,z))}}function S(){const z=v.let("ruleErrs",null);return v.try(()=>O((0,e._)`await `),B=>v.assign(I,!1).if((0,e._)`${B} instanceof ${C.ValidationError}`,()=>v.assign(z,(0,e._)`${B}.errors`),()=>v.throw(B))),z}function j(){const z=(0,e._)`${T}.errors`;return v.assign(z,null),O(e.nil),z}function O(z=h.async?(0,e._)`await `:e.nil){const B=C.opts.passContext?t.default.this:t.default.self,X=!("compile"in h&&!m||h.schema===!1);v.assign(I,(0,e._)`${z}${(0,r.callValidateCode)(p,T,B,X)}`,h.modifying)}function L(z){var B;v.if((0,e.not)((B=h.valid)!==null&&B!==void 0?B:I),z)}}Cr.funcKeywordCode=s;function i(p){const{gen:h,data:g,it:v}=p;h.if(v.parentData,()=>h.assign(g,(0,e._)`${v.parentData}[${v.parentDataProperty}]`))}function a(p,h){const{gen:g}=p;g.if((0,e._)`Array.isArray(${h})`,()=>{g.assign(t.default.vErrors,(0,e._)`${t.default.vErrors} === null ? ${h} : ${t.default.vErrors}.concat(${h})`).assign(t.default.errors,(0,e._)`${t.default.vErrors}.length`),(0,n.extendErrors)(p)},()=>p.error())}function l({schemaEnv:p},h){if(h.async&&!p.$async)throw new Error("async keyword in sync schema")}function c(p,h,g){if(g===void 0)throw new Error(`keyword "${h}" failed to compile`);return p.scopeValue("keyword",typeof g=="function"?{ref:g}:{ref:g,code:(0,e.stringify)(g)})}function u(p,h,g=!1){return!h.length||h.some(v=>v==="array"?Array.isArray(p):v==="object"?p&&typeof p=="object"&&!Array.isArray(p):typeof p==v||g&&typeof p>"u")}Cr.validSchemaType=u;function f({schema:p,opts:h,self:g,errSchemaPath:v},_,w){if(Array.isArray(_.keyword)?!_.keyword.includes(w):_.keyword!==w)throw new Error("ajv implementation error");const y=_.dependencies;if(y?.some(m=>!Object.prototype.hasOwnProperty.call(p,m)))throw new Error(`parent schema must have dependencies of ${w}: ${y.join(",")}`);if(_.validateSchema&&!_.validateSchema(p[w])){const C=`keyword "${w}" value is invalid at path "${v}": `+g.errorsText(_.validateSchema.errors);if(h.validateSchema==="log")g.logger.error(C);else throw new Error(C)}}return Cr.validateKeywordUsage=f,Cr}var Wr={},p_;function t7(){if(p_)return Wr;p_=1,Object.defineProperty(Wr,"__esModule",{value:!0}),Wr.extendSubschemaMode=Wr.extendSubschemaData=Wr.getSubschema=void 0;const e=Pe(),t=De();function r(s,{keyword:i,schemaProp:a,schema:l,schemaPath:c,errSchemaPath:u,topSchemaRef:f}){if(i!==void 0&&l!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(i!==void 0){const p=s.schema[i];return a===void 0?{schema:p,schemaPath:(0,e._)`${s.schemaPath}${(0,e.getProperty)(i)}`,errSchemaPath:`${s.errSchemaPath}/${i}`}:{schema:p[a],schemaPath:(0,e._)`${s.schemaPath}${(0,e.getProperty)(i)}${(0,e.getProperty)(a)}`,errSchemaPath:`${s.errSchemaPath}/${i}/${(0,t.escapeFragment)(a)}`}}if(l!==void 0){if(c===void 0||u===void 0||f===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:l,schemaPath:c,topSchemaRef:f,errSchemaPath:u}}throw new Error('either "keyword" or "schema" must be passed')}Wr.getSubschema=r;function n(s,i,{dataProp:a,dataPropType:l,data:c,dataTypes:u,propertyName:f}){if(c!==void 0&&a!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:p}=i;if(a!==void 0){const{errorPath:g,dataPathArr:v,opts:_}=i,w=p.let("data",(0,e._)`${i.data}${(0,e.getProperty)(a)}`,!0);h(w),s.errorPath=(0,e.str)`${g}${(0,t.getErrorPath)(a,l,_.jsPropertySyntax)}`,s.parentDataProperty=(0,e._)`${a}`,s.dataPathArr=[...v,s.parentDataProperty]}if(c!==void 0){const g=c instanceof e.Name?c:p.let("data",c,!0);h(g),f!==void 0&&(s.propertyName=f)}u&&(s.dataTypes=u);function h(g){s.data=g,s.dataLevel=i.dataLevel+1,s.dataTypes=[],i.definedProperties=new Set,s.parentData=i.data,s.dataNames=[...i.dataNames,g]}}Wr.extendSubschemaData=n;function o(s,{jtdDiscriminator:i,jtdMetadata:a,compositeRule:l,createErrors:c,allErrors:u}){l!==void 0&&(s.compositeRule=l),c!==void 0&&(s.createErrors=c),u!==void 0&&(s.allErrors=u),s.jtdDiscriminator=i,s.jtdMetadata=a}return Wr.extendSubschemaMode=o,Wr}var Zt={},Iu,f_;function h_(){return f_||(f_=1,Iu=function e(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(t)){if(n=t.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!e(t[o],r[o]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(s=Object.keys(t),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var i=s[o];if(!e(t[i],r[i]))return!1}return!0}return t!==t&&r!==r}),Iu}var xu={exports:{}},m_;function r7(){if(m_)return xu.exports;m_=1;var e=xu.exports=function(n,o,s){typeof o=="function"&&(s=o,o={}),s=o.cb||s;var i=typeof s=="function"?s:s.pre||function(){},a=s.post||function(){};t(o,i,a,n,"",n)};e.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},e.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},e.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},e.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 t(n,o,s,i,a,l,c,u,f,p){if(i&&typeof i=="object"&&!Array.isArray(i)){o(i,a,l,c,u,f,p);for(var h in i){var g=i[h];if(Array.isArray(g)){if(h in e.arrayKeywords)for(var v=0;v<g.length;v++)t(n,o,s,g[v],a+"/"+h+"/"+v,l,a,h,i,v)}else if(h in e.propsKeywords){if(g&&typeof g=="object")for(var _ in g)t(n,o,s,g[_],a+"/"+h+"/"+r(_),l,a,h,i,_)}else(h in e.keywords||n.allKeys&&!(h in e.skipKeywords))&&t(n,o,s,g,a+"/"+h,l,a,h,i)}s(i,a,l,c,u,f,p)}}function r(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}return xu.exports}var g_;function Ya(){if(g_)return Zt;g_=1,Object.defineProperty(Zt,"__esModule",{value:!0}),Zt.getSchemaRefs=Zt.resolveUrl=Zt.normalizeId=Zt._getFullPath=Zt.getFullPath=Zt.inlineRef=void 0;const e=De(),t=h_(),r=r7(),n=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function o(v,_=!0){return typeof v=="boolean"?!0:_===!0?!i(v):_?a(v)<=_:!1}Zt.inlineRef=o;const s=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function i(v){for(const _ in v){if(s.has(_))return!0;const w=v[_];if(Array.isArray(w)&&w.some(i)||typeof w=="object"&&i(w))return!0}return!1}function a(v){let _=0;for(const w in v){if(w==="$ref")return 1/0;if(_++,!n.has(w)&&(typeof v[w]=="object"&&(0,e.eachItem)(v[w],y=>_+=a(y)),_===1/0))return 1/0}return _}function l(v,_="",w){w!==!1&&(_=f(_));const y=v.parse(_);return c(v,y)}Zt.getFullPath=l;function c(v,_){return v.serialize(_).split("#")[0]+"#"}Zt._getFullPath=c;const u=/#\/?$/;function f(v){return v?v.replace(u,""):""}Zt.normalizeId=f;function p(v,_,w){return w=f(w),v.resolve(_,w)}Zt.resolveUrl=p;const h=/^[a-z_][-a-z0-9._]*$/i;function g(v,_){if(typeof v=="boolean")return{};const{schemaId:w,uriResolver:y}=this.opts,m=f(v[w]||_),C={"":m},b=l(y,m,!1),T={},I=new Set;return r(v,{allKeys:!0},(j,O,L,z)=>{if(z===void 0)return;const B=b+O;let X=C[z];typeof j[w]=="string"&&(X=ee.call(this,j[w])),Q.call(this,j.$anchor),Q.call(this,j.$dynamicAnchor),C[O]=X;function ee(Z){const ne=this.opts.uriResolver.resolve;if(Z=f(X?ne(X,Z):Z),I.has(Z))throw S(Z);I.add(Z);let D=this.refs[Z];return typeof D=="string"&&(D=this.refs[D]),typeof D=="object"?R(j,D.schema,Z):Z!==f(B)&&(Z[0]==="#"?(R(j,T[Z],Z),T[Z]=j):this.refs[Z]=B),Z}function Q(Z){if(typeof Z=="string"){if(!h.test(Z))throw new Error(`invalid anchor "${Z}"`);ee.call(this,`#${Z}`)}}}),T;function R(j,O,L){if(O!==void 0&&!t(j,O))throw S(L)}function S(j){return new Error(`reference "${j}" resolves to more than one schema`)}}return Zt.getSchemaRefs=g,Zt}var __;function Qa(){if(__)return Jr;__=1,Object.defineProperty(Jr,"__esModule",{value:!0}),Jr.getData=Jr.KeywordCxt=Jr.validateFunctionCode=void 0;const e=Qx(),t=Ka(),r=i_(),n=Ka(),o=Xx(),s=e7(),i=t7(),a=Pe(),l=fn(),c=Ya(),u=De(),f=Wa();function p(A){if(b(A)&&(I(A),C(A))){_(A);return}h(A,()=>(0,e.topBoolOrEmptySchema)(A))}Jr.validateFunctionCode=p;function h({gen:A,validateName:V,schema:J,schemaEnv:Y,opts:ue},Ce){ue.code.es5?A.func(V,(0,a._)`${l.default.data}, ${l.default.valCxt}`,Y.$async,()=>{A.code((0,a._)`"use strict"; ${y(J,ue)}`),v(A,ue),A.code(Ce)}):A.func(V,(0,a._)`${l.default.data}, ${g(ue)}`,Y.$async,()=>A.code(y(J,ue)).code(Ce))}function g(A){return(0,a._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${A.dynamicRef?(0,a._)`, ${l.default.dynamicAnchors}={}`:a.nil}}={}`}function v(A,V){A.if(l.default.valCxt,()=>{A.var(l.default.instancePath,(0,a._)`${l.default.valCxt}.${l.default.instancePath}`),A.var(l.default.parentData,(0,a._)`${l.default.valCxt}.${l.default.parentData}`),A.var(l.default.parentDataProperty,(0,a._)`${l.default.valCxt}.${l.default.parentDataProperty}`),A.var(l.default.rootData,(0,a._)`${l.default.valCxt}.${l.default.rootData}`),V.dynamicRef&&A.var(l.default.dynamicAnchors,(0,a._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{A.var(l.default.instancePath,(0,a._)`""`),A.var(l.default.parentData,(0,a._)`undefined`),A.var(l.default.parentDataProperty,(0,a._)`undefined`),A.var(l.default.rootData,l.default.data),V.dynamicRef&&A.var(l.default.dynamicAnchors,(0,a._)`{}`)})}function _(A){const{schema:V,opts:J,gen:Y}=A;h(A,()=>{J.$comment&&V.$comment&&z(A),j(A),Y.let(l.default.vErrors,null),Y.let(l.default.errors,0),J.unevaluated&&w(A),R(A),B(A)})}function w(A){const{gen:V,validateName:J}=A;A.evaluated=V.const("evaluated",(0,a._)`${J}.evaluated`),V.if((0,a._)`${A.evaluated}.dynamicProps`,()=>V.assign((0,a._)`${A.evaluated}.props`,(0,a._)`undefined`)),V.if((0,a._)`${A.evaluated}.dynamicItems`,()=>V.assign((0,a._)`${A.evaluated}.items`,(0,a._)`undefined`))}function y(A,V){const J=typeof A=="object"&&A[V.schemaId];return J&&(V.code.source||V.code.process)?(0,a._)`/*# sourceURL=${J} */`:a.nil}function m(A,V){if(b(A)&&(I(A),C(A))){T(A,V);return}(0,e.boolOrEmptySchema)(A,V)}function C({schema:A,self:V}){if(typeof A=="boolean")return!A;for(const J in A)if(V.RULES.all[J])return!0;return!1}function b(A){return typeof A.schema!="boolean"}function T(A,V){const{schema:J,gen:Y,opts:ue}=A;ue.$comment&&J.$comment&&z(A),O(A),L(A);const Ce=Y.const("_errs",l.default.errors);R(A,Ce),Y.var(V,(0,a._)`${Ce} === ${l.default.errors}`)}function I(A){(0,u.checkUnknownRules)(A),S(A)}function R(A,V){if(A.opts.jtd)return ee(A,[],!1,V);const J=(0,t.getSchemaTypes)(A.schema),Y=(0,t.coerceAndCheckDataType)(A,J);ee(A,J,!Y,V)}function S(A){const{schema:V,errSchemaPath:J,opts:Y,self:ue}=A;V.$ref&&Y.ignoreKeywordsWithRef&&(0,u.schemaHasRulesButRef)(V,ue.RULES)&&ue.logger.warn(`$ref: keywords ignored in schema at path "${J}"`)}function j(A){const{schema:V,opts:J}=A;V.default!==void 0&&J.useDefaults&&J.strictSchema&&(0,u.checkStrictMode)(A,"default is ignored in the schema root")}function O(A){const V=A.schema[A.opts.schemaId];V&&(A.baseId=(0,c.resolveUrl)(A.opts.uriResolver,A.baseId,V))}function L(A){if(A.schema.$async&&!A.schemaEnv.$async)throw new Error("async schema in sync schema")}function z({gen:A,schemaEnv:V,schema:J,errSchemaPath:Y,opts:ue}){const Ce=J.$comment;if(ue.$comment===!0)A.code((0,a._)`${l.default.self}.logger.log(${Ce})`);else if(typeof ue.$comment=="function"){const Ze=(0,a.str)`${Y}/$comment`,ot=A.scopeValue("root",{ref:V.root});A.code((0,a._)`${l.default.self}.opts.$comment(${Ce}, ${Ze}, ${ot}.schema)`)}}function B(A){const{gen:V,schemaEnv:J,validateName:Y,ValidationError:ue,opts:Ce}=A;J.$async?V.if((0,a._)`${l.default.errors} === 0`,()=>V.return(l.default.data),()=>V.throw((0,a._)`new ${ue}(${l.default.vErrors})`)):(V.assign((0,a._)`${Y}.errors`,l.default.vErrors),Ce.unevaluated&&X(A),V.return((0,a._)`${l.default.errors} === 0`))}function X({gen:A,evaluated:V,props:J,items:Y}){J instanceof a.Name&&A.assign((0,a._)`${V}.props`,J),Y instanceof a.Name&&A.assign((0,a._)`${V}.items`,Y)}function ee(A,V,J,Y){const{gen:ue,schema:Ce,data:Ze,allErrors:ot,opts:pt,self:Qe}=A,{RULES:et}=Qe;if(Ce.$ref&&(pt.ignoreKeywordsWithRef||!(0,u.schemaHasRulesButRef)(Ce,et))){ue.block(()=>re(A,"$ref",et.all.$ref.definition));return}pt.jtd||Z(A,V),ue.block(()=>{for(const mt of et.rules)At(mt);At(et.post)});function At(mt){(0,r.shouldUseGroup)(Ce,mt)&&(mt.type?(ue.if((0,n.checkDataType)(mt.type,Ze,pt.strictNumbers)),Q(A,mt),V.length===1&&V[0]===mt.type&&J&&(ue.else(),(0,n.reportTypeError)(A)),ue.endIf()):Q(A,mt),ot||ue.if((0,a._)`${l.default.errors} === ${Y||0}`))}}function Q(A,V){const{gen:J,schema:Y,opts:{useDefaults:ue}}=A;ue&&(0,o.assignDefaults)(A,V.type),J.block(()=>{for(const Ce of V.rules)(0,r.shouldUseRule)(Y,Ce)&&re(A,Ce.keyword,Ce.definition,V.type)})}function Z(A,V){A.schemaEnv.meta||!A.opts.strictTypes||(ne(A,V),A.opts.allowUnionTypes||D(A,V),E(A,A.dataTypes))}function ne(A,V){if(V.length){if(!A.dataTypes.length){A.dataTypes=V;return}V.forEach(J=>{F(A.dataTypes,J)||M(A,`type "${J}" not allowed by context "${A.dataTypes.join(",")}"`)}),x(A,V)}}function D(A,V){V.length>1&&!(V.length===2&&V.includes("null"))&&M(A,"use allowUnionTypes to allow union type keyword")}function E(A,V){const J=A.self.RULES.all;for(const Y in J){const ue=J[Y];if(typeof ue=="object"&&(0,r.shouldUseRule)(A.schema,ue)){const{type:Ce}=ue.definition;Ce.length&&!Ce.some(Ze=>U(V,Ze))&&M(A,`missing type "${Ce.join(",")}" for keyword "${Y}"`)}}}function U(A,V){return A.includes(V)||V==="number"&&A.includes("integer")}function F(A,V){return A.includes(V)||V==="integer"&&A.includes("number")}function x(A,V){const J=[];for(const Y of A.dataTypes)F(V,Y)?J.push(Y):V.includes("integer")&&Y==="number"&&J.push("integer");A.dataTypes=J}function M(A,V){const J=A.schemaEnv.baseId+A.errSchemaPath;V+=` at "${J}" (strictTypes)`,(0,u.checkStrictMode)(A,V,A.opts.strictTypes)}class H{constructor(V,J,Y){if((0,s.validateKeywordUsage)(V,J,Y),this.gen=V.gen,this.allErrors=V.allErrors,this.keyword=Y,this.data=V.data,this.schema=V.schema[Y],this.$data=J.$data&&V.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,u.schemaRefOrVal)(V,this.schema,Y,this.$data),this.schemaType=J.schemaType,this.parentSchema=V.schema,this.params={},this.it=V,this.def=J,this.$data)this.schemaCode=V.gen.const("vSchema",G(this.$data,V));else if(this.schemaCode=this.schemaValue,!(0,s.validSchemaType)(this.schema,J.schemaType,J.allowUndefined))throw new Error(`${Y} value must be ${JSON.stringify(J.schemaType)}`);("code"in J?J.trackErrors:J.errors!==!1)&&(this.errsCount=V.gen.const("_errs",l.default.errors))}result(V,J,Y){this.failResult((0,a.not)(V),J,Y)}failResult(V,J,Y){this.gen.if(V),Y?Y():this.error(),J?(this.gen.else(),J(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(V,J){this.failResult((0,a.not)(V),void 0,J)}fail(V){if(V===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(V),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(V){if(!this.$data)return this.fail(V);const{schemaCode:J}=this;this.fail((0,a._)`${J} !== undefined && (${(0,a.or)(this.invalid$data(),V)})`)}error(V,J,Y){if(J){this.setParams(J),this._error(V,Y),this.setParams({});return}this._error(V,Y)}_error(V,J){(V?f.reportExtraError:f.reportError)(this,this.def.error,J)}$dataError(){(0,f.reportError)(this,this.def.$dataError||f.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,f.resetErrorsCount)(this.gen,this.errsCount)}ok(V){this.allErrors||this.gen.if(V)}setParams(V,J){J?Object.assign(this.params,V):this.params=V}block$data(V,J,Y=a.nil){this.gen.block(()=>{this.check$data(V,Y),J()})}check$data(V=a.nil,J=a.nil){if(!this.$data)return;const{gen:Y,schemaCode:ue,schemaType:Ce,def:Ze}=this;Y.if((0,a.or)((0,a._)`${ue} === undefined`,J)),V!==a.nil&&Y.assign(V,!0),(Ce.length||Ze.validateSchema)&&(Y.elseIf(this.invalid$data()),this.$dataError(),V!==a.nil&&Y.assign(V,!1)),Y.else()}invalid$data(){const{gen:V,schemaCode:J,schemaType:Y,def:ue,it:Ce}=this;return(0,a.or)(Ze(),ot());function Ze(){if(Y.length){if(!(J instanceof a.Name))throw new Error("ajv implementation error");const pt=Array.isArray(Y)?Y:[Y];return(0,a._)`${(0,n.checkDataTypes)(pt,J,Ce.opts.strictNumbers,n.DataType.Wrong)}`}return a.nil}function ot(){if(ue.validateSchema){const pt=V.scopeValue("validate$data",{ref:ue.validateSchema});return(0,a._)`!${pt}(${J})`}return a.nil}}subschema(V,J){const Y=(0,i.getSubschema)(this.it,V);(0,i.extendSubschemaData)(Y,this.it,V),(0,i.extendSubschemaMode)(Y,V);const ue={...this.it,...Y,items:void 0,props:void 0};return m(ue,J),ue}mergeEvaluated(V,J){const{it:Y,gen:ue}=this;Y.opts.unevaluated&&(Y.props!==!0&&V.props!==void 0&&(Y.props=u.mergeEvaluated.props(ue,V.props,Y.props,J)),Y.items!==!0&&V.items!==void 0&&(Y.items=u.mergeEvaluated.items(ue,V.items,Y.items,J)))}mergeValidEvaluated(V,J){const{it:Y,gen:ue}=this;if(Y.opts.unevaluated&&(Y.props!==!0||Y.items!==!0))return ue.if(J,()=>this.mergeEvaluated(V,a.Name)),!0}}Jr.KeywordCxt=H;function re(A,V,J,Y){const ue=new H(A,J,V);"code"in J?J.code(ue,Y):ue.$data&&J.validate?(0,s.funcKeywordCode)(ue,J):"macro"in J?(0,s.macroKeywordCode)(ue,J):(J.compile||J.validate)&&(0,s.funcKeywordCode)(ue,J)}const te=/^\/(?:[^~]|~0|~1)*$/,_e=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function G(A,{dataLevel:V,dataNames:J,dataPathArr:Y}){let ue,Ce;if(A==="")return l.default.rootData;if(A[0]==="/"){if(!te.test(A))throw new Error(`Invalid JSON-pointer: ${A}`);ue=A,Ce=l.default.rootData}else{const Qe=_e.exec(A);if(!Qe)throw new Error(`Invalid JSON-pointer: ${A}`);const et=+Qe[1];if(ue=Qe[2],ue==="#"){if(et>=V)throw new Error(pt("property/index",et));return Y[V-et]}if(et>V)throw new Error(pt("data",et));if(Ce=J[V-et],!ue)return Ce}let Ze=Ce;const ot=ue.split("/");for(const Qe of ot)Qe&&(Ce=(0,a._)`${Ce}${(0,a.getProperty)((0,u.unescapeJsonPointer)(Qe))}`,Ze=(0,a._)`${Ze} && ${Ce}`);return Ze;function pt(Qe,et){return`Cannot access ${Qe} ${et} levels up, current level is ${V}`}}return Jr.getData=G,Jr}var Xa={},y_;function Eu(){if(y_)return Xa;y_=1,Object.defineProperty(Xa,"__esModule",{value:!0});class e extends Error{constructor(r){super("validation failed"),this.errors=r,this.ajv=this.validation=!0}}return Xa.default=e,Xa}var ei={},v_;function ti(){if(v_)return ei;v_=1,Object.defineProperty(ei,"__esModule",{value:!0});const e=Ya();class t extends Error{constructor(n,o,s,i){super(i||`can't resolve reference ${s} from id ${o}`),this.missingRef=(0,e.resolveUrl)(n,o,s),this.missingSchema=(0,e.normalizeId)((0,e.getFullPath)(n,this.missingRef))}}return ei.default=t,ei}var or={},w_;function $u(){if(w_)return or;w_=1,Object.defineProperty(or,"__esModule",{value:!0}),or.resolveSchema=or.getCompilingSchema=or.resolveRef=or.compileSchema=or.SchemaEnv=void 0;const e=Pe(),t=Eu(),r=fn(),n=Ya(),o=De(),s=Qa();class i{constructor(w){var y;this.refs={},this.dynamicAnchors={};let m;typeof w.schema=="object"&&(m=w.schema),this.schema=w.schema,this.schemaId=w.schemaId,this.root=w.root||this,this.baseId=(y=w.baseId)!==null&&y!==void 0?y:(0,n.normalizeId)(m?.[w.schemaId||"$id"]),this.schemaPath=w.schemaPath,this.localRefs=w.localRefs,this.meta=w.meta,this.$async=m?.$async,this.refs={}}}or.SchemaEnv=i;function a(_){const w=u.call(this,_);if(w)return w;const y=(0,n.getFullPath)(this.opts.uriResolver,_.root.baseId),{es5:m,lines:C}=this.opts.code,{ownProperties:b}=this.opts,T=new e.CodeGen(this.scope,{es5:m,lines:C,ownProperties:b});let I;_.$async&&(I=T.scopeValue("Error",{ref:t.default,code:(0,e._)`require("ajv/dist/runtime/validation_error").default`}));const R=T.scopeName("validate");_.validateName=R;const S={gen:T,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[e.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:T.scopeValue("schema",this.opts.code.source===!0?{ref:_.schema,code:(0,e.stringify)(_.schema)}:{ref:_.schema}),validateName:R,ValidationError:I,schema:_.schema,schemaEnv:_,rootId:y,baseId:_.baseId||y,schemaPath:e.nil,errSchemaPath:_.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,e._)`""`,opts:this.opts,self:this};let j;try{this._compilations.add(_),(0,s.validateFunctionCode)(S),T.optimize(this.opts.code.optimize);const O=T.toString();j=`${T.scopeRefs(r.default.scope)}return ${O}`,this.opts.code.process&&(j=this.opts.code.process(j,_));const z=new Function(`${r.default.self}`,`${r.default.scope}`,j)(this,this.scope.get());if(this.scope.value(R,{ref:z}),z.errors=null,z.schema=_.schema,z.schemaEnv=_,_.$async&&(z.$async=!0),this.opts.code.source===!0&&(z.source={validateName:R,validateCode:O,scopeValues:T._values}),this.opts.unevaluated){const{props:B,items:X}=S;z.evaluated={props:B instanceof e.Name?void 0:B,items:X instanceof e.Name?void 0:X,dynamicProps:B instanceof e.Name,dynamicItems:X instanceof e.Name},z.source&&(z.source.evaluated=(0,e.stringify)(z.evaluated))}return _.validate=z,_}catch(O){throw delete _.validate,delete _.validateName,j&&this.logger.error("Error compiling schema, function code:",j),O}finally{this._compilations.delete(_)}}or.compileSchema=a;function l(_,w,y){var m;y=(0,n.resolveUrl)(this.opts.uriResolver,w,y);const C=_.refs[y];if(C)return C;let b=p.call(this,_,y);if(b===void 0){const T=(m=_.localRefs)===null||m===void 0?void 0:m[y],{schemaId:I}=this.opts;T&&(b=new i({schema:T,schemaId:I,root:_,baseId:w}))}if(b!==void 0)return _.refs[y]=c.call(this,b)}or.resolveRef=l;function c(_){return(0,n.inlineRef)(_.schema,this.opts.inlineRefs)?_.schema:_.validate?_:a.call(this,_)}function u(_){for(const w of this._compilations)if(f(w,_))return w}or.getCompilingSchema=u;function f(_,w){return _.schema===w.schema&&_.root===w.root&&_.baseId===w.baseId}function p(_,w){let y;for(;typeof(y=this.refs[w])=="string";)w=y;return y||this.schemas[w]||h.call(this,_,w)}function h(_,w){const y=this.opts.uriResolver.parse(w),m=(0,n._getFullPath)(this.opts.uriResolver,y);let C=(0,n.getFullPath)(this.opts.uriResolver,_.baseId,void 0);if(Object.keys(_.schema).length>0&&m===C)return v.call(this,y,_);const b=(0,n.normalizeId)(m),T=this.refs[b]||this.schemas[b];if(typeof T=="string"){const I=h.call(this,_,T);return typeof I?.schema!="object"?void 0:v.call(this,y,I)}if(typeof T?.schema=="object"){if(T.validate||a.call(this,T),b===(0,n.normalizeId)(w)){const{schema:I}=T,{schemaId:R}=this.opts,S=I[R];return S&&(C=(0,n.resolveUrl)(this.opts.uriResolver,C,S)),new i({schema:I,schemaId:R,root:_,baseId:C})}return v.call(this,y,T)}}or.resolveSchema=h;const g=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function v(_,{baseId:w,schema:y,root:m}){var C;if(((C=_.fragment)===null||C===void 0?void 0:C[0])!=="/")return;for(const I of _.fragment.slice(1).split("/")){if(typeof y=="boolean")return;const R=y[(0,o.unescapeFragment)(I)];if(R===void 0)return;y=R;const S=typeof y=="object"&&y[this.opts.schemaId];!g.has(I)&&S&&(w=(0,n.resolveUrl)(this.opts.uriResolver,w,S))}let b;if(typeof y!="boolean"&&y.$ref&&!(0,o.schemaHasRulesButRef)(y,this.RULES)){const I=(0,n.resolveUrl)(this.opts.uriResolver,w,y.$ref);b=h.call(this,m,I)}const{schemaId:T}=this.opts;if(b=b||new i({schema:y,schemaId:T,root:m,baseId:w}),b.schema!==b.root.schema)return b}return or}const n7={$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 ri={},Cs={exports:{}},Ru,b_;function k_(){if(b_)return Ru;b_=1;const e=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),t=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 r(p){let h="",g=0,v=0;for(v=0;v<p.length;v++)if(g=p[v].charCodeAt(0),g!==48){if(!(g>=48&&g<=57||g>=65&&g<=70||g>=97&&g<=102))return"";h+=p[v];break}for(v+=1;v<p.length;v++){if(g=p[v].charCodeAt(0),!(g>=48&&g<=57||g>=65&&g<=70||g>=97&&g<=102))return"";h+=p[v]}return h}const n=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function o(p){return p.length=0,!0}function s(p,h,g){if(p.length){const v=r(p);if(v!=="")h.push(v);else return g.error=!0,!1;p.length=0}return!0}function i(p){let h=0;const g={error:!1,address:"",zone:""},v=[],_=[];let w=!1,y=!1,m=s;for(let C=0;C<p.length;C++){const b=p[C];if(!(b==="["||b==="]"))if(b===":"){if(w===!0&&(y=!0),!m(_,v,g))break;if(++h>7){g.error=!0;break}C>0&&p[C-1]===":"&&(w=!0),v.push(":");continue}else if(b==="%"){if(!m(_,v,g))break;m=o}else{_.push(b);continue}}return _.length&&(m===o?g.zone=_.join(""):y?v.push(_.join("")):v.push(r(_))),g.address=v.join(""),g}function a(p){if(l(p,":")<2)return{host:p,isIPV6:!1};const h=i(p);if(h.error)return{host:p,isIPV6:!1};{let g=h.address,v=h.address;return h.zone&&(g+="%"+h.zone,v+="%25"+h.zone),{host:g,isIPV6:!0,escapedHost:v}}}function l(p,h){let g=0;for(let v=0;v<p.length;v++)p[v]===h&&g++;return g}function c(p){let h=p;const g=[];let v=-1,_=0;for(;_=h.length;){if(_===1){if(h===".")break;if(h==="/"){g.push("/");break}else{g.push(h);break}}else if(_===2){if(h[0]==="."){if(h[1]===".")break;if(h[1]==="/"){h=h.slice(2);continue}}else if(h[0]==="/"&&(h[1]==="."||h[1]==="/")){g.push("/");break}}else if(_===3&&h==="/.."){g.length!==0&&g.pop(),g.push("/");break}if(h[0]==="."){if(h[1]==="."){if(h[2]==="/"){h=h.slice(3);continue}}else if(h[1]==="/"){h=h.slice(2);continue}}else if(h[0]==="/"&&h[1]==="."){if(h[2]==="/"){h=h.slice(2);continue}else if(h[2]==="."&&h[3]==="/"){h=h.slice(3),g.length!==0&&g.pop();continue}}if((v=h.indexOf("/",1))===-1){g.push(h);break}else g.push(h.slice(0,v)),h=h.slice(v)}return g.join("")}function u(p,h){const g=h!==!0?escape:unescape;return p.scheme!==void 0&&(p.scheme=g(p.scheme)),p.userinfo!==void 0&&(p.userinfo=g(p.userinfo)),p.host!==void 0&&(p.host=g(p.host)),p.path!==void 0&&(p.path=g(p.path)),p.query!==void 0&&(p.query=g(p.query)),p.fragment!==void 0&&(p.fragment=g(p.fragment)),p}function f(p){const h=[];if(p.userinfo!==void 0&&(h.push(p.userinfo),h.push("@")),p.host!==void 0){let g=unescape(p.host);if(!t(g)){const v=a(g);v.isIPV6===!0?g=`[${v.escapedHost}]`:g=p.host}h.push(g)}return(typeof p.port=="number"||typeof p.port=="string")&&(h.push(":"),h.push(String(p.port))),h.length?h.join(""):void 0}return Ru={nonSimpleDomain:n,recomposeAuthority:f,normalizeComponentEncoding:u,removeDotSegments:c,isIPv4:t,isUUID:e,normalizeIPv6:a,stringArrayToHexStripped:r},Ru}var Pu,T_;function o7(){if(T_)return Pu;T_=1;const{isUUID:e}=k_(),t=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,r=["http","https","ws","wss","urn","urn:uuid"];function n(b){return r.indexOf(b)!==-1}function o(b){return b.secure===!0?!0:b.secure===!1?!1:b.scheme?b.scheme.length===3&&(b.scheme[0]==="w"||b.scheme[0]==="W")&&(b.scheme[1]==="s"||b.scheme[1]==="S")&&(b.scheme[2]==="s"||b.scheme[2]==="S"):!1}function s(b){return b.host||(b.error=b.error||"HTTP URIs must have a host."),b}function i(b){const T=String(b.scheme).toLowerCase()==="https";return(b.port===(T?443:80)||b.port==="")&&(b.port=void 0),b.path||(b.path="/"),b}function a(b){return b.secure=o(b),b.resourceName=(b.path||"/")+(b.query?"?"+b.query:""),b.path=void 0,b.query=void 0,b}function l(b){if((b.port===(o(b)?443:80)||b.port==="")&&(b.port=void 0),typeof b.secure=="boolean"&&(b.scheme=b.secure?"wss":"ws",b.secure=void 0),b.resourceName){const[T,I]=b.resourceName.split("?");b.path=T&&T!=="/"?T:void 0,b.query=I,b.resourceName=void 0}return b.fragment=void 0,b}function c(b,T){if(!b.path)return b.error="URN can not be parsed",b;const I=b.path.match(t);if(I){const R=T.scheme||b.scheme||"urn";b.nid=I[1].toLowerCase(),b.nss=I[2];const S=`${R}:${T.nid||b.nid}`,j=C(S);b.path=void 0,j&&(b=j.parse(b,T))}else b.error=b.error||"URN can not be parsed.";return b}function u(b,T){if(b.nid===void 0)throw new Error("URN without nid cannot be serialized");const I=T.scheme||b.scheme||"urn",R=b.nid.toLowerCase(),S=`${I}:${T.nid||R}`,j=C(S);j&&(b=j.serialize(b,T));const O=b,L=b.nss;return O.path=`${R||T.nid}:${L}`,T.skipEscape=!0,O}function f(b,T){const I=b;return I.uuid=I.nss,I.nss=void 0,!T.tolerant&&(!I.uuid||!e(I.uuid))&&(I.error=I.error||"UUID is not valid."),I}function p(b){const T=b;return T.nss=(b.uuid||"").toLowerCase(),T}const h={scheme:"http",domainHost:!0,parse:s,serialize:i},g={scheme:"https",domainHost:h.domainHost,parse:s,serialize:i},v={scheme:"ws",domainHost:!0,parse:a,serialize:l},_={scheme:"wss",domainHost:v.domainHost,parse:v.parse,serialize:v.serialize},m={http:h,https:g,ws:v,wss:_,urn:{scheme:"urn",parse:c,serialize:u,skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:f,serialize:p,skipNormalize:!0}};Object.setPrototypeOf(m,null);function C(b){return b&&(m[b]||m[b.toLowerCase()])||void 0}return Pu={wsIsSecure:o,SCHEMES:m,isValidSchemeName:n,getSchemeHandler:C},Pu}var C_;function s7(){if(C_)return Cs.exports;C_=1;const{normalizeIPv6:e,removeDotSegments:t,recomposeAuthority:r,normalizeComponentEncoding:n,isIPv4:o,nonSimpleDomain:s}=k_(),{SCHEMES:i,getSchemeHandler:a}=o7();function l(_,w){return typeof _=="string"?_=p(g(_,w),w):typeof _=="object"&&(_=g(p(_,w),w)),_}function c(_,w,y){const m=y?Object.assign({scheme:"null"},y):{scheme:"null"},C=u(g(_,m),g(w,m),m,!0);return m.skipEscape=!0,p(C,m)}function u(_,w,y,m){const C={};return m||(_=g(p(_,y),y),w=g(p(w,y),y)),y=y||{},!y.tolerant&&w.scheme?(C.scheme=w.scheme,C.userinfo=w.userinfo,C.host=w.host,C.port=w.port,C.path=t(w.path||""),C.query=w.query):(w.userinfo!==void 0||w.host!==void 0||w.port!==void 0?(C.userinfo=w.userinfo,C.host=w.host,C.port=w.port,C.path=t(w.path||""),C.query=w.query):(w.path?(w.path[0]==="/"?C.path=t(w.path):((_.userinfo!==void 0||_.host!==void 0||_.port!==void 0)&&!_.path?C.path="/"+w.path:_.path?C.path=_.path.slice(0,_.path.lastIndexOf("/")+1)+w.path:C.path=w.path,C.path=t(C.path)),C.query=w.query):(C.path=_.path,w.query!==void 0?C.query=w.query:C.query=_.query),C.userinfo=_.userinfo,C.host=_.host,C.port=_.port),C.scheme=_.scheme),C.fragment=w.fragment,C}function f(_,w,y){return typeof _=="string"?(_=unescape(_),_=p(n(g(_,y),!0),{...y,skipEscape:!0})):typeof _=="object"&&(_=p(n(_,!0),{...y,skipEscape:!0})),typeof w=="string"?(w=unescape(w),w=p(n(g(w,y),!0),{...y,skipEscape:!0})):typeof w=="object"&&(w=p(n(w,!0),{...y,skipEscape:!0})),_.toLowerCase()===w.toLowerCase()}function p(_,w){const y={host:_.host,scheme:_.scheme,userinfo:_.userinfo,port:_.port,path:_.path,query:_.query,nid:_.nid,nss:_.nss,uuid:_.uuid,fragment:_.fragment,reference:_.reference,resourceName:_.resourceName,secure:_.secure,error:""},m=Object.assign({},w),C=[],b=a(m.scheme||y.scheme);b&&b.serialize&&b.serialize(y,m),y.path!==void 0&&(m.skipEscape?y.path=unescape(y.path):(y.path=escape(y.path),y.scheme!==void 0&&(y.path=y.path.split("%3A").join(":")))),m.reference!=="suffix"&&y.scheme&&C.push(y.scheme,":");const T=r(y);if(T!==void 0&&(m.reference!=="suffix"&&C.push("//"),C.push(T),y.path&&y.path[0]!=="/"&&C.push("/")),y.path!==void 0){let I=y.path;!m.absolutePath&&(!b||!b.absolutePath)&&(I=t(I)),T===void 0&&I[0]==="/"&&I[1]==="/"&&(I="/%2F"+I.slice(2)),C.push(I)}return y.query!==void 0&&C.push("?",y.query),y.fragment!==void 0&&C.push("#",y.fragment),C.join("")}const h=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function g(_,w){const y=Object.assign({},w),m={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let C=!1;y.reference==="suffix"&&(y.scheme?_=y.scheme+":"+_:_="//"+_);const b=_.match(h);if(b){if(m.scheme=b[1],m.userinfo=b[3],m.host=b[4],m.port=parseInt(b[5],10),m.path=b[6]||"",m.query=b[7],m.fragment=b[8],isNaN(m.port)&&(m.port=b[5]),m.host)if(o(m.host)===!1){const R=e(m.host);m.host=R.host.toLowerCase(),C=R.isIPV6}else C=!0;m.scheme===void 0&&m.userinfo===void 0&&m.host===void 0&&m.port===void 0&&m.query===void 0&&!m.path?m.reference="same-document":m.scheme===void 0?m.reference="relative":m.fragment===void 0?m.reference="absolute":m.reference="uri",y.reference&&y.reference!=="suffix"&&y.reference!==m.reference&&(m.error=m.error||"URI is not a "+y.reference+" reference.");const T=a(y.scheme||m.scheme);if(!y.unicodeSupport&&(!T||!T.unicodeSupport)&&m.host&&(y.domainHost||T&&T.domainHost)&&C===!1&&s(m.host))try{m.host=URL.domainToASCII(m.host.toLowerCase())}catch(I){m.error=m.error||"Host's domain name can not be converted to ASCII: "+I}(!T||T&&!T.skipNormalize)&&(_.indexOf("%")!==-1&&(m.scheme!==void 0&&(m.scheme=unescape(m.scheme)),m.host!==void 0&&(m.host=unescape(m.host))),m.path&&(m.path=escape(unescape(m.path))),m.fragment&&(m.fragment=encodeURI(decodeURIComponent(m.fragment)))),T&&T.parse&&T.parse(m,y)}else m.error=m.error||"URI can not be parsed.";return m}const v={SCHEMES:i,normalize:l,resolve:c,resolveComponent:u,equal:f,serialize:p,parse:g};return Cs.exports=v,Cs.exports.default=v,Cs.exports.fastUri=v,Cs.exports}var S_;function a7(){if(S_)return ri;S_=1,Object.defineProperty(ri,"__esModule",{value:!0});const e=s7();return e.code='require("ajv/dist/runtime/uri").default',ri.default=e,ri}var I_;function i7(){return I_||(I_=1,(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=Qa();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var r=Pe();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return r.CodeGen}});const n=Eu(),o=ti(),s=s_(),i=$u(),a=Pe(),l=Ya(),c=Ka(),u=De(),f=n7,p=a7(),h=(D,E)=>new RegExp(D,E);h.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"]),_={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."},w={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},y=200;function m(D){var E,U,F,x,M,H,re,te,_e,G,A,V,J,Y,ue,Ce,Ze,ot,pt,Qe,et,At,mt,$r,Yt;const Je=D.strict,hr=(E=D.code)===null||E===void 0?void 0:E.optimize,$=hr===!0||hr===void 0?1:hr||0,K=(F=(U=D.code)===null||U===void 0?void 0:U.regExp)!==null&&F!==void 0?F:h,Le=(x=D.uriResolver)!==null&&x!==void 0?x:p.default;return{strictSchema:(H=(M=D.strictSchema)!==null&&M!==void 0?M:Je)!==null&&H!==void 0?H:!0,strictNumbers:(te=(re=D.strictNumbers)!==null&&re!==void 0?re:Je)!==null&&te!==void 0?te:!0,strictTypes:(G=(_e=D.strictTypes)!==null&&_e!==void 0?_e:Je)!==null&&G!==void 0?G:"log",strictTuples:(V=(A=D.strictTuples)!==null&&A!==void 0?A:Je)!==null&&V!==void 0?V:"log",strictRequired:(Y=(J=D.strictRequired)!==null&&J!==void 0?J:Je)!==null&&Y!==void 0?Y:!1,code:D.code?{...D.code,optimize:$,regExp:K}:{optimize:$,regExp:K},loopRequired:(ue=D.loopRequired)!==null&&ue!==void 0?ue:y,loopEnum:(Ce=D.loopEnum)!==null&&Ce!==void 0?Ce:y,meta:(Ze=D.meta)!==null&&Ze!==void 0?Ze:!0,messages:(ot=D.messages)!==null&&ot!==void 0?ot:!0,inlineRefs:(pt=D.inlineRefs)!==null&&pt!==void 0?pt:!0,schemaId:(Qe=D.schemaId)!==null&&Qe!==void 0?Qe:"$id",addUsedSchema:(et=D.addUsedSchema)!==null&&et!==void 0?et:!0,validateSchema:(At=D.validateSchema)!==null&&At!==void 0?At:!0,validateFormats:(mt=D.validateFormats)!==null&&mt!==void 0?mt:!0,unicodeRegExp:($r=D.unicodeRegExp)!==null&&$r!==void 0?$r:!0,int32range:(Yt=D.int32range)!==null&&Yt!==void 0?Yt:!0,uriResolver:Le}}class C{constructor(E={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,E=this.opts={...E,...m(E)};const{es5:U,lines:F}=this.opts.code;this.scope=new a.ValueScope({scope:{},prefixes:v,es5:U,lines:F}),this.logger=L(E.logger);const x=E.validateFormats;E.validateFormats=!1,this.RULES=(0,s.getRules)(),b.call(this,_,E,"NOT SUPPORTED"),b.call(this,w,E,"DEPRECATED","warn"),this._metaOpts=j.call(this),E.formats&&R.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),E.keywords&&S.call(this,E.keywords),typeof E.meta=="object"&&this.addMetaSchema(E.meta),I.call(this),E.validateFormats=x}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:E,meta:U,schemaId:F}=this.opts;let x=f;F==="id"&&(x={...f},x.id=x.$id,delete x.$id),U&&E&&this.addMetaSchema(x,x[F],!1)}defaultMeta(){const{meta:E,schemaId:U}=this.opts;return this.opts.defaultMeta=typeof E=="object"?E[U]||E:void 0}validate(E,U){let F;if(typeof E=="string"){if(F=this.getSchema(E),!F)throw new Error(`no schema with key or ref "${E}"`)}else F=this.compile(E);const x=F(U);return"$async"in F||(this.errors=F.errors),x}compile(E,U){const F=this._addSchema(E,U);return F.validate||this._compileSchemaEnv(F)}compileAsync(E,U){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:F}=this.opts;return x.call(this,E,U);async function x(G,A){await M.call(this,G.$schema);const V=this._addSchema(G,A);return V.validate||H.call(this,V)}async function M(G){G&&!this.getSchema(G)&&await x.call(this,{$ref:G},!0)}async function H(G){try{return this._compileSchemaEnv(G)}catch(A){if(!(A instanceof o.default))throw A;return re.call(this,A),await te.call(this,A.missingSchema),H.call(this,G)}}function re({missingSchema:G,missingRef:A}){if(this.refs[G])throw new Error(`AnySchema ${G} is loaded but ${A} cannot be resolved`)}async function te(G){const A=await _e.call(this,G);this.refs[G]||await M.call(this,A.$schema),this.refs[G]||this.addSchema(A,G,U)}async function _e(G){const A=this._loading[G];if(A)return A;try{return await(this._loading[G]=F(G))}finally{delete this._loading[G]}}}addSchema(E,U,F,x=this.opts.validateSchema){if(Array.isArray(E)){for(const H of E)this.addSchema(H,void 0,F,x);return this}let M;if(typeof E=="object"){const{schemaId:H}=this.opts;if(M=E[H],M!==void 0&&typeof M!="string")throw new Error(`schema ${H} must be string`)}return U=(0,l.normalizeId)(U||M),this._checkUnique(U),this.schemas[U]=this._addSchema(E,F,U,x,!0),this}addMetaSchema(E,U,F=this.opts.validateSchema){return this.addSchema(E,U,!0,F),this}validateSchema(E,U){if(typeof E=="boolean")return!0;let F;if(F=E.$schema,F!==void 0&&typeof F!="string")throw new Error("$schema must be a string");if(F=F||this.opts.defaultMeta||this.defaultMeta(),!F)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const x=this.validate(F,E);if(!x&&U){const M="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(M);else throw new Error(M)}return x}getSchema(E){let U;for(;typeof(U=T.call(this,E))=="string";)E=U;if(U===void 0){const{schemaId:F}=this.opts,x=new i.SchemaEnv({schema:{},schemaId:F});if(U=i.resolveSchema.call(this,x,E),!U)return;this.refs[E]=U}return U.validate||this._compileSchemaEnv(U)}removeSchema(E){if(E instanceof RegExp)return this._removeAllSchemas(this.schemas,E),this._removeAllSchemas(this.refs,E),this;switch(typeof E){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const U=T.call(this,E);return typeof U=="object"&&this._cache.delete(U.schema),delete this.schemas[E],delete this.refs[E],this}case"object":{const U=E;this._cache.delete(U);let F=E[this.opts.schemaId];return F&&(F=(0,l.normalizeId)(F),delete this.schemas[F],delete this.refs[F]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(E){for(const U of E)this.addKeyword(U);return this}addKeyword(E,U){let F;if(typeof E=="string")F=E,typeof U=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),U.keyword=F);else if(typeof E=="object"&&U===void 0){if(U=E,F=U.keyword,Array.isArray(F)&&!F.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(B.call(this,F,U),!U)return(0,u.eachItem)(F,M=>X.call(this,M)),this;Q.call(this,U);const x={...U,type:(0,c.getJSONTypes)(U.type),schemaType:(0,c.getJSONTypes)(U.schemaType)};return(0,u.eachItem)(F,x.type.length===0?M=>X.call(this,M,x):M=>x.type.forEach(H=>X.call(this,M,x,H))),this}getKeyword(E){const U=this.RULES.all[E];return typeof U=="object"?U.definition:!!U}removeKeyword(E){const{RULES:U}=this;delete U.keywords[E],delete U.all[E];for(const F of U.rules){const x=F.rules.findIndex(M=>M.keyword===E);x>=0&&F.rules.splice(x,1)}return this}addFormat(E,U){return typeof U=="string"&&(U=new RegExp(U)),this.formats[E]=U,this}errorsText(E=this.errors,{separator:U=", ",dataVar:F="data"}={}){return!E||E.length===0?"No errors":E.map(x=>`${F}${x.instancePath} ${x.message}`).reduce((x,M)=>x+U+M)}$dataMetaSchema(E,U){const F=this.RULES.all;E=JSON.parse(JSON.stringify(E));for(const x of U){const M=x.split("/").slice(1);let H=E;for(const re of M)H=H[re];for(const re in F){const te=F[re];if(typeof te!="object")continue;const{$data:_e}=te.definition,G=H[re];_e&&G&&(H[re]=ne(G))}}return E}_removeAllSchemas(E,U){for(const F in E){const x=E[F];(!U||U.test(F))&&(typeof x=="string"?delete E[F]:x&&!x.meta&&(this._cache.delete(x.schema),delete E[F]))}}_addSchema(E,U,F,x=this.opts.validateSchema,M=this.opts.addUsedSchema){let H;const{schemaId:re}=this.opts;if(typeof E=="object")H=E[re];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof E!="boolean")throw new Error("schema must be object or boolean")}let te=this._cache.get(E);if(te!==void 0)return te;F=(0,l.normalizeId)(H||F);const _e=l.getSchemaRefs.call(this,E,F);return te=new i.SchemaEnv({schema:E,schemaId:re,meta:U,baseId:F,localRefs:_e}),this._cache.set(te.schema,te),M&&!F.startsWith("#")&&(F&&this._checkUnique(F),this.refs[F]=te),x&&this.validateSchema(E,!0),te}_checkUnique(E){if(this.schemas[E]||this.refs[E])throw new Error(`schema with key or id "${E}" already exists`)}_compileSchemaEnv(E){if(E.meta?this._compileMetaSchema(E):i.compileSchema.call(this,E),!E.validate)throw new Error("ajv implementation error");return E.validate}_compileMetaSchema(E){const U=this.opts;this.opts=this._metaOpts;try{i.compileSchema.call(this,E)}finally{this.opts=U}}}C.ValidationError=n.default,C.MissingRefError=o.default,e.default=C;function b(D,E,U,F="error"){for(const x in D){const M=x;M in E&&this.logger[F](`${U}: option ${x}. ${D[M]}`)}}function T(D){return D=(0,l.normalizeId)(D),this.schemas[D]||this.refs[D]}function I(){const D=this.opts.schemas;if(D)if(Array.isArray(D))this.addSchema(D);else for(const E in D)this.addSchema(D[E],E)}function R(){for(const D in this.opts.formats){const E=this.opts.formats[D];E&&this.addFormat(D,E)}}function S(D){if(Array.isArray(D)){this.addVocabulary(D);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const E in D){const U=D[E];U.keyword||(U.keyword=E),this.addKeyword(U)}}function j(){const D={...this.opts};for(const E of g)delete D[E];return D}const O={log(){},warn(){},error(){}};function L(D){if(D===!1)return O;if(D===void 0)return console;if(D.log&&D.warn&&D.error)return D;throw new Error("logger must implement log, warn and error methods")}const z=/^[a-z_$][a-z0-9_$:-]*$/i;function B(D,E){const{RULES:U}=this;if((0,u.eachItem)(D,F=>{if(U.keywords[F])throw new Error(`Keyword ${F} is already defined`);if(!z.test(F))throw new Error(`Keyword ${F} has invalid name`)}),!!E&&E.$data&&!("code"in E||"validate"in E))throw new Error('$data keyword must have "code" or "validate" function')}function X(D,E,U){var F;const x=E?.post;if(U&&x)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:M}=this;let H=x?M.post:M.rules.find(({type:te})=>te===U);if(H||(H={type:U,rules:[]},M.rules.push(H)),M.keywords[D]=!0,!E)return;const re={keyword:D,definition:{...E,type:(0,c.getJSONTypes)(E.type),schemaType:(0,c.getJSONTypes)(E.schemaType)}};E.before?ee.call(this,H,re,E.before):H.rules.push(re),M.all[D]=re,(F=E.implements)===null||F===void 0||F.forEach(te=>this.addKeyword(te))}function ee(D,E,U){const F=D.rules.findIndex(x=>x.keyword===U);F>=0?D.rules.splice(F,0,E):(D.rules.push(E),this.logger.warn(`rule ${U} is not defined`))}function Q(D){let{metaSchema:E}=D;E!==void 0&&(D.$data&&this.opts.$data&&(E=ne(E)),D.validateSchema=this.compile(E,!0))}const Z={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function ne(D){return{anyOf:[D,Z]}}})(bu)),bu}var ni={},oi={},si={},x_;function l7(){if(x_)return si;x_=1,Object.defineProperty(si,"__esModule",{value:!0});const e={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};return si.default=e,si}var hn={},E_;function c7(){if(E_)return hn;E_=1,Object.defineProperty(hn,"__esModule",{value:!0}),hn.callRef=hn.getValidate=void 0;const e=ti(),t=Sr(),r=Pe(),n=fn(),o=$u(),s=De(),i={keyword:"$ref",schemaType:"string",code(c){const{gen:u,schema:f,it:p}=c,{baseId:h,schemaEnv:g,validateName:v,opts:_,self:w}=p,{root:y}=g;if((f==="#"||f==="#/")&&h===y.baseId)return C();const m=o.resolveRef.call(w,y,h,f);if(m===void 0)throw new e.default(p.opts.uriResolver,h,f);if(m instanceof o.SchemaEnv)return b(m);return T(m);function C(){if(g===y)return l(c,v,g,g.$async);const I=u.scopeValue("root",{ref:y});return l(c,(0,r._)`${I}.validate`,y,y.$async)}function b(I){const R=a(c,I);l(c,R,I,I.$async)}function T(I){const R=u.scopeValue("schema",_.code.source===!0?{ref:I,code:(0,r.stringify)(I)}:{ref:I}),S=u.name("valid"),j=c.subschema({schema:I,dataTypes:[],schemaPath:r.nil,topSchemaRef:R,errSchemaPath:f},S);c.mergeEvaluated(j),c.ok(S)}}};function a(c,u){const{gen:f}=c;return u.validate?f.scopeValue("validate",{ref:u.validate}):(0,r._)`${f.scopeValue("wrapper",{ref:u})}.validate`}hn.getValidate=a;function l(c,u,f,p){const{gen:h,it:g}=c,{allErrors:v,schemaEnv:_,opts:w}=g,y=w.passContext?n.default.this:r.nil;p?m():C();function m(){if(!_.$async)throw new Error("async schema referenced by sync schema");const I=h.let("valid");h.try(()=>{h.code((0,r._)`await ${(0,t.callValidateCode)(c,u,y)}`),T(u),v||h.assign(I,!0)},R=>{h.if((0,r._)`!(${R} instanceof ${g.ValidationError})`,()=>h.throw(R)),b(R),v||h.assign(I,!1)}),c.ok(I)}function C(){c.result((0,t.callValidateCode)(c,u,y),()=>T(u),()=>b(u))}function b(I){const R=(0,r._)`${I}.errors`;h.assign(n.default.vErrors,(0,r._)`${n.default.vErrors} === null ? ${R} : ${n.default.vErrors}.concat(${R})`),h.assign(n.default.errors,(0,r._)`${n.default.vErrors}.length`)}function T(I){var R;if(!g.opts.unevaluated)return;const S=(R=f?.validate)===null||R===void 0?void 0:R.evaluated;if(g.props!==!0)if(S&&!S.dynamicProps)S.props!==void 0&&(g.props=s.mergeEvaluated.props(h,S.props,g.props));else{const j=h.var("props",(0,r._)`${I}.evaluated.props`);g.props=s.mergeEvaluated.props(h,j,g.props,r.Name)}if(g.items!==!0)if(S&&!S.dynamicItems)S.items!==void 0&&(g.items=s.mergeEvaluated.items(h,S.items,g.items));else{const j=h.var("items",(0,r._)`${I}.evaluated.items`);g.items=s.mergeEvaluated.items(h,j,g.items,r.Name)}}}return hn.callRef=l,hn.default=i,hn}var $_;function u7(){if($_)return oi;$_=1,Object.defineProperty(oi,"__esModule",{value:!0});const e=l7(),t=c7(),r=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",e.default,t.default];return oi.default=r,oi}var ai={},ii={},R_;function d7(){if(R_)return ii;R_=1,Object.defineProperty(ii,"__esModule",{value:!0});const e=Pe(),t=e.operators,r={maximum:{okStr:"<=",ok:t.LTE,fail:t.GT},minimum:{okStr:">=",ok:t.GTE,fail:t.LT},exclusiveMaximum:{okStr:"<",ok:t.LT,fail:t.GTE},exclusiveMinimum:{okStr:">",ok:t.GT,fail:t.LTE}},n={message:({keyword:s,schemaCode:i})=>(0,e.str)`must be ${r[s].okStr} ${i}`,params:({keyword:s,schemaCode:i})=>(0,e._)`{comparison: ${r[s].okStr}, limit: ${i}}`},o={keyword:Object.keys(r),type:"number",schemaType:"number",$data:!0,error:n,code(s){const{keyword:i,data:a,schemaCode:l}=s;s.fail$data((0,e._)`${a} ${r[i].fail} ${l} || isNaN(${a})`)}};return ii.default=o,ii}var li={},P_;function p7(){if(P_)return li;P_=1,Object.defineProperty(li,"__esModule",{value:!0});const e=Pe(),r={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:n})=>(0,e.str)`must be multiple of ${n}`,params:({schemaCode:n})=>(0,e._)`{multipleOf: ${n}}`},code(n){const{gen:o,data:s,schemaCode:i,it:a}=n,l=a.opts.multipleOfPrecision,c=o.let("res"),u=l?(0,e._)`Math.abs(Math.round(${c}) - ${c}) > 1e-${l}`:(0,e._)`${c} !== parseInt(${c})`;n.fail$data((0,e._)`(${i} === 0 || (${c} = ${s}/${i}, ${u}))`)}};return li.default=r,li}var ci={},ui={},M_;function f7(){if(M_)return ui;M_=1,Object.defineProperty(ui,"__esModule",{value:!0});function e(t){const r=t.length;let n=0,o=0,s;for(;o<r;)n++,s=t.charCodeAt(o++),s>=55296&&s<=56319&&o<r&&(s=t.charCodeAt(o),(s&64512)===56320&&o++);return n}return ui.default=e,e.code='require("ajv/dist/runtime/ucs2length").default',ui}var N_;function h7(){if(N_)return ci;N_=1,Object.defineProperty(ci,"__esModule",{value:!0});const e=Pe(),t=De(),r=f7(),o={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message({keyword:s,schemaCode:i}){const a=s==="maxLength"?"more":"fewer";return(0,e.str)`must NOT have ${a} than ${i} characters`},params:({schemaCode:s})=>(0,e._)`{limit: ${s}}`},code(s){const{keyword:i,data:a,schemaCode:l,it:c}=s,u=i==="maxLength"?e.operators.GT:e.operators.LT,f=c.opts.unicode===!1?(0,e._)`${a}.length`:(0,e._)`${(0,t.useFunc)(s.gen,r.default)}(${a})`;s.fail$data((0,e._)`${f} ${u} ${l}`)}};return ci.default=o,ci}var di={},O_;function m7(){if(O_)return di;O_=1,Object.defineProperty(di,"__esModule",{value:!0});const e=Sr(),t=De(),r=Pe(),o={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:s})=>(0,r.str)`must match pattern "${s}"`,params:({schemaCode:s})=>(0,r._)`{pattern: ${s}}`},code(s){const{gen:i,data:a,$data:l,schema:c,schemaCode:u,it:f}=s,p=f.opts.unicodeRegExp?"u":"";if(l){const{regExp:h}=f.opts.code,g=h.code==="new RegExp"?(0,r._)`new RegExp`:(0,t.useFunc)(i,h),v=i.let("valid");i.try(()=>i.assign(v,(0,r._)`${g}(${u}, ${p}).test(${a})`),()=>i.assign(v,!1)),s.fail$data((0,r._)`!${v}`)}else{const h=(0,e.usePattern)(s,c);s.fail$data((0,r._)`!${h}.test(${a})`)}}};return di.default=o,di}var pi={},A_;function g7(){if(A_)return pi;A_=1,Object.defineProperty(pi,"__esModule",{value:!0});const e=Pe(),r={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:{message({keyword:n,schemaCode:o}){const s=n==="maxProperties"?"more":"fewer";return(0,e.str)`must NOT have ${s} than ${o} properties`},params:({schemaCode:n})=>(0,e._)`{limit: ${n}}`},code(n){const{keyword:o,data:s,schemaCode:i}=n,a=o==="maxProperties"?e.operators.GT:e.operators.LT;n.fail$data((0,e._)`Object.keys(${s}).length ${a} ${i}`)}};return pi.default=r,pi}var fi={},q_;function _7(){if(q_)return fi;q_=1,Object.defineProperty(fi,"__esModule",{value:!0});const e=Sr(),t=Pe(),r=De(),o={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:s}})=>(0,t.str)`must have required property '${s}'`,params:({params:{missingProperty:s}})=>(0,t._)`{missingProperty: ${s}}`},code(s){const{gen:i,schema:a,schemaCode:l,data:c,$data:u,it:f}=s,{opts:p}=f;if(!u&&a.length===0)return;const h=a.length>=p.loopRequired;if(f.allErrors?g():v(),p.strictRequired){const y=s.parentSchema.properties,{definedProperties:m}=s.it;for(const C of a)if(y?.[C]===void 0&&!m.has(C)){const b=f.schemaEnv.baseId+f.errSchemaPath,T=`required property "${C}" is not defined at "${b}" (strictRequired)`;(0,r.checkStrictMode)(f,T,f.opts.strictRequired)}}function g(){if(h||u)s.block$data(t.nil,_);else for(const y of a)(0,e.checkReportMissingProp)(s,y)}function v(){const y=i.let("missing");if(h||u){const m=i.let("valid",!0);s.block$data(m,()=>w(y,m)),s.ok(m)}else i.if((0,e.checkMissingProp)(s,a,y)),(0,e.reportMissingProp)(s,y),i.else()}function _(){i.forOf("prop",l,y=>{s.setParams({missingProperty:y}),i.if((0,e.noPropertyInData)(i,c,y,p.ownProperties),()=>s.error())})}function w(y,m){s.setParams({missingProperty:y}),i.forOf(y,l,()=>{i.assign(m,(0,e.propertyInData)(i,c,y,p.ownProperties)),i.if((0,t.not)(m),()=>{s.error(),i.break()})},t.nil)}}};return fi.default=o,fi}var hi={},L_;function y7(){if(L_)return hi;L_=1,Object.defineProperty(hi,"__esModule",{value:!0});const e=Pe(),r={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message({keyword:n,schemaCode:o}){const s=n==="maxItems"?"more":"fewer";return(0,e.str)`must NOT have ${s} than ${o} items`},params:({schemaCode:n})=>(0,e._)`{limit: ${n}}`},code(n){const{keyword:o,data:s,schemaCode:i}=n,a=o==="maxItems"?e.operators.GT:e.operators.LT;n.fail$data((0,e._)`${s}.length ${a} ${i}`)}};return hi.default=r,hi}var mi={},gi={},j_;function Mu(){if(j_)return gi;j_=1,Object.defineProperty(gi,"__esModule",{value:!0});const e=h_();return e.code='require("ajv/dist/runtime/equal").default',gi.default=e,gi}var D_;function v7(){if(D_)return mi;D_=1,Object.defineProperty(mi,"__esModule",{value:!0});const e=Ka(),t=Pe(),r=De(),n=Mu(),s={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i,j:a}})=>(0,t.str)`must NOT have duplicate items (items ## ${a} and ${i} are identical)`,params:({params:{i,j:a}})=>(0,t._)`{i: ${i}, j: ${a}}`},code(i){const{gen:a,data:l,$data:c,schema:u,parentSchema:f,schemaCode:p,it:h}=i;if(!c&&!u)return;const g=a.let("valid"),v=f.items?(0,e.getSchemaTypes)(f.items):[];i.block$data(g,_,(0,t._)`${p} === false`),i.ok(g);function _(){const C=a.let("i",(0,t._)`${l}.length`),b=a.let("j");i.setParams({i:C,j:b}),a.assign(g,!0),a.if((0,t._)`${C} > 1`,()=>(w()?y:m)(C,b))}function w(){return v.length>0&&!v.some(C=>C==="object"||C==="array")}function y(C,b){const T=a.name("item"),I=(0,e.checkDataTypes)(v,T,h.opts.strictNumbers,e.DataType.Wrong),R=a.const("indices",(0,t._)`{}`);a.for((0,t._)`;${C}--;`,()=>{a.let(T,(0,t._)`${l}[${C}]`),a.if(I,(0,t._)`continue`),v.length>1&&a.if((0,t._)`typeof ${T} == "string"`,(0,t._)`${T} += "_"`),a.if((0,t._)`typeof ${R}[${T}] == "number"`,()=>{a.assign(b,(0,t._)`${R}[${T}]`),i.error(),a.assign(g,!1).break()}).code((0,t._)`${R}[${T}] = ${C}`)})}function m(C,b){const T=(0,r.useFunc)(a,n.default),I=a.name("outer");a.label(I).for((0,t._)`;${C}--;`,()=>a.for((0,t._)`${b} = ${C}; ${b}--;`,()=>a.if((0,t._)`${T}(${l}[${C}], ${l}[${b}])`,()=>{i.error(),a.assign(g,!1).break(I)})))}}};return mi.default=s,mi}var _i={},U_;function w7(){if(U_)return _i;U_=1,Object.defineProperty(_i,"__esModule",{value:!0});const e=Pe(),t=De(),r=Mu(),o={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:s})=>(0,e._)`{allowedValue: ${s}}`},code(s){const{gen:i,data:a,$data:l,schemaCode:c,schema:u}=s;l||u&&typeof u=="object"?s.fail$data((0,e._)`!${(0,t.useFunc)(i,r.default)}(${a}, ${c})`):s.fail((0,e._)`${u} !== ${a}`)}};return _i.default=o,_i}var yi={},z_;function b7(){if(z_)return yi;z_=1,Object.defineProperty(yi,"__esModule",{value:!0});const e=Pe(),t=De(),r=Mu(),o={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:s})=>(0,e._)`{allowedValues: ${s}}`},code(s){const{gen:i,data:a,$data:l,schema:c,schemaCode:u,it:f}=s;if(!l&&c.length===0)throw new Error("enum must have non-empty array");const p=c.length>=f.opts.loopEnum;let h;const g=()=>h??(h=(0,t.useFunc)(i,r.default));let v;if(p||l)v=i.let("valid"),s.block$data(v,_);else{if(!Array.isArray(c))throw new Error("ajv implementation error");const y=i.const("vSchema",u);v=(0,e.or)(...c.map((m,C)=>w(y,C)))}s.pass(v);function _(){i.assign(v,!1),i.forOf("v",u,y=>i.if((0,e._)`${g()}(${a}, ${y})`,()=>i.assign(v,!0).break()))}function w(y,m){const C=c[m];return typeof C=="object"&&C!==null?(0,e._)`${g()}(${a}, ${y}[${m}])`:(0,e._)`${a} === ${C}`}}};return yi.default=o,yi}var F_;function k7(){if(F_)return ai;F_=1,Object.defineProperty(ai,"__esModule",{value:!0});const e=d7(),t=p7(),r=h7(),n=m7(),o=g7(),s=_7(),i=y7(),a=v7(),l=w7(),c=b7(),u=[e.default,t.default,r.default,n.default,o.default,s.default,i.default,a.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},l.default,c.default];return ai.default=u,ai}var vi={},bo={},V_;function Z_(){if(V_)return bo;V_=1,Object.defineProperty(bo,"__esModule",{value:!0}),bo.validateAdditionalItems=void 0;const e=Pe(),t=De(),n={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:s}})=>(0,e.str)`must NOT have more than ${s} items`,params:({params:{len:s}})=>(0,e._)`{limit: ${s}}`},code(s){const{parentSchema:i,it:a}=s,{items:l}=i;if(!Array.isArray(l)){(0,t.checkStrictMode)(a,'"additionalItems" is ignored when "items" is not an array of schemas');return}o(s,l)}};function o(s,i){const{gen:a,schema:l,data:c,keyword:u,it:f}=s;f.items=!0;const p=a.const("len",(0,e._)`${c}.length`);if(l===!1)s.setParams({len:i.length}),s.pass((0,e._)`${p} <= ${i.length}`);else if(typeof l=="object"&&!(0,t.alwaysValidSchema)(f,l)){const g=a.var("valid",(0,e._)`${p} <= ${i.length}`);a.if((0,e.not)(g),()=>h(g)),s.ok(g)}function h(g){a.forRange("i",i.length,p,v=>{s.subschema({keyword:u,dataProp:v,dataPropType:t.Type.Num},g),f.allErrors||a.if((0,e.not)(g),()=>a.break())})}}return bo.validateAdditionalItems=o,bo.default=n,bo}var wi={},ko={},B_;function H_(){if(B_)return ko;B_=1,Object.defineProperty(ko,"__esModule",{value:!0}),ko.validateTuple=void 0;const e=Pe(),t=De(),r=Sr(),n={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(s){const{schema:i,it:a}=s;if(Array.isArray(i))return o(s,"additionalItems",i);a.items=!0,!(0,t.alwaysValidSchema)(a,i)&&s.ok((0,r.validateArray)(s))}};function o(s,i,a=s.schema){const{gen:l,parentSchema:c,data:u,keyword:f,it:p}=s;v(c),p.opts.unevaluated&&a.length&&p.items!==!0&&(p.items=t.mergeEvaluated.items(l,a.length,p.items));const h=l.name("valid"),g=l.const("len",(0,e._)`${u}.length`);a.forEach((_,w)=>{(0,t.alwaysValidSchema)(p,_)||(l.if((0,e._)`${g} > ${w}`,()=>s.subschema({keyword:f,schemaProp:w,dataProp:w},h)),s.ok(h))});function v(_){const{opts:w,errSchemaPath:y}=p,m=a.length,C=m===_.minItems&&(m===_.maxItems||_[i]===!1);if(w.strictTuples&&!C){const b=`"${f}" is ${m}-tuple, but minItems or maxItems/${i} are not specified or different at path "${y}"`;(0,t.checkStrictMode)(p,b,w.strictTuples)}}}return ko.validateTuple=o,ko.default=n,ko}var J_;function T7(){if(J_)return wi;J_=1,Object.defineProperty(wi,"__esModule",{value:!0});const e=H_(),t={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,e.validateTuple)(r,"items")};return wi.default=t,wi}var bi={},G_;function C7(){if(G_)return bi;G_=1,Object.defineProperty(bi,"__esModule",{value:!0});const e=Pe(),t=De(),r=Sr(),n=Z_(),s={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:i}})=>(0,e.str)`must NOT have more than ${i} items`,params:({params:{len:i}})=>(0,e._)`{limit: ${i}}`},code(i){const{schema:a,parentSchema:l,it:c}=i,{prefixItems:u}=l;c.items=!0,!(0,t.alwaysValidSchema)(c,a)&&(u?(0,n.validateAdditionalItems)(i,u):i.ok((0,r.validateArray)(i)))}};return bi.default=s,bi}var ki={},W_;function S7(){if(W_)return ki;W_=1,Object.defineProperty(ki,"__esModule",{value:!0});const e=Pe(),t=De(),n={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:o,max:s}})=>s===void 0?(0,e.str)`must contain at least ${o} valid item(s)`:(0,e.str)`must contain at least ${o} and no more than ${s} valid item(s)`,params:({params:{min:o,max:s}})=>s===void 0?(0,e._)`{minContains: ${o}}`:(0,e._)`{minContains: ${o}, maxContains: ${s}}`},code(o){const{gen:s,schema:i,parentSchema:a,data:l,it:c}=o;let u,f;const{minContains:p,maxContains:h}=a;c.opts.next?(u=p===void 0?1:p,f=h):u=1;const g=s.const("len",(0,e._)`${l}.length`);if(o.setParams({min:u,max:f}),f===void 0&&u===0){(0,t.checkStrictMode)(c,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(f!==void 0&&u>f){(0,t.checkStrictMode)(c,'"minContains" > "maxContains" is always invalid'),o.fail();return}if((0,t.alwaysValidSchema)(c,i)){let m=(0,e._)`${g} >= ${u}`;f!==void 0&&(m=(0,e._)`${m} && ${g} <= ${f}`),o.pass(m);return}c.items=!0;const v=s.name("valid");f===void 0&&u===1?w(v,()=>s.if(v,()=>s.break())):u===0?(s.let(v,!0),f!==void 0&&s.if((0,e._)`${l}.length > 0`,_)):(s.let(v,!1),_()),o.result(v,()=>o.reset());function _(){const m=s.name("_valid"),C=s.let("count",0);w(m,()=>s.if(m,()=>y(C)))}function w(m,C){s.forRange("i",0,g,b=>{o.subschema({keyword:"contains",dataProp:b,dataPropType:t.Type.Num,compositeRule:!0},m),C()})}function y(m){s.code((0,e._)`${m}++`),f===void 0?s.if((0,e._)`${m} >= ${u}`,()=>s.assign(v,!0).break()):(s.if((0,e._)`${m} > ${f}`,()=>s.assign(v,!1).break()),u===1?s.assign(v,!0):s.if((0,e._)`${m} >= ${u}`,()=>s.assign(v,!0)))}}};return ki.default=n,ki}var Nu={},K_;function I7(){return K_||(K_=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=Pe(),r=De(),n=Sr();e.error={message:({params:{property:l,depsCount:c,deps:u}})=>{const f=c===1?"property":"properties";return(0,t.str)`must have ${f} ${u} when property ${l} is present`},params:({params:{property:l,depsCount:c,deps:u,missingProperty:f}})=>(0,t._)`{property: ${l},
85
- missingProperty: ${f},
86
- depsCount: ${c},
87
- 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 f in l){if(f==="__proto__")continue;const p=Array.isArray(l[f])?c:u;p[f]=l[f]}return[c,u]}function i(l,c=l.schema){const{gen:u,data:f,it:p}=l;if(Object.keys(c).length===0)return;const h=u.let("missing");for(const g in c){const v=c[g];if(v.length===0)continue;const _=(0,n.propertyInData)(u,f,g,p.opts.ownProperties);l.setParams({property:g,depsCount:v.length,deps:v.join(", ")}),p.allErrors?u.if(_,()=>{for(const w of v)(0,n.checkReportMissingProp)(l,w)}):(u.if((0,t._)`${_} && (${(0,n.checkMissingProp)(l,v,h)})`),(0,n.reportMissingProp)(l,h),u.else())}}e.validatePropertyDeps=i;function a(l,c=l.schema){const{gen:u,data:f,keyword:p,it:h}=l,g=u.name("valid");for(const v in c)(0,r.alwaysValidSchema)(h,c[v])||(u.if((0,n.propertyInData)(u,f,v,h.opts.ownProperties),()=>{const _=l.subschema({keyword:p,schemaProp:v},g);l.mergeValidEvaluated(_,g)},()=>u.var(g,!0)),l.ok(g))}e.validateSchemaDeps=a,e.default=o})(Nu)),Nu}var Ti={},Y_;function x7(){if(Y_)return Ti;Y_=1,Object.defineProperty(Ti,"__esModule",{value:!0});const e=Pe(),t=De(),n={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:o})=>(0,e._)`{propertyName: ${o.propertyName}}`},code(o){const{gen:s,schema:i,data:a,it:l}=o;if((0,t.alwaysValidSchema)(l,i))return;const c=s.name("valid");s.forIn("key",a,u=>{o.setParams({propertyName:u}),o.subschema({keyword:"propertyNames",data:u,dataTypes:["string"],propertyName:u,compositeRule:!0},c),s.if((0,e.not)(c),()=>{o.error(!0),l.allErrors||s.break()})}),o.ok(c)}};return Ti.default=n,Ti}var Ci={},Q_;function X_(){if(Q_)return Ci;Q_=1,Object.defineProperty(Ci,"__esModule",{value:!0});const e=Sr(),t=Pe(),r=fn(),n=De(),s={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:i})=>(0,t._)`{additionalProperty: ${i.additionalProperty}}`},code(i){const{gen:a,schema:l,parentSchema:c,data:u,errsCount:f,it:p}=i;if(!f)throw new Error("ajv implementation error");const{allErrors:h,opts:g}=p;if(p.props=!0,g.removeAdditional!=="all"&&(0,n.alwaysValidSchema)(p,l))return;const v=(0,e.allSchemaProperties)(c.properties),_=(0,e.allSchemaProperties)(c.patternProperties);w(),i.ok((0,t._)`${f} === ${r.default.errors}`);function w(){a.forIn("key",u,T=>{!v.length&&!_.length?C(T):a.if(y(T),()=>C(T))})}function y(T){let I;if(v.length>8){const R=(0,n.schemaRefOrVal)(p,c.properties,"properties");I=(0,e.isOwnProperty)(a,R,T)}else v.length?I=(0,t.or)(...v.map(R=>(0,t._)`${T} === ${R}`)):I=t.nil;return _.length&&(I=(0,t.or)(I,..._.map(R=>(0,t._)`${(0,e.usePattern)(i,R)}.test(${T})`))),(0,t.not)(I)}function m(T){a.code((0,t._)`delete ${u}[${T}]`)}function C(T){if(g.removeAdditional==="all"||g.removeAdditional&&l===!1){m(T);return}if(l===!1){i.setParams({additionalProperty:T}),i.error(),h||a.break();return}if(typeof l=="object"&&!(0,n.alwaysValidSchema)(p,l)){const I=a.name("valid");g.removeAdditional==="failing"?(b(T,I,!1),a.if((0,t.not)(I),()=>{i.reset(),m(T)})):(b(T,I),h||a.if((0,t.not)(I),()=>a.break()))}}function b(T,I,R){const S={keyword:"additionalProperties",dataProp:T,dataPropType:n.Type.Str};R===!1&&Object.assign(S,{compositeRule:!0,createErrors:!1,allErrors:!1}),i.subschema(S,I)}}};return Ci.default=s,Ci}var Si={},ey;function E7(){if(ey)return Si;ey=1,Object.defineProperty(Si,"__esModule",{value:!0});const e=Qa(),t=Sr(),r=De(),n=X_(),o={keyword:"properties",type:"object",schemaType:"object",code(s){const{gen:i,schema:a,parentSchema:l,data:c,it:u}=s;u.opts.removeAdditional==="all"&&l.additionalProperties===void 0&&n.default.code(new e.KeywordCxt(u,n.default,"additionalProperties"));const f=(0,t.allSchemaProperties)(a);for(const _ of f)u.definedProperties.add(_);u.opts.unevaluated&&f.length&&u.props!==!0&&(u.props=r.mergeEvaluated.props(i,(0,r.toHash)(f),u.props));const p=f.filter(_=>!(0,r.alwaysValidSchema)(u,a[_]));if(p.length===0)return;const h=i.name("valid");for(const _ of p)g(_)?v(_):(i.if((0,t.propertyInData)(i,c,_,u.opts.ownProperties)),v(_),u.allErrors||i.else().var(h,!0),i.endIf()),s.it.definedProperties.add(_),s.ok(h);function g(_){return u.opts.useDefaults&&!u.compositeRule&&a[_].default!==void 0}function v(_){s.subschema({keyword:"properties",schemaProp:_,dataProp:_},h)}}};return Si.default=o,Si}var Ii={},ty;function $7(){if(ty)return Ii;ty=1,Object.defineProperty(Ii,"__esModule",{value:!0});const e=Sr(),t=Pe(),r=De(),n=De(),o={keyword:"patternProperties",type:"object",schemaType:"object",code(s){const{gen:i,schema:a,data:l,parentSchema:c,it:u}=s,{opts:f}=u,p=(0,e.allSchemaProperties)(a),h=p.filter(C=>(0,r.alwaysValidSchema)(u,a[C]));if(p.length===0||h.length===p.length&&(!u.opts.unevaluated||u.props===!0))return;const g=f.strictSchema&&!f.allowMatchingProperties&&c.properties,v=i.name("valid");u.props!==!0&&!(u.props instanceof t.Name)&&(u.props=(0,n.evaluatedPropsToName)(i,u.props));const{props:_}=u;w();function w(){for(const C of p)g&&y(C),u.allErrors?m(C):(i.var(v,!0),m(C),i.if(v))}function y(C){for(const b in g)new RegExp(C).test(b)&&(0,r.checkStrictMode)(u,`property ${b} matches pattern ${C} (use allowMatchingProperties)`)}function m(C){i.forIn("key",l,b=>{i.if((0,t._)`${(0,e.usePattern)(s,C)}.test(${b})`,()=>{const T=h.includes(C);T||s.subschema({keyword:"patternProperties",schemaProp:C,dataProp:b,dataPropType:n.Type.Str},v),u.opts.unevaluated&&_!==!0?i.assign((0,t._)`${_}[${b}]`,!0):!T&&!u.allErrors&&i.if((0,t.not)(v),()=>i.break())})})}}};return Ii.default=o,Ii}var xi={},ry;function R7(){if(ry)return xi;ry=1,Object.defineProperty(xi,"__esModule",{value:!0});const e=De(),t={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(r){const{gen:n,schema:o,it:s}=r;if((0,e.alwaysValidSchema)(s,o)){r.fail();return}const i=n.name("valid");r.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},i),r.failResult(i,()=>r.reset(),()=>r.error())},error:{message:"must NOT be valid"}};return xi.default=t,xi}var Ei={},ny;function P7(){if(ny)return Ei;ny=1,Object.defineProperty(Ei,"__esModule",{value:!0});const t={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Sr().validateUnion,error:{message:"must match a schema in anyOf"}};return Ei.default=t,Ei}var $i={},oy;function M7(){if(oy)return $i;oy=1,Object.defineProperty($i,"__esModule",{value:!0});const e=Pe(),t=De(),n={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params:o})=>(0,e._)`{passingSchemas: ${o.passing}}`},code(o){const{gen:s,schema:i,parentSchema:a,it:l}=o;if(!Array.isArray(i))throw new Error("ajv implementation error");if(l.opts.discriminator&&a.discriminator)return;const c=i,u=s.let("valid",!1),f=s.let("passing",null),p=s.name("_valid");o.setParams({passing:f}),s.block(h),o.result(u,()=>o.reset(),()=>o.error(!0));function h(){c.forEach((g,v)=>{let _;(0,t.alwaysValidSchema)(l,g)?s.var(p,!0):_=o.subschema({keyword:"oneOf",schemaProp:v,compositeRule:!0},p),v>0&&s.if((0,e._)`${p} && ${u}`).assign(u,!1).assign(f,(0,e._)`[${f}, ${v}]`).else(),s.if(p,()=>{s.assign(u,!0),s.assign(f,v),_&&o.mergeEvaluated(_,e.Name)})})}}};return $i.default=n,$i}var Ri={},sy;function N7(){if(sy)return Ri;sy=1,Object.defineProperty(Ri,"__esModule",{value:!0});const e=De(),t={keyword:"allOf",schemaType:"array",code(r){const{gen:n,schema:o,it:s}=r;if(!Array.isArray(o))throw new Error("ajv implementation error");const i=n.name("valid");o.forEach((a,l)=>{if((0,e.alwaysValidSchema)(s,a))return;const c=r.subschema({keyword:"allOf",schemaProp:l},i);r.ok(i),r.mergeEvaluated(c)})}};return Ri.default=t,Ri}var Pi={},ay;function O7(){if(ay)return Pi;ay=1,Object.defineProperty(Pi,"__esModule",{value:!0});const e=Pe(),t=De(),n={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:s})=>(0,e.str)`must match "${s.ifClause}" schema`,params:({params:s})=>(0,e._)`{failingKeyword: ${s.ifClause}}`},code(s){const{gen:i,parentSchema:a,it:l}=s;a.then===void 0&&a.else===void 0&&(0,t.checkStrictMode)(l,'"if" without "then" and "else" is ignored');const c=o(l,"then"),u=o(l,"else");if(!c&&!u)return;const f=i.let("valid",!0),p=i.name("_valid");if(h(),s.reset(),c&&u){const v=i.let("ifClause");s.setParams({ifClause:v}),i.if(p,g("then",v),g("else",v))}else c?i.if(p,g("then")):i.if((0,e.not)(p),g("else"));s.pass(f,()=>s.error(!0));function h(){const v=s.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},p);s.mergeEvaluated(v)}function g(v,_){return()=>{const w=s.subschema({keyword:v},p);i.assign(f,p),s.mergeValidEvaluated(w,f),_?i.assign(_,(0,e._)`${v}`):s.setParams({ifClause:v})}}}};function o(s,i){const a=s.schema[i];return a!==void 0&&!(0,t.alwaysValidSchema)(s,a)}return Pi.default=n,Pi}var Mi={},iy;function A7(){if(iy)return Mi;iy=1,Object.defineProperty(Mi,"__esModule",{value:!0});const e=De(),t={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:r,parentSchema:n,it:o}){n.if===void 0&&(0,e.checkStrictMode)(o,`"${r}" without "if" is ignored`)}};return Mi.default=t,Mi}var ly;function q7(){if(ly)return vi;ly=1,Object.defineProperty(vi,"__esModule",{value:!0});const e=Z_(),t=T7(),r=H_(),n=C7(),o=S7(),s=I7(),i=x7(),a=X_(),l=E7(),c=$7(),u=R7(),f=P7(),p=M7(),h=N7(),g=O7(),v=A7();function _(w=!1){const y=[u.default,f.default,p.default,h.default,g.default,v.default,i.default,a.default,s.default,l.default,c.default];return w?y.push(t.default,n.default):y.push(e.default,r.default),y.push(o.default),y}return vi.default=_,vi}var Ni={},Oi={},cy;function L7(){if(cy)return Oi;cy=1,Object.defineProperty(Oi,"__esModule",{value:!0});const e=Pe(),r={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:n})=>(0,e.str)`must match format "${n}"`,params:({schemaCode:n})=>(0,e._)`{format: ${n}}`},code(n,o){const{gen:s,data:i,$data:a,schema:l,schemaCode:c,it:u}=n,{opts:f,errSchemaPath:p,schemaEnv:h,self:g}=u;if(!f.validateFormats)return;a?v():_();function v(){const w=s.scopeValue("formats",{ref:g.formats,code:f.code.formats}),y=s.const("fDef",(0,e._)`${w}[${c}]`),m=s.let("fType"),C=s.let("format");s.if((0,e._)`typeof ${y} == "object" && !(${y} instanceof RegExp)`,()=>s.assign(m,(0,e._)`${y}.type || "string"`).assign(C,(0,e._)`${y}.validate`),()=>s.assign(m,(0,e._)`"string"`).assign(C,y)),n.fail$data((0,e.or)(b(),T()));function b(){return f.strictSchema===!1?e.nil:(0,e._)`${c} && !${C}`}function T(){const I=h.$async?(0,e._)`(${y}.async ? await ${C}(${i}) : ${C}(${i}))`:(0,e._)`${C}(${i})`,R=(0,e._)`(typeof ${C} == "function" ? ${I} : ${C}.test(${i}))`;return(0,e._)`${C} && ${C} !== true && ${m} === ${o} && !${R}`}}function _(){const w=g.formats[l];if(!w){b();return}if(w===!0)return;const[y,m,C]=T(w);y===o&&n.pass(I());function b(){if(f.strictSchema===!1){g.logger.warn(R());return}throw new Error(R());function R(){return`unknown format "${l}" ignored in schema at path "${p}"`}}function T(R){const S=R instanceof RegExp?(0,e.regexpCode)(R):f.code.formats?(0,e._)`${f.code.formats}${(0,e.getProperty)(l)}`:void 0,j=s.scopeValue("formats",{key:l,ref:R,code:S});return typeof R=="object"&&!(R instanceof RegExp)?[R.type||"string",R.validate,(0,e._)`${j}.validate`]:["string",R,j]}function I(){if(typeof w=="object"&&!(w instanceof RegExp)&&w.async){if(!h.$async)throw new Error("async format in sync schema");return(0,e._)`await ${C}(${i})`}return typeof m=="function"?(0,e._)`${C}(${i})`:(0,e._)`${C}.test(${i})`}}}};return Oi.default=r,Oi}var uy;function j7(){if(uy)return Ni;uy=1,Object.defineProperty(Ni,"__esModule",{value:!0});const t=[L7().default];return Ni.default=t,Ni}var Hn={},dy;function D7(){return dy||(dy=1,Object.defineProperty(Hn,"__esModule",{value:!0}),Hn.contentVocabulary=Hn.metadataVocabulary=void 0,Hn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],Hn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]),Hn}var py;function U7(){if(py)return ni;py=1,Object.defineProperty(ni,"__esModule",{value:!0});const e=u7(),t=k7(),r=q7(),n=j7(),o=D7(),s=[e.default,t.default,(0,r.default)(),n.default,o.metadataVocabulary,o.contentVocabulary];return ni.default=s,ni}var Ai={},Ss={},fy;function z7(){if(fy)return Ss;fy=1,Object.defineProperty(Ss,"__esModule",{value:!0}),Ss.DiscrError=void 0;var e;return(function(t){t.Tag="tag",t.Mapping="mapping"})(e||(Ss.DiscrError=e={})),Ss}var hy;function F7(){if(hy)return Ai;hy=1,Object.defineProperty(Ai,"__esModule",{value:!0});const e=Pe(),t=z7(),r=$u(),n=ti(),o=De(),i={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:a,tagName:l}})=>a===t.DiscrError.Tag?`tag "${l}" must be string`:`value of tag "${l}" must be in oneOf`,params:({params:{discrError:a,tag:l,tagName:c}})=>(0,e._)`{error: ${a}, tag: ${c}, tagValue: ${l}}`},code(a){const{gen:l,data:c,schema:u,parentSchema:f,it:p}=a,{oneOf:h}=f;if(!p.opts.discriminator)throw new Error("discriminator: requires discriminator option");const g=u.propertyName;if(typeof g!="string")throw new Error("discriminator: requires propertyName");if(u.mapping)throw new Error("discriminator: mapping is not supported");if(!h)throw new Error("discriminator: requires oneOf keyword");const v=l.let("valid",!1),_=l.const("tag",(0,e._)`${c}${(0,e.getProperty)(g)}`);l.if((0,e._)`typeof ${_} == "string"`,()=>w(),()=>a.error(!1,{discrError:t.DiscrError.Tag,tag:_,tagName:g})),a.ok(v);function w(){const C=m();l.if(!1);for(const b in C)l.elseIf((0,e._)`${_} === ${b}`),l.assign(v,y(C[b]));l.else(),a.error(!1,{discrError:t.DiscrError.Mapping,tag:_,tagName:g}),l.endIf()}function y(C){const b=l.name("valid"),T=a.subschema({keyword:"oneOf",schemaProp:C},b);return a.mergeEvaluated(T,e.Name),b}function m(){var C;const b={},T=R(f);let I=!0;for(let O=0;O<h.length;O++){let L=h[O];if(L?.$ref&&!(0,o.schemaHasRulesButRef)(L,p.self.RULES)){const B=L.$ref;if(L=r.resolveRef.call(p.self,p.schemaEnv.root,p.baseId,B),L instanceof r.SchemaEnv&&(L=L.schema),L===void 0)throw new n.default(p.opts.uriResolver,p.baseId,B)}const z=(C=L?.properties)===null||C===void 0?void 0:C[g];if(typeof z!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${g}"`);I=I&&(T||R(L)),S(z,O)}if(!I)throw new Error(`discriminator: "${g}" must be required`);return b;function R({required:O}){return Array.isArray(O)&&O.includes(g)}function S(O,L){if(O.const)j(O.const,L);else if(O.enum)for(const z of O.enum)j(z,L);else throw new Error(`discriminator: "properties/${g}" must have "const" or "enum"`)}function j(O,L){if(typeof O!="string"||O in b)throw new Error(`discriminator: "${g}" values must be unique strings`);b[O]=L}}}};return Ai.default=i,Ai}const V7={$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 my;function gy(){return my||(my=1,(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 r=i7(),n=U7(),o=F7(),s=V7,i=["/properties"],a="http://json-schema.org/draft-07/schema";class l extends r.default{_addVocabularies(){super._addVocabularies(),n.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=Qa();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return c.KeywordCxt}});var u=Pe();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 f=Eu();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return f.default}});var p=ti();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return p.default}})})(Ha,Ha.exports)),Ha.exports}var Z7=gy();const B7=Pl(Z7);var qi={exports:{}},Ou={},_y;function H7(){return _y||(_y=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(O,L){return{validate:O,compare:L}}e.fullFormats={date:t(s,i),time:t(l(!0),c),"date-time":t(p(!0),h),"iso-time":t(l(),u),"iso-date-time":t(p(),g),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:w,"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:j,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:m,int32:{type:"number",validate:T},int64:{type:"number",validate:I},float:{type:"number",validate:R},double:{type:"number",validate:R},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,h),"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 r(O){return O%4===0&&(O%100!==0||O%400===0)}const n=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,o=[0,31,28,31,30,31,30,31,31,30,31,30,31];function s(O){const L=n.exec(O);if(!L)return!1;const z=+L[1],B=+L[2],X=+L[3];return B>=1&&B<=12&&X>=1&&X<=(B===2&&r(z)?29:o[B])}function i(O,L){if(O&&L)return O>L?1:O<L?-1:0}const a=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function l(O){return function(z){const B=a.exec(z);if(!B)return!1;const X=+B[1],ee=+B[2],Q=+B[3],Z=B[4],ne=B[5]==="-"?-1:1,D=+(B[6]||0),E=+(B[7]||0);if(D>23||E>59||O&&!Z)return!1;if(X<=23&&ee<=59&&Q<60)return!0;const U=ee-E*ne,F=X-D*ne-(U<0?1:0);return(F===23||F===-1)&&(U===59||U===-1)&&Q<61}}function c(O,L){if(!(O&&L))return;const z=new Date("2020-01-01T"+O).valueOf(),B=new Date("2020-01-01T"+L).valueOf();if(z&&B)return z-B}function u(O,L){if(!(O&&L))return;const z=a.exec(O),B=a.exec(L);if(z&&B)return O=z[1]+z[2]+z[3],L=B[1]+B[2]+B[3],O>L?1:O<L?-1:0}const f=/t|\s/i;function p(O){const L=l(O);return function(B){const X=B.split(f);return X.length===2&&s(X[0])&&L(X[1])}}function h(O,L){if(!(O&&L))return;const z=new Date(O).valueOf(),B=new Date(L).valueOf();if(z&&B)return z-B}function g(O,L){if(!(O&&L))return;const[z,B]=O.split(f),[X,ee]=L.split(f),Q=i(z,X);if(Q!==void 0)return Q||c(B,ee)}const v=/\/|:/,_=/^(?:[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 w(O){return v.test(O)&&_.test(O)}const y=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function m(O){return y.lastIndex=0,y.test(O)}const C=-2147483648,b=2**31-1;function T(O){return Number.isInteger(O)&&O<=b&&O>=C}function I(O){return Number.isInteger(O)}function R(){return!0}const S=/[^\\]\\Z/;function j(O){if(S.test(O))return!1;try{return new RegExp(O),!0}catch{return!1}}})(Ou)),Ou}var Au={},yy;function J7(){return yy||(yy=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;const t=gy(),r=Pe(),n=r.operators,o={formatMaximum:{okStr:"<=",ok:n.LTE,fail:n.GT},formatMinimum:{okStr:">=",ok:n.GTE,fail:n.LT},formatExclusiveMaximum:{okStr:"<",ok:n.LT,fail:n.GTE},formatExclusiveMinimum:{okStr:">",ok:n.GT,fail:n.LTE}},s={message:({keyword:a,schemaCode:l})=>(0,r.str)`should be ${o[a].okStr} ${l}`,params:({keyword:a,schemaCode:l})=>(0,r._)`{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:f,it:p}=a,{opts:h,self:g}=p;if(!h.validateFormats)return;const v=new t.KeywordCxt(p,g.RULES.all.format.definition,"format");v.$data?_():w();function _(){const m=l.scopeValue("formats",{ref:g.formats,code:h.code.formats}),C=l.const("fmt",(0,r._)`${m}[${v.schemaCode}]`);a.fail$data((0,r.or)((0,r._)`typeof ${C} != "object"`,(0,r._)`${C} instanceof RegExp`,(0,r._)`typeof ${C}.compare != "function"`,y(C)))}function w(){const m=v.schema,C=g.formats[m];if(!C||C===!0)return;if(typeof C!="object"||C instanceof RegExp||typeof C.compare!="function")throw new Error(`"${f}": format "${m}" does not define "compare" function`);const b=l.scopeValue("formats",{key:m,ref:C,code:h.code.formats?(0,r._)`${h.code.formats}${(0,r.getProperty)(m)}`:void 0});a.fail$data(y(b))}function y(m){return(0,r._)`${m}.compare(${c}, ${u}) ${o[f].fail} 0`}},dependencies:["format"]};const i=a=>(a.addKeyword(e.formatLimitDefinition),a);e.default=i})(Au)),Au}var vy;function G7(){return vy||(vy=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r=H7(),n=J7(),o=Pe(),s=new o.Name("fullFormats"),i=new o.Name("fastFormats"),a=(c,u={keywords:!0})=>{if(Array.isArray(u))return l(c,u,r.fullFormats,s),c;const[f,p]=u.mode==="fast"?[r.fastFormats,i]:[r.fullFormats,s],h=u.formats||r.formatNames;return l(c,h,f,p),u.keywords&&(0,n.default)(c),c};a.get=(c,u="full")=>{const p=(u==="fast"?r.fastFormats:r.fullFormats)[c];if(!p)throw new Error(`Unknown format "${c}"`);return p};function l(c,u,f,p){var h,g;(h=(g=c.opts.code).formats)!==null&&h!==void 0||(g.formats=(0,o._)`require("ajv-formats/dist/formats").${p}`);for(const v of u)c.addFormat(v,f[v])}e.exports=t=a,Object.defineProperty(t,"__esModule",{value:!0}),t.default=a})(qi,qi.exports)),qi.exports}var W7=G7();const K7=Pl(W7);function Y7(){const e=new B7({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return K7(e),e}class Q7{constructor(t){this._ajv=t??Y7()}getValidator(t){const r="$id"in t&&typeof t.$id=="string"?this._ajv.getSchema(t.$id)??this._ajv.compile(t):this._ajv.compile(t);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}}class X7{constructor(t){this._client=t}async*callToolStream(t,r=hs,n){const o=this._client,s={...n,task:n?.task??(o.isToolTask(t.name)?{}:void 0)},i=o.requestStream({method:"tools/call",params:t},r,s),a=o.getToolOutputValidator(t.name);for await(const l of i){if(l.type==="result"&&a){const c=l.result;if(!c.structuredContent&&!c.isError){yield{type:"error",error:new Te($e.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`)};return}if(c.structuredContent)try{const u=a(c.structuredContent);if(!u.valid){yield{type:"error",error:new Te($e.InvalidParams,`Structured content does not match the tool's output schema: ${u.errorMessage}`)};return}}catch(u){if(u instanceof Te){yield{type:"error",error:u};return}yield{type:"error",error:new Te($e.InvalidParams,`Failed to validate structured content: ${u instanceof Error?u.message:String(u)}`)};return}}yield l}}async getTask(t,r){return this._client.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._client.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._client.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._client.cancelTask({taskId:t},r)}requestStream(t,r,n){return this._client.requestStream(t,r,n)}}function eE(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`);break}}function tE(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break}}function Li(e,t){if(!(!e||t===null||typeof t!="object")){if(e.type==="object"&&e.properties&&typeof e.properties=="object"){const r=t,n=e.properties;for(const o of Object.keys(n)){const s=n[o];r[o]===void 0&&Object.prototype.hasOwnProperty.call(s,"default")&&(r[o]=s.default),r[o]!==void 0&&Li(s,r[o])}}if(Array.isArray(e.anyOf))for(const r of e.anyOf)typeof r!="boolean"&&Li(r,t);if(Array.isArray(e.oneOf))for(const r of e.oneOf)typeof r!="boolean"&&Li(r,t)}}function rE(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};const t=e.form!==void 0,r=e.url!==void 0;return{supportsFormMode:t||!t&&!r,supportsUrlMode:r}}class ji extends Kx{constructor(t,r){super(r),this._clientInfo=t,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=r?.capabilities??{},this._jsonSchemaValidator=r?.jsonSchemaValidator??new Q7,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Nc,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Mc,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",xc,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new X7(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Yx(this._capabilities,t)}setRequestHandler(t,r){const o=Hg(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(Ba(o)){const a=o;s=a._zod?.def?.value??a.value}else{const a=o;s=a._def?.value??a.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");const i=s;if(i==="elicitation/create"){const a=async(l,c)=>{const u=pn(qc,l);if(!u.success){const y=u.error instanceof Error?u.error.message:String(u.error);throw new Te($e.InvalidParams,`Invalid elicitation request: ${y}`)}const{params:f}=u.data;f.mode=f.mode??"form";const{supportsFormMode:p,supportsUrlMode:h}=rE(this._capabilities.elicitation);if(f.mode==="form"&&!p)throw new Te($e.InvalidParams,"Client does not support form-mode elicitation requests");if(f.mode==="url"&&!h)throw new Te($e.InvalidParams,"Client does not support URL-mode elicitation requests");const g=await Promise.resolve(r(l,c));if(f.task){const y=pn(ps,g);if(!y.success){const m=y.error instanceof Error?y.error.message:String(y.error);throw new Te($e.InvalidParams,`Invalid task creation result: ${m}`)}return y.data}const v=pn(Lc,g);if(!v.success){const y=v.error instanceof Error?v.error.message:String(v.error);throw new Te($e.InvalidParams,`Invalid elicitation result: ${y}`)}const _=v.data,w=f.mode==="form"?f.requestedSchema:void 0;if(f.mode==="form"&&_.action==="accept"&&_.content&&w&&this._capabilities.elicitation?.form?.applyDefaults)try{Li(w,_.content)}catch{}return _};return super.setRequestHandler(t,a)}if(i==="sampling/createMessage"){const a=async(l,c)=>{const u=pn(Oc,l);if(!u.success){const _=u.error instanceof Error?u.error.message:String(u.error);throw new Te($e.InvalidParams,`Invalid sampling request: ${_}`)}const{params:f}=u.data,p=await Promise.resolve(r(l,c));if(f.task){const _=pn(ps,p);if(!_.success){const w=_.error instanceof Error?_.error.message:String(_.error);throw new Te($e.InvalidParams,`Invalid task creation result: ${w}`)}return _.data}const g=f.tools||f.toolChoice?m2:Ac,v=pn(g,p);if(!v.success){const _=v.error instanceof Error?v.error.message:String(v.error);throw new Te($e.InvalidParams,`Invalid sampling result: ${_}`)}return v.data};return super.setRequestHandler(t,a)}return super.setRequestHandler(t,r)}assertCapability(t,r){if(!this._serverCapabilities?.[t])throw new Error(`Server does not support ${t} (required for ${r})`)}async connect(t,r){if(await super.connect(t),t.sessionId===void 0)try{const n=await this.request({method:"initialize",params:{protocolVersion:Sa,capabilities:this._capabilities,clientInfo:this._clientInfo}},Xm,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!iC.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,t.setProtocolVersion&&t.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(t){switch(t){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.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(!this._serverCapabilities?.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(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${t})`);break}}assertNotificationCapability(t){switch(t){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${t})`);break}}assertRequestHandlerCapability(t){if(this._capabilities)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;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${t})`);break}}assertTaskCapability(t){eE(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&tE(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},Dn,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},g2,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},Dn,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},u2,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},c2,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},s2,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},a2,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},i2,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},Dn,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},Dn,r)}async callTool(t,r=hs,n){if(this.isToolTaskRequired(t.name))throw new Te($e.InvalidRequest,`Tool "${t.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);const o=await this.request({method:"tools/call",params:t},r,n),s=this.getToolOutputValidator(t.name);if(s){if(!o.structuredContent&&!o.isError)throw new Te($e.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 Te($e.InvalidParams,`Structured content does not match the tool's output schema: ${i.errorMessage}`)}catch(i){throw i instanceof Te?i:new Te($e.InvalidParams,`Failed to validate structured content: ${i instanceof Error?i.message:String(i)}`)}}return o}isToolTask(t){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(t):!1}isToolTaskRequired(t){return this._cachedRequiredTaskTools.has(t)}cacheToolMetadata(t){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(const r of t){if(r.outputSchema){const o=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,o)}const n=r.execution?.taskSupport;(n==="required"||n==="optional")&&this._cachedKnownTaskTools.add(r.name),n==="required"&&this._cachedRequiredTaskTools.add(r.name)}}getToolOutputValidator(t){return this._cachedToolOutputValidators.get(t)}async listTools(t,r){const n=await this.request({method:"tools/list",params:t},p2,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,o){const s=eS.safeParse(n);if(!s.success)throw new Error(`Invalid ${t} listChanged options: ${s.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${t} listChanged options: onChanged must be a function`);const{autoRefresh:i,debounceMs:a}=s.data,{onChanged:l}=n,c=async()=>{if(!i){l(null,null);return}try{const f=await o();l(null,f)}catch(f){const p=f instanceof Error?f:new Error(String(f));l(p,null)}},u=()=>{if(a){const f=this._listChangedDebounceTimers.get(t);f&&clearTimeout(f);const p=setTimeout(c,a);this._listChangedDebounceTimers.set(t,p)}else c()};this.setNotificationHandler(r,u)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}const nE="mcp";class wy{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,r)=>{this._socket=new WebSocket(this._url,nE),this._socket.onerror=n=>{const o="error"in n?n.error:new Error(`WebSocket error: ${JSON.stringify(n)}`);r(o),this.onerror?.(o)},this._socket.onopen=()=>{t()},this._socket.onclose=()=>{this.onclose?.()},this._socket.onmessage=n=>{let o;try{o=jn.parse(JSON.parse(n.data))}catch(s){this.onerror?.(s);return}this.onmessage?.(o)}})}async close(){this._socket?.close()}send(t){return new Promise((r,n)=>{if(!this._socket){n(new Error("Not connected"));return}this._socket?.send(JSON.stringify(t)),r()})}}const To=Ir;(function(e,t){const r=Ir,n=Ir,o=e();for(;;)try{if(parseInt(r(403))/1+-parseInt(r(411))/2*(-parseInt(n(406))/3)+-parseInt(n(425))/4*(parseInt(r(387))/5)+-parseInt(n(426))/6+parseInt(n(395))/7*(-parseInt(r(419))/8)+-parseInt(r(413))/9+parseInt(n(400))/10===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(Di,-118057+3521*-35+-2099*-233);const oE=()=>{const e=Ir,t=Ir,r={};r[e(420)]="3|0|2|1|4",r.vQYJZ=function(i,a){return i!==a},r[t(394)]=t(414),r.ktWqD=function(i,a){return i!==a},r[e(424)]=e(391);const n=r,o=n[t(420)].split("|");let s=859*2+-3*-1039+-4835*1;for(;;){switch(o[s++]){case"0":if(n[t(407)](typeof window,"undefined"))return window;continue;case"1":if(n.vQYJZ(typeof self,n.NZmUq))return self;continue;case"2":if(n[t(405)](typeof global,"undefined"))return global;continue;case"3":if(n[t(405)](typeof globalThis,n[e(394)]))return globalThis;continue;case"4":return Function(n[e(424)])()}break}},sE=(e,t,r)=>{const n=Ir,o=Ir,s={};s.eOzBp=function(a,l){return a!==l},s.ooaJk="undefined",s[n(402)]=function(a,l){return a===l},s[n(421)]="function";const i=s;i[o(389)](typeof window,i.ooaJk)?e[o(423)](t,"*",r):n(423)in e&&i.pTvSc(typeof e[o(423)],i[n(421)])&&e.postMessage(t,r)};class by{constructor(t){this._port=t}async[To(401)](){const t=To,r=To;this[t(422)]&&(this[r(422)].onmessage=n=>{var o,s;const i=t;try{const a=jn.parse(n.data.message);(o=this.onmessage)==null||o.call(this,a,n[i(412)][i(428)])}catch(a){const l=new Error("MessageChannel failed to parse message: "+a);(s=this[i(383)])==null||s.call(this,l)}},this._port.onmessageerror=n=>{var o;const s=r,i=new Error("MessageChannel transport error: "+JSON[s(415)](n));(o=this.onerror)==null||o.call(this,i)},this[r(422)].start())}async send(t,r){const n={EoBZE:function(o){return o()},leEiG:function(o,s){return o instanceof s},cDUwk:function(o,s){return o(s)}};return new Promise((o,s)=>{var i;const a=Ir,l=Ir;try{const c={};c[a(404)]=r?.[a(404)];const u={};u[a(392)]=t,u.extra=c,this._port&&this._port[l(423)](u),n[a(399)](o)}catch(c){const u=n.leEiG(c,Error)?c:new Error(n.cDUwk(String,c));(i=this.onerror)==null||i.call(this,u),s(u)}})}async close(){var t,r;const n=To,o=To;(t=this._port)==null||t[n(393)](),this[n(422)]=void 0,(r=this[o(408)])==null||r.call(this)}}class aE extends by{constructor(t,r=oE()){const n=To,o={lSpBh:function(i,a,l,c){return i(a,l,c)}};super(),this._endpoint=t,this._globalObject=r;const s=new MessageChannel;this._port=s[n(410)],o[n(418)](sE,this._globalObject,{endpoint:this[n(397)]},[s[n(429)]])}}function Di(){const e=["message","close","NZmUq","177464iLQCGm","endpoint","_endpoint","FPOYW","EoBZE","3022630ngzRBs","start","pTvSc","272809yMhhPJ","authInfo","ktWqD","21849KofsKk","vQYJZ","onclose","mkHJS","port1","22dUTKmE","data","608229RXNlUs","undefined","stringify","_listen","onmessage","lSpBh","8FmlYyF","XwdDB","cHbAW","_port","postMessage","kFtNB","72572mbPnfL","689424jqaGZE","jowPp","extra","port2","ports","onerror","Fzdib","mkuHv","addEventListener","55juYkZZ","_globalObject","eOzBp","ogKey","return this"];return Di=function(){return e},Di()}function Ir(e,t){const r=Di();return Ir=function(n,o){return n=n-(17227+1*-16844),r[n]},Ir(e,t)}(function(e,t){const r=Ge,n=Ge,o=e();for(;;)try{if(parseInt(r(452))/1*(parseInt(n(441))/2)+parseInt(n(434))/3*(-parseInt(n(418))/4)+parseInt(r(459))/5+parseInt(r(482))/6*(-parseInt(r(479))/7)+-parseInt(r(458))/8*(parseInt(r(457))/9)+-parseInt(n(416))/10+-parseInt(r(450))/11*(-parseInt(r(433))/12)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(Ui,-411935*1+228107+208149*2);const iE=async(e,t,r)=>{var n;const o=Ge,s=Ge,i={};i.VRyiJ="tools/list",i.VkPYu="tools/call",i[o(475)]=o(411),i.SoCaE="resources/templates/list",i[s(484)]="resources/read",i[o(461)]="prompts/get",i.srIIC=s(477),i[s(436)]=s(478),i[s(442)]=o(437),i.dEmVs=o(465);const a=i,{id:l,method:c,params:u}=r;let f={};switch(c){case a.VRyiJ:f=await t.listTools(u);break;case a.VkPYu:f=await t.callTool(u);break;case a.fgMSD:f=await t.listResources(u);break;case a[s(466)]:f=await t.listResourceTemplates(u);break;case a.sthgI:f=await t[o(455)](u);break;case s(486):f=await t.subscribeResource(u);break;case o(410):f=await t.unsubscribeResource(u);break;case a[s(461)]:f=await t[s(414)](u);break;case a[o(412)]:f=await t[o(491)](u);break;case a[o(436)]:f=await t[o(478)]();break;case a.kkNqg:f=await t.complete(u);break;case o(464):f=await t.setLoggingLevel(u?.[s(443)]);break}const p={};p.result=f,p.jsonrpc=a[s(472)],p.id=l,await((n=e?.[s(488)])==null?void 0:n[o(460)](p))},lE=async(e,t,r)=>{var n;const o=Ge,s=Ge,i={};i[o(487)]=s(462),i.ypHTC="ping",i.fPExS=o(465);const a=i,{id:l,method:c,params:u}=r;let f={};switch(c){case"roots/list":const h={};h.method=c,h[s(446)]=u,f=await t[o(469)](h,y2);break;case"sampling/createMessage":const g={};g[o(481)]=c,g[o(446)]=u,f=await t.request(g,Ac);break;case a[o(487)]:const v={};v.method=c,v[s(446)]=u,f=await t.request(v,Lc);break;case a.ypHTC:const _={};_.method=c,f=await t.request(_,Dn);break}const p={};return p.result=f,p.jsonrpc=a.fPExS,p.id=l,await((n=e?.transport)==null?void 0:n.send(p)),f};function Ge(e,t){const r=Ui();return Ge=function(n,o){return n=n-(-8023+4*-2344+-17809*-1),r[n]},Ge(e,t)}const cE=(e,t)=>{const r=Ge,n=Ge,o={vYlhn:function(i,a){return i===a},DhPFX:r(470),NYVNC:function(i,a,l,c){return i(a,l,c)},yfZbw:"2.0"},s=e._onrequest;e[n(463)]=async(i,a)=>{var l,c,u,f,p;const h=n,g=r,{id:v,method:_}=i;try{o[h(451)](_,o.DhPFX)?await s.call(e,i,a):await o[g(474)](iE,e,t,i)}catch(w){const{code:y,message:m,data:C}=w;try{if(y){const b={};b[g(485)]=y,b[h(422)]=m,b.data=C;const T={};T[g(448)]=b,T.jsonrpc=o[h(417)],T.id=v,await((l=e?.transport)==null?void 0:l[g(460)](T))}else(u=(c=e?.transport)==null?void 0:c.onerror)==null||u.call(c,w)}catch(b){(p=(f=e?.transport)==null?void 0:f.onerror)==null||p.call(f,b)}}}},uE=(e,t)=>{const r=Ge,n=Ge,o={};o[r(476)]=r(439),o[r(431)]=function(i,a){return i!==a},o.UPdQt="notifications/cancelled";const s=o;e[r(421)]=async i=>{var a,l;const c=r,u=n,{method:f,params:p}=i;if(f!==s[c(476)]&&(s.QWYMz(f,s.UPdQt)||p?.[u(490)]))try{await t[c(445)](i)}catch(h){(l=(a=e?.[c(488)])==null?void 0:a[c(480)])==null||l.call(a,h)}}},dE=(e,t)=>async r=>{var n,o,s,i,a;const l=Ge,c=Ge,u={TJhyV:function(f,p,h,g){return f(p,h,g)},MMNTY:l(465)};try{return await u.TJhyV(lE,e,t,r)}catch(f){const{code:p,message:h,data:g}=f;try{if(p){const v={};v.code=p,v[l(422)]=h,v[c(419)]=g;const _={};_[l(448)]=v,_[l(424)]=u.MMNTY,_.id=r.id,await((n=e?.transport)==null?void 0:n[c(460)](_))}else(s=(o=e?.transport)==null?void 0:o[l(480)])==null||s.call(o,f)}catch(v){(a=(i=e?.[l(488)])==null?void 0:i.onerror)==null||a.call(i,v)}}},pE=(e,t)=>async r=>{var n,o,s;const i=Ge,a=Ge,l={};l.xmcLM=function(p,h){return p!==h},l.xSWLt="notifications/initialized",l[i(420)]=a(453);const c=l,{method:u,params:f}=r;if(c.xmcLM(u,c.xSWLt)&&(c.xmcLM(u,c[a(420)])||f?.[a(490)]))try{const p={...r};p.jsonrpc=i(465),await((n=t?.[i(488)])==null?void 0:n.send(p))}catch(p){(s=(o=e?.transport)==null?void 0:o.onerror)==null||s.call(o,p)}};function Ui(){const e=["JMaxV","cNneM","completion/complete","addResponseListener","notifications/initialized","call","570686biwZQB","kkNqg","level","addNotificationListener","notification","params","addListener","error","_onresponse","164054EGcqjc","vYlhn","1PDRdga","notifications/cancelled","_requestHandlers","readResource","FjTAY","1782ueLDLp","4496TJFZWc","1767765yPcVQJ","send","HefvS","elicitation/create","_onrequest","logging/setLevel","2.0","SoCaE","HucXo","function","request","initialize","push","dEmVs","addRequestListener","NYVNC","fgMSD","CSjwA","prompts/list","ping","35pZrnNj","onerror","method","238086YifXhM","get","sthgI","code","resources/subscribe","sttJM","transport","jsmFN","forward","listPrompts","resources/unsubscribe","resources/list","srIIC","originalOnResponse","getPrompt","indexOf","3653560KcjkMk","yfZbw","4SAWlvk","data","rCDHw","_onnotification","message","UlqiY","jsonrpc","yCyFn","clearNotificationListener","VWsxO","name","UynHf","length","QWYMz","fallbackRequestHandler","492jTClKn","1028589HsbHVQ"];return Ui=function(){return e},Ui()}const fE=(e,t)=>async r=>{var n,o,s,i,a,l;const c=Ge,u=Ge,f={};f.kSvAZ=c(465);const p=f;try{await((n=t?.[u(488)])==null?void 0:n[u(460)](r))}catch(h){const{code:g,message:v,data:_}=h;try{if(g){const w={};w.code=g,w.message=v,w.data=_;const y={};y.error=w,y[u(424)]=p.kSvAZ,y.id=r.id,await((o=e?.transport)==null?void 0:o.send(y))}else(i=(s=e?.transport)==null?void 0:s[c(480)])==null||i.call(s,h)}catch(w){(l=(a=e?.[c(488)])==null?void 0:a[u(480)])==null||l.call(a,w)}}},qu=()=>{const e=Ge,t={rgPZO:function(l,c){return l!==c},VWsxO:function(l,c){return l(c)},FjTAY:"function"},r=[],n=(l,c)=>{const u=Ge;if(c){const f=[];for(const p of r)try{f.push(p(l,c))}catch{}for(const p of f)if(t.rgPZO(p,null))return p}else for(const f of r)try{t[u(427)](f,l)}catch{}},o=l=>{const c=Ge,u=Ge;typeof l===t[c(456)]&&!r.includes(l)&&r[u(471)](l)},s=l=>{const c=Ge,u=r[c(415)](l);u!==-1&&r.splice(u,-17591+6*2932)},i=()=>{const l=Ge;r[l(430)]=-505*7+1322+2213},a={};return a.handleListener=n,a[e(447)]=o,a.removeListener=s,a.clearListener=i,a},hE=e=>{const t=Ge,r=Ge,n={UlqiY:function(o){return o()},jsmFN:function(o){return o()}};{const{handleListener:o,addListener:s,removeListener:i,clearListener:a}=n[t(423)](qu);e._onresponse=o,e[r(438)]=s,e.removeResponseListener=i,e.clearResponseListener=a}{const{handleListener:o,addListener:s,removeListener:i,clearListener:a}=n[t(489)](qu);e[t(432)]=o,e[r(473)]=s,e.removeRequestListener=i,e.clearRequestListener=a}{const{handleListener:o,addListener:s,removeListener:i,clearListener:a}=n.jsmFN(qu);e.fallbackNotificationHandler=o,e[t(444)]=s,e.removeNotificationListener=i,e[r(426)]=a}},mE=(e,{beforeInit:t,afterInit:r}={})=>{const n=Ge,o=Ge,s={HucXo:function(a,l){return a===l},HicFO:n(468),JMaxV:function(a){return a()},DclXr:function(a,l){return a(l)},UynHf:function(a,l){return a===l},yCyFn:function(a){return a()}},i=new Map(e._notificationHandlers);e[n(454)].clear(),e._notificationHandlers.clear(),s.HucXo(typeof t,s.HicFO)&&s[n(435)](t),s[n(467)](e[n(449)][o(428)],n(449))&&(e[o(413)]=e[o(449)]),s.DclXr(hE,e),e[o(438)](a=>{const l=n;e.originalOnResponse[l(440)](e,a)}),s[n(429)](typeof r,s.HicFO)&&s[o(425)](r),e[o(444)](a=>{const l=o,{method:c}=a,u=i[l(483)](c);s[l(467)](typeof u,"function")&&u(a)})},gE=Kr;(function(e,t){const r=Kr,n=Kr,o=e();for(;;)try{if(parseInt(r(215))/1*(-parseInt(n(217))/2)+parseInt(r(216))/3+parseInt(r(210))/4*(parseInt(n(223))/5)+-parseInt(n(214))/6*(parseInt(n(220))/7)+parseInt(n(212))/8*(parseInt(r(228))/9)+parseInt(r(219))/10+parseInt(r(222))/11*(parseInt(r(224))/12)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(zi,995159+-6*-266138+-1619768);const _E=()=>{const e=Kr,t=Kr,r={};r.svuxn=function(o,s){return o&s},r.ZUPdr=function(o,s){return o===s},r[e(227)]=function(o,s){return o===s},r.SpRzi="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";const n=r;return n[t(227)](typeof crypto,"object")&&crypto[e(211)]?crypto.randomUUID():n.SpRzi.replace(/[xy]/g,o=>{const s=e,i=n.svuxn(crypto.getRandomValues(new Uint8Array(-3798+8571*-1+12370))[0],-8324+8339*1);return(n[s(225)](o,"x")?i:n[s(209)](i,-12998+-1*-13001)|813*10+-3707+883*-5).toString(-1*-1851+6493+-8328)})},yE=e=>{const t=Kr,r=Kr,n=new Uint8Array(e);return crypto[t(221)](n),Array[r(218)](n,o=>o[r(226)](11424+4*-2852).padStart(8950+2237*-4,"0"))[t(213)]("")},mn={};mn[gE(211)]=_E,mn.randomBytes=yE;function Kr(e,t){const r=zi();return Kr=function(n,o){return n=n-(-7373+7187*1+395),r[n]},Kr(e,t)}function zi(){const e=["join","2500590yHdCUG","3CzpgOE","219762yRRBUK","592022JqIdxi","from","6033730pSHJFF","28gKZiuO","getRandomValues","147169GUBreL","5fFOMNB","1140KVOWlq","ZUPdr","toString","DBGzc","45351XtLuDF","svuxn","9892WpQPGF","randomUUID","2504EaskHQ"];return zi=function(){return e},zi()}function Yr(e,t){const r=Fi();return Yr=function(n,o){return n=n-(-1483*3+-5564+20*513),r[n]},Yr(e,t)}const xr=Yr,Is=Yr;(function(e,t){const r=Yr,n=Yr,o=e();for(;;)try{if(parseInt(r(302))/1+-parseInt(n(249))/2+-parseInt(r(291))/3+-parseInt(r(292))/4*(parseInt(r(264))/5)+-parseInt(n(273))/6*(parseInt(r(266))/7)+parseInt(r(300))/8*(parseInt(r(269))/9)+parseInt(n(255))/10*(parseInt(r(284))/11)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(Fi,-4*308317+753182*2+658196);const vE=(e,t)=>{const r=Yr,n=Yr,o={olCWX:function(l,c,u){return l(c,u)},sfXDX:function(l,c,u){return l(c,u)},ksWFu:function(l,c,u){return l(c,u)}};o[r(283)](cE,e,t),uE(e,t);const s=o[n(283)](dE,t,e),i=o[n(294)](fE,t,e),a=o[r(277)](pE,t,e);t.addRequestListener(s),t.addResponseListener(i),t[n(287)](a),e.onclose=()=>{const l=r,c=n;t[l(247)](s),t.removeResponseListener(i),t[c(252)](a)}},Lu=(e,t,r)=>{const n={QhPqi:function(i,a){return i instanceof a},AIICR:"close",Qalmc:function(i,a,l){return i(a,l)}},o=()=>{var i;n.QhPqi(r,Da)&&((i=r._eventSource)==null||i.addEventListener(n.AIICR,()=>{var a;(a=r[Yr(295)])==null||a.close()})),n.Qalmc(vE,e,t)},s={};s.afterInit=o,n.Qalmc(mE,t,s)},ky=(e,t=mn[xr(299)]())=>{const r=xr,n=xr,o={RVabx:function(u,f,p){return u(f,p)},crCTs:"include"},s={};s["sse-session-id"]=t;const i=s,a={};a["sse-session-id"]=t;const l={};l.headers=a,l.credentials=o[r(304)];const c={requestInit:l,eventSourceInit:{async fetch(u,f){const p=r,h=r,g=new Headers(f?.[p(268)]||{});Object.entries(i).forEach(([_,w])=>{g.set(_,w)});const v={...f};return v.headers=g,o[h(279)](fetch,u,v)},withCredentials:!0}};return e&&(c[r(280)].headers.Authorization="Bearer "+e,i.Authorization=n(256)+e),c},Ty=(e,t=mn[xr(299)]())=>{const r=Is,n=xr,o={};o[r(271)]="include";const s=o,i={};i["stream-session-id"]=t;const a={};a[n(268)]=i,a.credentials=s[r(271)];const l={};l.requestInit=a;const c=l;return e&&(c[n(280)][r(268)][n(301)]=r(256)+e),c},ju=async(e,t,r)=>{const n=xr,o=xr,s={rRtFD:function(a){return a()},ToRAF:function(a,l){return a instanceof l}},i=s[n(276)](r);try{return await e[o(260)](i),i}catch(a){if(s[n(275)](a,fr)){const l=await t();return await i[n(257)](l),await ju(e,t,r)}else throw a}},Cy=(e,t)=>{const r=Is,n=Is,o={};o[r(267)]=function(i,a){return i in a},o.timcZ="waitForOAuthCode",o[r(253)]=function(i,a){return i===a},o.ufiEQ=r(285),o[n(250)]=r(293);const s=o;if(s.oGmBG(s[r(258)],e))return e[n(278)];if(s[n(253)](typeof t,s.ufiEQ))return t;throw new Error(s.daYBw)};function Fi(){const e=["oGmBG","headers","1233BqDPfE","eventSourceInit","jmVYh","wfHUn","1336686qzpbXm","_endpoint","ToRAF","rRtFD","ksWFu","waitForOAuthCode","RVabx","requestInit","mcp-sse-proxy-client","CfBXU","olCWX","341WrxLOu","function","sessionId","addNotificationListener","version","GKDjq","roots","5390433vAXkON","4NpGpPF","waitForOAuthCode need to be provided when authProvider is provided","sfXDX","_eventSource","PdsSn","get","sampling","randomUUID","4064jocfPO","Authorization","452565rqIeHi","elicitation","crCTs","authProvider","removeRequestListener","1.0.0","104070FoHgyi","daYBw","capabilities","removeNotificationListener","lauIp","listChanged","1255910ovFXHu","Bearer ","finishAuth","timcZ","eZwNI","connect","JzpWy","tUMle","kdowC","379385gxVFVP","&token=","49TIzdXg"];return Fi=function(){return e},Fi()}const wE=async e=>{const t=Is,r=xr,n={GKDjq:function(S,j,O){return S(j,O)},JzpWy:t(281),mcbiU:"1.0.0",CfBXU:function(S){return S()},kdowC:function(S,j,O,L){return S(j,O,L)},KkViY:"sessionId"},{client:o,url:s,token:i,sessionId:a,authProvider:l,requestInit:c,eventSourceInit:u,waitForOAuthCode:f}=e,p={};p[r(305)]=l,p.requestInit=c,p.eventSourceInit=u;const h=p,g=a||mn[r(299)](),v=n[t(289)](ky,i,g);if(c){const S={...v.requestInit,...c};S[r(268)]={...v[r(280)][t(268)],...c.headers},h.requestInit=S}else h.requestInit=v[t(280)];if(u){const S={...v[t(270)],...u};h.eventSourceInit=S}else h.eventSourceInit=v[t(270)];const _={};_[t(254)]=!0;const w={};w.roots=_,w[t(298)]={},w[r(303)]={};const y=w,m={};m.name=n[r(261)],m[t(288)]=n.mcbiU;const C={};C[t(251)]=y;const b=new ji(m,C),T=()=>new Da(new URL(s),h);let I=n[t(282)](T);if(l){const S=Cy(l,f);I=await n[t(263)](ju,b,S,T)}else await b.connect(I);Lu(b,o,I),I.sessionId=I[r(274)].searchParams[t(297)](n.KkViY);const R={};return R.transport=I,R.sessionId=I[r(286)],R},bE=async e=>{const t=Is,r=xr,n={wfHUn:function(S,j,O){return S(j,O)},tUMle:"mcp-stream-proxy-client",omKPe:t(248),rSiEq:function(S){return S()},PdsSn:function(S,j,O,L){return S(j,O,L)}},{client:o,url:s,token:i,sessionId:a,authProvider:l,requestInit:c,reconnectionOptions:u,waitForOAuthCode:f}=e,p={};p.authProvider=l,p.requestInit=c,p.reconnectionOptions=u;const h=p,g=a||mn.randomUUID(),v=n[r(272)](Ty,i,g);if(c){const S={...v[t(280)],...c};S.headers={...v.requestInit[t(268)],...c.headers},h.requestInit=S}else h[r(280)]=v[r(280)];const _={};_[r(254)]=!0;const w={};w.roots=_,w[t(298)]={},w[t(303)]={};const y=w,m={};m.name=n[t(262)],m.version=n.omKPe;const C={};C.capabilities=y;const b=new ji(m,C),T=()=>new Aa(new URL(s),h);let I=n.rSiEq(T);if(l){const S=n[t(272)](Cy,l,f);I=await n[t(296)](ju,b,S,T)}else await b[t(260)](I);n.PdsSn(Lu,b,o,I);const R={};return R.transport=I,R[r(286)]=I[r(286)],R},kE=async e=>{const t=xr,r=xr,n={eZwNI:function(w,y,m,C){return w(y,m,C)}},{client:o,url:s,token:i,sessionId:a}=e,l={};l[t(254)]=!0;const c={};c[r(290)]=l,c.sampling={},c.elicitation={};const u=c,f={};f.name="mcp-socket-proxy-client",f.version=r(248);const p={};p[r(251)]=u;const h=new ji(f,p),g=a||mn[r(299)](),v=new wy(new URL(s+"?sessionId="+g+r(265)+i));await h.connect(v),n[t(259)](Lu,h,o,v);const _={};return _.transport=v,_[r(286)]=g,_},gn=Er,xs=Er;(function(e,t){const r=Er,n=Er,o=e();for(;;)try{if(parseInt(r(216))/1+-parseInt(n(219))/2+-parseInt(r(203))/3*(-parseInt(n(204))/4)+-parseInt(n(199))/5*(parseInt(r(193))/6)+-parseInt(r(211))/7*(-parseInt(r(192))/8)+-parseInt(n(221))/9+parseInt(n(201))/10*(parseInt(r(220))/11)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(Vi,1297719+-42747*-22+-1289197);function Er(e,t){const r=Vi();return Er=function(n,o){return n=n-(-4158*1+-2*581+-1*-5510),r[n]},Er(e,t)}const TE=()=>mn.randomBytes(-8746+-382*-23);class S${constructor(t){const r=Er,n=Er,o={HbwOh:function(u){return u()}};this._callBackPromise={};const{clientMetadata:s,state:i,redirectCallback:a,getAuthCodeByState:l,waitForOAuthCode:c}=t;this._clientMetadata=s,this[r(206)]=s.redirect_uris[-10*629+1*7646+-1356],this[n(197)]=i||o.HbwOh(TE),this._redirectCallback=a||this[n(202)],this[n(195)]=l||this[r(191)],this.waitForOAuthCode=c||this.waitForOAuthCodeFunction()}async redirectCallbackFunction(t){var r,n,o,s,i,a;const l=Er,c=Er,u={};u[l(198)]="GET";const f=await fetch(t,u);!f.ok&&((n=(r=this[c(207)])[c(196)])==null||n.call(r,l(208)+f[c(205)]));const p=await this[c(195)](this._redirectUrl,this[l(197)]);if(!p.ok){(s=(o=this[l(207)]).reject)==null||s.call(o,"Failed to fetch auth code: "+p[c(205)]);return}const h=await p.json();(a=(i=this._callBackPromise).resolve)==null||a.call(i,h.code)}async[gn(191)](t,r){const n=gn,o={};o.xAOmI="POST";const s=o,i={};i["Content-Type"]=n(217);const a={};return a.state=r,fetch(t,{method:s.xAOmI,headers:i,body:new URLSearchParams(a)})}waitForOAuthCodeFunction(){const t=this._callBackPromise;return()=>new Promise((r,n)=>{const o=Er;t.resolve=r,t[o(196)]=n})}get redirectUrl(){return this[gn(206)]}get[xs(190)](){return this._clientMetadata}[gn(213)](){return this[gn(197)]}[xs(218)](){return this[xs(200)]}[gn(194)](t){this._clientInformation=t}tokens(){return this[xs(210)]}saveTokens(t){const r=xs;this[r(210)]=t}redirectToAuthorization(t){this._redirectCallback(t)}saveCodeVerifier(t){this._codeVerifier=t}[gn(212)](){const t=gn,r={};r[t(215)]=t(214);const n=r;if(!this[t(209)])throw new Error(n.mMdVl);return this[t(209)]}}function Vi(){const e=["370aKMzOb","redirectCallbackFunction","6AWGiLu","697420WEpDtk","statusText","_redirectUrl","_callBackPromise","Failed to redirect: ","_codeVerifier","_tokens","21ofrYNd","codeVerifier","state","No code verifier saved","mMdVl","1546908KURscU","application/x-www-form-urlencoded","clientInformation","2551694UzDoIS","571637jVsNJQ","4355271orhxAD","clientMetadata","getAuthCodeByStateFunction","1400360ybYjeP","30zRTJNb","saveClientInformation","_getAuthCodeByState","reject","_state","method","1634810cQPomO","_clientInformation"];return Vi=function(){return e},Vi()}(function(e,t){for(var r=Bi,n=Bi,o=e();;)try{var s=parseInt(r(291))/1+-parseInt(r(295))/2*(parseInt(r(288))/3)+parseInt(r(290))/4*(parseInt(r(296))/5)+-parseInt(n(289))/6+parseInt(r(293))/7*(-parseInt(n(294))/8)+parseInt(n(287))/9+parseInt(n(292))/10;if(s===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(Zi,262*-2438+1346066*-1+2*1373311);function Zi(){var e=["279100FsqxFu","7326315yxcNFg","50823VTWXXj","6441948uoPUwt","92BSiBRu","1361711dyawqa","5202960gnlAWp","7tNVFlv","11056792usEcvw","90CRWXmt"];return Zi=function(){return e},Zi()}function Bi(e,t){var r=Zi();return Bi=function(n,o){n=n-287;var s=r[n];return s},Bi(e,t)}const CE=e=>{const t=()=>typeof navigator>"u"?null:navigator.modelContextTesting||null;e.onmessage=async r=>{if(!r||typeof r!="object")return;const n=r.id,o=r.method;try{if(o==="initialize")await e.send({jsonrpc:"2.0",id:n,result:{protocolVersion:"2024-11-05",capabilities:{tools:{listChanged:!0},logging:{}},serverInfo:{name:"browser-builtin-webmcp-proxy",version:"1.0.0"}}});else if(o!=="notifications/initialized")if(o==="ping"||o==="custom_ping")await e.send({jsonrpc:"2.0",id:n,result:{}});else if(o==="tools/list"){const s=t();if(s&&s.listTools){const a=(await s.listTools()).map(l=>{let c={};if(typeof l.inputSchema=="string")try{c=JSON.parse(l.inputSchema)}catch(u){console.error("Failed to parse inputSchema:",u)}else typeof l.inputSchema=="object"&&l.inputSchema!==null&&(c=l.inputSchema);return{name:l.name,description:l.description||"",inputSchema:{type:"object",properties:c.properties||{},required:c.required||[]}}});await e.send({jsonrpc:"2.0",id:n,result:{tools:a}})}else await e.send({jsonrpc:"2.0",id:n,result:{tools:[]}})}else if(o==="tools/call"){const s=t();if(s&&s.executeTool){if(!r.params||typeof r.params!="object"||!r.params.name){const u=new Error('Invalid params: "name" is required and params must be an object');throw u.code=-32602,u}const{name:i,arguments:a}=r.params,l=await s.executeTool(i,JSON.stringify(a||{})),c=l&&typeof l=="object"&&"content"in l?l:{content:[{type:"text",text:typeof l=="string"?l:JSON.stringify(l)}]};await e.send({jsonrpc:"2.0",id:n,result:c})}else{const i=new Error("executeTool not implemented in Browser built-in WebMCP");throw i.code=-32601,i}}else o==="logging/setLevel"?await e.send({jsonrpc:"2.0",id:n,result:{}}):o==="prompts/list"?await e.send({jsonrpc:"2.0",id:n,result:{prompts:[]}}):o==="resources/list"?await e.send({jsonrpc:"2.0",id:n,result:{resources:[]}}):n!==void 0&&await e.send({jsonrpc:"2.0",id:n,error:{code:-32601,message:`Method not found: ${o}`}})}catch(s){n!==void 0&&await e.send({jsonrpc:"2.0",id:n,error:{code:s.code||-32e3,message:s.message||String(s)}})}}};class SE{constructor(t,r){const n={name:"web-mcp-client",version:"1.0.0"},o={roots:{listChanged:!0},sampling:{},elicitation:{}};this.client=new ji(t||n,r||{capabilities:o}),this.client.onclose=()=>{this.onclose?.()},this.client.onerror=s=>{this.onerror?.(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:r,token:n,sessionId:o,type:s,agent:i,builtin:a,onError:l}=t;if(i){const f={client:this.client,url:r,token:n,sessionId:o},p=s==="sse"?await wE(f):s==="socket"?await kE(f):await bE(f);return p.transport.onerror=async h=>{l?.(h)},a&&CE(p.transport),p}const c=new URL(r);let u;if(s==="channel"&&(u=new aE(r),await this.client.connect(u)),s==="sse"){const f=ky(n,o);u=new Da(c,f),await this.client.connect(u)}if(s==="socket"&&(u=new wy(new URL(`${r}?sessionId=${o}&token=${n}`)),u.sessionId=o,await this.client.connect(u)),s==="stream"||typeof u>"u"){const f=Ty(n,o);u=new Aa(c,f),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(t){return await this.client.ping(t)}async complete(t,r){return await this.client.complete(t,r)}async setLoggingLevel(t,r){return await this.client.setLoggingLevel(t,r)}async getPrompt(t,r){return await this.client.getPrompt(t,r)}async listPrompts(t,r){return await this.client.listPrompts(t,r)}async listResources(t,r){return await this.client.listResources(t,r)}async listResourceTemplates(t,r){return await this.client.listResourceTemplates(t,r)}async readResource(t,r){return await this.client.readResource(t,r)}async subscribeResource(t,r){return await this.client.subscribeResource(t,r)}async unsubscribeResource(t,r){return await this.client.unsubscribeResource(t,r)}async callTool(t,r){return await this.client.callTool(t,hs,r)}async listTools(t,r){return await this.client.listTools(t,r)}async sendRootsListChanged(){return await this.client.sendRootsListChanged()}request(t,r,n){return this.client.request(t,r,n)}async notification(t,r){return await this.client.notification(t,r)}setRequestHandler(t,r){this.client.setRequestHandler(t,r)}removeRequestHandler(t){this.client.removeRequestHandler(t)}setNotificationHandler(t,r){this.client.setNotificationHandler(t,r)}removeNotificationHandler(t){this.client.removeNotificationHandler(t)}onElicit(t){this.client.setRequestHandler(qc,t)}onCreateMessage(t){this.client.setRequestHandler(Oc,t)}onListRoots(t){this.client.setRequestHandler(_2,t)}onToolListChanged(t){this.client.setNotificationHandler(Nc,t)}onPromptListChanged(t){this.client.setNotificationHandler(Mc,t)}onResourceListChanged(t){this.client.setNotificationHandler(xc,t)}onResourceUpdated(t){this.client.setNotificationHandler(l2,t)}onLoggingMessage(t){this.client.setNotificationHandler(h2,t)}async onPagehide(t){t.persisted||(IE(this.transport)?await this.transport.terminateSession():this.transport&&typeof this.transport.close=="function"&&await this.transport.close())}}const IE=e=>e instanceof Aa,Sy=async e=>{const t={};try{const r=await e.listTools();for(const{name:n,description:o,inputSchema:s}of r.tools){const i=async(a,l)=>e.callTool({name:n,arguments:a},{signal:l?.abortSignal});t[n]=Rl({description:o,inputSchema:Pn({...s,properties:s.properties??{},additionalProperties:!1}),execute:i})}return t}catch(r){throw r}},xE=async e=>{const t={};if(!e)return t;const r=e,n=r.listTools??r.getTools;if(!n)return t;const o=await n.call(r),s=Array.isArray(o)?o:[];for(const i of s){const{name:a,description:l}=i,c=i.inputSchema;let u={};if(typeof c=="string")try{u=JSON.parse(c)}catch(p){console.error("Failed to parse inputSchema in getBuiltinMcpTools:",p)}else typeof c=="object"&&c!==null&&(u=c);const f={type:"object",properties:u.properties??{},...u.required?{required:u.required}:{},additionalProperties:!1,...u};t[a]=Rl({description:l??"",inputSchema:Pn(f),async execute(p){if(!r.executeTool)throw new Error("navigator.modelContextTesting.executeTool is not available");return r.executeTool(a,JSON.stringify(p??{}))}})}return t};function EE(e){const t=Object.entries(e);if(t.length===0)return"";let r=`
88
- # 工具调用
89
-
90
- 你可以根据需要调用以下工具:
91
-
92
- <tools>
93
- `;return t.forEach(([n,o])=>{const s=o,i=s.description||"无描述",a=s.parameters||s.inputSchema||{};r+=`${JSON.stringify({name:n,description:i,parameters:a},null,2)}
94
- `}),r+=`
95
- </tools>
96
-
97
- ## 工具调用格式
98
-
99
- 要调用工具,请使用以下 XML 格式:
100
- Thought: [你的思考过程]
101
- <tool_call>
102
- {"name": "toolName", "arguments": {"arg1": "value1"}}
103
- </tool_call>
104
-
105
- 工具执行后,你将收到 <tool_response> 格式的结果。你可以继续思考或调用其他工具。
106
-
107
- ## 使用示例
108
-
109
- 如果用户要求"获取今天的日期",你可以这样调用工具:
110
- Thought: 用户想要获取今天的日期,我需要调用日期相关的工具。
111
- <tool_call>{"name": "get-today", "arguments": {}}</tool_call>
112
-
113
- 然后等待工具返回结果(Observation),再根据结果给出最终答案。
114
-
115
- ## 任务完成
116
-
117
- 当任务完成或无法继续时,直接给出最终答案即可。
118
-
119
- **重要提示**:
120
- - 必须严格按照 XML 格式调用工具
121
- - arguments 必须是有效的 JSON 格式
122
- - 如果不需要调用工具,直接给出最终答案即可
123
- `,r}function Iy(e,t){if(!e||typeof e!="string")return null;const r=e.match(/<tool_call>([\s\S]*?)<\/tool_call>/i);if(r)try{const n=r[1].trim(),o=JSON.parse(n),s=o.name||o.action||o.tool,i=o.arguments||o.args||o.input||{};if(s&&t[s])return{toolName:s,arguments:i}}catch{}return null}const $E={openai:Q2,deepseek:Bg};class RE{constructor({llmConfig:t,mcpServers:r}){if(this.mcpServers={},this.mcpClients={},this.mcpTools={},this.ignoreToolnames=[],this.responseMessages=[],this.useReActMode=!1,!t)throw new Error("llmConfig is required to initialize AgentModelProvider");if(this.mcpServers=r||{},this.mcpClients={},this.mcpTools={},t.llm)this.llm=t.llm;else if(t.providerType){const n=t.providerType;let o;typeof n=="string"?o=$E[n]:o=n,this.llm=o({apiKey:t.apiKey,baseURL:t.baseURL})}else throw new Error("Either llmConfig.llm or llmConfig.providerType must be provided");this.useReActMode=t.useReActMode??!1}async _createOneClient(t){try{let r;if("type"in t&&t.type==="builtin"){const o=t.client;return{tools:()=>xE(o),close:async()=>{}}}if("type"in t&&t.type.toLocaleLowerCase()==="streamablehttp"){const o=t,s=o.headers?{headers:o.headers}:void 0;r=new Aa(new URL(o.url),{requestInit:s})}else if("type"in t&&t.type==="sse"){const o=t,s=o.headers?{headers:o.headers}:void 0;r=new Da(new URL(o.url),{requestInit:s})}else"type"in t&&t.type==="extension"?r=new Jx(t.sessionId):"transport"in t?r=t.transport:r=t;if(t.useAISdkClient??!1){const o=await sC({transport:r});return o.__transport__=r,o}else{const o=new SE({name:"mcp-web-client",version:"1.0.0"},{capabilities:{roots:{listChanged:!0},sampling:{},elicitation:{}}});return await o.connect(r),o.__transport__=r,o}}catch(r){return this.onError&&this.onError(r?.message||"Failed to create MCP client",r),console.error("Failed to create MCP client",t,r),null}}async _closeOneClient(t){try{const r=t.__transport__;if(r&&r instanceof Ua||r&&r instanceof by)return;await r?.terminateSession?.(),await r?.close?.(),await t?.close?.()}catch{}}async _createMpcClients(){const t=Object.entries(this.mcpServers),r=await Promise.all(t.map(async([n,o])=>{const s=await this._createOneClient(o);return{serverName:n,client:s}}));this.mcpClients={},r.forEach(({serverName:n,client:o})=>{this.mcpClients[n]=o})}async _getClientTools(t,r){if(!t)return null;try{return typeof t.tools=="function"?await t.tools():await Sy(t)}catch(n){return this.onError&&this.onError(n?.message||`Failed to query tools for ${r}`,n),console.error(`Failed to query tools for ${r}`,n),null}}async _createMpcTools(){const t=Object.entries(this.mcpClients),r=await Promise.all(t.map(async([n,o])=>{const s=await this._getClientTools(o,n);return{serverName:n,tools:s}}));this.mcpTools={},r.forEach(({serverName:n,tools:o})=>{const s=o&&typeof o=="object"?o:{};this.mcpTools[n]=s})}async closeAll(){await Promise.all(Object.values(this.mcpClients).map(async t=>{try{await this._closeOneClient(t)}catch(r){this.onError&&this.onError(r?.message||"Failed to close client",r),console.error("Failed to close client",r)}}))}async initClientsAndTools(){await this._createMpcClients(),await this._createMpcTools(),this.onUpdatedTools?.()}async refreshTools(){await this._createMpcTools(),this.onUpdatedTools?.()}async updateMcpServers(t){await this.closeAll(),this.mcpServers=t||this.mcpServers,await this.initClientsAndTools()}async insertMcpServer(t,r){if(this.mcpServers[t])return!1;const n=await this._createOneClient(r);if(!n)return this.onError?.(`Failed to create MCP client: ${t}`),null;this.mcpClients[t]=n;const o=await this._getClientTools(n,t);return this.mcpTools[t]=o&&typeof o=="object"?o:{},this.mcpServers[t]=r,this.onUpdatedTools?.(),n}async removeMcpServer(t){if(!this.mcpServers[t])return;delete this.mcpServers[t];const r=this.mcpClients[t];delete this.mcpClients[t];try{await this._closeOneClient(r)}catch{}const n=this.mcpTools[t];delete this.mcpTools[t],n&&Object.keys(n).forEach(o=>{this.ignoreToolnames=this.ignoreToolnames.filter(s=>s!==o)}),this.onUpdatedTools?.()}_tempMergeTools(t={},r=!0){const n=Object.values(this.mcpTools).reduce((o,s)=>({...o,...s}),{});return Object.assign(n,t),r&&this.ignoreToolnames.forEach(o=>{delete n[o]}),n}_getActiveToolNames(t){return Object.keys(t).filter(r=>!this.ignoreToolnames.includes(r))}_generateReActSystemPrompt(t,r,n){const o=EE(t);return n?`${n}${o}`:`你是一个智能助手,可以通过调用工具来完成任务。
124
- ${o}`}async _executeReActToolCall(t,r,n){const o=n[t];if(!o)return{success:!1,error:`工具 ${t} 不存在`};try{const s=o,i=s.execute||s.call;return typeof i!="function"?{success:!1,error:`工具 ${t} 没有可执行的函数`}:{success:!0,result:await i(r,{})}}catch(s){return{success:!1,error:s?.message||String(s)||"工具执行失败"}}}async _chatReAct(t,{model:r,maxSteps:n=5,...o}){if(!this.llm)throw new Error("LLM is not initialized");await this.initClientsAndTools();const s=this._tempMergeTools(o.tools);if(Object.keys(s).length===0)return this._chat(t,{model:r,maxSteps:n,...o});let a=[];o.message&&!o.messages?a.push({role:"user",content:o.message}):o.messages?a=[...o.messages]:a=[...this.responseMessages];const l=typeof r=="string"?r:r?.modelId||"default-model",u={role:"system",content:this._generateReActSystemPrompt(s,l,o.system)},f=a[0]?.role==="system"?a:[u,...a];return t===sc?this._chatReActStream(f,s,l,n,o):this._chatReActNonStream(f,s,l,n,o)}_messageHasImage(t){return t&&Array.isArray(t)?t.some(r=>r&&r.type==="image"):!1}_removeImageFromMessage(t){if(!t||!t.content)return null;if(!Array.isArray(t.content))return t;const r=t.content.filter(n=>n&&n.type!=="image");return r.length===0?null:{...t,content:r}}_buildMessagesForModel(t,r,n=3){const o=[];t&&o.push(t);let s=0;const i=[];for(let a=r.length-1;a>=0;a--){const l=r[a];if(this._messageHasImage(l.content))if(s<n)i.unshift(l),s++;else{const u=this._removeImageFromMessage(l);u&&i.unshift(u)}else i.unshift(l)}return o.push(...i),o}async _chatReActNonStream(t,r,n,o,s){let i=[...t];const a=t[0]?.role==="system"?t[0]:null,l=a?t.slice(1):t;let c=0;const u=s.maxImages??3;for(;c<o;){c++;const p=this._buildMessagesForModel(a,l,u),{tools:h,...g}=s,_=(await mm({model:this.llm(n),messages:p,...g})).text,w={role:"assistant",content:_};l.push(w),i.push(w);const y=Iy(_,r);if(!y)return this.responseMessages=i,{text:_,response:{messages:i}};const m=await this._executeReActToolCall(y.toolName,y.arguments,r),T={role:"user",content:`<tool_response>
125
- ${m.success?JSON.stringify(m.result):`工具执行失败 - ${m.error}`}
126
- </tool_response>`};l.push(T),i.push(T)}return this.responseMessages=i,{text:i[i.length-2]?.content||"",response:{messages:i}}}_chatReActStream(t,r,n,o,s){const i=this,a=this.llm(n);let l,c;const u=new Promise((p,h)=>{l=p,c=h});return{fullStream:new ReadableStream({async start(p){let h=[...t];const g=t[0]?.role==="system"?t[0]:null,v=g?t.slice(1):[...t];let _=0,w="";const y=s.maxImages??3;p.enqueue({type:"start"}),p.enqueue({type:"start-step"});try{for(;_<o;){_++;const m=i._buildMessagesForModel(g,v,y),{tools:C,...b}=s;delete b.system,delete b.onFinish;const T=await sc({...b,model:a,messages:m});let I="";for await(const ee of T.fullStream)ee.type==="text-delta"?(I+=ee.text||"",p.enqueue({type:"text-delta",text:ee.text})):ee.type==="text-start"?p.enqueue({type:"text-start"}):ee.type==="text-end"||ee.type==="finish-step"||ee.type==="finish"||ee.type==="start"||ee.type==="start-step"||p.enqueue(ee);w+=I;const R={role:"assistant",content:w};v.push(R),h.push(R);const S=Iy(w,r);if(!S){p.enqueue({type:"text-end"}),p.enqueue({type:"finish-step"}),p.enqueue({type:"finish"}),p.close(),i.responseMessages=h,l({messages:h});return}if(S.toolName==="computer"&&S.arguments?.action==="terminate"){p.enqueue({type:"text-end"}),p.enqueue({type:"finish-step"}),p.enqueue({type:"finish"}),p.close(),i.responseMessages=h,l({messages:h});return}const j=`react-${Date.now()}`;p.enqueue({type:"tool-input-start",id:j,toolName:S.toolName});const O=JSON.stringify(S.arguments,null,2);p.enqueue({type:"tool-input-delta",id:j,delta:O}),p.enqueue({type:"tool-input-end",id:j}),p.enqueue({type:"tool-call",toolCallId:j,toolName:S.toolName,input:S.arguments});const L=await i._executeReActToolCall(S.toolName,S.arguments,r);let z,B=L.result;if(L.success&&L.result&&typeof L.result=="object"&&L.result.screenshot){z=L.result.screenshot;const{screenshot:ee,...Q}=L.result;B=Q}let X="";if(L.success){B&&Array.isArray(B.content)&&B.content.length>0&&B.content[0].text?X=B.content[0].text:X=JSON.stringify(B);let ee=`<tool_response>
127
- ${X}
128
- </tool_response>`;z&&(ee+=`
129
- 请检查截图以确认操作是否成功。如果成功,请继续下一步;如果失败,请重试。`),p.enqueue({type:"tool-result",toolCallId:j,result:ee});const Q=z?{role:"user",content:[{type:"text",text:ee},{type:"image",image:z}]}:{role:"user",content:ee};v.push(Q),h.push(Q),w=""}else X=`工具执行失败 - ${L.error}`,p.enqueue({type:"tool-error",toolCallId:j,input:S.arguments,error:{message:X}})}p.enqueue({type:"text-end"}),p.enqueue({type:"finish-step"}),p.enqueue({type:"finish"}),p.close(),i.responseMessages=h,l({messages:h})}catch(m){p.error(m),c(m)}}}),response:u}}async _chat(t,{model:r,maxSteps:n=5,...o}){if(this.useReActMode)return this._chatReAct(t,{model:r,maxSteps:n,...o});if(!this.llm)throw new Error("LLM is not initialized");await this.initClientsAndTools();const s=o.tools||{},i=this._tempMergeTools(s,!1),a=()=>{const h=this._tempMergeTools(s,!1);Object.entries(h).forEach(([g,v])=>{i[g]=v}),Object.keys(i).forEach(g=>{g in h||delete i[g]})},l=o.prepareStep,c=async h=>{a();const g=this._getActiveToolNames(i),v=typeof l=="function"?await l(h):void 0,_=v&&typeof v=="object"?v:{};return{..._,activeTools:Array.isArray(_.activeTools)?_.activeTools.filter(w=>g.includes(w)):g}},u={model:this.llm(r),stopWhen:rc(n),...o,tools:i,prepareStep:c,activeTools:this._getActiveToolNames(i)};let f=null;if(o.message&&!o.messages)f={role:"user",content:o.message},this.responseMessages.push(f),u.messages=[...this.responseMessages];else if(o.messages&&o.messages.length>0){const h=o.messages[o.messages.length-1];h.role==="user"&&(f=h)}const p=t(u);return p?.response?.then(h=>{const g=h.messages?.[0];f&&g?.role!=="user"&&this.responseMessages.push(f),this.responseMessages.push(...h.messages)}),p}async chat(t){return this._chat(mm,t)}async chatStream(t){return this._chat(sc,t)}}var Co={},Du,xy;function PE(){return xy||(xy=1,Du=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),Du}var Uu={},_n={},Ey;function Jn(){if(Ey)return _n;Ey=1;let e;const t=[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];return _n.getSymbolSize=function(n){if(!n)throw new Error('"version" cannot be null or undefined');if(n<1||n>40)throw new Error('"version" should be in range from 1 to 40');return n*4+17},_n.getSymbolTotalCodewords=function(n){return t[n]},_n.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},_n.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');e=n},_n.isKanjiModeEnabled=function(){return typeof e<"u"},_n.toSJIS=function(n){return e(n)},_n}var zu={},$y;function Fu(){return $y||($y=1,(function(e){e.L={bit:1},e.M={bit:0},e.Q={bit:3},e.H={bit:2};function t(r){if(typeof r!="string")throw new Error("Param is not a string");switch(r.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: "+r)}}e.isValid=function(n){return n&&typeof n.bit<"u"&&n.bit>=0&&n.bit<4},e.from=function(n,o){if(e.isValid(n))return n;try{return t(n)}catch{return o}}})(zu)),zu}var Vu,Ry;function ME(){if(Ry)return Vu;Ry=1;function e(){this.buffer=[],this.length=0}return e.prototype={get:function(t){const r=Math.floor(t/8);return(this.buffer[r]>>>7-t%8&1)===1},put:function(t,r){for(let n=0;n<r;n++)this.putBit((t>>>r-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){const r=Math.floor(this.length/8);this.buffer.length<=r&&this.buffer.push(0),t&&(this.buffer[r]|=128>>>this.length%8),this.length++}},Vu=e,Vu}var Zu,Py;function NE(){if(Py)return Zu;Py=1;function e(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)}return e.prototype.set=function(t,r,n,o){const s=t*this.size+r;this.data[s]=n,o&&(this.reservedBit[s]=!0)},e.prototype.get=function(t,r){return this.data[t*this.size+r]},e.prototype.xor=function(t,r,n){this.data[t*this.size+r]^=n},e.prototype.isReserved=function(t,r){return this.reservedBit[t*this.size+r]},Zu=e,Zu}var Bu={},My;function OE(){return My||(My=1,(function(e){const t=Jn().getSymbolSize;e.getRowColCoords=function(n){if(n===1)return[];const o=Math.floor(n/7)+2,s=t(n),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(n){const o=[],s=e.getRowColCoords(n),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}})(Bu)),Bu}var Hu={},Ny;function AE(){if(Ny)return Hu;Ny=1;const e=Jn().getSymbolSize,t=7;return Hu.getPositions=function(n){const o=e(n);return[[0,0],[o-t,0],[0,o-t]]},Hu}var Ju={},Oy;function qE(){return Oy||(Oy=1,(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 f=0;f<s;f++){a=l=0,c=u=null;for(let p=0;p<s;p++){let h=o.get(f,p);h===c?a++:(a>=5&&(i+=t.N1+(a-5)),c=h,a=1),h=o.get(p,f),h===u?l++:(l>=5&&(i+=t.N1+(l-5)),u=h,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 r(n,o,s){switch(n){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:"+n)}}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,r(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}})(Ju)),Ju}var Hi={},Ay;function qy(){if(Ay)return Hi;Ay=1;const e=Fu(),t=[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],r=[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];return Hi.getBlocksCount=function(o,s){switch(s){case e.L:return t[(o-1)*4+0];case e.M:return t[(o-1)*4+1];case e.Q:return t[(o-1)*4+2];case e.H:return t[(o-1)*4+3];default:return}},Hi.getTotalCodewordsCount=function(o,s){switch(s){case e.L:return r[(o-1)*4+0];case e.M:return r[(o-1)*4+1];case e.Q:return r[(o-1)*4+2];case e.H:return r[(o-1)*4+3];default:return}},Hi}var Gu={},Es={},Ly;function LE(){if(Ly)return Es;Ly=1;const e=new Uint8Array(512),t=new Uint8Array(256);return(function(){let n=1;for(let o=0;o<255;o++)e[o]=n,t[n]=o,n<<=1,n&256&&(n^=285);for(let o=255;o<512;o++)e[o]=e[o-255]})(),Es.log=function(n){if(n<1)throw new Error("log("+n+")");return t[n]},Es.exp=function(n){return e[n]},Es.mul=function(n,o){return n===0||o===0?0:e[t[n]+t[o]]},Es}var jy;function jE(){return jy||(jy=1,(function(e){const t=LE();e.mul=function(n,o){const s=new Uint8Array(n.length+o.length-1);for(let i=0;i<n.length;i++)for(let a=0;a<o.length;a++)s[i+a]^=t.mul(n[i],o[a]);return s},e.mod=function(n,o){let s=new Uint8Array(n);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(n){let o=new Uint8Array([1]);for(let s=0;s<n;s++)o=e.mul(o,new Uint8Array([1,t.exp(s)]));return o}})(Gu)),Gu}var Wu,Dy;function DE(){if(Dy)return Wu;Dy=1;const e=jE();function t(r){this.genPoly=void 0,this.degree=r,this.degree&&this.initialize(this.degree)}return t.prototype.initialize=function(n){this.degree=n,this.genPoly=e.generateECPolynomial(this.degree)},t.prototype.encode=function(n){if(!this.genPoly)throw new Error("Encoder not initialized");const o=new Uint8Array(n.length+this.degree);o.set(n);const s=e.mod(o,this.genPoly),i=this.degree-s.length;if(i>0){const a=new Uint8Array(this.degree);return a.set(s,i),a}return s},Wu=t,Wu}var Ku={},Yu={},Qu={},Uy;function zy(){return Uy||(Uy=1,Qu.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),Qu}var Lr={},Fy;function Vy(){if(Fy)return Lr;Fy=1;const e="[0-9]+",t="[A-Z $%*+\\-./:]+";let r="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";r=r.replace(/u/g,"\\u");const n="(?:(?![A-Z0-9 $%*+\\-./:]|"+r+`)(?:.|[\r
130
- ]))+`;Lr.KANJI=new RegExp(r,"g"),Lr.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),Lr.BYTE=new RegExp(n,"g"),Lr.NUMERIC=new RegExp(e,"g"),Lr.ALPHANUMERIC=new RegExp(t,"g");const o=new RegExp("^"+r+"$"),s=new RegExp("^"+e+"$"),i=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return Lr.testKanji=function(l){return o.test(l)},Lr.testNumeric=function(l){return s.test(l)},Lr.testAlphanumeric=function(l){return i.test(l)},Lr}var Zy;function Gn(){return Zy||(Zy=1,(function(e){const t=zy(),r=Vy();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 r.testNumeric(s)?e.NUMERIC:r.testAlphanumeric(s)?e.ALPHANUMERIC:r.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 n(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 n(s)}catch{return i}}})(Yu)),Yu}var By;function UE(){return By||(By=1,(function(e){const t=Jn(),r=qy(),n=Fu(),o=Gn(),s=zy(),i=7973,a=t.getBCHDigit(i);function l(p,h,g){for(let v=1;v<=40;v++)if(h<=e.getCapacity(v,g,p))return v}function c(p,h){return o.getCharCountIndicator(p,h)+4}function u(p,h){let g=0;return p.forEach(function(v){const _=c(v.mode,h);g+=_+v.getBitsLength()}),g}function f(p,h){for(let g=1;g<=40;g++)if(u(p,g)<=e.getCapacity(g,h,o.MIXED))return g}e.from=function(h,g){return s.isValid(h)?parseInt(h,10):g},e.getCapacity=function(h,g,v){if(!s.isValid(h))throw new Error("Invalid QR Code version");typeof v>"u"&&(v=o.BYTE);const _=t.getSymbolTotalCodewords(h),w=r.getTotalCodewordsCount(h,g),y=(_-w)*8;if(v===o.MIXED)return y;const m=y-c(v,h);switch(v){case o.NUMERIC:return Math.floor(m/10*3);case o.ALPHANUMERIC:return Math.floor(m/11*2);case o.KANJI:return Math.floor(m/13);case o.BYTE:default:return Math.floor(m/8)}},e.getBestVersionForData=function(h,g){let v;const _=n.from(g,n.M);if(Array.isArray(h)){if(h.length>1)return f(h,_);if(h.length===0)return 1;v=h[0]}else v=h;return l(v.mode,v.getLength(),_)},e.getEncodedBits=function(h){if(!s.isValid(h)||h<7)throw new Error("Invalid QR Code version");let g=h<<12;for(;t.getBCHDigit(g)-a>=0;)g^=i<<t.getBCHDigit(g)-a;return h<<12|g}})(Ku)),Ku}var Xu={},Hy;function zE(){if(Hy)return Xu;Hy=1;const e=Jn(),t=1335,r=21522,n=e.getBCHDigit(t);return Xu.getEncodedBits=function(s,i){const a=s.bit<<3|i;let l=a<<10;for(;e.getBCHDigit(l)-n>=0;)l^=t<<e.getBCHDigit(l)-n;return(a<<10|l)^r},Xu}var ed={},td,Jy;function FE(){if(Jy)return td;Jy=1;const e=Gn();function t(r){this.mode=e.NUMERIC,this.data=r.toString()}return t.getBitsLength=function(n){return 10*Math.floor(n/3)+(n%3?n%3*3+1:0)},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(n){let o,s,i;for(o=0;o+3<=this.data.length;o+=3)s=this.data.substr(o,3),i=parseInt(s,10),n.put(i,10);const a=this.data.length-o;a>0&&(s=this.data.substr(o),i=parseInt(s,10),n.put(i,a*3+1))},td=t,td}var rd,Gy;function VE(){if(Gy)return rd;Gy=1;const e=Gn(),t=["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 r(n){this.mode=e.ALPHANUMERIC,this.data=n}return r.getBitsLength=function(o){return 11*Math.floor(o/2)+6*(o%2)},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(o){let s;for(s=0;s+2<=this.data.length;s+=2){let i=t.indexOf(this.data[s])*45;i+=t.indexOf(this.data[s+1]),o.put(i,11)}this.data.length%2&&o.put(t.indexOf(this.data[s]),6)},rd=r,rd}var nd,Wy;function ZE(){if(Wy)return nd;Wy=1;const e=Gn();function t(r){this.mode=e.BYTE,typeof r=="string"?this.data=new TextEncoder().encode(r):this.data=new Uint8Array(r)}return t.getBitsLength=function(n){return n*8},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(r){for(let n=0,o=this.data.length;n<o;n++)r.put(this.data[n],8)},nd=t,nd}var od,Ky;function BE(){if(Ky)return od;Ky=1;const e=Gn(),t=Jn();function r(n){this.mode=e.KANJI,this.data=n}return r.getBitsLength=function(o){return o*13},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(n){let o;for(o=0;o<this.data.length;o++){let s=t.toSJIS(this.data[o]);if(s>=33088&&s<=40956)s-=33088;else if(s>=57408&&s<=60351)s-=49472;else throw new Error("Invalid SJIS character: "+this.data[o]+`
131
- Make sure your charset is UTF-8`);s=(s>>>8&255)*192+(s&255),n.put(s,13)}},od=r,od}var sd={exports:{}},Yy;function HE(){return Yy||(Yy=1,(function(e){var t={single_source_shortest_paths:function(r,n,o){var s={},i={};i[n]=0;var a=t.PriorityQueue.make();a.push(n,0);for(var l,c,u,f,p,h,g,v,_;!a.empty();){l=a.pop(),c=l.value,f=l.cost,p=r[c]||{};for(u in p)p.hasOwnProperty(u)&&(h=p[u],g=f+h,v=i[u],_=typeof i[u]>"u",(_||v>g)&&(i[u]=g,a.push(u,g),s[u]=c))}if(typeof o<"u"&&typeof i[o]>"u"){var w=["Could not find a path from ",n," to ",o,"."].join("");throw new Error(w)}return s},extract_shortest_path_from_predecessor_list:function(r,n){for(var o=[],s=n;s;)o.push(s),r[s],s=r[s];return o.reverse(),o},find_path:function(r,n,o){var s=t.single_source_shortest_paths(r,n,o);return t.extract_shortest_path_from_predecessor_list(s,o)},PriorityQueue:{make:function(r){var n=t.PriorityQueue,o={},s;r=r||{};for(s in n)n.hasOwnProperty(s)&&(o[s]=n[s]);return o.queue=[],o.sorter=r.sorter||n.default_sorter,o},default_sorter:function(r,n){return r.cost-n.cost},push:function(r,n){var o={value:r,cost:n};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})(sd)),sd.exports}var Qy;function JE(){return Qy||(Qy=1,(function(e){const t=Gn(),r=FE(),n=VE(),o=ZE(),s=BE(),i=Vy(),a=Jn(),l=HE();function c(w){return unescape(encodeURIComponent(w)).length}function u(w,y,m){const C=[];let b;for(;(b=w.exec(m))!==null;)C.push({data:b[0],index:b.index,mode:y,length:b[0].length});return C}function f(w){const y=u(i.NUMERIC,t.NUMERIC,w),m=u(i.ALPHANUMERIC,t.ALPHANUMERIC,w);let C,b;return a.isKanjiModeEnabled()?(C=u(i.BYTE,t.BYTE,w),b=u(i.KANJI,t.KANJI,w)):(C=u(i.BYTE_KANJI,t.BYTE,w),b=[]),y.concat(m,C,b).sort(function(I,R){return I.index-R.index}).map(function(I){return{data:I.data,mode:I.mode,length:I.length}})}function p(w,y){switch(y){case t.NUMERIC:return r.getBitsLength(w);case t.ALPHANUMERIC:return n.getBitsLength(w);case t.KANJI:return s.getBitsLength(w);case t.BYTE:return o.getBitsLength(w)}}function h(w){return w.reduce(function(y,m){const C=y.length-1>=0?y[y.length-1]:null;return C&&C.mode===m.mode?(y[y.length-1].data+=m.data,y):(y.push(m),y)},[])}function g(w){const y=[];for(let m=0;m<w.length;m++){const C=w[m];switch(C.mode){case t.NUMERIC:y.push([C,{data:C.data,mode:t.ALPHANUMERIC,length:C.length},{data:C.data,mode:t.BYTE,length:C.length}]);break;case t.ALPHANUMERIC:y.push([C,{data:C.data,mode:t.BYTE,length:C.length}]);break;case t.KANJI:y.push([C,{data:C.data,mode:t.BYTE,length:c(C.data)}]);break;case t.BYTE:y.push([{data:C.data,mode:t.BYTE,length:c(C.data)}])}}return y}function v(w,y){const m={},C={start:{}};let b=["start"];for(let T=0;T<w.length;T++){const I=w[T],R=[];for(let S=0;S<I.length;S++){const j=I[S],O=""+T+S;R.push(O),m[O]={node:j,lastCount:0},C[O]={};for(let L=0;L<b.length;L++){const z=b[L];m[z]&&m[z].node.mode===j.mode?(C[z][O]=p(m[z].lastCount+j.length,j.mode)-p(m[z].lastCount,j.mode),m[z].lastCount+=j.length):(m[z]&&(m[z].lastCount=j.length),C[z][O]=p(j.length,j.mode)+4+t.getCharCountIndicator(j.mode,y))}}b=R}for(let T=0;T<b.length;T++)C[b[T]].end=0;return{map:C,table:m}}function _(w,y){let m;const C=t.getBestModeForData(w);if(m=t.from(y,C),m!==t.BYTE&&m.bit<C.bit)throw new Error('"'+w+'" cannot be encoded with mode '+t.toString(m)+`.
132
- Suggested mode is: `+t.toString(C));switch(m===t.KANJI&&!a.isKanjiModeEnabled()&&(m=t.BYTE),m){case t.NUMERIC:return new r(w);case t.ALPHANUMERIC:return new n(w);case t.KANJI:return new s(w);case t.BYTE:return new o(w)}}e.fromArray=function(y){return y.reduce(function(m,C){return typeof C=="string"?m.push(_(C,null)):C.data&&m.push(_(C.data,C.mode)),m},[])},e.fromString=function(y,m){const C=f(y,a.isKanjiModeEnabled()),b=g(C),T=v(b,m),I=l.find_path(T.map,"start","end"),R=[];for(let S=1;S<I.length-1;S++)R.push(T.table[I[S]].node);return e.fromArray(h(R))},e.rawSplit=function(y){return e.fromArray(f(y,a.isKanjiModeEnabled()))}})(ed)),ed}var Xy;function GE(){if(Xy)return Uu;Xy=1;const e=Jn(),t=Fu(),r=ME(),n=NE(),o=OE(),s=AE(),i=qE(),a=qy(),l=DE(),c=UE(),u=zE(),f=Gn(),p=JE();function h(T,I){const R=T.size,S=s.getPositions(I);for(let j=0;j<S.length;j++){const O=S[j][0],L=S[j][1];for(let z=-1;z<=7;z++)if(!(O+z<=-1||R<=O+z))for(let B=-1;B<=7;B++)L+B<=-1||R<=L+B||(z>=0&&z<=6&&(B===0||B===6)||B>=0&&B<=6&&(z===0||z===6)||z>=2&&z<=4&&B>=2&&B<=4?T.set(O+z,L+B,!0,!0):T.set(O+z,L+B,!1,!0))}}function g(T){const I=T.size;for(let R=8;R<I-8;R++){const S=R%2===0;T.set(R,6,S,!0),T.set(6,R,S,!0)}}function v(T,I){const R=o.getPositions(I);for(let S=0;S<R.length;S++){const j=R[S][0],O=R[S][1];for(let L=-2;L<=2;L++)for(let z=-2;z<=2;z++)L===-2||L===2||z===-2||z===2||L===0&&z===0?T.set(j+L,O+z,!0,!0):T.set(j+L,O+z,!1,!0)}}function _(T,I){const R=T.size,S=c.getEncodedBits(I);let j,O,L;for(let z=0;z<18;z++)j=Math.floor(z/3),O=z%3+R-8-3,L=(S>>z&1)===1,T.set(j,O,L,!0),T.set(O,j,L,!0)}function w(T,I,R){const S=T.size,j=u.getEncodedBits(I,R);let O,L;for(O=0;O<15;O++)L=(j>>O&1)===1,O<6?T.set(O,8,L,!0):O<8?T.set(O+1,8,L,!0):T.set(S-15+O,8,L,!0),O<8?T.set(8,S-O-1,L,!0):O<9?T.set(8,15-O-1+1,L,!0):T.set(8,15-O-1,L,!0);T.set(S-8,8,1,!0)}function y(T,I){const R=T.size;let S=-1,j=R-1,O=7,L=0;for(let z=R-1;z>0;z-=2)for(z===6&&z--;;){for(let B=0;B<2;B++)if(!T.isReserved(j,z-B)){let X=!1;L<I.length&&(X=(I[L]>>>O&1)===1),T.set(j,z-B,X),O--,O===-1&&(L++,O=7)}if(j+=S,j<0||R<=j){j-=S,S=-S;break}}}function m(T,I,R){const S=new r;R.forEach(function(B){S.put(B.mode.bit,4),S.put(B.getLength(),f.getCharCountIndicator(B.mode,T)),B.write(S)});const j=e.getSymbolTotalCodewords(T),O=a.getTotalCodewordsCount(T,I),L=(j-O)*8;for(S.getLengthInBits()+4<=L&&S.put(0,4);S.getLengthInBits()%8!==0;)S.putBit(0);const z=(L-S.getLengthInBits())/8;for(let B=0;B<z;B++)S.put(B%2?17:236,8);return C(S,T,I)}function C(T,I,R){const S=e.getSymbolTotalCodewords(I),j=a.getTotalCodewordsCount(I,R),O=S-j,L=a.getBlocksCount(I,R),z=S%L,B=L-z,X=Math.floor(S/L),ee=Math.floor(O/L),Q=ee+1,Z=X-ee,ne=new l(Z);let D=0;const E=new Array(L),U=new Array(L);let F=0;const x=new Uint8Array(T.buffer);for(let _e=0;_e<L;_e++){const G=_e<B?ee:Q;E[_e]=x.slice(D,D+G),U[_e]=ne.encode(E[_e]),D+=G,F=Math.max(F,G)}const M=new Uint8Array(S);let H=0,re,te;for(re=0;re<F;re++)for(te=0;te<L;te++)re<E[te].length&&(M[H++]=E[te][re]);for(re=0;re<Z;re++)for(te=0;te<L;te++)M[H++]=U[te][re];return M}function b(T,I,R,S){let j;if(Array.isArray(T))j=p.fromArray(T);else if(typeof T=="string"){let X=I;if(!X){const ee=p.rawSplit(T);X=c.getBestVersionForData(ee,R)}j=p.fromString(T,X||40)}else throw new Error("Invalid data");const O=c.getBestVersionForData(j,R);if(!O)throw new Error("The amount of data is too big to be stored in a QR Code");if(!I)I=O;else if(I<O)throw new Error(`
133
- The chosen QR Code version cannot contain this amount of data.
134
- Minimum version required to store current data is: `+O+`.
135
- `);const L=m(I,R,j),z=e.getSymbolSize(I),B=new n(z);return h(B,I),g(B),v(B,I),w(B,R,0),I>=7&&_(B,I),y(B,L),isNaN(S)&&(S=i.getBestMask(B,w.bind(null,B,R))),i.applyMask(S,B),w(B,R,S),{modules:B,version:I,errorCorrectionLevel:R,maskPattern:S,segments:j}}return Uu.create=function(I,R){if(typeof I>"u"||I==="")throw new Error("No input text");let S=t.M,j,O;return typeof R<"u"&&(S=t.from(R.errorCorrectionLevel,t.M),j=c.from(R.version),O=i.from(R.maskPattern),R.toSJISFunc&&e.setToSJISFunction(R.toSJISFunc)),b(I,j,S,O)},Uu}var ad={},id={},ev;function tv(){return ev||(ev=1,(function(e){function t(r){if(typeof r=="number"&&(r=r.toString()),typeof r!="string")throw new Error("Color should be defined as hex string");let n=r.slice().replace("#","").split("");if(n.length<3||n.length===5||n.length>8)throw new Error("Invalid hex color: "+r);(n.length===3||n.length===4)&&(n=Array.prototype.concat.apply([],n.map(function(s){return[s,s]}))),n.length===6&&n.push("F","F");const o=parseInt(n.join(""),16);return{r:o>>24&255,g:o>>16&255,b:o>>8&255,a:o&255,hex:"#"+n.slice(0,6).join("")}}e.getOptions=function(n){n||(n={}),n.color||(n.color={});const o=typeof n.margin>"u"||n.margin===null||n.margin<0?4:n.margin,s=n.width&&n.width>=21?n.width:void 0,i=n.scale||4;return{width:s,scale:s?4:i,margin:o,color:{dark:t(n.color.dark||"#000000ff"),light:t(n.color.light||"#ffffffff")},type:n.type,rendererOpts:n.rendererOpts||{}}},e.getScale=function(n,o){return o.width&&o.width>=n+o.margin*2?o.width/(n+o.margin*2):o.scale},e.getImageWidth=function(n,o){const s=e.getScale(n,o);return Math.floor((n+o.margin*2)*s)},e.qrToImageData=function(n,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,f=[s.color.light,s.color.dark];for(let p=0;p<c;p++)for(let h=0;h<c;h++){let g=(p*c+h)*4,v=s.color.light;if(p>=u&&h>=u&&p<c-u&&h<c-u){const _=Math.floor((p-u)/l),w=Math.floor((h-u)/l);v=f[a[_*i+w]?1:0]}n[g++]=v.r,n[g++]=v.g,n[g++]=v.b,n[g]=v.a}}})(id)),id}var rv;function WE(){return rv||(rv=1,(function(e){const t=tv();function r(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 n(){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=n()),l=t.getOptions(l);const u=t.getImageWidth(s.modules.size,l),f=c.getContext("2d"),p=f.createImageData(u,u);return t.qrToImageData(p.data,s,l),r(f,c,u),f.putImageData(p,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",f=l.rendererOpts||{};return c.toDataURL(u,f.quality)}})(ad)),ad}var ld={},nv;function KE(){if(nv)return ld;nv=1;const e=tv();function t(o,s){const i=o.a/255,a=s+'="'+o.hex+'"';return i<1?a+" "+s+'-opacity="'+i.toFixed(2).slice(1)+'"':a}function r(o,s,i){let a=o+s;return typeof i<"u"&&(a+=" "+i),a}function n(o,s,i){let a="",l=0,c=!1,u=0;for(let f=0;f<o.length;f++){const p=Math.floor(f%s),h=Math.floor(f/s);!p&&!c&&(c=!0),o[f]?(u++,f>0&&p>0&&o[f-1]||(a+=c?r("M",p+i,.5+h+i):r("m",l,0),l=0,c=!1),p+1<s&&o[f+1]||(a+=r("h",u),u=0)):l++}return a}return ld.render=function(s,i,a){const l=e.getOptions(i),c=s.modules.size,u=s.modules.data,f=c+l.margin*2,p=l.color.light.a?"<path "+t(l.color.light,"fill")+' d="M0 0h'+f+"v"+f+'H0z"/>':"",h="<path "+t(l.color.dark,"stroke")+' d="'+n(u,c,l.margin)+'"/>',g='viewBox="0 0 '+f+" "+f+'"',_='<svg xmlns="http://www.w3.org/2000/svg" '+(l.width?'width="'+l.width+'" height="'+l.width+'" ':"")+g+' shape-rendering="crispEdges">'+p+h+`</svg>
136
- `;return typeof a=="function"&&a(null,_),_},ld}var ov;function YE(){if(ov)return Co;ov=1;const e=PE(),t=GE(),r=WE(),n=KE();function o(s,i,a,l,c){const u=[].slice.call(arguments,1),f=u.length,p=typeof u[f-1]=="function";if(!p&&!e())throw new Error("Callback required as last argument");if(p){if(f<2)throw new Error("Too few arguments provided");f===2?(c=a,a=i,i=l=void 0):f===3&&(i.getContext&&typeof c>"u"?(c=l,l=void 0):(c=l,l=a,a=i,i=void 0))}else{if(f<1)throw new Error("Too few arguments provided");return f===1?(a=i,i=l=void 0):f===2&&!i.getContext&&(l=a,a=i,i=void 0),new Promise(function(h,g){try{const v=t.create(a,l);h(s(v,i,l))}catch(v){g(v)}})}try{const h=t.create(a,l);c(null,s(h,i,l))}catch(h){c(h)}}return Co.create=t.create,Co.toCanvas=o.bind(null,r.render),Co.toDataURL=o.bind(null,r.renderToDataURL),Co.toString=o.bind(null,function(s,i,a){return n.render(s,a)}),Co}var QE=YE();const sv=Pl(QE);class av{constructor(t,{size:r=200,margin:n=4,color:o="#000",bgColor:s="#fff"}){this.value=t,this.size=r,this.margin=n,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 sv.toDataURL(this.value,this.qrCodeOption)}async toCanvas(t){return sv.toCanvas(t,this.value,this.qrCodeOption)}async toImage(t){t.src=await this.toDataURL()}}const XE={content:"",placement:"top",trigger:"hover",delay:150,hideDelay:150,container:document.body,className:"tiny-remoter-native-tooltip"};class e${constructor(t,r={}){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={...XE,...r},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(()=>{this.tip?.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=`
137
- <div class="${this.opts.className}__arrow"></div>
138
- <div class="${this.opts.className}__inner">${t}</div>
139
- `}reposition(){const t=this.placementList(this.opts.placement);for(const r of t){const n=this.calcStyle(r);if(this.checkViewport(n)){this.applyStyle(n),this.tip.className=`${this.opts.className} ${this.opts.className}--${r}`;return}}this.applyStyle(this.calcStyle("top"))}calcStyle(t){const r=this.el.getBoundingClientRect(),n=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=r.top+o-n.height-i:a==="bottom"?c=r.bottom+o+i:a==="left"?u=r.left+s-n.width-i:a==="right"&&(u=r.right+s+i),(a==="top"||a==="bottom")&&(l==="start"?u=r.left+s:l==="end"?u=r.right+s-n.width:u=(r.left+r.right)/2+s-n.width/2),(a==="left"||a==="right")&&(l==="start"?c=r.top+o:l==="end"?c=r.bottom+o-n.height:c=(r.top+r.bottom)/2+o-n.height/2),{top:Math.round(c),left:Math.round(u)}}applyStyle({top:t,left:r}){Object.assign(this.tip.style,{position:"absolute",top:`${t}px`,left:`${r}px`})}checkViewport({top:t,left:r}){const o=window.innerWidth,s=window.innerHeight,i=this.tip.getBoundingClientRect();return r>=5&&t>=5&&r+i.width<=o-5&&t+i.height<=s-5}placementList(t){const r={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 r[t.split("-")[0]]||r.top}attachExtraEvents(){this.opts.trigger==="click"?(this.clickOutside=t=>{const r=t.composedPath();!r.includes(this.el)&&!r.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(){return!!this.tip?.parentNode}}const iv="tiny-remoter-native-tooltip-style";(()=>{if(document.getElementById(iv))return;const e=document.createElement("style");e.id=iv,e.textContent=`
140
- .tiny-remoter-native-tooltip {
141
- position: absolute;
142
- z-index: 9999;
143
- max-width: 200px;
144
- padding: 6px 10px;
145
- font-size: 12px;
146
- line-height: 1.4;
147
- color: #fff;
148
- background: #191919;
149
- border-radius: 4px;
150
- pointer-events: none;
151
- box-shadow: 0px 4px 8px 0px rgba(0, 0, 0, 0.2);
152
- }
153
- .tiny-remoter-native-tooltip__arrow {
154
- position: absolute;
155
- width: 0; height: 0;
156
- border: 6px solid transparent;
157
- }
158
- .tiny-remoter-native-tooltip--top
159
- .tiny-remoter-native-tooltip__arrow {
160
- bottom: -12px;
161
- left: 50%; transform:
162
- translateX(-50%);
163
- border-top-color: rgba(0,0,0,.75);
164
- }
165
- .tiny-remoter-native-tooltip--bottom
166
- .tiny-remoter-native-tooltip__arrow {
167
- top: -12px;
168
- left: 50%; transform:
169
- translateX(-50%);
170
- border-bottom-color: rgba(0,0,0,.75);
171
- }
172
- .tiny-remoter-native-tooltip--left
173
- .tiny-remoter-native-tooltip__arrow {
174
- right: -12px;
175
- top: 50%;
176
- transform: translateY(-50%);
177
- border-left-color: rgba(0,0,0,.75);
178
- }
179
- .tiny-remoter-native-tooltip--right
180
- .tiny-remoter-native-tooltip__arrow {
181
- left: -12px;
182
- top: 50%;
183
- transform: translateY(-50%);
184
- border-right-color: rgba(0,0,0,.75);
185
- }
186
- `,document.head.appendChild(e)})();const lv="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",cv="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",uv="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",dv="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",t$="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",r$="data:image/svg+xml,%3csvg%20width='100.000000'%20height='100.000000'%20viewBox='0%200%20100%20100'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%3e%3cdesc%3e%20Created%20with%20Pixso.%20%3c/desc%3e%3cdefs%3e%3cradialGradient%20gradientTransform='translate(67.5526%2065.1155)%20rotate(51.0683)%20scale(22.991%2020.6919)'%20cx='0.000000'%20cy='0.000000'%20r='1.000000'%20id='paint_radial_9_3036_0'%20gradientUnits='userSpaceOnUse'%3e%3cstop%20stop-color='%235ADDF8'/%3e%3cstop%20stop-color='%23AEBFFF'/%3e%3cstop%20offset='0.329153'%20stop-color='%231476FF'/%3e%3cstop%20offset='0.667785'%20stop-color='%23655AF8'/%3e%3cstop%20offset='0.868255'%20stop-color='%23948CFF'/%3e%3cstop%20offset='1.000000'%20stop-color='%23D25AF8'/%3e%3cstop%20offset='1.000000'%20stop-color='%235A8BF8'/%3e%3c/radialGradient%3e%3clinearGradient%20x1='69.000122'%20y1='85.000198'%20x2='69.500107'%20y2='70.500183'%20id='paint_linear_9_3039_0'%20gradientUnits='userSpaceOnUse'%3e%3cstop%20stop-color='%23000000'%20stop-opacity='0.000000'/%3e%3cstop%20offset='1.000000'%20stop-color='%23000000'/%3e%3c/linearGradient%3e%3cradialGradient%20gradientTransform='translate(26.9999%2024.7118)%20rotate(38.3655)%20scale(77.7996%20109.496)'%20cx='0.000000'%20cy='0.000000'%20r='1.000000'%20id='paint_radial_9_3040_0'%20gradientUnits='userSpaceOnUse'%3e%3cstop%20stop-color='%235ADDF8'/%3e%3cstop%20stop-color='%23AEBFFF'/%3e%3cstop%20offset='0.329153'%20stop-color='%231476FF'/%3e%3cstop%20offset='0.667785'%20stop-color='%23655AF8'/%3e%3cstop%20offset='0.868255'%20stop-color='%23948CFF'/%3e%3cstop%20offset='1.000000'%20stop-color='%23D25AF8'/%3e%3cstop%20offset='1.000000'%20stop-color='%235A8BF8'/%3e%3c/radialGradient%3e%3c/defs%3e%3crect%20id='NEXT-LOGO-无背景渐变-左'%20width='100.000000'%20height='99.999939'%20fill='%23FFFFFF'%20fill-opacity='0'/%3e%3cmask%20id='mask9_3032'%20mask-type='alpha'%20maskUnits='userSpaceOnUse'%20x='0.000000'%20y='0.000061'%20width='99.999939'%20height='99.999939'%3e%3crect%20id='画板%201773'%20y='0.000061'%20width='99.999962'%20height='99.999947'%20fill='%23000000'%20fill-opacity='1.000000'/%3e%3c/mask%3e%3cg%20mask='url(%23mask9_3032)'%3e%3cpath%20id='矢量%201'%20d='M64.07%2081.01L64%2063L82%2063.07L67.51%2082.23C66.39%2083.71%2064.07%2082.9%2064.07%2081.01Z'%20fill='url(%23paint_radial_9_3036_0)'%20fill-opacity='1.000000'%20fill-rule='evenodd'/%3e%3cg%20opacity='0.100000'%20style='mix-blend-mode:normal'%3e%3cpath%20id='矢量%201'%20d='M64.07%2081.01L64%2063L82%2063.07L67.51%2082.23C66.39%2083.71%2064.07%2082.9%2064.07%2081.01Z'%20fill='url(%23paint_linear_9_3039_0)'%20fill-opacity='1.000000'%20fill-rule='evenodd'/%3e%3c/g%3e%3crect%20id='矩形%205'%20x='12.000000'%20y='19.000153'%20rx='26.999992'%20width='75.999977'%20height='53.999985'%20fill='url(%23paint_radial_9_3040_0)'%20fill-opacity='1.000000'/%3e%3crect%20id='矩形%205'%20x='12.500000'%20y='19.500153'%20rx='26.499992'%20width='74.999977'%20height='52.999985'%20fill='%23000000'%20fill-opacity='0'/%3e%3crect%20id='矩形%205'%20x='12.500000'%20y='19.500153'%20rx='26.499992'%20width='74.999977'%20height='52.999985'%20stroke='%23000000'%20stroke-opacity='0'%20stroke-width='1.000000'/%3e%3cpath%20id='path'%20d='M54.61%2059.06C55.78%2060.05%2057.1%2060.66%2058.57%2060.89C60.05%2061.12%2061.43%2061.04%2062.72%2060.65C64%2060.26%2065.96%2058.58%2065.96%2058.58C65.96%2058.58%2070.98%2054.73%2070.98%2045.61C70.98%2036.5%2066.5%2032.5%2066.5%2032.5C66.5%2032.5%2065.28%2031.31%2063.5%2031C61.71%2030.68%2060.57%2030.98%2059.34%2031.33C49.11%2034.23%2037.62%2034.33%2027.42%2031.33C26.19%2030.98%2025.09%2030.93%2024.11%2031.17C23.13%2031.42%2022.29%2031.89%2021.58%2032.59C18.35%2035.81%2017.12%2041.06%2017%2045.61C16.87%2050.09%2018.03%2055.24%2021.06%2058.54C21.96%2059.52%2023.02%2060.22%2024.22%2060.63C25.41%2061.04%2026.68%2061.12%2028.01%2060.89C29.34%2060.66%2030.52%2060.05%2031.54%2059.06C31.98%2058.62%2032.61%2058.07%2033.43%2057.4C34.24%2056.73%2035.16%2056.08%2036.21%2055.44C37.25%2054.8%2038.38%2054.25%2039.61%2053.8C40.84%2053.35%2042.09%2053.13%2043.38%2053.13C44.64%2053.13%2045.84%2053.36%2047%2053.83C48.15%2054.29%2049.21%2054.84%2050.18%2055.48C51.14%2056.12%2052%2056.78%2052.74%2057.45C53.49%2058.11%2054.11%2058.65%2054.61%2059.06Z'%20fill='%23FFFFFF'%20fill-opacity='1.000000'%20fill-rule='nonzero'/%3e%3crect%20id='矩形%20840'%20x='58.016602'%20y='38.000046'%20rx='2.000000'%20width='3.999999'%20height='11.999996'%20transform='rotate(1.39597%2058.016602%2038.000046)'%20fill='%231476FF'%20fill-opacity='1.000000'/%3e%3cpath%20id='合并'%20d='M28.97%2038C28.17%2037.97%2027.38%2038.42%2027.01%2039.19L23.2%2047.11C22.71%2048.13%2023.15%2049.34%2024.18%2049.81C25.22%2050.28%2026.45%2049.83%2026.94%2048.8L28.97%2044.59L30.99%2048.81C31.48%2049.83%2032.72%2050.28%2033.75%2049.81C34.79%2049.34%2035.23%2048.13%2034.74%2047.11L30.93%2039.19C30.56%2038.42%2029.78%2037.98%2028.97%2038Z'%20fill='%231476FF'%20fill-opacity='1.000000'%20fill-rule='evenodd'/%3e%3c/g%3e%3c/svg%3e",n$="https://chat.opentiny.design",o$="https://ai.opentiny.design/next-remoter",s$=r$,a$=e=>{const t=!!e.sessionId;return[{action:"qr-code",show:t,text:"扫码登录",desc:"使用手机遥控页面",icon:dv},{action:"ai-chat",show:!0,text:"打开对话框",desc:"支持在网页端操作AI",icon:lv},{action:"remote-url",show:t,text:"遥控器链接",desc:`${e.remoteUrl}`,active:!0,tip:e.remoteUrl,showCopyIcon:!0,icon:uv},{action:"remote-control",show:t,text:"识别码",desc:t?`${e.sessionId.slice(-6)}`:"",know:!0,showCopyIcon:!0,icon:cv}]};class i${constructor(t){this.isExpanded=!1,this.closingTimer=0,this.getImageUrl=r=>{if(!r)return;const n=new Image;return n.src=r,n},this.renderItem=()=>{this.menuItems.filter(r=>r.show!==!1).map(r=>{const n=document.getElementById(`tiny-remoter-icon-item-${r.action}`);if(!n)return;n.innerHTML="";const o=this.getImageUrl(r.icon);o&&n.appendChild(o)})},this.readyTips=r=>{const n=document.getElementById(r);n&&new e$(n,{content:"复制",placement:"top",trigger:"hover"})},this.options={...t,qrCodeUrl:t.qrCodeUrl||o$,remoteUrl:t.remoteUrl||n$,logoUrl:t.logoUrl||s$},t.menuItems&&t.menuItems.length===0?this.menuItems=[]:this.menuItems=this.mergeMenuItems(t.menuItems),this.init()}get sessionPrefix(){return this.options.qrCodeUrl?.includes("?")?"&sessionId=":"?sessionId="}mergeMenuItems(t){const r={"qr-code":dv,"ai-chat":lv,"remote-url":uv,"remote-control":cv};return t?t.map(n=>({...n,icon:n.icon??r[n.action]})):this.options.sessionId?a$(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=`
187
- <div class="tiny-remoter-floating-block__icon">
188
- <img style="display: block; width: 56px;" src="${this.options.logoUrl}" alt="icon" />
189
- </div>
190
- `,document.body.appendChild(this.floatingBlock)}createDropdownMenu(){this.dropdownMenu=document.createElement("div"),this.dropdownMenu.className="tiny-remoter-floating-dropdown";const t=this.menuItems.filter(r=>r.show!==!1).map(r=>`
191
- <div class="tiny-remoter-dropdown-item" data-action="${r.action}">
192
- <div id="tiny-remoter-icon-item-${r.action}" class="tiny-remoter-dropdown-item__icon">
193
- </div>
194
- <div class="tiny-remoter-dropdown-item__content">
195
- <div title="${r.tip}">${r.text}</div>
196
- <div class="tiny-remoter-dropdown-item__desc-wrapper">
197
- <div class="tiny-remoter-dropdown-item__desc ${r.active?"tiny-remoter-dropdown-item__desc--active":""} ${r.know?"tiny-remoter-dropdown-item__desc--know":""}">${r.desc??""}</div>
198
- <div>
199
- ${r.showCopyIcon?`
200
- <div class="tiny-remoter-copy-icon" id="${r.action}" data-action="${r.action}">
201
- <img src="${t$}"/>
202
- </div>
203
- `:""}
204
- </div>
205
- </div>
206
- </div>
207
- </div>
208
- `).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.showAIChat()}),this.floatingBlock.addEventListener("mouseenter",()=>{this.openDropdown(),this.closingTimer&&(window.clearTimeout(this.closingTimer),this.closingTimer=0)}),this.floatingBlock.addEventListener("mouseleave",()=>{this.shouldCloseDropdown()}),this.dropdownMenu.addEventListener("mouseenter",t=>{this.closingTimer&&(window.clearTimeout(this.closingTimer),this.closingTimer=0)}),this.dropdownMenu.addEventListener("mouseleave",t=>{this.shouldCloseDropdown()}),this.dropdownMenu.addEventListener("click",t=>{const r=t.target,n=r.closest(".tiny-remoter-copy-icon");if(n){t.stopPropagation();const i=n.dataset.action;i&&this.handleAction(i);return}const s=r.closest(".tiny-remoter-dropdown-item")?.dataset.action;s&&this.handleAction(s)}),document.addEventListener("click",t=>{const r=t.target;!this.floatingBlock.contains(r)&&!this.dropdownMenu.contains(r)&&this.closeDropdown()}),document.addEventListener("keydown",t=>{t.key==="Escape"&&this.closeDropdown()})}openDropdown(){!this.menuItems||this.menuItems&&this.menuItems.length===0||(this.isExpanded=!0,this.floatingBlock.classList.add("expanded"),this.dropdownMenu.classList.add("show"))}shouldCloseDropdown(){this.closingTimer=window.setTimeout(()=>{this.closeDropdown()},300)}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(){const t=this.menuItems.find(n=>n.action==="remote-control"),r=t?.desc||t?.text||(this.options.sessionId?this.options.sessionId.slice(-6):"");r&&this.copyToClipboard(r)}copyRemoteURL(){const t=this.menuItems.find(s=>s.action==="remote-url"),r=this.options.sessionId?this.options.remoteUrl+this.sessionPrefix+this.options.sessionId:"",o=(t?.desc&&t.desc!==this.options.remoteUrl?t.desc:void 0)||r||t?.text||"";o&&this.copyToClipboard(o)}async copyToClipboard(t){try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(t),this.showCopyFeedback(!0);else{const r=document.createElement("textarea");r.value=t,r.style.position="fixed",r.style.left="-999999px",r.style.top="-999999px",document.body.appendChild(r),r.focus(),r.select();const n=document.execCommand("copy");document.body.removeChild(r),n?this.showCopyFeedback(!0):this.showCopyFeedback(!1)}}catch(r){console.error("复制失败:",r),this.showCopyFeedback(!1)}}showCopyFeedback(t){const r=t?"复制成功!":"复制失败,请手动复制",n=document.createElement("div");n.className=`tiny-remoter-copy-feedback ${t?"success":"error"}`,n.textContent=r,document.body.appendChild(n),setTimeout(()=>n.classList.add("show"),10),setTimeout(()=>{n.classList.remove("show"),setTimeout(()=>{n.parentNode&&n.parentNode.removeChild(n)},300)},1500)}async showQRCode(){if(!this.options.sessionId)return;const r=await new av((this.options.qrCodeUrl||"")+this.sessionPrefix+this.options.sessionId,{}).toDataURL(),n=this.createModal("扫码前往智能遥控器",`
209
- <div style="text-align: center; padding: 32px;">
210
- <!-- 二维码容器 - 添加渐变背景和阴影效果 -->
211
- <div style="
212
- width: 240px;
213
- height: 240px;
214
- background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
215
- margin: 0 auto 24px;
216
- display: flex;
217
- align-items: center;
218
- justify-content: center;
219
- border-radius: 20px;
220
- box-shadow: 0 20px 40px rgba(102, 126, 234, 0.3);
221
- position: relative;
222
- overflow: hidden;
223
- ">
224
- <!-- 装饰性背景元素 -->
225
- <div style="
226
- position: absolute;
227
- top: -50%;
228
- left: -50%;
229
- width: 200%;
230
- height: 200%;
231
- background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
232
- animation: rotate 20s linear infinite;
233
- "></div>
234
-
235
- <!-- 二维码图片容器 -->
236
- <div style="
237
- width: 200px;
238
- height: 200px;
239
- background: white;
240
- border-radius: 16px;
241
- padding: 16px;
242
- box-shadow: 0 8px 32px rgba(0,0,0,0.1);
243
- position: relative;
244
- z-index: 1;
245
- ">
246
- <img src="${r}" alt="二维码" style="
247
- width: 100%;
248
- height: 100%;
249
- object-fit: contain;
250
- border-radius: 8px;
251
- ">
252
- </div>
253
- </div>
254
-
255
- <!-- 标题文字 -->
256
- <h3 style="
257
- color: #333;
258
- margin: 0 0 12px 0;
259
- font-size: 20px;
260
- font-weight: 600;
261
- letter-spacing: 0.5px;
262
- ">扫描二维码</h3>
263
-
264
- <!-- 描述文字 -->
265
- <p style="
266
- color: #666;
267
- margin: 0 auto;
268
- margin-bottom: 20px;
269
- font-size: 14px;
270
- line-height: 1.6;
271
- max-width: 280px;
272
- ">请使用手机微信或者浏览器扫描二维码跳转到智能遥控器</p>
273
-
274
- <!-- 提示图标和文字 -->
275
- <div style="
276
- display: flex;
277
- align-items: center;
278
- justify-content: center;
279
- gap: 8px;
280
- color: #999;
281
- font-size: 12px;
282
- ">
283
- <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" style="opacity: 0.7;">
284
- <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z" fill="currentColor"/>
285
- </svg>
286
- <span>支持微信、浏览器等多种方式</span>
287
- </div>
288
- </div>
289
- `);this.showModal(n)}showAIChat(){this.options.onShowAIChat?.()}createModal(t,r){const n=document.createElement("div");n.className="tiny-remoter-floating-modal",n.innerHTML=`
290
- <div class="tiny-remoter-modal-overlay"></div>
291
- <div class="tiny-remoter-modal-content">
292
- <div class="tiny-remoter-modal-header">
293
- <h3>${t}</h3>
294
- <button class="tiny-remoter-modal-close">&times;</button>
295
- </div>
296
- <div class="tiny-remoter-modal-body">
297
- ${r}
298
- </div>
299
- </div>
300
- `;const o=n.querySelector(".tiny-remoter-modal-close"),s=n.querySelector(".tiny-remoter-modal-overlay");return o.addEventListener("click",()=>this.hideModal(n)),s.addEventListener("click",()=>this.hideModal(n)),n}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=`
301
- /* 浮动块样式 */
302
- .tiny-remoter-floating-block {
303
- position: fixed;
304
- bottom: 30px;
305
- right: 30px;
306
- width: 60px;
307
- height: 60px;
308
- cursor: pointer;
309
- display: flex;
310
- align-items: center;
311
- justify-content: center;
312
- color: white;
313
- transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
314
- z-index: 99;
315
- overflow: hidden;
316
- border-radius: 50%;
317
- }
318
-
319
- .tiny-remoter-floating-block__icon {
320
- transform: scale(0.8);
321
- transition: transform 0.3s ease;
322
- }
323
-
324
- .tiny-remoter-floating-block__icon:hover {
325
- transform: scale(1.1);
326
- }
327
-
328
- .tiny-remoter-floating-block.expanded .tiny-remoter-floating-block__icon {
329
- transform: scale(1.1);
330
- }
331
-
332
- /* 下拉菜单样式 */
333
- .tiny-remoter-floating-dropdown {
334
- position: fixed;
335
- bottom: 100px;
336
- right: 30px;
337
- background: white;
338
- border-radius: 18px;
339
- box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
340
- padding: 24px 24px 0px 24px;
341
- opacity: 0;
342
- visibility: hidden;
343
- transform: translateY(20px) scale(0.95);
344
- transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
345
- z-index: 999;
346
- min-width: 200px;
347
- width: 223px;
348
- height: auto;
349
- }
350
-
351
- .tiny-remoter-floating-dropdown.show {
352
- opacity: 1;
353
- visibility: visible;
354
- transform: translateY(0) scale(1);
355
- }
356
-
357
- .tiny-remoter-dropdown-item {
358
- display: flex;
359
- align-items: center;
360
- border-radius: 12px;
361
- cursor: pointer;
362
- transition: all 0.2s ease;
363
- color: #333;
364
- margin-bottom: 24px;
365
- height: 40px;
366
- }
367
-
368
- .tiny-remoter-dropdown-item:last-child {
369
- margin-bottom: 32px;
370
- }
371
-
372
- .tiny-remoter-dropdown-item > span {
373
- flex: 1;
374
- overflow: hidden;
375
- max-width: 120px;
376
- text-overflow: ellipsis;
377
- white-space: nowrap;
378
- }
379
-
380
- .tiny-remoter-dropdown-item__icon {
381
- display: flex;
382
- align-items: center;
383
- justify-content: center;
384
- width: 40px;
385
- height: 40px;
386
- background: #f8f9fa;
387
- border-radius: 8px;
388
- color: #667eea;
389
- }
390
-
391
- .tiny-remoter-dropdown-item__content {
392
- flex: 1;
393
- display: flex;
394
- flex-direction: column;
395
- gap: 4px;
396
- overflow: hidden;
397
- font-size: 12px;
398
- margin-left: 16px;
399
- }
400
-
401
- .tiny-remoter-dropdown-item__desc-wrapper {
402
- display: flex;
403
- align-items: center;
404
- gap: 4px;
405
- }
406
-
407
- .tiny-remoter-dropdown-item__desc {
408
- color: #808080;
409
- overflow: hidden;
410
- white-space: nowrap;
411
- text-overflow: ellipsis;
412
- }
413
-
414
- .tiny-remoter-dropdown-item__desc--active {
415
- color: #1476ff;
416
- }
417
-
418
- .tiny-remoter-dropdown-item__desc--know {
419
- color: #191919;
420
- }
421
-
422
- /* 复制图标样式 */
423
- .tiny-remoter-copy-icon {
424
- display: flex;
425
- align-items: center;
426
- justify-content: center;
427
- width: 24px;
428
- height: 24px;
429
- background: #f0f0f0;
430
- border-radius: 6px;
431
- color: #666;
432
- cursor: pointer;
433
- transition: all 0.2s ease;
434
- opacity: 0.7;
435
- margin-left: auto;
436
- }
437
-
438
- .tiny-remoter-copy-icon:hover {
439
- background: #e0e0e0;
440
- color: #333;
441
- opacity: 1;
442
- transform: scale(1.1);
443
- }
444
-
445
- .tiny-remoter-copy-icon:active {
446
- transform: scale(0.95);
447
- }
448
-
449
- /* 弹窗样式 */
450
- .tiny-remoter-floating-modal {
451
- position: fixed;
452
- top: 0;
453
- left: 0;
454
- width: 100%;
455
- height: 100%;
456
- z-index: 2000;
457
- display: flex;
458
- align-items: center;
459
- justify-content: center;
460
- }
461
-
462
- .tiny-remoter-modal-overlay {
463
- position: absolute;
464
- top: 0;
465
- left: 0;
466
- width: 100%;
467
- height: 100%;
468
- background: rgba(0, 0, 0, 0.5);
469
- backdrop-filter: blur(4px);
470
- opacity: 0;
471
- transition: opacity 0.3s ease;
472
- }
473
-
474
- .tiny-remoter-modal-content {
475
- background: white;
476
- border-radius: 16px;
477
- box-shadow: 0 25px 80px rgba(0, 0, 0, 0.2);
478
- max-width: 500px;
479
- width: 90%;
480
- max-height: 80vh;
481
- overflow: hidden;
482
- transform: scale(0.9) translateY(20px);
483
- transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
484
- }
485
-
486
- .tiny-remoter-floating-modal.show .tiny-remoter-modal-overlay {
487
- opacity: 1;
488
- }
489
-
490
- .tiny-remoter-floating-modal.show .tiny-remoter-modal-content {
491
- transform: scale(1) translateY(0);
492
- }
493
-
494
- .tiny-remoter-modal-header {
495
- display: flex;
496
- align-items: center;
497
- justify-content: space-between;
498
- padding: 20px 24px;
499
- border-bottom: 1px solid #f0f0f0;
500
- }
501
-
502
- .tiny-remoter-modal-header h3 {
503
- margin: 0;
504
- font-size: 18px;
505
- font-weight: 600;
506
- color: #333;
507
- }
508
-
509
- .tiny-remoter-modal-close {
510
- background: none;
511
- border: none;
512
- font-size: 24px;
513
- cursor: pointer;
514
- color: #999;
515
- padding: 0;
516
- width: 32px;
517
- height: 32px;
518
- border-radius: 50%;
519
- display: flex;
520
- align-items: center;
521
- justify-content: center;
522
- transition: all 0.2s ease;
523
- }
524
-
525
- .tiny-remoter-modal-close:hover {
526
- background: #f5f5f5;
527
- color: #666;
528
- }
529
-
530
- .tiny-remoter-modal-body {
531
- padding: 24px;
532
- }
533
-
534
- /* 二维码弹窗动画 */
535
- @keyframes rotate {
536
- from {
537
- transform: rotate(0deg);
538
- }
539
- to {
540
- transform: rotate(360deg);
541
- }
542
- }
543
-
544
- /* 响应式设计 */
545
- @media (max-width: 768px) {
546
- .tiny-remoter-floating-block {
547
- bottom: 20px;
548
- right: 20px;
549
- width: 56px;
550
- height: 56px;
551
- }
552
-
553
- .tiny-remoter-floating-dropdown {
554
- bottom: 90px;
555
- right: 20px;
556
- min-width: 180px;
557
- }
558
-
559
- .tiny-remoter-modal-content {
560
- width: 95%;
561
- margin: 20px;
562
- }
563
- }
564
-
565
- /* 复制反馈提示样式 */
566
- .tiny-remoter-copy-feedback {
567
- position: fixed;
568
- top: 50%;
569
- left: 50%;
570
- transform: translate(-50%, -50%);
571
- background: rgba(0, 0, 0, 0.8);
572
- color: white;
573
- padding: 12px 24px;
574
- border-radius: 8px;
575
- font-size: 14px;
576
- font-weight: 500;
577
- z-index: 10000;
578
- opacity: 0;
579
- visibility: hidden;
580
- transition: all 0.3s ease;
581
- backdrop-filter: blur(4px);
582
- box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
583
- }
584
-
585
- .tiny-remoter-copy-feedback.show {
586
- opacity: 1;
587
- visibility: visible;
588
- transform: translate(-50%, -50%) scale(1);
589
- }
590
-
591
- .tiny-remoter-copy-feedback.success {
592
- background: rgba(34, 197, 94, 0.9);
593
- }
594
-
595
- .tiny-remoter-copy-feedback.error {
596
- background: rgba(239, 68, 68, 0.9);
597
- }
598
-
599
- /* 深色主题支持 */
600
- @media (prefers-color-scheme: dark) {
601
- .tiny-remoter-floating-dropdown {
602
- background: #1a1a1a;
603
- color: white;
604
- }
605
-
606
- .tiny-remoter-dropdown-item {
607
- color: white;
608
- }
609
-
610
-
611
- .tiny-remoter-copy-icon {
612
- background: #2a2a2a;
613
- color: #ccc;
614
- }
615
-
616
- .tiny-remoter-copy-icon:hover {
617
- background: #3a3a3a;
618
- color: white;
619
- }
620
-
621
- .tiny-remoter-modal-content {
622
- background: #1a1a1a;
623
- color: white;
624
- }
625
-
626
- .tiny-remoter-modal-header {
627
- border-bottom-color: #333;
628
- }
629
-
630
- .tiny-remoter-modal-header h3 {
631
- color: white;
632
- }
633
- }
634
- `,document.head.appendChild(t)}destroy(){this.floatingBlock.parentNode&&this.floatingBlock.parentNode.removeChild(this.floatingBlock),this.dropdownMenu.parentNode&&this.dropdownMenu.parentNode.removeChild(this.dropdownMenu)}hide(){this.floatingBlock&&(this.floatingBlock.style.display="none"),this.closeDropdown()}show(){this.floatingBlock&&(this.floatingBlock.style.display="flex")}}const l$=(e={})=>new i$(e);zr.AgentModelProvider=RE,zr.QrCode=av,zr.createRemoter=l$,zr.getAISDKTools=Sy,Object.defineProperty(zr,Symbol.toStringTag,{value:"Module"})}));