@opentiny/next-sdk 0.3.1 → 0.3.3-alpha.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.
- package/WebMcp.ts +6 -0
- package/WebMcpClient.ts +16 -21
- package/agent/type.ts +93 -69
- package/core.ts +1 -0
- package/dist/SimulatorMask-BHVXyogh-BFEGpD5S.js +1048 -0
- package/dist/SimulatorMask-BHVXyogh-CCYbrb84.js +801 -0
- package/dist/WebMcp.d.ts +3 -0
- package/dist/WebMcpClient.d.ts +7 -13
- package/dist/agent/type.d.ts +10 -0
- package/dist/core.d.ts +1 -0
- package/dist/core.js +16 -15
- package/dist/index.d.ts +3 -2
- package/dist/index.es.dev.js +8384 -2700
- package/dist/index.es.js +21608 -16893
- package/dist/index.js +4033 -1850
- package/dist/index.umd.dev.js +9739 -3110
- package/dist/index.umd.js +500 -66
- package/dist/initialize-builtin-WebMCP-HgObT902.js +6279 -0
- package/dist/mcpsdk@1.25.3.dev.js +253 -94
- package/dist/mcpsdk@1.25.3.es.dev.js +253 -94
- package/dist/mcpsdk@1.25.3.es.js +5689 -5531
- package/dist/mcpsdk@1.25.3.js +32 -27
- package/dist/page-tools/a11y-tree.d.ts +103 -0
- package/dist/page-tools/bridge.d.ts +0 -6
- package/dist/page-tools/initialize-builtin-WebMCP.d.ts +1 -0
- package/dist/page-tools/page-agent-tool.d.ts +9 -0
- package/dist/page-tools/page-state-cache.d.ts +36 -0
- package/dist/skills/index.d.ts +7 -12
- package/dist/webagent.dev.js +3772 -1919
- package/dist/webagent.es.dev.js +3528 -1571
- package/dist/webagent.es.js +16380 -14585
- package/dist/webagent.js +74 -66
- package/dist/webmcp-full.dev.js +7670 -747
- package/dist/webmcp-full.es.dev.js +6482 -608
- package/dist/webmcp-full.es.js +12180 -7618
- package/dist/webmcp-full.js +631 -29
- package/dist/webmcp.dev.js +8047 -53
- package/dist/webmcp.es.dev.js +6977 -31
- package/dist/webmcp.es.js +6187 -860
- package/dist/webmcp.js +602 -1
- package/index.ts +2 -15
- package/package.json +11 -4
- package/page-tools/a11y-tree.ts +532 -0
- package/page-tools/bridge.ts +48 -14
- package/page-tools/initialize-builtin-WebMCP.ts +20 -0
- package/page-tools/page-agent-prompt.md +123 -0
- package/page-tools/page-agent-tool.ts +223 -0
- package/page-tools/page-state-cache.ts +78 -0
- package/remoter/createRemoter.ts +2 -1
- package/remoter/svgs/logo.svg +45 -0
- package/skills/index.ts +50 -31
- package/utils/builtinProxy.ts +42 -20
- package/vite-env.d.ts +5 -0
- package/dist/AgentModelProvider-BnMj6YSC.js +0 -4182
package/dist/webagent.js
CHANGED
|
@@ -1,58 +1,63 @@
|
|
|
1
|
-
(function(
|
|
2
|
-
Error message: ${
|
|
3
|
-
Error message: ${Tn(r)}`,cause:r}),this[Qd]=!0,this.value=t,this.context=n}static isInstance(t){return we.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,Mr=class extends(np=we,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 we.hasMarker(t,tp)}};const op=Object.freeze({status:"aborted"});function G(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 Xr(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 Qi(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Xi(e){return e==null}function el(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 Ze(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=Qi(()=>{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 en(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 tl(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=G("$ZodError",lp),up=G("$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=>en(l,s,Xr())));throw ip(a,o?.callee),a}return i.value},Wv=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=>en(l,s,Xr())));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=>en(i,o,Xr())))}:{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=>en(i,o,Xr())))}:{success:!0,data:s.value}},Gv=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]*$/,Bt=G("$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=G("$ZodCheckLessThan",(e,t)=>{Bt.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=G("$ZodCheckGreaterThan",(e,t)=>{Bt.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=G("$ZodCheckMultipleOf",(e,t)=>{Bt.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=G("$ZodCheckNumberFormat",(e,t)=>{Bt.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=G("$ZodCheckMaxLength",(e,t)=>{var r;Bt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!Xi(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=tl(o);n.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),x1=G("$ZodCheckMinLength",(e,t)=>{var r;Bt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!Xi(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=tl(o);n.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),E1=G("$ZodCheckLengthEquals",(e,t)=>{var r;Bt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!Xi(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=tl(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=G("$ZodCheckStringFormat",(e,t)=>{var r,n;Bt.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=G("$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=G("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=k1),Bs.init(e,t)}),P1=G("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=T1),Bs.init(e,t)}),M1=G("$ZodCheckIncludes",(e,t)=>{Bt.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=G("$ZodCheckStartsWith",(e,t)=>{Bt.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=G("$ZodCheckEndsWith",(e,t)=>{Bt.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=G("$ZodCheckOverwrite",(e,t)=>{Bt.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)),
|
|
5
|
-
`))}}const
|
|
6
|
-
if (${
|
|
7
|
-
if (input[${
|
|
8
|
-
if (${
|
|
9
|
-
newResult[${
|
|
1
|
+
(function(Kr,lo){typeof exports=="object"&&typeof module<"u"?lo(exports):typeof define=="function"&&define.amd?define(["exports"],lo):(Kr=typeof globalThis<"u"?globalThis:Kr||self,lo(Kr.WebAgent={}))})(this,(function(Kr){"use strict";var lo="vercel.ai.error",b1=Symbol.for(lo),Fd,Vd,we=class g1 extends(Vd=Error,Fd=b1,Vd){constructor({name:t,message:r,cause:n}){super(r),this[Fd]=!0,this.name=t,this.cause=n}static isInstance(t){return g1.hasMarker(t,lo)}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}},Zd="AI_APICallError",Hd=`vercel.ai.error.${Zd}`,k1=Symbol.for(Hd),Bd,Jd,tt=class extends(Jd=we,Bd=k1,Jd){constructor({message:t,url:r,requestBodyValues:n,statusCode:o,responseHeaders:a,responseBody:i,cause:s,isRetryable:l=o!=null&&(o===408||o===409||o===429||o>=500),data:c}){super({name:Zd,message:t,cause:s}),this[Bd]=!0,this.url=r,this.requestBodyValues=n,this.statusCode=o,this.responseHeaders=a,this.responseBody=i,this.isRetryable=l,this.data=c}static isInstance(t){return we.hasMarker(t,Hd)}},Gd="AI_EmptyResponseBodyError",Wd=`vercel.ai.error.${Gd}`,T1=Symbol.for(Wd),Kd,Yd,C1=class extends(Yd=we,Kd=T1,Yd){constructor({message:t="Empty response body"}={}){super({name:Gd,message:t}),this[Kd]=!0}static isInstance(t){return we.hasMarker(t,Wd)}};function co(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var Qd="AI_InvalidArgumentError",Xd=`vercel.ai.error.${Qd}`,S1=Symbol.for(Xd),ep,tp,rp=class extends(tp=we,ep=S1,tp){constructor({message:t,cause:r,argument:n}){super({name:Qd,message:t,cause:r}),this[ep]=!0,this.argument=n}static isInstance(t){return we.hasMarker(t,Xd)}},np="AI_InvalidPromptError",op=`vercel.ai.error.${np}`,I1=Symbol.for(op),ap,sp,un=class extends(sp=we,ap=I1,sp){constructor({prompt:e,message:t,cause:r}){super({name:np,message:`Invalid prompt: ${t}`,cause:r}),this[ap]=!0,this.prompt=e}static isInstance(e){return we.hasMarker(e,op)}},ip="AI_InvalidResponseDataError",lp=`vercel.ai.error.${ip}`,x1=Symbol.for(lp),cp,up,cl=class extends(up=we,cp=x1,up){constructor({data:t,message:r=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:ip,message:r}),this[cp]=!0,this.data=t}static isInstance(t){return we.hasMarker(t,lp)}},dp="AI_JSONParseError",pp=`vercel.ai.error.${dp}`,E1=Symbol.for(pp),hp,fp,Wa=class extends(fp=we,hp=E1,fp){constructor({text:t,cause:r}){super({name:dp,message:`JSON parsing failed: Text: ${t}.
|
|
2
|
+
Error message: ${co(r)}`,cause:r}),this[hp]=!0,this.text=t}static isInstance(t){return we.hasMarker(t,pp)}},mp="AI_LoadAPIKeyError",gp=`vercel.ai.error.${mp}`,$1=Symbol.for(gp),_p,yp,Ka=class extends(yp=we,_p=$1,yp){constructor({message:t}){super({name:mp,message:t}),this[_p]=!0}static isInstance(t){return we.hasMarker(t,gp)}},vp="AI_TooManyEmbeddingValuesForCallError",wp=`vercel.ai.error.${vp}`,R1=Symbol.for(wp),bp,kp,P1=class extends(kp=we,bp=R1,kp){constructor(e){super({name:vp,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[bp]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return we.hasMarker(e,wp)}},Tp="AI_TypeValidationError",Cp=`vercel.ai.error.${Tp}`,M1=Symbol.for(Cp),Sp,Ip,An=class Ud extends(Ip=we,Sp=M1,Ip){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 a=[];n.entityName&&a.push(n.entityName),n.entityId&&a.push(`id: "${n.entityId}"`),o+=a.join(", "),o+=")"}super({name:Tp,message:`${o}: Value: ${JSON.stringify(t)}.
|
|
3
|
+
Error message: ${co(r)}`,cause:r}),this[Sp]=!0,this.value=t,this.context=n}static isInstance(t){return we.hasMarker(t,Cp)}static wrap({value:t,cause:r,context:n}){var o,a,i;return Ud.isInstance(r)&&r.value===t&&((o=r.context)==null?void 0:o.field)===n?.field&&((a=r.context)==null?void 0:a.entityName)===n?.entityName&&((i=r.context)==null?void 0:i.entityId)===n?.entityId?r:new Ud({value:t,cause:r,context:n})}},xp="AI_UnsupportedFunctionalityError",Ep=`vercel.ai.error.${xp}`,O1=Symbol.for(Ep),$p,Rp,Tr=class extends(Rp=we,$p=O1,Rp){constructor({functionality:t,message:r=`'${t}' functionality not supported.`}){super({name:xp,message:r}),this[$p]=!0,this.functionality=t}static isInstance(t){return we.hasMarker(t,Ep)}};const Pp=Object.freeze({status:"aborted"});function K(e,t,r){function n(s,l){var c;Object.defineProperty(s,"_zod",{value:s._zod??{},enumerable:!1}),(c=s._zod).traits??(c.traits=new Set),s._zod.traits.add(e),t(s,l);for(const u in i.prototype)u in s||Object.defineProperty(s,u,{value:i.prototype[u].bind(s)});s._zod.constr=i,s._zod.def=l}const o=r?.Parent??Object;class a extends o{}Object.defineProperty(a,"name",{value:e});function i(s){var l;const c=r?.Parent?new a:this;n(c,s),(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:s=>r?.Parent&&s instanceof r.Parent?!0:s?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}class Ho extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const Mp={};function dn(e){return Mp}function Op(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 A1(e,t){return typeof t=="bigint"?t.toString():t}function ul(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function dl(e){return e==null}function pl(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function N1(e,t){const r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,a=Number.parseInt(e.toFixed(o).replace(".","")),i=Number.parseInt(t.toFixed(o).replace(".",""));return a%i/10**o}function He(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 Ya(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Bo(e){return JSON.stringify(e)}const Ap=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function Qa(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const q1=ul(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Xa(e){if(Qa(e)===!1)return!1;const t=e.constructor;if(t===void 0)return!0;const r=t.prototype;return!(Qa(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}const L1=new Set(["string","number","symbol"]);function Jo(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Nn(e,t,r){const n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function ge(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 j1(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const D1={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 U1(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 Nn(e,{...e._zod.def,shape:r,checks:[]})}function z1(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 Nn(e,{...e._zod.def,shape:r,checks:[]})}function F1(e,t){if(!Xa(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 Ya(this,"shape",n),n},checks:[]};return Nn(e,r)}function V1(e,t){return Nn(e,{...e._zod.def,get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return Ya(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function Z1(e,t,r){const n=t._zod.def.shape,o={...n};if(r)for(const a in r){if(!(a in n))throw new Error(`Unrecognized key: "${a}"`);r[a]&&(o[a]=e?new e({type:"optional",innerType:n[a]}):n[a])}else for(const a in n)o[a]=e?new e({type:"optional",innerType:n[a]}):n[a];return Nn(t,{...t._zod.def,shape:o,checks:[]})}function H1(e,t,r){const n=t._zod.def.shape,o={...n};if(r)for(const a in r){if(!(a in o))throw new Error(`Unrecognized key: "${a}"`);r[a]&&(o[a]=new e({type:"nonoptional",innerType:n[a]}))}else for(const a in n)o[a]=new e({type:"nonoptional",innerType:n[a]});return Nn(t,{...t._zod.def,shape:o,checks:[]})}function Go(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function qn(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function es(e){return typeof e=="string"?e:e?.message}function pn(e,t,r){const n={...e,path:e.path??[]};if(!e.message){const o=es(e.inst?._zod.def?.error?.(e))??es(t?.error?.(e))??es(r.customError?.(e))??es(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function hl(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Wo(...e){const[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}const Np=(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,A1,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},qp=K("$ZodError",Np),Lp=K("$ZodError",Np,{Parent:Error});function B1(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 J1(e,t){const r=t||function(a){return a.message},n={_errors:[]},o=a=>{for(const i of a.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(s=>o({issues:s}));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 s=n,l=0;for(;l<i.path.length;){const c=i.path[l];l===i.path.length-1?(s[c]=s[c]||{_errors:[]},s[c]._errors.push(r(i))):s[c]=s[c]||{_errors:[]},s=s[c],l++}}};return o(e),n}const G1=e=>(t,r,n,o)=>{const a=n?Object.assign(n,{async:!1}):{async:!1},i=t._zod.run({value:r,issues:[]},a);if(i instanceof Promise)throw new Ho;if(i.issues.length){const s=new(o?.Err??e)(i.issues.map(l=>pn(l,a,dn())));throw Ap(s,o?.callee),s}return i.value},W1=e=>async(t,r,n,o)=>{const a=n?Object.assign(n,{async:!0}):{async:!0};let i=t._zod.run({value:r,issues:[]},a);if(i instanceof Promise&&(i=await i),i.issues.length){const s=new(o?.Err??e)(i.issues.map(l=>pn(l,a,dn())));throw Ap(s,o?.callee),s}return i.value},jp=e=>(t,r,n)=>{const o=n?{...n,async:!1}:{async:!1},a=t._zod.run({value:r,issues:[]},o);if(a instanceof Promise)throw new Ho;return a.issues.length?{success:!1,error:new(e??qp)(a.issues.map(i=>pn(i,o,dn())))}:{success:!0,data:a.value}},Dp=jp(Lp),Up=e=>async(t,r,n)=>{const o=n?Object.assign(n,{async:!0}):{async:!0};let a=t._zod.run({value:r,issues:[]},o);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(i=>pn(i,o,dn())))}:{success:!0,data:a.value}},K1=Up(Lp),Y1=/^[cC][^\s-]{8,}$/,Q1=/^[0-9a-z]+$/,X1=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,ew=/^[0-9a-vA-V]{20}$/,tw=/^[A-Za-z0-9]{27}$/,rw=/^[a-zA-Z0-9_-]{21}$/,nw=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,ow=/^([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})$/,zp=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)$/,aw=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,sw="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function iw(){return new RegExp(sw,"u")}const lw=/^(?:(?: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])$/,cw=/^(([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})$/,uw=/^((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])$/,dw=/^(([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])$/,pw=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Fp=/^[A-Za-z0-9_-]*$/,hw=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,fw=/^\+(?:[0-9]){6,14}[0-9]$/,Vp="(?:(?:\\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])))",mw=new RegExp(`^${Vp}$`);function Zp(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 gw(e){return new RegExp(`^${Zp(e)}$`)}function _w(e){const t=Zp({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(`^${Vp}T(?:${n})$`)}const yw=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},vw=/^\d+$/,ww=/^-?\d+(?:\.\d+)?/i,bw=/true|false/i,kw=/null/i,Tw=/^[^A-Z]*$/,Cw=/^[^a-z]*$/,Xt=K("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Hp={number:"number",bigint:"bigint",object:"date"},Bp=K("$ZodCheckLessThan",(e,t)=>{Xt.init(e,t);const r=Hp[typeof t.value];e._zod.onattach.push(n=>{const o=n._zod.bag,a=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<a&&(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})}}),Jp=K("$ZodCheckGreaterThan",(e,t)=>{Xt.init(e,t);const r=Hp[typeof t.value];e._zod.onattach.push(n=>{const o=n._zod.bag,a=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>a&&(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})}}),Sw=K("$ZodCheckMultipleOf",(e,t)=>{Xt.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):N1(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})}}),Iw=K("$ZodCheckNumberFormat",(e,t)=>{Xt.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),n=r?"int":"number",[o,a]=D1[t.format];e._zod.onattach.push(i=>{const s=i._zod.bag;s.format=t.format,s.minimum=o,s.maximum=a,r&&(s.pattern=vw)}),e._zod.check=i=>{const s=i.value;if(r){if(!Number.isInteger(s)){i.issues.push({expected:n,format:t.format,code:"invalid_type",input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?i.issues.push({input:s,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:s,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}}s<o&&i.issues.push({origin:"number",input:s,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),s>a&&i.issues.push({origin:"number",input:s,code:"too_big",maximum:a,inst:e})}}),xw=K("$ZodCheckMaxLength",(e,t)=>{var r;Xt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!dl(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=hl(o);n.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Ew=K("$ZodCheckMinLength",(e,t)=>{var r;Xt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!dl(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=hl(o);n.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),$w=K("$ZodCheckLengthEquals",(e,t)=>{var r;Xt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!dl(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,a=o.length;if(a===t.length)return;const i=hl(o),s=a>t.length;n.issues.push({origin:i,...s?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),ts=K("$ZodCheckStringFormat",(e,t)=>{var r,n;Xt.init(e,t),e._zod.onattach.push(o=>{const a=o._zod.bag;a.format=t.format,t.pattern&&(a.patterns??(a.patterns=new Set),a.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=()=>{})}),Rw=K("$ZodCheckRegex",(e,t)=>{ts.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})}}),Pw=K("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Tw),ts.init(e,t)}),Mw=K("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Cw),ts.init(e,t)}),Ow=K("$ZodCheckIncludes",(e,t)=>{Xt.init(e,t);const r=Jo(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(o=>{const a=o._zod.bag;a.patterns??(a.patterns=new Set),a.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})}}),Aw=K("$ZodCheckStartsWith",(e,t)=>{Xt.init(e,t);const r=new RegExp(`^${Jo(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})}}),Nw=K("$ZodCheckEndsWith",(e,t)=>{Xt.init(e,t);const r=new RegExp(`.*${Jo(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})}}),qw=K("$ZodCheckOverwrite",(e,t)=>{Xt.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});class Lw{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)),a=n.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(const i of a)this.content.push(i)}compile(){const t=Function,r=this?.args,o=[...(this?.content??[""]).map(a=>` ${a}`)];return new t(...r,o.join(`
|
|
5
|
+
`))}}const jw={major:4,minor:0,patch:0},Xe=K("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=jw;const n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(const o of n)for(const a of o._zod.onattach)a(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const o=(a,i,s)=>{let l=Go(a),c;for(const u of i){if(u._zod.def.when){if(!u._zod.def.when(a))continue}else if(l)continue;const h=a.issues.length,p=u._zod.check(a);if(p instanceof Promise&&s?.async===!1)throw new Ho;if(c||p instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await p,a.issues.length!==h&&(l||(l=Go(a,h)))});else{if(a.issues.length===h)continue;l||(l=Go(a,h))}}return c?c.then(()=>a):a};e._zod.run=(a,i)=>{const s=e._zod.parse(a,i);if(s instanceof Promise){if(i.async===!1)throw new Ho;return s.then(l=>o(l,n,i))}return o(s,n,i)}}e["~standard"]={validate:o=>{try{const a=Dp(e,o);return a.success?{value:a.data}:{issues:a.error?.issues}}catch{return K1(e,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),fl=K("$ZodString",(e,t)=>{Xe.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??yw(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}}),ot=K("$ZodStringFormat",(e,t)=>{ts.init(e,t),fl.init(e,t)}),Dw=K("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=ow),ot.init(e,t)}),Uw=K("$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=zp(n))}else t.pattern??(t.pattern=zp());ot.init(e,t)}),zw=K("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=aw),ot.init(e,t)}),Fw=K("$ZodURL",(e,t)=>{ot.init(e,t),e._zod.check=r=>{try{const n=r.value,o=new URL(n),a=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:hw.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("/")&&a.endsWith("/")?r.value=a.slice(0,-1):r.value=a;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),Vw=K("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=iw()),ot.init(e,t)}),Zw=K("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=rw),ot.init(e,t)}),Hw=K("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Y1),ot.init(e,t)}),Bw=K("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Q1),ot.init(e,t)}),Jw=K("$ZodULID",(e,t)=>{t.pattern??(t.pattern=X1),ot.init(e,t)}),Gw=K("$ZodXID",(e,t)=>{t.pattern??(t.pattern=ew),ot.init(e,t)}),Ww=K("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=tw),ot.init(e,t)}),Kw=K("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=_w(t)),ot.init(e,t)}),Yw=K("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=mw),ot.init(e,t)}),Qw=K("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=gw(t)),ot.init(e,t)}),Xw=K("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=nw),ot.init(e,t)}),eb=K("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=lw),ot.init(e,t),e._zod.onattach.push(r=>{const n=r._zod.bag;n.format="ipv4"})}),tb=K("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=cw),ot.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})}}}),rb=K("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=uw),ot.init(e,t)}),nb=K("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=dw),ot.init(e,t),e._zod.check=r=>{const[n,o]=r.value.split("/");try{if(!o)throw new Error;const a=Number(o);if(`${a}`!==o)throw new Error;if(a<0||a>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 Gp(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const ob=K("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=pw),ot.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{Gp(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function ab(e){if(!Fp.test(e))return!1;const t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return Gp(r)}const sb=K("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Fp),ot.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{ab(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),ib=K("$ZodE164",(e,t)=>{t.pattern??(t.pattern=fw),ot.init(e,t)});function lb(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 cb=K("$ZodJWT",(e,t)=>{ot.init(e,t),e._zod.check=r=>{lb(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),Wp=K("$ZodNumber",(e,t)=>{Xe.init(e,t),e._zod.pattern=e._zod.bag.pattern??ww,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 a=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,...a?{received:a}:{}}),r}}),ub=K("$ZodNumber",(e,t)=>{Iw.init(e,t),Wp.init(e,t)}),db=K("$ZodBoolean",(e,t)=>{Xe.init(e,t),e._zod.pattern=bw,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}}),pb=K("$ZodNull",(e,t)=>{Xe.init(e,t),e._zod.pattern=kw,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}}),hb=K("$ZodAny",(e,t)=>{Xe.init(e,t),e._zod.parse=r=>r}),fb=K("$ZodUnknown",(e,t)=>{Xe.init(e,t),e._zod.parse=r=>r}),mb=K("$ZodNever",(e,t)=>{Xe.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function Kp(e,t,r){e.issues.length&&t.issues.push(...qn(r,e.issues)),t.value[r]=e.value}const gb=K("$ZodArray",(e,t)=>{Xe.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 a=[];for(let i=0;i<o.length;i++){const s=o[i],l=t.element._zod.run({value:s,issues:[]},n);l instanceof Promise?a.push(l.then(c=>Kp(c,r,i))):Kp(l,r,i)}return a.length?Promise.all(a).then(()=>r):r}});function rs(e,t,r){e.issues.length&&t.issues.push(...qn(r,e.issues)),t.value[r]=e.value}function Yp(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(...qn(r,e.issues)):e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}const _b=K("$ZodObject",(e,t)=>{Xe.init(e,t);const r=ul(()=>{const h=Object.keys(t.shape);for(const m of h)if(!(t.shape[m]instanceof Xe))throw new Error(`Invalid element at key "${m}": expected a Zod schema`);const p=j1(t.shape);return{shape:t.shape,keys:h,keySet:new Set(h),numKeys:h.length,optionalKeys:new Set(p)}});He(e._zod,"propValues",()=>{const h=t.shape,p={};for(const m in h){const f=h[m]._zod;if(f.values){p[m]??(p[m]=new Set);for(const b of f.values)p[m].add(b)}}return p});const n=h=>{const p=new Lw(["shape","payload","ctx"]),m=r.value,f=v=>{const g=Bo(v);return`shape[${g}]._zod.run({ value: input[${g}], issues: [] }, ctx)`};p.write("const input = payload.value;");const b=Object.create(null);let w=0;for(const v of m.keys)b[v]=`key_${w++}`;p.write("const newResult = {}");for(const v of m.keys)if(m.optionalKeys.has(v)){const g=b[v];p.write(`const ${g} = ${f(v)};`);const I=Bo(v);p.write(`
|
|
6
|
+
if (${g}.issues.length) {
|
|
7
|
+
if (input[${I}] === undefined) {
|
|
8
|
+
if (${I} in input) {
|
|
9
|
+
newResult[${I}] = undefined;
|
|
10
10
|
}
|
|
11
11
|
} else {
|
|
12
12
|
payload.issues = payload.issues.concat(
|
|
13
|
-
${
|
|
13
|
+
${g}.issues.map((iss) => ({
|
|
14
14
|
...iss,
|
|
15
|
-
path: iss.path ? [${
|
|
15
|
+
path: iss.path ? [${I}, ...iss.path] : [${I}],
|
|
16
16
|
}))
|
|
17
17
|
);
|
|
18
18
|
}
|
|
19
|
-
} else if (${
|
|
20
|
-
if (${
|
|
19
|
+
} else if (${g}.value === undefined) {
|
|
20
|
+
if (${I} in input) newResult[${I}] = undefined;
|
|
21
21
|
} else {
|
|
22
|
-
newResult[${
|
|
22
|
+
newResult[${I}] = ${g}.value;
|
|
23
23
|
}
|
|
24
|
-
`)}else{const
|
|
25
|
-
if (${
|
|
24
|
+
`)}else{const g=b[v];p.write(`const ${g} = ${f(v)};`),p.write(`
|
|
25
|
+
if (${g}.issues.length) payload.issues = payload.issues.concat(${g}.issues.map(iss => ({
|
|
26
26
|
...iss,
|
|
27
|
-
path: iss.path ? [${
|
|
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=>en(s,n,Xr())))}),t}const Ip=G("$ZodUnion",(e,t)=>{Xe.init(e,t),Ze(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Ze(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Ze(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),Ze(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=>el(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=G("$ZodDiscriminatedUnion",(e,t)=>{Ip.init(e,t);const r=e._zod.parse;Ze(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=Qi(()=>{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=G("$ZodIntersection",(e,t)=>{Xe.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 nl(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=nl(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=nl(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=nl(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=G("$ZodRecord",(e,t)=>{Xe.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=>en(c,n,Xr())),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=G("$ZodEnum",(e,t)=>{Xe.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=G("$ZodLiteral",(e,t)=>{Xe.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=G("$ZodTransform",(e,t)=>{Xe.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=G("$ZodOptional",(e,t)=>{Xe.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Ze(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Ze(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${el(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=G("$ZodNullable",(e,t)=>{Xe.init(e,t),Ze(e._zod,"optin",()=>t.innerType._zod.optin),Ze(e._zod,"optout",()=>t.innerType._zod.optout),Ze(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${el(r.source)}|null)$`):void 0}),Ze(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=G("$ZodDefault",(e,t)=>{Xe.init(e,t),e._zod.optin="optional",Ze(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=G("$ZodPrefault",(e,t)=>{Xe.init(e,t),e._zod.optin="optional",Ze(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=G("$ZodNonOptional",(e,t)=>{Xe.init(e,t),Ze(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=G("$ZodCatch",(e,t)=>{Xe.init(e,t),e._zod.optin="optional",Ze(e._zod,"optout",()=>t.innerType._zod.optout),Ze(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=>en(i,n,Xr()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(s=>en(s,n,Xr()))},input:r.value}),r.issues=[]),r)}}),$w=G("$ZodPipe",(e,t)=>{Xe.init(e,t),Ze(e._zod,"values",()=>t.in._zod.values),Ze(e._zod,"optin",()=>t.in._zod.optin),Ze(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=G("$ZodReadonly",(e,t)=>{Xe.init(e,t),Ze(e._zod,"propValues",()=>t.innerType._zod.propValues),Ze(e._zod,"values",()=>t.innerType._zod.values),Ze(e._zod,"optin",()=>t.innerType._zod.optin),Ze(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=G("$ZodLazy",(e,t)=>{Xe.init(e,t),Ze(e._zod,"innerType",()=>t.getter()),Ze(e._zod,"pattern",()=>e._zod.innerType._zod.pattern),Ze(e._zod,"propValues",()=>e._zod.innerType._zod.propValues),Ze(e._zod,"optin",()=>e._zod.innerType._zod.optin),Ze(e._zod,"optout",()=>e._zod.innerType._zod.optout),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)}),Mw=G("$ZodCustom",(e,t)=>{Bt.init(e,t),Xe.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 Ww(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...fe(t)})}function Gw(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 ol(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 sl(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"&&kt(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 kt(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 kt(o.element,r);case"object":{for(const s in o.shape)if(kt(o.shape[s],r))return!0;return!1}case"union":{for(const s of o.options)if(kt(s,r))return!0;return!1}case"intersection":return kt(o.left,r)||kt(o.right,r);case"tuple":{for(const s of o.items)if(kt(s,r))return!0;return!!(o.rest&&kt(o.rest,r))}case"record":return kt(o.keyType,r)||kt(o.valueType,r);case"map":return kt(o.keyType,r)||kt(o.valueType,r);case"set":return kt(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return kt(o.innerType,r);case"lazy":return kt(o.getter(),r);case"default":return kt(o.innerType,r);case"prefault":return kt(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return kt(o.in,r)||kt(o.out,r);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${o.type}`)}const Ib=G("ZodISODateTime",(e,t)=>{G1.init(e,t),ct.init(e,t)});function Vp(e){return eb(Ib,e)}const xb=G("ZodISODate",(e,t)=>{K1.init(e,t),ct.init(e,t)});function Eb(e){return tb(xb,e)}const $b=G("ZodISOTime",(e,t)=>{Y1.init(e,t),ct.init(e,t)});function Rb(e){return rb($b,e)}const Pb=G("ZodISODuration",(e,t)=>{Q1.init(e,t),ct.init(e,t)});function Mb(e){return nb(Pb,e)}const Ws=G("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(Ws),Ob=Wv(Ws),Ab=dp(Ws),Zp=fp(Ws),rt=G("ZodType",(e,t)=>(Xe.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=>il(e,r),e.transform=r=>cl(e,Xp(r)),e.default=r=>h3(e,r),e.prefault=r=>g3(e,r),e.catch=r=>v3(e,r),e.pipe=r=>cl(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=G("_ZodString",(e,t)=>{rl.init(e,t),rt.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=G("ZodString",(e,t)=>{rl.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(Gs,r)),e.uuidv4=r=>e.check(Lw(Gs,r)),e.uuidv6=r=>e.check(jw(Gs,r)),e.uuidv7=r=>e.check(Dw(Gs,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(Wp,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(Ww(Jb,r)),e.cidrv4=r=>e.check(Gw(Wb,r)),e.cidrv6=r=>e.check(Kw(Gb,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 ct=G("ZodStringFormat",(e,t)=>{st.init(e,t),Bp.init(e,t)}),Lb=G("ZodEmail",(e,t)=>{U1.init(e,t),ct.init(e,t)}),Hp=G("ZodGUID",(e,t)=>{j1.init(e,t),ct.init(e,t)}),Gs=G("ZodUUID",(e,t)=>{D1.init(e,t),ct.init(e,t)}),Jp=G("ZodURL",(e,t)=>{z1.init(e,t),ct.init(e,t)});function jb(e){return Ap(Jp,e)}const Db=G("ZodEmoji",(e,t)=>{F1.init(e,t),ct.init(e,t)}),Ub=G("ZodNanoID",(e,t)=>{V1.init(e,t),ct.init(e,t)}),zb=G("ZodCUID",(e,t)=>{Z1.init(e,t),ct.init(e,t)}),Fb=G("ZodCUID2",(e,t)=>{B1.init(e,t),ct.init(e,t)}),Vb=G("ZodULID",(e,t)=>{H1.init(e,t),ct.init(e,t)}),Zb=G("ZodXID",(e,t)=>{J1.init(e,t),ct.init(e,t)}),Bb=G("ZodKSUID",(e,t)=>{W1.init(e,t),ct.init(e,t)}),Hb=G("ZodIPv4",(e,t)=>{X1.init(e,t),ct.init(e,t)}),Jb=G("ZodIPv6",(e,t)=>{ew.init(e,t),ct.init(e,t)}),Wb=G("ZodCIDRv4",(e,t)=>{tw.init(e,t),ct.init(e,t)}),Gb=G("ZodCIDRv6",(e,t)=>{rw.init(e,t),ct.init(e,t)}),Wp=G("ZodBase64",(e,t)=>{nw.init(e,t),ct.init(e,t)});function Gp(e){return qp(Wp,e)}const Kb=G("ZodBase64URL",(e,t)=>{sw.init(e,t),ct.init(e,t)}),Yb=G("ZodE164",(e,t)=>{aw.init(e,t),ct.init(e,t)}),Qb=G("ZodJWT",(e,t)=>{lw.init(e,t),ct.init(e,t)}),al=G("ZodNumber",(e,t)=>{kp.init(e,t),rt.init(e,t),e.gt=(n,o)=>e.check(jp(n,o)),e.gte=(n,o)=>e.check(sl(n,o)),e.min=(n,o)=>e.check(sl(n,o)),e.lt=(n,o)=>e.check(Lp(n,o)),e.lte=(n,o)=>e.check(ol(n,o)),e.max=(n,o)=>e.check(ol(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(sl(0,n)),e.negative=n=>e.check(Lp(0,n)),e.nonpositive=n=>e.check(ol(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 O(e){return ob(al,e)}const Xb=G("ZodNumberFormat",(e,t)=>{cw.init(e,t),al.init(e,t)});function Kp(e){return ab(Xb,e)}const e3=G("ZodBoolean",(e,t)=>{uw.init(e,t),rt.init(e,t)});function me(e){return ib(e3,e)}const t3=G("ZodNull",(e,t)=>{dw.init(e,t),rt.init(e,t)});function Do(e){return lb(t3,e)}const r3=G("ZodAny",(e,t)=>{pw.init(e,t),rt.init(e,t)});function yt(){return cb(r3)}const n3=G("ZodUnknown",(e,t)=>{fw.init(e,t),rt.init(e,t)});function Ce(){return ub(n3)}const o3=G("ZodNever",(e,t)=>{hw.init(e,t),rt.init(e,t)});function s3(e){return db(o3,e)}const a3=G("ZodArray",(e,t)=>{mw.init(e,t),rt.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=G("ZodObject",(e,t)=>{gw.init(e,t),rt.init(e,t),Ze(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:Ce()}),e.loose=()=>e.clone({...e._zod.def,catchall:Ce()}),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 ut(e,t){return new Yp({type:"object",get shape(){return zs(this,"shape",{...e}),this.shape},catchall:Ce(),...fe(t)})}const Qp=G("ZodUnion",(e,t)=>{Ip.init(e,t),rt.init(e,t),e.options=t.options});function ae(e,t){return new Qp({type:"union",options:e,...fe(t)})}const i3=G("ZodDiscriminatedUnion",(e,t)=>{Qp.init(e,t),_w.init(e,t)});function ze(e,t,r){return new i3({type:"union",options:t,discriminator:e,...fe(r)})}const l3=G("ZodIntersection",(e,t)=>{yw.init(e,t),rt.init(e,t)});function il(e,t){return new l3({type:"intersection",left:e,right:t})}const c3=G("ZodRecord",(e,t)=>{vw.init(e,t),rt.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function ge(e,t,r){return new c3({type:"record",keyType:e,valueType:t,...fe(r)})}const ll=G("ZodEnum",(e,t)=>{ww.init(e,t),rt.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 ll({...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 ll({...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 ll({type:"enum",entries:r,...fe(t)})}const u3=G("ZodLiteral",(e,t)=>{bw.init(e,t),rt.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=G("ZodTransform",(e,t)=>{kw.init(e,t),rt.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=G("ZodOptional",(e,t)=>{Tw.init(e,t),rt.init(e,t),e.unwrap=()=>e._zod.def.innerType});function de(e){return new ef({type:"optional",innerType:e})}const p3=G("ZodNullable",(e,t)=>{Cw.init(e,t),rt.init(e,t),e.unwrap=()=>e._zod.def.innerType});function tf(e){return new p3({type:"nullable",innerType:e})}const f3=G("ZodDefault",(e,t)=>{Sw.init(e,t),rt.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=G("ZodPrefault",(e,t)=>{Iw.init(e,t),rt.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=G("ZodNonOptional",(e,t)=>{xw.init(e,t),rt.init(e,t),e.unwrap=()=>e._zod.def.innerType});function _3(e,t){return new rf({type:"nonoptional",innerType:e,...fe(t)})}const y3=G("ZodCatch",(e,t)=>{Ew.init(e,t),rt.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=G("ZodPipe",(e,t)=>{$w.init(e,t),rt.init(e,t),e.in=t.in,e.out=t.out});function cl(e,t){return new w3({type:"pipe",in:e,out:t})}const b3=G("ZodReadonly",(e,t)=>{Rw.init(e,t),rt.init(e,t)});function k3(e){return new b3({type:"readonly",innerType:e})}const T3=G("ZodLazy",(e,t)=>{Pw.init(e,t),rt.init(e,t),e.unwrap=()=>e._zod.def.getter()});function Ks(e){return new T3({type:"lazy",getter:e})}const ul=G("ZodCustom",(e,t)=>{Mw.init(e,t),rt.init(e,t)});function C3(e){const t=new Bt({check:"custom"});return t._zod.check=e,t}function nf(e,t){return Tb(ul,e??(()=>!0),t)}function S3(e,t={}){return Cb(ul,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 ul({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 cl(Xp(e),t)}const sf={custom:"custom"};function af(e){return sb(al,e)}var Fe;(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})(Fe||(Fe={}));var lf;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(lf||(lf={}));const pe=Fe.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),tn=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=Fe.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 zr 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 zr))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Fe.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()}}zr.create=e=>new zr(e);const dl=(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,Fe.jsonStringifyReplacer)}`;break;case oe.unrecognized_keys:r=`Unrecognized key(s) in object: ${Fe.joinValues(e.keys,", ")}`;break;case oe.invalid_union:r="Invalid input";break;case oe.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Fe.joinValues(e.options)}`;break;case oe.invalid_enum_value:r=`Invalid enum value. Expected ${Fe.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}"`:Fe.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,Fe.assertNever(e)}return{message:r}};let x3=dl;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===dl?void 0:dl].filter(o=>!!o)});e.common.issues.push(n)}class Xt{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 Ie;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 Xt.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 Ie;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 Ie=Object.freeze({status:"aborted"}),Uo=e=>({status:"dirty",value:e}),cr=e=>({status:"valid",value:e}),cf=e=>e.status==="aborted",uf=e=>e.status==="dirty",Xn=e=>e.status==="valid",Qs=e=>typeof Promise<"u"&&e instanceof Promise;var he;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(he||(he={}));class rn{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(Xn(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 zr(e.common.issues);return this._error=r,this._error}}};function Ne(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 De{get description(){return this._def.description}_getType(t){return tn(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:tn(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Xt,ctx:{common:t.parent.common,data:t.data,parsedType:tn(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:tn(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:tn(t)};if(!this["~standard"].async)try{const n=this._parseSync({data:t,path:[],parent:r});return Xn(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=>Xn(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:tn(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 no({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 sn.create(this,this._def)}nullable(){return oo.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Nr.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 no({...Ne(this._def),schema:this,typeName:se.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const r=typeof t=="function"?t:()=>t;return new hl({...Ne(this._def),innerType:this,defaultValue:r,typeName:se.ZodDefault})}brand(){return new Q3({typeName:se.ZodBranded,type:this,...Ne(this._def)})}catch(t){const r=typeof t=="function"?t:()=>t;return new ml({...Ne(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 gl.create(this,t)}readonly(){return _l.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 pl;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 W3(e,t){return!!((t==="v4"||!t)&&D3.test(e)||(t==="v6"||!t)&&z3.test(e))}function G3(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 nn extends De{_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}),Ie}const n=new Xt;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")pl||(pl=new RegExp(j3,"u")),pl.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"?W3(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"?G3(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()):Fe.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,...he.errToObj(n)})}_addCheck(t){return new nn({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...he.errToObj(t)})}url(t){return this._addCheck({kind:"url",...he.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...he.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...he.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...he.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...he.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...he.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...he.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...he.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...he.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...he.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...he.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...he.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,...he.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,...he.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...he.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...he.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...he.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...he.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...he.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...he.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...he.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...he.errToObj(r)})}nonempty(t){return this.min(1,he.errToObj(t))}trim(){return new nn({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new nn({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new nn({...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}}nn.create=e=>new nn({checks:[],typeName:se.ZodString,coerce:e?.coerce??!1,...Ne(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 eo extends De{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}),Ie}let n;const o=new Xt;for(const s of this._def.checks)s.kind==="int"?Fe.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()):Fe.assertNever(s);return{status:o.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,he.toString(r))}gt(t,r){return this.setLimit("min",t,!1,he.toString(r))}lte(t,r){return this.setLimit("max",t,!0,he.toString(r))}lt(t,r){return this.setLimit("max",t,!1,he.toString(r))}setLimit(t,r,n,o){return new eo({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:he.toString(o)}]})}_addCheck(t){return new eo({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:he.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:he.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:he.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:he.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:he.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:he.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:he.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:he.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:he.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"&&Fe.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)}}eo.create=e=>new eo({checks:[],typeName:se.ZodNumber,coerce:e?.coerce||!1,...Ne(e)});class zo extends De{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 Xt;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()):Fe.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}),Ie}gte(t,r){return this.setLimit("min",t,!0,he.toString(r))}gt(t,r){return this.setLimit("min",t,!1,he.toString(r))}lte(t,r){return this.setLimit("max",t,!0,he.toString(r))}lt(t,r){return this.setLimit("max",t,!1,he.toString(r))}setLimit(t,r,n,o){return new zo({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:he.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:he.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:he.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:he.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:he.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:he.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,...Ne(e)});class hf extends De{_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}),Ie}return cr(t.data)}}hf.create=e=>new hf({typeName:se.ZodBoolean,coerce:e?.coerce||!1,...Ne(e)});class Xs extends De{_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}),Ie}if(Number.isNaN(t.data.getTime())){const s=this._getOrReturnCtx(t);return le(s,{code:oe.invalid_date}),Ie}const n=new Xt;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()):Fe.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:he.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:he.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,...Ne(e)});class mf extends De{_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}),Ie}return cr(t.data)}}mf.create=e=>new mf({typeName:se.ZodSymbol,...Ne(e)});class gf extends De{_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}),Ie}return cr(t.data)}}gf.create=e=>new gf({typeName:se.ZodUndefined,...Ne(e)});class _f extends De{_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}),Ie}return cr(t.data)}}_f.create=e=>new _f({typeName:se.ZodNull,...Ne(e)});class yf extends De{constructor(){super(...arguments),this._any=!0}_parse(t){return cr(t.data)}}yf.create=e=>new yf({typeName:se.ZodAny,...Ne(e)});class vf extends De{constructor(){super(...arguments),this._unknown=!0}_parse(t){return cr(t.data)}}vf.create=e=>new vf({typeName:se.ZodUnknown,...Ne(e)});class on extends De{_parse(t){const r=this._getOrReturnCtx(t);return le(r,{code:oe.invalid_type,expected:pe.never,received:r.parsedType}),Ie}}on.create=e=>new on({typeName:se.ZodNever,...Ne(e)});class wf extends De{_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}),Ie}return cr(t.data)}}wf.create=e=>new wf({typeName:se.ZodVoid,...Ne(e)});class Nr extends De{_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}),Ie;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 rn(r,i,r.path,a)))).then(i=>Xt.mergeArray(n,i));const s=[...r.data].map((i,a)=>o.type._parseSync(new rn(r,i,r.path,a)));return Xt.mergeArray(n,s)}get element(){return this._def.type}min(t,r){return new Nr({...this._def,minLength:{value:t,message:he.toString(r)}})}max(t,r){return new Nr({...this._def,maxLength:{value:t,message:he.toString(r)}})}length(t,r){return new Nr({...this._def,exactLength:{value:t,message:he.toString(r)}})}nonempty(t){return this.min(1,t)}}Nr.create=(e,t)=>new Nr({type:e,minLength:null,maxLength:null,exactLength:null,typeName:se.ZodArray,...Ne(t)});function to(e){if(e instanceof vt){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=sn.create(to(n))}return new vt({...e._def,shape:()=>t})}else return e instanceof Nr?new Nr({...e._def,type:to(e.element)}):e instanceof sn?sn.create(to(e.unwrap())):e instanceof oo?oo.create(to(e.unwrap())):e instanceof En?En.create(e.items.map(t=>to(t))):e}class vt extends De{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=Fe.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}),Ie}const{status:n,ctx:o}=this._processInputParams(t),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof on&&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 rn(o,f,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof on){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 rn(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=>Xt.mergeObjectSync(n,c)):Xt.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(t){return he.errToObj,new vt({...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:he.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new vt({...this._def,unknownKeys:"strip"})}passthrough(){return new vt({...this._def,unknownKeys:"passthrough"})}extend(t){return new vt({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new vt({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 vt({...this._def,catchall:t})}pick(t){const r={};for(const n of Fe.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new vt({...this._def,shape:()=>r})}omit(t){const r={};for(const n of Fe.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new vt({...this._def,shape:()=>r})}deepPartial(){return to(this)}partial(t){const r={};for(const n of Fe.objectKeys(this.shape)){const o=this.shape[n];t&&!t[n]?r[n]=o:r[n]=o.optional()}return new vt({...this._def,shape:()=>r})}required(t){const r={};for(const n of Fe.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof sn;)s=s._def.innerType;r[n]=s}return new vt({...this._def,shape:()=>r})}keyof(){return Cf(Fe.objectKeys(this.shape))}}vt.create=(e,t)=>new vt({shape:()=>e,unknownKeys:"strip",catchall:on.create(),typeName:se.ZodObject,...Ne(t)}),vt.strictCreate=(e,t)=>new vt({shape:()=>e,unknownKeys:"strict",catchall:on.create(),typeName:se.ZodObject,...Ne(t)}),vt.lazycreate=(e,t)=>new vt({shape:e,unknownKeys:"strip",catchall:on.create(),typeName:se.ZodObject,...Ne(t)});class ea extends De{_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 zr(a.ctx.common.issues));return le(r,{code:oe.invalid_union,unionErrors:i}),Ie}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 zr(l));return le(r,{code:oe.invalid_union,unionErrors:a}),Ie}}get options(){return this._def.options}}ea.create=(e,t)=>new ea({options:e,typeName:se.ZodUnion,...Ne(t)});function fl(e,t){const r=tn(e),n=tn(t);if(e===t)return{valid:!0,data:e};if(r===pe.object&&n===pe.object){const o=Fe.objectKeys(t),s=Fe.objectKeys(e).filter(a=>o.indexOf(a)!==-1),i={...e,...t};for(const a of s){const l=fl(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=fl(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 De{_parse(t){const{status:r,ctx:n}=this._processInputParams(t),o=(s,i)=>{if(cf(s)||cf(i))return Ie;const a=fl(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}),Ie)};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,...Ne(r)});class En extends De{_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}),Ie;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"}),Ie;!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 rn(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>Xt.mergeArray(r,i)):Xt.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,...Ne(t)})};class bf extends De{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}),Ie;const o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,l],c)=>({key:o._parse(new rn(n,a,n.path,[c,"key"])),value:s._parse(new rn(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 Ie;(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 Ie;(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,...Ne(r)});class Fo extends De{_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}),Ie;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 Ie;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 rn(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:he.toString(r)}})}max(t,r){return new Fo({...this._def,maxSize:{value:t,message:he.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,...Ne(t)});class kf extends De{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,...Ne(t)});class Tf extends De{_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}),Ie}return{status:"valid",value:t.data}}get value(){return this._def.value}}Tf.create=(e,t)=>new Tf({value:e,typeName:se.ZodLiteral,...Ne(t)});function Cf(e,t){return new ro({values:e,typeName:se.ZodEnum,...Ne(t)})}class ro extends De{_parse(t){if(typeof t.data!="string"){const r=this._getOrReturnCtx(t),n=this._def.values;return le(r,{expected:Fe.joinValues(n),received:r.parsedType,code:oe.invalid_type}),Ie}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}),Ie}return cr(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 ro.create(t,{...this._def,...r})}exclude(t,r=this._def){return ro.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}}ro.create=Cf;class Sf extends De{_parse(t){const r=Fe.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==pe.string&&n.parsedType!==pe.number){const o=Fe.objectValues(r);return le(n,{expected:Fe.joinValues(o),received:n.parsedType,code:oe.invalid_type}),Ie}if(this._cache||(this._cache=new Set(Fe.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const o=Fe.objectValues(r);return le(n,{received:n.data,code:oe.invalid_enum_value,options:o}),Ie}return cr(t.data)}get enum(){return this._def.values}}Sf.create=(e,t)=>new Sf({values:e,typeName:se.ZodNativeEnum,...Ne(t)});class ra extends De{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}),Ie;const n=r.parsedType===pe.promise?r.data:Promise.resolve(r.data);return cr(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,...Ne(t)});class no extends De{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 Ie;const l=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return l.status==="aborted"?Ie:l.status==="dirty"||r.value==="dirty"?Uo(l.value):l});{if(r.value==="aborted")return Ie;const a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?Ie: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"?Ie:(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"?Ie:(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(!Xn(i))return Ie;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=>Xn(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):Ie);Fe.assertNever(o)}}no.create=(e,t,r)=>new no({schema:e,typeName:se.ZodEffects,effect:t,...Ne(r)}),no.createWithPreprocess=(e,t,r)=>new no({schema:t,effect:{type:"preprocess",transform:e},typeName:se.ZodEffects,...Ne(r)});class sn extends De{_parse(t){return this._getType(t)===pe.undefined?cr(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}sn.create=(e,t)=>new sn({innerType:e,typeName:se.ZodOptional,...Ne(t)});class oo extends De{_parse(t){return this._getType(t)===pe.null?cr(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}oo.create=(e,t)=>new oo({innerType:e,typeName:se.ZodNullable,...Ne(t)});class hl extends De{_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}}hl.create=(e,t)=>new hl({innerType:e,typeName:se.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Ne(t)});class ml extends De{_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 zr(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new zr(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}ml.create=(e,t)=>new ml({innerType:e,typeName:se.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Ne(t)});class If extends De{_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}),Ie}return{status:"valid",value:t.data}}}If.create=e=>new If({typeName:se.ZodNaN,...Ne(e)});class Q3 extends De{_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 gl extends De{_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"?Ie: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"?Ie: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 gl({in:t,out:r,typeName:se.ZodPipeline})}}class _l extends De{_parse(t){const r=this._def.innerType._parse(t),n=o=>(Xn(o)&&(o.value=Object.freeze(o.value)),o);return Qs(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}}_l.create=(e,t)=>new _l({innerType:e,typeName:se.ZodReadonly,...Ne(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 et=nn.create,Or=eo.create;on.create;const an=Nr.create,yr=vt.create,yl=ea.create;ta.create,En.create;const na=ro.create;ra.create,sn.create,oo.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 vl(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=vl,onError:r=vl,onRetry:n=vl,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
|
-
|
|
32
|
-
|
|
33
|
-
`,
|
|
34
|
-
`&&n++}}return[t,r]}class so 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 At(...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 ao(e){return Object.fromEntries([...e.headers])}var{btoa:r9,atob:n9}=globalThis;function io(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=n9(t);return Uint8Array.from(r,n=>n.codePointAt(0))}function lo(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return r9(t)}function co(e){return e instanceof Uint8Array?lo(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,Ht=class extends(Nf=we,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 we.hasMarker(e,Pf)}},wl=2*1024*1024*1024;async function Of({response:e,url:t,maxBytes:r=wl}){const n=e.headers.get("content-length");if(n!=null){const u=parseInt(n,10);if(!isNaN(u)&&u>r)throw new Ht({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 Ht({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 Ht({url:e,message:`Invalid URL: ${e}`})}if(t.protocol==="data:")return;if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Ht({url:e,message:`URL scheme must be http, https, or data, got ${t.protocol}`});const r=t.hostname;if(!r)throw new Ht({url:e,message:"URL must have a hostname"});if(r==="localhost"||r.endsWith(".local")||r.endsWith(".localhost"))throw new Ht({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 Ht({url:e,message:`URL with IPv6 address ${r} is not allowed`});return}if(Af(r)){if(bl(r))throw new Ht({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 bl(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 bl(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 bl(`${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 Ht({url:e,statusCode:o.status,statusText:o.statusText});const s=await Of({response:o,url:e,maxBytes:(r=t?.maxBytes)!=null?r:wl}),i=(n=o.headers.get("content-type"))!=null?n:void 0;return new Blob([s],i?{type:i}:void 0)}catch(o){throw Ht.isInstance(o)?o:new Ht({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()}`},Ut=Zo();function kl(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 lt({message:`Cannot connect to API: ${n.message}`,cause:n,url:t,requestBodyValues:r,isRetryable:!0})}return c9(e)?new lt({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 ln(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.22",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:ln(t,`ai-sdk/provider-utils/${jf}`,Bo()),signal:o}),a=ao(i);if(!i.ok){let l;try{l=await n({response:i,url:e,requestBodyValues:{}})}catch(c){throw $n(c)||lt.isInstance(c)?c:new lt({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)||lt.isInstance(l))?l:new lt({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 is 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 uo({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 Tl(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return Uf(e)}try{return Uf(e)}finally{Error.stackTraceLimit=t}}function Cl(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:Cl(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 er(){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=Je(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 Je(e.type._def,t)}var T9=(e,t)=>Je(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{...Je(e.innerType._def,t),default:e.defaultValue()}}function I9(e,t){return t.effectStrategy==="input"?Je(e.schema._def,t):er()}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=[Je(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Je(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 Sl=void 0,vr={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:()=>(Sl===void 0&&(Sl=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Sl),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":wr(r,"email",n.message,t);break;case"format:idn-email":wr(r,"idn-email",n.message,t);break;case"pattern:zod":zt(r,vr.email,n.message,t);break}break;case"url":wr(r,"uri",n.message,t);break;case"uuid":wr(r,"uuid",n.message,t);break;case"regex":zt(r,n.regex,n.message,t);break;case"cuid":zt(r,vr.cuid,n.message,t);break;case"cuid2":zt(r,vr.cuid2,n.message,t);break;case"startsWith":zt(r,RegExp(`^${Il(n.value,t)}`),n.message,t);break;case"endsWith":zt(r,RegExp(`${Il(n.value,t)}$`),n.message,t);break;case"datetime":wr(r,"date-time",n.message,t);break;case"date":wr(r,"date",n.message,t);break;case"time":wr(r,"time",n.message,t);break;case"duration":wr(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":{zt(r,RegExp(Il(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&wr(r,"ipv4",n.message,t),n.version!=="v4"&&wr(r,"ipv6",n.message,t);break}case"base64url":zt(r,vr.base64url,n.message,t);break;case"jwt":zt(r,vr.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&zt(r,vr.ipv4Cidr,n.message,t),n.version!=="v4"&&zt(r,vr.ipv6Cidr,n.message,t);break}case"emoji":zt(r,vr.emoji(),n.message,t);break;case"ulid":{zt(r,vr.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{wr(r,"binary",n.message,t);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{zt(r,vr.base64,n.message,t);break}}break}case"nanoid":zt(r,vr.nanoid,n.message,t)}return r}function Il(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 wr(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 zt(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
|
-
|
|
36
|
-
|
|
27
|
+
path: iss.path ? [${Bo(v)}, ...iss.path] : [${Bo(v)}]
|
|
28
|
+
})));`),p.write(`newResult[${Bo(v)}] = ${g}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");const C=p.compile();return(v,g)=>C(h,v,g)};let o;const a=Qa,i=!Mp.jitless,l=i&&q1.value,c=t.catchall;let u;e._zod.parse=(h,p)=>{u??(u=r.value);const m=h.value;if(!a(m))return h.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),h;const f=[];if(i&&l&&p?.async===!1&&p.jitless!==!0)o||(o=n(t.shape)),h=o(h,p);else{h.value={};const g=u.shape;for(const I of u.keys){const y=g[I],_=y._zod.run({value:m[I],issues:[]},p),k=y._zod.optin==="optional"&&y._zod.optout==="optional";_ instanceof Promise?f.push(_.then(S=>k?Yp(S,h,I,m):rs(S,h,I))):k?Yp(_,h,I,m):rs(_,h,I)}}if(!c)return f.length?Promise.all(f).then(()=>h):h;const b=[],w=u.keySet,C=c._zod,v=C.def.type;for(const g of Object.keys(m)){if(w.has(g))continue;if(v==="never"){b.push(g);continue}const I=C.run({value:m[g],issues:[]},p);I instanceof Promise?f.push(I.then(y=>rs(y,h,g))):rs(I,h,g)}return b.length&&h.issues.push({code:"unrecognized_keys",keys:b,input:m,inst:e}),f.length?Promise.all(f).then(()=>h):h}});function Qp(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(a=>pn(a,n,dn())))}),t}const Xp=K("$ZodUnion",(e,t)=>{Xe.init(e,t),He(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),He(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),He(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),He(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=>pl(n.source)).join("|")})$`)}}),e._zod.parse=(r,n)=>{let o=!1;const a=[];for(const i of t.options){const s=i._zod.run({value:r.value,issues:[]},n);if(s instanceof Promise)a.push(s),o=!0;else{if(s.issues.length===0)return s;a.push(s)}}return o?Promise.all(a).then(i=>Qp(i,r,e,n)):Qp(a,r,e,n)}}),yb=K("$ZodDiscriminatedUnion",(e,t)=>{Xp.init(e,t);const r=e._zod.parse;He(e._zod,"propValues",()=>{const o={};for(const a of t.options){const i=a._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(a)}"`);for(const[s,l]of Object.entries(i)){o[s]||(o[s]=new Set);for(const c of l)o[s].add(c)}}return o});const n=ul(()=>{const o=t.options,a=new Map;for(const i of o){const s=i._zod.propValues[t.discriminator];if(!s||s.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(const l of s){if(a.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);a.set(l,i)}}return a});e._zod.parse=(o,a)=>{const i=o.value;if(!Qa(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:e}),o;const s=n.value.get(i?.[t.discriminator]);return s?s._zod.run(o,a):t.unionFallback?r(o,a):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[t.discriminator],inst:e}),o)}}),vb=K("$ZodIntersection",(e,t)=>{Xe.init(e,t),e._zod.parse=(r,n)=>{const o=r.value,a=t.left._zod.run({value:o,issues:[]},n),i=t.right._zod.run({value:o,issues:[]},n);return a instanceof Promise||i instanceof Promise?Promise.all([a,i]).then(([l,c])=>eh(r,l,c)):eh(r,a,i)}});function ml(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(Xa(e)&&Xa(t)){const r=Object.keys(t),n=Object.keys(e).filter(a=>r.indexOf(a)!==-1),o={...e,...t};for(const a of n){const i=ml(e[a],t[a]);if(!i.valid)return{valid:!1,mergeErrorPath:[a,...i.mergeErrorPath]};o[a]=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],a=t[n],i=ml(o,a);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function eh(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),Go(e))return e;const n=ml(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 wb=K("$ZodRecord",(e,t)=>{Xe.init(e,t),e._zod.parse=(r,n)=>{const o=r.value;if(!Xa(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;const a=[];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?a.push(c.then(u=>{u.issues.length&&r.issues.push(...qn(l,u.issues)),r.value[l]=u.value})):(c.issues.length&&r.issues.push(...qn(l,c.issues)),r.value[l]=c.value)}let s;for(const l in o)i.has(l)||(s=s??[],s.push(l));s&&s.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:s})}else{r.value={};for(const i of Reflect.ownKeys(o)){if(i==="__proto__")continue;const s=t.keyType._zod.run({value:i,issues:[]},n);if(s instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(s.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:s.issues.map(c=>pn(c,n,dn())),input:i,path:[i],inst:e}),r.value[s.value]=s.value;continue}const l=t.valueType._zod.run({value:o[i],issues:[]},n);l instanceof Promise?a.push(l.then(c=>{c.issues.length&&r.issues.push(...qn(i,c.issues)),r.value[s.value]=c.value})):(l.issues.length&&r.issues.push(...qn(i,l.issues)),r.value[s.value]=l.value)}}return a.length?Promise.all(a).then(()=>r):r}}),bb=K("$ZodEnum",(e,t)=>{Xe.init(e,t);const r=Op(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(n=>L1.has(typeof n)).map(n=>typeof n=="string"?Jo(n):n.toString()).join("|")})$`),e._zod.parse=(n,o)=>{const a=n.value;return e._zod.values.has(a)||n.issues.push({code:"invalid_value",values:r,input:a,inst:e}),n}}),kb=K("$ZodLiteral",(e,t)=>{Xe.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?Jo(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}}),Tb=K("$ZodTransform",(e,t)=>{Xe.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 Ho;return r.value=o,r}}),Cb=K("$ZodOptional",(e,t)=>{Xe.init(e,t),e._zod.optin="optional",e._zod.optout="optional",He(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),He(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${pl(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)}),Sb=K("$ZodNullable",(e,t)=>{Xe.init(e,t),He(e._zod,"optin",()=>t.innerType._zod.optin),He(e._zod,"optout",()=>t.innerType._zod.optout),He(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${pl(r.source)}|null)$`):void 0}),He(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)}),Ib=K("$ZodDefault",(e,t)=>{Xe.init(e,t),e._zod.optin="optional",He(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(a=>th(a,t)):th(o,t)}});function th(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const xb=K("$ZodPrefault",(e,t)=>{Xe.init(e,t),e._zod.optin="optional",He(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))}),Eb=K("$ZodNonOptional",(e,t)=>{Xe.init(e,t),He(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(a=>rh(a,e)):rh(o,e)}});function rh(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 $b=K("$ZodCatch",(e,t)=>{Xe.init(e,t),e._zod.optin="optional",He(e._zod,"optout",()=>t.innerType._zod.optout),He(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(a=>(r.value=a.value,a.issues.length&&(r.value=t.catchValue({...r,error:{issues:a.issues.map(i=>pn(i,n,dn()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(a=>pn(a,n,dn()))},input:r.value}),r.issues=[]),r)}}),Rb=K("$ZodPipe",(e,t)=>{Xe.init(e,t),He(e._zod,"values",()=>t.in._zod.values),He(e._zod,"optin",()=>t.in._zod.optin),He(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(a=>nh(a,t,n)):nh(o,t,n)}});function nh(e,t,r){return Go(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}const Pb=K("$ZodReadonly",(e,t)=>{Xe.init(e,t),He(e._zod,"propValues",()=>t.innerType._zod.propValues),He(e._zod,"values",()=>t.innerType._zod.values),He(e._zod,"optin",()=>t.innerType._zod.optin),He(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(oh):oh(o)}});function oh(e){return e.value=Object.freeze(e.value),e}const Mb=K("$ZodLazy",(e,t)=>{Xe.init(e,t),He(e._zod,"innerType",()=>t.getter()),He(e._zod,"pattern",()=>e._zod.innerType._zod.pattern),He(e._zod,"propValues",()=>e._zod.innerType._zod.propValues),He(e._zod,"optin",()=>e._zod.innerType._zod.optin),He(e._zod,"optout",()=>e._zod.innerType._zod.optout),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)}),Ob=K("$ZodCustom",(e,t)=>{Xt.init(e,t),Xe.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(a=>ah(a,r,n,e));ah(o,r,n,e)}});function ah(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(Wo(o))}}class sh{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 Ab(){return new sh}const Ko=Ab();function Nb(e,t){return new e({type:"string",...ge(t)})}function qb(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...ge(t)})}function ih(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...ge(t)})}function Lb(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...ge(t)})}function jb(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...ge(t)})}function Db(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...ge(t)})}function Ub(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...ge(t)})}function lh(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...ge(t)})}function zb(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...ge(t)})}function Fb(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...ge(t)})}function Vb(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...ge(t)})}function Zb(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...ge(t)})}function Hb(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...ge(t)})}function Bb(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...ge(t)})}function Jb(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...ge(t)})}function Gb(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...ge(t)})}function Wb(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...ge(t)})}function Kb(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...ge(t)})}function Yb(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...ge(t)})}function ch(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...ge(t)})}function Qb(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...ge(t)})}function Xb(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...ge(t)})}function e3(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...ge(t)})}function t3(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...ge(t)})}function r3(e,t){return new e({type:"string",format:"date",check:"string_format",...ge(t)})}function n3(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...ge(t)})}function o3(e,t){return new e({type:"string",format:"duration",check:"string_format",...ge(t)})}function a3(e,t){return new e({type:"number",checks:[],...ge(t)})}function s3(e,t){return new e({type:"number",coerce:!0,checks:[],...ge(t)})}function i3(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...ge(t)})}function l3(e,t){return new e({type:"boolean",...ge(t)})}function c3(e,t){return new e({type:"null",...ge(t)})}function u3(e){return new e({type:"any"})}function d3(e){return new e({type:"unknown"})}function p3(e,t){return new e({type:"never",...ge(t)})}function uh(e,t){return new Bp({check:"less_than",...ge(t),value:e,inclusive:!1})}function gl(e,t){return new Bp({check:"less_than",...ge(t),value:e,inclusive:!0})}function dh(e,t){return new Jp({check:"greater_than",...ge(t),value:e,inclusive:!1})}function _l(e,t){return new Jp({check:"greater_than",...ge(t),value:e,inclusive:!0})}function ph(e,t){return new Sw({check:"multiple_of",...ge(t),value:e})}function hh(e,t){return new xw({check:"max_length",...ge(t),maximum:e})}function ns(e,t){return new Ew({check:"min_length",...ge(t),minimum:e})}function fh(e,t){return new $w({check:"length_equals",...ge(t),length:e})}function h3(e,t){return new Rw({check:"string_format",format:"regex",...ge(t),pattern:e})}function f3(e){return new Pw({check:"string_format",format:"lowercase",...ge(e)})}function m3(e){return new Mw({check:"string_format",format:"uppercase",...ge(e)})}function g3(e,t){return new Ow({check:"string_format",format:"includes",...ge(t),includes:e})}function _3(e,t){return new Aw({check:"string_format",format:"starts_with",...ge(t),prefix:e})}function y3(e,t){return new Nw({check:"string_format",format:"ends_with",...ge(t),suffix:e})}function Yo(e){return new qw({check:"overwrite",tx:e})}function v3(e){return Yo(t=>t.normalize(e))}function w3(){return Yo(e=>e.trim())}function b3(){return Yo(e=>e.toLowerCase())}function k3(){return Yo(e=>e.toUpperCase())}function T3(e,t,r){return new e({type:"array",element:t,...ge(r)})}function C3(e,t,r){const n=ge(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function S3(e,t,r){return new e({type:"custom",check:"custom",fn:t,...ge(r)})}class mh{constructor(t){this.counter=0,this.metadataRegistry=t?.metadata??Ko,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,a={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 s={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(t,s);const l=t._zod.toJSONSchema?.();if(l)s.schema=l;else{const h={...r,schemaPath:[...r.schemaPath,t],path:r.path},p=t._zod.parent;if(p)s.ref=p,this.process(p,h),this.seen.get(p).isParent=!0;else{const m=s.schema;switch(o.type){case"string":{const f=m;f.type="string";const{minimum:b,maximum:w,format:C,patterns:v,contentEncoding:g}=t._zod.bag;if(typeof b=="number"&&(f.minLength=b),typeof w=="number"&&(f.maxLength=w),C&&(f.format=a[C]??C,f.format===""&&delete f.format),g&&(f.contentEncoding=g),v&&v.size>0){const I=[...v];I.length===1?f.pattern=I[0].source:I.length>1&&(s.schema.allOf=[...I.map(y=>({...this.target==="draft-7"?{type:"string"}:{},pattern:y.source}))])}break}case"number":{const f=m,{minimum:b,maximum:w,format:C,multipleOf:v,exclusiveMaximum:g,exclusiveMinimum:I}=t._zod.bag;typeof C=="string"&&C.includes("int")?f.type="integer":f.type="number",typeof I=="number"&&(f.exclusiveMinimum=I),typeof b=="number"&&(f.minimum=b,typeof I=="number"&&(I>=b?delete f.minimum:delete f.exclusiveMinimum)),typeof g=="number"&&(f.exclusiveMaximum=g),typeof w=="number"&&(f.maximum=w,typeof g=="number"&&(g<=w?delete f.maximum:delete f.exclusiveMaximum)),typeof v=="number"&&(f.multipleOf=v);break}case"boolean":{const f=m;f.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{m.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{m.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const f=m,{minimum:b,maximum:w}=t._zod.bag;typeof b=="number"&&(f.minItems=b),typeof w=="number"&&(f.maxItems=w),f.type="array",f.items=this.process(o.element,{...h,path:[...h.path,"items"]});break}case"object":{const f=m;f.type="object",f.properties={};const b=o.shape;for(const v in b)f.properties[v]=this.process(b[v],{...h,path:[...h.path,"properties",v]});const w=new Set(Object.keys(b)),C=new Set([...w].filter(v=>{const g=o.shape[v]._zod;return this.io==="input"?g.optin===void 0:g.optout===void 0}));C.size>0&&(f.required=Array.from(C)),o.catchall?._zod.def.type==="never"?f.additionalProperties=!1:o.catchall?o.catchall&&(f.additionalProperties=this.process(o.catchall,{...h,path:[...h.path,"additionalProperties"]})):this.io==="output"&&(f.additionalProperties=!1);break}case"union":{const f=m;f.anyOf=o.options.map((b,w)=>this.process(b,{...h,path:[...h.path,"anyOf",w]}));break}case"intersection":{const f=m,b=this.process(o.left,{...h,path:[...h.path,"allOf",0]}),w=this.process(o.right,{...h,path:[...h.path,"allOf",1]}),C=g=>"allOf"in g&&Object.keys(g).length===1,v=[...C(b)?b.allOf:[b],...C(w)?w.allOf:[w]];f.allOf=v;break}case"tuple":{const f=m;f.type="array";const b=o.items.map((v,g)=>this.process(v,{...h,path:[...h.path,"prefixItems",g]}));if(this.target==="draft-2020-12"?f.prefixItems=b:f.items=b,o.rest){const v=this.process(o.rest,{...h,path:[...h.path,"items"]});this.target==="draft-2020-12"?f.items=v:f.additionalItems=v}o.rest&&(f.items=this.process(o.rest,{...h,path:[...h.path,"items"]}));const{minimum:w,maximum:C}=t._zod.bag;typeof w=="number"&&(f.minItems=w),typeof C=="number"&&(f.maxItems=C);break}case"record":{const f=m;f.type="object",f.propertyNames=this.process(o.keyType,{...h,path:[...h.path,"propertyNames"]}),f.additionalProperties=this.process(o.valueType,{...h,path:[...h.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{const f=m,b=Op(o.entries);b.every(w=>typeof w=="number")&&(f.type="number"),b.every(w=>typeof w=="string")&&(f.type="string"),f.enum=b;break}case"literal":{const f=m,b=[];for(const w of o.values)if(w===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof w=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");b.push(Number(w))}else b.push(w);if(b.length!==0)if(b.length===1){const w=b[0];f.type=w===null?"null":typeof w,f.const=w}else b.every(w=>typeof w=="number")&&(f.type="number"),b.every(w=>typeof w=="string")&&(f.type="string"),b.every(w=>typeof w=="boolean")&&(f.type="string"),b.every(w=>w===null)&&(f.type="null"),f.enum=b;break}case"file":{const f=m,b={type:"string",format:"binary",contentEncoding:"binary"},{minimum:w,maximum:C,mime:v}=t._zod.bag;w!==void 0&&(b.minLength=w),C!==void 0&&(b.maxLength=C),v?v.length===1?(b.contentMediaType=v[0],Object.assign(f,b)):f.anyOf=v.map(g=>({...b,contentMediaType:g})):Object.assign(f,b);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const f=this.process(o.innerType,h);m.anyOf=[f,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,h),s.ref=o.innerType;break}case"success":{const f=m;f.type="boolean";break}case"default":{this.process(o.innerType,h),s.ref=o.innerType,m.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,h),s.ref=o.innerType,this.io==="input"&&(m._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,h),s.ref=o.innerType;let f;try{f=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}m.default=f;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const f=m,b=t._zod.pattern;if(!b)throw new Error("Pattern not found in template literal");f.type="string",f.pattern=b.source;break}case"pipe":{const f=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(f,h),s.ref=f;break}case"readonly":{this.process(o.innerType,h),s.ref=o.innerType,m.readOnly=!0;break}case"promise":{this.process(o.innerType,h),s.ref=o.innerType;break}case"optional":{this.process(o.innerType,h),s.ref=o.innerType;break}case"lazy":{const f=t._zod.innerType;this.process(f,h),s.ref=f;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(s.schema,c),this.io==="input"&&Ct(t)&&(delete s.schema.examples,delete s.schema.default),this.io==="input"&&s.schema._prefault&&((n=s.schema).default??(n.default=s.schema._prefault)),delete s.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 a=u=>{const h=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){const b=n.external.registry.get(u[0])?.id,w=n.external.uri??(v=>v);if(b)return{ref:w(b)};const C=u[1].defId??u[1].schema.id??`schema${this.counter++}`;return u[1].defId=C,{defId:C,ref:`${w("__shared")}#/${h}/${C}`}}if(u[1]===o)return{ref:"#"};const m=`#/${h}/`,f=u[1].schema.id??`__schema${this.counter++}`;return{defId:f,ref:m+f}},i=u=>{if(u[1].schema.$ref)return;const h=u[1],{ref:p,defId:m}=a(u);h.def={...h.schema},m&&(h.defId=m);const f=h.schema;for(const b in f)delete f[b];f.$ref=p};if(n.cycles==="throw")for(const u of this.seen.entries()){const h=u[1];if(h.cycle)throw new Error(`Cycle detected: #/${h.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 h=u[1];if(t===u[0]){i(u);continue}if(n.external){const m=n.external.registry.get(u[0])?.id;if(t!==u[0]&&m){i(u);continue}}if(this.metadataRegistry.get(u[0])?.id){i(u);continue}if(h.cycle){i(u);continue}if(h.count>1&&n.reused==="ref"){i(u);continue}}const s=(u,h)=>{const p=this.seen.get(u),m=p.def??p.schema,f={...m};if(p.ref===null)return;const b=p.ref;if(p.ref=null,b){s(b,h);const w=this.seen.get(b).schema;w.$ref&&h.target==="draft-7"?(m.allOf=m.allOf??[],m.allOf.push(w)):(Object.assign(m,w),Object.assign(m,f))}p.isParent||this.override({zodSchema:u,jsonSchema:m,path:p.path??[]})};for(const u of[...this.seen.entries()].reverse())s(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 h=u[1];h.def&&h.defId&&(c[h.defId]=h.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 I3(e,t){if(e instanceof sh){const n=new mh(t),o={};for(const s of e._idmap.entries()){const[l,c]=s;n.process(c)}const a={},i={registry:e,uri:t?.uri,defs:o};for(const s of e._idmap.entries()){const[l,c]=s;a[l]=n.emit(c,{...t,external:i})}if(Object.keys(o).length>0){const s=n.target==="draft-2020-12"?"$defs":"definitions";a.__shared={[s]:o}}return{schemas:a}}const r=new mh(t);return r.process(e),r.emit(e,t)}function Ct(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 Ct(o.element,r);case"object":{for(const a in o.shape)if(Ct(o.shape[a],r))return!0;return!1}case"union":{for(const a of o.options)if(Ct(a,r))return!0;return!1}case"intersection":return Ct(o.left,r)||Ct(o.right,r);case"tuple":{for(const a of o.items)if(Ct(a,r))return!0;return!!(o.rest&&Ct(o.rest,r))}case"record":return Ct(o.keyType,r)||Ct(o.valueType,r);case"map":return Ct(o.keyType,r)||Ct(o.valueType,r);case"set":return Ct(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Ct(o.innerType,r);case"lazy":return Ct(o.getter(),r);case"default":return Ct(o.innerType,r);case"prefault":return Ct(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Ct(o.in,r)||Ct(o.out,r);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${o.type}`)}const x3=K("ZodISODateTime",(e,t)=>{Kw.init(e,t),ct.init(e,t)});function gh(e){return t3(x3,e)}const E3=K("ZodISODate",(e,t)=>{Yw.init(e,t),ct.init(e,t)});function $3(e){return r3(E3,e)}const R3=K("ZodISOTime",(e,t)=>{Qw.init(e,t),ct.init(e,t)});function P3(e){return n3(R3,e)}const M3=K("ZodISODuration",(e,t)=>{Xw.init(e,t),ct.init(e,t)});function O3(e){return o3(M3,e)}const os=K("ZodError",(e,t)=>{qp.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>J1(e,r)},flatten:{value:r=>B1(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}),A3=G1(os),N3=W1(os),q3=jp(os),_h=Up(os),rt=K("ZodType",(e,t)=>(Xe.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)=>Nn(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.parse=(r,n)=>A3(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>q3(e,r,n),e.parseAsync=async(r,n)=>N3(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>_h(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check(I9(r,n)),e.superRefine=r=>e.check(x9(r)),e.overwrite=r=>e.check(Yo(r)),e.optional=()=>ce(e),e.nullable=()=>Eh(e),e.nullish=()=>ce(Eh(e)),e.nonoptional=r=>y9(e,r),e.array=()=>L(e),e.or=r=>ae([e,r]),e.and=r=>vl(e,r),e.transform=r=>bl(e,Ih(r)),e.default=r=>m9(e,r),e.prefault=r=>_9(e,r),e.catch=r=>w9(e,r),e.pipe=r=>bl(e,r),e.readonly=()=>T9(e),e.describe=r=>{const n=e.clone();return Ko.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return Ko.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return Ko.get(e);const n=e.clone();return Ko.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),yh=K("_ZodString",(e,t)=>{fl.init(e,t),rt.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(h3(...n)),e.includes=(...n)=>e.check(g3(...n)),e.startsWith=(...n)=>e.check(_3(...n)),e.endsWith=(...n)=>e.check(y3(...n)),e.min=(...n)=>e.check(ns(...n)),e.max=(...n)=>e.check(hh(...n)),e.length=(...n)=>e.check(fh(...n)),e.nonempty=(...n)=>e.check(ns(1,...n)),e.lowercase=n=>e.check(f3(n)),e.uppercase=n=>e.check(m3(n)),e.trim=()=>e.check(w3()),e.normalize=(...n)=>e.check(v3(...n)),e.toLowerCase=()=>e.check(b3()),e.toUpperCase=()=>e.check(k3())}),L3=K("ZodString",(e,t)=>{fl.init(e,t),yh.init(e,t),e.email=r=>e.check(qb(j3,r)),e.url=r=>e.check(lh(wh,r)),e.jwt=r=>e.check(e3(X3,r)),e.emoji=r=>e.check(zb(U3,r)),e.guid=r=>e.check(ih(vh,r)),e.uuid=r=>e.check(Lb(as,r)),e.uuidv4=r=>e.check(jb(as,r)),e.uuidv6=r=>e.check(Db(as,r)),e.uuidv7=r=>e.check(Ub(as,r)),e.nanoid=r=>e.check(Fb(z3,r)),e.guid=r=>e.check(ih(vh,r)),e.cuid=r=>e.check(Vb(F3,r)),e.cuid2=r=>e.check(Zb(V3,r)),e.ulid=r=>e.check(Hb(Z3,r)),e.base64=r=>e.check(ch(bh,r)),e.base64url=r=>e.check(Qb(Y3,r)),e.xid=r=>e.check(Bb(H3,r)),e.ksuid=r=>e.check(Jb(B3,r)),e.ipv4=r=>e.check(Gb(J3,r)),e.ipv6=r=>e.check(Wb(G3,r)),e.cidrv4=r=>e.check(Kb(W3,r)),e.cidrv6=r=>e.check(Yb(K3,r)),e.e164=r=>e.check(Xb(Q3,r)),e.datetime=r=>e.check(gh(r)),e.date=r=>e.check($3(r)),e.time=r=>e.check(P3(r)),e.duration=r=>e.check(O3(r))});function d(e){return Nb(L3,e)}const ct=K("ZodStringFormat",(e,t)=>{ot.init(e,t),yh.init(e,t)}),j3=K("ZodEmail",(e,t)=>{zw.init(e,t),ct.init(e,t)}),vh=K("ZodGUID",(e,t)=>{Dw.init(e,t),ct.init(e,t)}),as=K("ZodUUID",(e,t)=>{Uw.init(e,t),ct.init(e,t)}),wh=K("ZodURL",(e,t)=>{Fw.init(e,t),ct.init(e,t)});function D3(e){return lh(wh,e)}const U3=K("ZodEmoji",(e,t)=>{Vw.init(e,t),ct.init(e,t)}),z3=K("ZodNanoID",(e,t)=>{Zw.init(e,t),ct.init(e,t)}),F3=K("ZodCUID",(e,t)=>{Hw.init(e,t),ct.init(e,t)}),V3=K("ZodCUID2",(e,t)=>{Bw.init(e,t),ct.init(e,t)}),Z3=K("ZodULID",(e,t)=>{Jw.init(e,t),ct.init(e,t)}),H3=K("ZodXID",(e,t)=>{Gw.init(e,t),ct.init(e,t)}),B3=K("ZodKSUID",(e,t)=>{Ww.init(e,t),ct.init(e,t)}),J3=K("ZodIPv4",(e,t)=>{eb.init(e,t),ct.init(e,t)}),G3=K("ZodIPv6",(e,t)=>{tb.init(e,t),ct.init(e,t)}),W3=K("ZodCIDRv4",(e,t)=>{rb.init(e,t),ct.init(e,t)}),K3=K("ZodCIDRv6",(e,t)=>{nb.init(e,t),ct.init(e,t)}),bh=K("ZodBase64",(e,t)=>{ob.init(e,t),ct.init(e,t)});function kh(e){return ch(bh,e)}const Y3=K("ZodBase64URL",(e,t)=>{sb.init(e,t),ct.init(e,t)}),Q3=K("ZodE164",(e,t)=>{ib.init(e,t),ct.init(e,t)}),X3=K("ZodJWT",(e,t)=>{cb.init(e,t),ct.init(e,t)}),yl=K("ZodNumber",(e,t)=>{Wp.init(e,t),rt.init(e,t),e.gt=(n,o)=>e.check(dh(n,o)),e.gte=(n,o)=>e.check(_l(n,o)),e.min=(n,o)=>e.check(_l(n,o)),e.lt=(n,o)=>e.check(uh(n,o)),e.lte=(n,o)=>e.check(gl(n,o)),e.max=(n,o)=>e.check(gl(n,o)),e.int=n=>e.check(Th(n)),e.safe=n=>e.check(Th(n)),e.positive=n=>e.check(dh(0,n)),e.nonnegative=n=>e.check(_l(0,n)),e.negative=n=>e.check(uh(0,n)),e.nonpositive=n=>e.check(gl(0,n)),e.multipleOf=(n,o)=>e.check(ph(n,o)),e.step=(n,o)=>e.check(ph(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 q(e){return a3(yl,e)}const e9=K("ZodNumberFormat",(e,t)=>{ub.init(e,t),yl.init(e,t)});function Th(e){return i3(e9,e)}const t9=K("ZodBoolean",(e,t)=>{db.init(e,t),rt.init(e,t)});function _e(e){return l3(t9,e)}const r9=K("ZodNull",(e,t)=>{pb.init(e,t),rt.init(e,t)});function Qo(e){return c3(r9,e)}const n9=K("ZodAny",(e,t)=>{hb.init(e,t),rt.init(e,t)});function ut(){return u3(n9)}const o9=K("ZodUnknown",(e,t)=>{fb.init(e,t),rt.init(e,t)});function Te(){return d3(o9)}const a9=K("ZodNever",(e,t)=>{mb.init(e,t),rt.init(e,t)});function s9(e){return p3(a9,e)}const i9=K("ZodArray",(e,t)=>{gb.init(e,t),rt.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(ns(r,n)),e.nonempty=r=>e.check(ns(1,r)),e.max=(r,n)=>e.check(hh(r,n)),e.length=(r,n)=>e.check(fh(r,n)),e.unwrap=()=>e.element});function L(e,t){return T3(i9,e,t)}const Ch=K("ZodObject",(e,t)=>{_b.init(e,t),rt.init(e,t),He(e,"shape",()=>t.shape),e.keyof=()=>le(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Te()}),e.loose=()=>e.clone({...e._zod.def,catchall:Te()}),e.strict=()=>e.clone({...e._zod.def,catchall:s9()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>F1(e,r),e.merge=r=>V1(e,r),e.pick=r=>U1(e,r),e.omit=r=>z1(e,r),e.partial=(...r)=>Z1(xh,e,r[0]),e.required=(...r)=>H1($h,e,r[0])});function T(e,t){const r={type:"object",get shape(){return Ya(this,"shape",{...e}),this.shape},...ge(t)};return new Ch(r)}function dt(e,t){return new Ch({type:"object",get shape(){return Ya(this,"shape",{...e}),this.shape},catchall:Te(),...ge(t)})}const Sh=K("ZodUnion",(e,t)=>{Xp.init(e,t),rt.init(e,t),e.options=t.options});function ae(e,t){return new Sh({type:"union",options:e,...ge(t)})}const l9=K("ZodDiscriminatedUnion",(e,t)=>{Sh.init(e,t),yb.init(e,t)});function Le(e,t,r){return new l9({type:"union",options:t,discriminator:e,...ge(r)})}const c9=K("ZodIntersection",(e,t)=>{vb.init(e,t),rt.init(e,t)});function vl(e,t){return new c9({type:"intersection",left:e,right:t})}const u9=K("ZodRecord",(e,t)=>{wb.init(e,t),rt.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function pe(e,t,r){return new u9({type:"record",keyType:e,valueType:t,...ge(r)})}const wl=K("ZodEnum",(e,t)=>{bb.init(e,t),rt.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 a={};for(const i of n)if(r.has(i))a[i]=t.entries[i];else throw new Error(`Key ${i} not found in enum`);return new wl({...t,checks:[],...ge(o),entries:a})},e.exclude=(n,o)=>{const a={...t.entries};for(const i of n)if(r.has(i))delete a[i];else throw new Error(`Key ${i} not found in enum`);return new wl({...t,checks:[],...ge(o),entries:a})}});function le(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new wl({type:"enum",entries:r,...ge(t)})}const d9=K("ZodLiteral",(e,t)=>{kb.init(e,t),rt.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 M(e,t){return new d9({type:"literal",values:Array.isArray(e)?e:[e],...ge(t)})}const p9=K("ZodTransform",(e,t)=>{Tb.init(e,t),rt.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=a=>{if(typeof a=="string")r.issues.push(Wo(a,r.value,t));else{const i=a;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(Wo(i))}};const o=t.transform(r.value,r);return o instanceof Promise?o.then(a=>(r.value=a,r)):(r.value=o,r)}});function Ih(e){return new p9({type:"transform",transform:e})}const xh=K("ZodOptional",(e,t)=>{Cb.init(e,t),rt.init(e,t),e.unwrap=()=>e._zod.def.innerType});function ce(e){return new xh({type:"optional",innerType:e})}const h9=K("ZodNullable",(e,t)=>{Sb.init(e,t),rt.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Eh(e){return new h9({type:"nullable",innerType:e})}const f9=K("ZodDefault",(e,t)=>{Ib.init(e,t),rt.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function m9(e,t){return new f9({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const g9=K("ZodPrefault",(e,t)=>{xb.init(e,t),rt.init(e,t),e.unwrap=()=>e._zod.def.innerType});function _9(e,t){return new g9({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const $h=K("ZodNonOptional",(e,t)=>{Eb.init(e,t),rt.init(e,t),e.unwrap=()=>e._zod.def.innerType});function y9(e,t){return new $h({type:"nonoptional",innerType:e,...ge(t)})}const v9=K("ZodCatch",(e,t)=>{$b.init(e,t),rt.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function w9(e,t){return new v9({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const b9=K("ZodPipe",(e,t)=>{Rb.init(e,t),rt.init(e,t),e.in=t.in,e.out=t.out});function bl(e,t){return new b9({type:"pipe",in:e,out:t})}const k9=K("ZodReadonly",(e,t)=>{Pb.init(e,t),rt.init(e,t)});function T9(e){return new k9({type:"readonly",innerType:e})}const C9=K("ZodLazy",(e,t)=>{Mb.init(e,t),rt.init(e,t),e.unwrap=()=>e._zod.def.getter()});function ss(e){return new C9({type:"lazy",getter:e})}const kl=K("ZodCustom",(e,t)=>{Ob.init(e,t),rt.init(e,t)});function S9(e){const t=new Xt({check:"custom"});return t._zod.check=e,t}function Rh(e,t){return C3(kl,e??(()=>!0),t)}function I9(e,t={}){return S3(kl,e,t)}function x9(e){const t=S9(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(Wo(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(Wo(o))}},e(r.value,r)));return t}function is(e,t={error:`Input not instance of ${e.name}`}){const r=new kl({type:"custom",check:"custom",fn:n=>n instanceof e,abort:!0,...ge(t)});return r._zod.bag.Class=e,r}function Ph(e,t){return bl(Ih(e),t)}const Mh={custom:"custom"};function Oh(e){return s3(yl,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 a={};for(const i of o)a[i]=i;return a},e.getValidEnumValues=o=>{const a=e.objectKeys(o).filter(s=>typeof o[o[s]]!="number"),i={};for(const s of a)i[s]=o[s];return e.objectValues(i)},e.objectValues=o=>e.objectKeys(o).map(function(a){return o[a]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const a=[];for(const i in o)Object.prototype.hasOwnProperty.call(o,i)&&a.push(i);return a},e.find=(o,a)=>{for(const i of o)if(a(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,a=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(a)}e.joinValues=n,e.jsonStringifyReplacer=(o,a)=>typeof a=="bigint"?a.toString():a})(Ze||(Ze={}));var Ah;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(Ah||(Ah={}));const he=Ze.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),hn=e=>{switch(typeof e){case"undefined":return he.undefined;case"string":return he.string;case"number":return Number.isNaN(e)?he.nan:he.number;case"boolean":return he.boolean;case"function":return he.function;case"bigint":return he.bigint;case"symbol":return he.symbol;case"object":return Array.isArray(e)?he.array:e===null?he.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?he.promise:typeof Map<"u"&&e instanceof Map?he.map:typeof Set<"u"&&e instanceof Set?he.set:typeof Date<"u"&&e instanceof Date?he.date:he.object;default:return he.unknown}},ne=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 Yr 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(a){return a.message},n={_errors:[]},o=a=>{for(const i of a.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 s=n,l=0;for(;l<i.path.length;){const c=i.path[l];l===i.path.length-1?(s[c]=s[c]||{_errors:[]},s[c]._errors.push(r(i))):s[c]=s[c]||{_errors:[]},s=s[c],l++}}};return o(this),n}static assert(t){if(!(t instanceof Yr))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 a=o.path[0];r[a]=r[a]||[],r[a].push(t(o))}else n.push(t(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}}Yr.create=e=>new Yr(e);const Tl=(e,t)=>{let r;switch(e.code){case ne.invalid_type:e.received===he.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case ne.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,Ze.jsonStringifyReplacer)}`;break;case ne.unrecognized_keys:r=`Unrecognized key(s) in object: ${Ze.joinValues(e.keys,", ")}`;break;case ne.invalid_union:r="Invalid input";break;case ne.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Ze.joinValues(e.options)}`;break;case ne.invalid_enum_value:r=`Invalid enum value. Expected ${Ze.joinValues(e.options)}, received '${e.received}'`;break;case ne.invalid_arguments:r="Invalid function arguments";break;case ne.invalid_return_type:r="Invalid function return type";break;case ne.invalid_date:r="Invalid date";break;case ne.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 ne.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 ne.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 ne.custom:r="Invalid input";break;case ne.invalid_intersection_types:r="Intersection results could not be merged";break;case ne.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case ne.not_finite:r="Number must be finite";break;default:r=t.defaultError,Ze.assertNever(e)}return{message:r}};let E9=Tl;function $9(){return E9}const R9=e=>{const{data:t,path:r,errorMaps:n,issueData:o}=e,a=[...r,...o.path||[]],i={...o,path:a};if(o.message!==void 0)return{...o,path:a,message:o.message};let s="";const l=n.filter(c=>!!c).slice().reverse();for(const c of l)s=c(i,{data:t,defaultError:s}).message;return{...o,path:a,message:s}};function ue(e,t){const r=$9(),n=R9({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===Tl?void 0:Tl].filter(o=>!!o)});e.common.issues.push(n)}class Wt{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 a=await o.key,i=await o.value;n.push({key:a,value:i})}return Wt.mergeObjectSync(t,n)}static mergeObjectSync(t,r){const n={};for(const o of r){const{key:a,value:i}=o;if(a.status==="aborted"||i.status==="aborted")return xe;a.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),a.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[a.value]=i.value)}return{status:t.value,value:n}}}const xe=Object.freeze({status:"aborted"}),Xo=e=>({status:"dirty",value:e}),mr=e=>({status:"valid",value:e}),Nh=e=>e.status==="aborted",qh=e=>e.status==="dirty",uo=e=>e.status==="valid",ls=e=>typeof Promise<"u"&&e instanceof Promise;var ve;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(ve||(ve={}));class zr{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 Lh=(e,t)=>{if(uo(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 Yr(e.common.issues);return this._error=r,this._error}}};function Pe(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,s)=>{const{message:l}=e;return i.code==="invalid_enum_value"?{message:l??s.defaultError}:typeof s.data>"u"?{message:l??n??s.defaultError}:i.code!=="invalid_type"?{message:s.defaultError}:{message:l??r??s.defaultError}},description:o}}class je{get description(){return this._def.description}_getType(t){return hn(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:hn(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Wt,ctx:{common:t.parent.common,data:t.data,parsedType:hn(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const r=this._parse(t);if(ls(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:hn(t)},o=this._parseSync({data:t,path:n.path,parent:n});return Lh(n,o)}"~validate"(t){const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:hn(t)};if(!this["~standard"].async)try{const n=this._parseSync({data:t,path:[],parent:r});return uo(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=>uo(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:hn(t)},o=this._parse({data:t,path:n.path,parent:n}),a=await(ls(o)?o:Promise.resolve(o));return Lh(n,a)}refine(t,r){const n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,a)=>{const i=t(o),s=()=>a.addIssue({code:ne.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(l=>l?!0:(s(),!1)):i?!0:(s(),!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 mo({schema:this,typeName:oe.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 mn.create(this,this._def)}nullable(){return go.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Fr.create(this)}promise(){return hs.create(this,this._def)}or(t){return us.create([this,t],this._def)}and(t){return ds.create(this,t,this._def)}transform(t){return new mo({...Pe(this._def),schema:this,typeName:oe.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const r=typeof t=="function"?t:()=>t;return new El({...Pe(this._def),innerType:this,defaultValue:r,typeName:oe.ZodDefault})}brand(){return new X9({typeName:oe.ZodBranded,type:this,...Pe(this._def)})}catch(t){const r=typeof t=="function"?t:()=>t;return new $l({...Pe(this._def),innerType:this,catchValue:r,typeName:oe.ZodCatch})}describe(t){const r=this.constructor;return new r({...this._def,description:t})}pipe(t){return Rl.create(this,t)}readonly(){return Pl.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const P9=/^c[^\s-]{8,}$/i,M9=/^[0-9a-z]+$/,O9=/^[0-9A-HJKMNP-TV-Z]{26}$/i,A9=/^[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,N9=/^[a-z0-9_-]{21}$/i,q9=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,L9=/^[-+]?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)?)??$/,j9=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,D9="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Cl;const U9=/^(?:(?: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])$/,z9=/^(?:(?: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])$/,F9=/^(([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]))$/,V9=/^(([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])$/,Z9=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,H9=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,jh="((\\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])))",B9=new RegExp(`^${jh}$`);function Dh(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 J9(e){return new RegExp(`^${Dh(e)}$`)}function G9(e){let t=`${jh}T${Dh(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 W9(e,t){return!!((t==="v4"||!t)&&U9.test(e)||(t==="v6"||!t)&&F9.test(e))}function K9(e,t){if(!q9.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 Y9(e,t){return!!((t==="v4"||!t)&&z9.test(e)||(t==="v6"||!t)&&V9.test(e))}class Qr extends je{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==he.string){const a=this._getOrReturnCtx(t);return ue(a,{code:ne.invalid_type,expected:he.string,received:a.parsedType}),xe}const n=new Wt;let o;for(const a of this._def.checks)if(a.kind==="min")t.data.length<a.value&&(o=this._getOrReturnCtx(t,o),ue(o,{code:ne.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="max")t.data.length>a.value&&(o=this._getOrReturnCtx(t,o),ue(o,{code:ne.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="length"){const i=t.data.length>a.value,s=t.data.length<a.value;(i||s)&&(o=this._getOrReturnCtx(t,o),i?ue(o,{code:ne.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):s&&ue(o,{code:ne.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),n.dirty())}else if(a.kind==="email")j9.test(t.data)||(o=this._getOrReturnCtx(t,o),ue(o,{validation:"email",code:ne.invalid_string,message:a.message}),n.dirty());else if(a.kind==="emoji")Cl||(Cl=new RegExp(D9,"u")),Cl.test(t.data)||(o=this._getOrReturnCtx(t,o),ue(o,{validation:"emoji",code:ne.invalid_string,message:a.message}),n.dirty());else if(a.kind==="uuid")A9.test(t.data)||(o=this._getOrReturnCtx(t,o),ue(o,{validation:"uuid",code:ne.invalid_string,message:a.message}),n.dirty());else if(a.kind==="nanoid")N9.test(t.data)||(o=this._getOrReturnCtx(t,o),ue(o,{validation:"nanoid",code:ne.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid")P9.test(t.data)||(o=this._getOrReturnCtx(t,o),ue(o,{validation:"cuid",code:ne.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid2")M9.test(t.data)||(o=this._getOrReturnCtx(t,o),ue(o,{validation:"cuid2",code:ne.invalid_string,message:a.message}),n.dirty());else if(a.kind==="ulid")O9.test(t.data)||(o=this._getOrReturnCtx(t,o),ue(o,{validation:"ulid",code:ne.invalid_string,message:a.message}),n.dirty());else if(a.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),ue(o,{validation:"url",code:ne.invalid_string,message:a.message}),n.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),ue(o,{validation:"regex",code:ne.invalid_string,message:a.message}),n.dirty())):a.kind==="trim"?t.data=t.data.trim():a.kind==="includes"?t.data.includes(a.value,a.position)||(o=this._getOrReturnCtx(t,o),ue(o,{code:ne.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),n.dirty()):a.kind==="toLowerCase"?t.data=t.data.toLowerCase():a.kind==="toUpperCase"?t.data=t.data.toUpperCase():a.kind==="startsWith"?t.data.startsWith(a.value)||(o=this._getOrReturnCtx(t,o),ue(o,{code:ne.invalid_string,validation:{startsWith:a.value},message:a.message}),n.dirty()):a.kind==="endsWith"?t.data.endsWith(a.value)||(o=this._getOrReturnCtx(t,o),ue(o,{code:ne.invalid_string,validation:{endsWith:a.value},message:a.message}),n.dirty()):a.kind==="datetime"?G9(a).test(t.data)||(o=this._getOrReturnCtx(t,o),ue(o,{code:ne.invalid_string,validation:"datetime",message:a.message}),n.dirty()):a.kind==="date"?B9.test(t.data)||(o=this._getOrReturnCtx(t,o),ue(o,{code:ne.invalid_string,validation:"date",message:a.message}),n.dirty()):a.kind==="time"?J9(a).test(t.data)||(o=this._getOrReturnCtx(t,o),ue(o,{code:ne.invalid_string,validation:"time",message:a.message}),n.dirty()):a.kind==="duration"?L9.test(t.data)||(o=this._getOrReturnCtx(t,o),ue(o,{validation:"duration",code:ne.invalid_string,message:a.message}),n.dirty()):a.kind==="ip"?W9(t.data,a.version)||(o=this._getOrReturnCtx(t,o),ue(o,{validation:"ip",code:ne.invalid_string,message:a.message}),n.dirty()):a.kind==="jwt"?K9(t.data,a.alg)||(o=this._getOrReturnCtx(t,o),ue(o,{validation:"jwt",code:ne.invalid_string,message:a.message}),n.dirty()):a.kind==="cidr"?Y9(t.data,a.version)||(o=this._getOrReturnCtx(t,o),ue(o,{validation:"cidr",code:ne.invalid_string,message:a.message}),n.dirty()):a.kind==="base64"?Z9.test(t.data)||(o=this._getOrReturnCtx(t,o),ue(o,{validation:"base64",code:ne.invalid_string,message:a.message}),n.dirty()):a.kind==="base64url"?H9.test(t.data)||(o=this._getOrReturnCtx(t,o),ue(o,{validation:"base64url",code:ne.invalid_string,message:a.message}),n.dirty()):Ze.assertNever(a);return{status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(o=>t.test(o),{validation:r,code:ne.invalid_string,...ve.errToObj(n)})}_addCheck(t){return new Qr({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...ve.errToObj(t)})}url(t){return this._addCheck({kind:"url",...ve.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...ve.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...ve.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...ve.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...ve.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...ve.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...ve.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...ve.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...ve.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...ve.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...ve.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...ve.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,...ve.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,...ve.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...ve.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...ve.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...ve.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...ve.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...ve.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...ve.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...ve.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...ve.errToObj(r)})}nonempty(t){return this.min(1,ve.errToObj(t))}trim(){return new Qr({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Qr({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Qr({...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}}Qr.create=e=>new Qr({checks:[],typeName:oe.ZodString,coerce:e?.coerce??!1,...Pe(e)});function Q9(e,t){const r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,a=Number.parseInt(e.toFixed(o).replace(".","")),i=Number.parseInt(t.toFixed(o).replace(".",""));return a%i/10**o}class po 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)!==he.number){const a=this._getOrReturnCtx(t);return ue(a,{code:ne.invalid_type,expected:he.number,received:a.parsedType}),xe}let n;const o=new Wt;for(const a of this._def.checks)a.kind==="int"?Ze.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),ue(n,{code:ne.invalid_type,expected:"integer",received:"float",message:a.message}),o.dirty()):a.kind==="min"?(a.inclusive?t.data<a.value:t.data<=a.value)&&(n=this._getOrReturnCtx(t,n),ue(n,{code:ne.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),o.dirty()):a.kind==="max"?(a.inclusive?t.data>a.value:t.data>=a.value)&&(n=this._getOrReturnCtx(t,n),ue(n,{code:ne.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),o.dirty()):a.kind==="multipleOf"?Q9(t.data,a.value)!==0&&(n=this._getOrReturnCtx(t,n),ue(n,{code:ne.not_multiple_of,multipleOf:a.value,message:a.message}),o.dirty()):a.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),ue(n,{code:ne.not_finite,message:a.message}),o.dirty()):Ze.assertNever(a);return{status:o.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,ve.toString(r))}gt(t,r){return this.setLimit("min",t,!1,ve.toString(r))}lte(t,r){return this.setLimit("max",t,!0,ve.toString(r))}lt(t,r){return this.setLimit("max",t,!1,ve.toString(r))}setLimit(t,r,n,o){return new po({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:ve.toString(o)}]})}_addCheck(t){return new po({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:ve.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:ve.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:ve.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:ve.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:ve.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:ve.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:ve.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:ve.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:ve.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)}}po.create=e=>new po({checks:[],typeName:oe.ZodNumber,coerce:e?.coerce||!1,...Pe(e)});class ea 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)!==he.bigint)return this._getInvalidInput(t);let n;const o=new Wt;for(const a of this._def.checks)a.kind==="min"?(a.inclusive?t.data<a.value:t.data<=a.value)&&(n=this._getOrReturnCtx(t,n),ue(n,{code:ne.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),o.dirty()):a.kind==="max"?(a.inclusive?t.data>a.value:t.data>=a.value)&&(n=this._getOrReturnCtx(t,n),ue(n,{code:ne.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),o.dirty()):a.kind==="multipleOf"?t.data%a.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),ue(n,{code:ne.not_multiple_of,multipleOf:a.value,message:a.message}),o.dirty()):Ze.assertNever(a);return{status:o.value,value:t.data}}_getInvalidInput(t){const r=this._getOrReturnCtx(t);return ue(r,{code:ne.invalid_type,expected:he.bigint,received:r.parsedType}),xe}gte(t,r){return this.setLimit("min",t,!0,ve.toString(r))}gt(t,r){return this.setLimit("min",t,!1,ve.toString(r))}lte(t,r){return this.setLimit("max",t,!0,ve.toString(r))}lt(t,r){return this.setLimit("max",t,!1,ve.toString(r))}setLimit(t,r,n,o){return new ea({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:ve.toString(o)}]})}_addCheck(t){return new ea({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:ve.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:ve.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:ve.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:ve.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:ve.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}}ea.create=e=>new ea({checks:[],typeName:oe.ZodBigInt,coerce:e?.coerce??!1,...Pe(e)});class Sl extends je{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==he.boolean){const n=this._getOrReturnCtx(t);return ue(n,{code:ne.invalid_type,expected:he.boolean,received:n.parsedType}),xe}return mr(t.data)}}Sl.create=e=>new Sl({typeName:oe.ZodBoolean,coerce:e?.coerce||!1,...Pe(e)});class cs extends je{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==he.date){const a=this._getOrReturnCtx(t);return ue(a,{code:ne.invalid_type,expected:he.date,received:a.parsedType}),xe}if(Number.isNaN(t.data.getTime())){const a=this._getOrReturnCtx(t);return ue(a,{code:ne.invalid_date}),xe}const n=new Wt;let o;for(const a of this._def.checks)a.kind==="min"?t.data.getTime()<a.value&&(o=this._getOrReturnCtx(t,o),ue(o,{code:ne.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),n.dirty()):a.kind==="max"?t.data.getTime()>a.value&&(o=this._getOrReturnCtx(t,o),ue(o,{code:ne.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),n.dirty()):Ze.assertNever(a);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new cs({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:ve.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:ve.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}}cs.create=e=>new cs({checks:[],coerce:e?.coerce||!1,typeName:oe.ZodDate,...Pe(e)});class Uh extends je{_parse(t){if(this._getType(t)!==he.symbol){const n=this._getOrReturnCtx(t);return ue(n,{code:ne.invalid_type,expected:he.symbol,received:n.parsedType}),xe}return mr(t.data)}}Uh.create=e=>new Uh({typeName:oe.ZodSymbol,...Pe(e)});class zh extends je{_parse(t){if(this._getType(t)!==he.undefined){const n=this._getOrReturnCtx(t);return ue(n,{code:ne.invalid_type,expected:he.undefined,received:n.parsedType}),xe}return mr(t.data)}}zh.create=e=>new zh({typeName:oe.ZodUndefined,...Pe(e)});class Fh extends je{_parse(t){if(this._getType(t)!==he.null){const n=this._getOrReturnCtx(t);return ue(n,{code:ne.invalid_type,expected:he.null,received:n.parsedType}),xe}return mr(t.data)}}Fh.create=e=>new Fh({typeName:oe.ZodNull,...Pe(e)});class Il extends je{constructor(){super(...arguments),this._any=!0}_parse(t){return mr(t.data)}}Il.create=e=>new Il({typeName:oe.ZodAny,...Pe(e)});class Vh extends je{constructor(){super(...arguments),this._unknown=!0}_parse(t){return mr(t.data)}}Vh.create=e=>new Vh({typeName:oe.ZodUnknown,...Pe(e)});class fn extends je{_parse(t){const r=this._getOrReturnCtx(t);return ue(r,{code:ne.invalid_type,expected:he.never,received:r.parsedType}),xe}}fn.create=e=>new fn({typeName:oe.ZodNever,...Pe(e)});class Zh extends je{_parse(t){if(this._getType(t)!==he.undefined){const n=this._getOrReturnCtx(t);return ue(n,{code:ne.invalid_type,expected:he.void,received:n.parsedType}),xe}return mr(t.data)}}Zh.create=e=>new Zh({typeName:oe.ZodVoid,...Pe(e)});class Fr extends je{_parse(t){const{ctx:r,status:n}=this._processInputParams(t),o=this._def;if(r.parsedType!==he.array)return ue(r,{code:ne.invalid_type,expected:he.array,received:r.parsedType}),xe;if(o.exactLength!==null){const i=r.data.length>o.exactLength.value,s=r.data.length<o.exactLength.value;(i||s)&&(ue(r,{code:i?ne.too_big:ne.too_small,minimum:s?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&&(ue(r,{code:ne.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&&(ue(r,{code:ne.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,s)=>o.type._parseAsync(new zr(r,i,r.path,s)))).then(i=>Wt.mergeArray(n,i));const a=[...r.data].map((i,s)=>o.type._parseSync(new zr(r,i,r.path,s)));return Wt.mergeArray(n,a)}get element(){return this._def.type}min(t,r){return new Fr({...this._def,minLength:{value:t,message:ve.toString(r)}})}max(t,r){return new Fr({...this._def,maxLength:{value:t,message:ve.toString(r)}})}length(t,r){return new Fr({...this._def,exactLength:{value:t,message:ve.toString(r)}})}nonempty(t){return this.min(1,t)}}Fr.create=(e,t)=>new Fr({type:e,minLength:null,maxLength:null,exactLength:null,typeName:oe.ZodArray,...Pe(t)});function ho(e){if(e instanceof bt){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=mn.create(ho(n))}return new bt({...e._def,shape:()=>t})}else return e instanceof Fr?new Fr({...e._def,type:ho(e.element)}):e instanceof mn?mn.create(ho(e.unwrap())):e instanceof go?go.create(ho(e.unwrap())):e instanceof Ln?Ln.create(e.items.map(t=>ho(t))):e}class bt 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)!==he.object){const c=this._getOrReturnCtx(t);return ue(c,{code:ne.invalid_type,expected:he.object,received:c.parsedType}),xe}const{status:n,ctx:o}=this._processInputParams(t),{shape:a,keys:i}=this._getCached(),s=[];if(!(this._def.catchall instanceof fn&&this._def.unknownKeys==="strip"))for(const c in o.data)i.includes(c)||s.push(c);const l=[];for(const c of i){const u=a[c],h=o.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new zr(o,h,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof fn){const c=this._def.unknownKeys;if(c==="passthrough")for(const u of s)l.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(c==="strict")s.length>0&&(ue(o,{code:ne.unrecognized_keys,keys:s}),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 s){const h=o.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new zr(o,h,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const c=[];for(const u of l){const h=await u.key,p=await u.value;c.push({key:h,value:p,alwaysSet:u.alwaysSet})}return c}).then(c=>Wt.mergeObjectSync(n,c)):Wt.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(t){return ve.errToObj,new bt({...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:ve.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new bt({...this._def,unknownKeys:"strip"})}passthrough(){return new bt({...this._def,unknownKeys:"passthrough"})}extend(t){return new bt({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new bt({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:oe.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new bt({...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 bt({...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 bt({...this._def,shape:()=>r})}deepPartial(){return ho(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 bt({...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 a=this.shape[n];for(;a instanceof mn;)a=a._def.innerType;r[n]=a}return new bt({...this._def,shape:()=>r})}keyof(){return Gh(Ze.objectKeys(this.shape))}}bt.create=(e,t)=>new bt({shape:()=>e,unknownKeys:"strip",catchall:fn.create(),typeName:oe.ZodObject,...Pe(t)}),bt.strictCreate=(e,t)=>new bt({shape:()=>e,unknownKeys:"strict",catchall:fn.create(),typeName:oe.ZodObject,...Pe(t)}),bt.lazycreate=(e,t)=>new bt({shape:e,unknownKeys:"strip",catchall:fn.create(),typeName:oe.ZodObject,...Pe(t)});class us extends je{_parse(t){const{ctx:r}=this._processInputParams(t),n=this._def.options;function o(a){for(const s of a)if(s.result.status==="valid")return s.result;for(const s of a)if(s.result.status==="dirty")return r.common.issues.push(...s.ctx.common.issues),s.result;const i=a.map(s=>new Yr(s.ctx.common.issues));return ue(r,{code:ne.invalid_union,unionErrors:i}),xe}if(r.common.async)return Promise.all(n.map(async a=>{const i={...r,common:{...r.common,issues:[]},parent:null};return{result:await a._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(o);{let a;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"&&!a&&(a={result:u,ctx:c}),c.common.issues.length&&i.push(c.common.issues)}if(a)return r.common.issues.push(...a.ctx.common.issues),a.result;const s=i.map(l=>new Yr(l));return ue(r,{code:ne.invalid_union,unionErrors:s}),xe}}get options(){return this._def.options}}us.create=(e,t)=>new us({options:e,typeName:oe.ZodUnion,...Pe(t)});function xl(e,t){const r=hn(e),n=hn(t);if(e===t)return{valid:!0,data:e};if(r===he.object&&n===he.object){const o=Ze.objectKeys(t),a=Ze.objectKeys(e).filter(s=>o.indexOf(s)!==-1),i={...e,...t};for(const s of a){const l=xl(e[s],t[s]);if(!l.valid)return{valid:!1};i[s]=l.data}return{valid:!0,data:i}}else if(r===he.array&&n===he.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let a=0;a<e.length;a++){const i=e[a],s=t[a],l=xl(i,s);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return r===he.date&&n===he.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class ds extends je{_parse(t){const{status:r,ctx:n}=this._processInputParams(t),o=(a,i)=>{if(Nh(a)||Nh(i))return xe;const s=xl(a.value,i.value);return s.valid?((qh(a)||qh(i))&&r.dirty(),{status:r.value,value:s.data}):(ue(n,{code:ne.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(([a,i])=>o(a,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}))}}ds.create=(e,t,r)=>new ds({left:e,right:t,typeName:oe.ZodIntersection,...Pe(r)});class Ln extends je{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==he.array)return ue(n,{code:ne.invalid_type,expected:he.array,received:n.parsedType}),xe;if(n.data.length<this._def.items.length)return ue(n,{code:ne.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),xe;!this._def.rest&&n.data.length>this._def.items.length&&(ue(n,{code:ne.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const a=[...n.data].map((i,s)=>{const l=this._def.items[s]||this._def.rest;return l?l._parse(new zr(n,i,n.path,s)):null}).filter(i=>!!i);return n.common.async?Promise.all(a).then(i=>Wt.mergeArray(r,i)):Wt.mergeArray(r,a)}get items(){return this._def.items}rest(t){return new Ln({...this._def,rest:t})}}Ln.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ln({items:e,typeName:oe.ZodTuple,rest:null,...Pe(t)})};class ps 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!==he.object)return ue(n,{code:ne.invalid_type,expected:he.object,received:n.parsedType}),xe;const o=[],a=this._def.keyType,i=this._def.valueType;for(const s in n.data)o.push({key:a._parse(new zr(n,s,n.path,s)),value:i._parse(new zr(n,n.data[s],n.path,s)),alwaysSet:s in n.data});return n.common.async?Wt.mergeObjectAsync(r,o):Wt.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof je?new ps({keyType:t,valueType:r,typeName:oe.ZodRecord,...Pe(n)}):new ps({keyType:Qr.create(),valueType:t,typeName:oe.ZodRecord,...Pe(r)})}}class Hh 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!==he.map)return ue(n,{code:ne.invalid_type,expected:he.map,received:n.parsedType}),xe;const o=this._def.keyType,a=this._def.valueType,i=[...n.data.entries()].map(([s,l],c)=>({key:o._parse(new zr(n,s,n.path,[c,"key"])),value:a._parse(new zr(n,l,n.path,[c,"value"]))}));if(n.common.async){const s=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(),s.set(c.value,u.value)}return{status:r.value,value:s}})}else{const s=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(),s.set(c.value,u.value)}return{status:r.value,value:s}}}}Hh.create=(e,t,r)=>new Hh({valueType:t,keyType:e,typeName:oe.ZodMap,...Pe(r)});class ta extends je{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==he.set)return ue(n,{code:ne.invalid_type,expected:he.set,received:n.parsedType}),xe;const o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(ue(n,{code:ne.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&&(ue(n,{code:ne.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());const a=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 s=[...n.data.values()].map((l,c)=>a._parse(new zr(n,l,n.path,c)));return n.common.async?Promise.all(s).then(l=>i(l)):i(s)}min(t,r){return new ta({...this._def,minSize:{value:t,message:ve.toString(r)}})}max(t,r){return new ta({...this._def,maxSize:{value:t,message:ve.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}}ta.create=(e,t)=>new ta({valueType:e,minSize:null,maxSize:null,typeName:oe.ZodSet,...Pe(t)});class Bh 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})}}Bh.create=(e,t)=>new Bh({getter:e,typeName:oe.ZodLazy,...Pe(t)});class Jh extends je{_parse(t){if(t.data!==this._def.value){const r=this._getOrReturnCtx(t);return ue(r,{received:r.data,code:ne.invalid_literal,expected:this._def.value}),xe}return{status:"valid",value:t.data}}get value(){return this._def.value}}Jh.create=(e,t)=>new Jh({value:e,typeName:oe.ZodLiteral,...Pe(t)});function Gh(e,t){return new fo({values:e,typeName:oe.ZodEnum,...Pe(t)})}class fo extends je{_parse(t){if(typeof t.data!="string"){const r=this._getOrReturnCtx(t),n=this._def.values;return ue(r,{expected:Ze.joinValues(n),received:r.parsedType,code:ne.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 ue(r,{received:r.data,code:ne.invalid_enum_value,options:n}),xe}return mr(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 fo.create(t,{...this._def,...r})}exclude(t,r=this._def){return fo.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}}fo.create=Gh;class Wh extends je{_parse(t){const r=Ze.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==he.string&&n.parsedType!==he.number){const o=Ze.objectValues(r);return ue(n,{expected:Ze.joinValues(o),received:n.parsedType,code:ne.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 ue(n,{received:n.data,code:ne.invalid_enum_value,options:o}),xe}return mr(t.data)}get enum(){return this._def.values}}Wh.create=(e,t)=>new Wh({values:e,typeName:oe.ZodNativeEnum,...Pe(t)});class hs extends je{unwrap(){return this._def.type}_parse(t){const{ctx:r}=this._processInputParams(t);if(r.parsedType!==he.promise&&r.common.async===!1)return ue(r,{code:ne.invalid_type,expected:he.promise,received:r.parsedType}),xe;const n=r.parsedType===he.promise?r.data:Promise.resolve(r.data);return mr(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}}hs.create=(e,t)=>new hs({type:e,typeName:oe.ZodPromise,...Pe(t)});class mo extends je{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===oe.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:r,ctx:n}=this._processInputParams(t),o=this._def.effect||null,a={addIssue:i=>{ue(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(a.addIssue=a.addIssue.bind(a),o.type==="preprocess"){const i=o.transform(n.data,a);if(n.common.async)return Promise.resolve(i).then(async s=>{if(r.value==="aborted")return xe;const l=await this._def.schema._parseAsync({data:s,path:n.path,parent:n});return l.status==="aborted"?xe:l.status==="dirty"||r.value==="dirty"?Xo(l.value):l});{if(r.value==="aborted")return xe;const s=this._def.schema._parseSync({data:i,path:n.path,parent:n});return s.status==="aborted"?xe:s.status==="dirty"||r.value==="dirty"?Xo(s.value):s}}if(o.type==="refinement"){const i=s=>{const l=o.refinement(s,a);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 s};if(n.common.async===!1){const s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?xe:(s.status==="dirty"&&r.dirty(),i(s.value),{status:r.value,value:s.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>s.status==="aborted"?xe:(s.status==="dirty"&&r.dirty(),i(s.value).then(()=>({status:r.value,value:s.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(!uo(i))return xe;const s=o.transform(i.value,a);if(s instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:s}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>uo(i)?Promise.resolve(o.transform(i.value,a)).then(s=>({status:r.value,value:s})):xe);Ze.assertNever(o)}}mo.create=(e,t,r)=>new mo({schema:e,typeName:oe.ZodEffects,effect:t,...Pe(r)}),mo.createWithPreprocess=(e,t,r)=>new mo({schema:t,effect:{type:"preprocess",transform:e},typeName:oe.ZodEffects,...Pe(r)});class mn extends je{_parse(t){return this._getType(t)===he.undefined?mr(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}mn.create=(e,t)=>new mn({innerType:e,typeName:oe.ZodOptional,...Pe(t)});class go extends je{_parse(t){return this._getType(t)===he.null?mr(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}go.create=(e,t)=>new go({innerType:e,typeName:oe.ZodNullable,...Pe(t)});class El extends je{_parse(t){const{ctx:r}=this._processInputParams(t);let n=r.data;return r.parsedType===he.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}El.create=(e,t)=>new El({innerType:e,typeName:oe.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Pe(t)});class $l 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 ls(o)?o.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new Yr(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Yr(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}$l.create=(e,t)=>new $l({innerType:e,typeName:oe.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Pe(t)});class Kh extends je{_parse(t){if(this._getType(t)!==he.nan){const n=this._getOrReturnCtx(t);return ue(n,{code:ne.invalid_type,expected:he.nan,received:n.parsedType}),xe}return{status:"valid",value:t.data}}}Kh.create=e=>new Kh({typeName:oe.ZodNaN,...Pe(e)});class X9 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 Rl extends je{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.common.async)return(async()=>{const a=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?xe:a.status==="dirty"?(r.dirty(),Xo(a.value)):this._def.out._parseAsync({data:a.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 Rl({in:t,out:r,typeName:oe.ZodPipeline})}}class Pl extends je{_parse(t){const r=this._def.innerType._parse(t),n=o=>(uo(o)&&(o.value=Object.freeze(o.value)),o);return ls(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}}Pl.create=(e,t)=>new Pl({innerType:e,typeName:oe.ZodReadonly,...Pe(t)});var oe;(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"})(oe||(oe={}));const be=Qr.create,gt=po.create,Ml=Sl.create,e4=Il.create;fn.create;const St=Fr.create,vt=bt.create,jn=us.create;ds.create,Ln.create;const t4=ps.create,Vr=fo.create;hs.create,mn.create,go.create;class Ol 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}}const Yh=10,r4=13,Dn=32;function Al(e){}function Qh(e){if(typeof e=="function")throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");const{onEvent:t=Al,onError:r=Al,onRetry:n=Al,onComment:o,maxBufferSize:a}=e,i=[];let s=0,l=!0,c,u="",h=0,p,m=!1;function f(y){if(m)throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(l&&(l=!1,y.charCodeAt(0)===239&&y.charCodeAt(1)===187&&y.charCodeAt(2)===191&&(y=y.slice(3))),i.length===0){const S=w(y);S!==""&&(i.push(S),s=S.length),b();return}if(y.indexOf(`
|
|
31
|
+
`)===-1&&y.indexOf("\r")===-1){i.push(y),s+=y.length,b();return}i.push(y);const _=i.join("");i.length=0,s=0;const k=w(_);k!==""&&(i.push(k),s=k.length),b()}function b(){a!==void 0&&(s+u.length<=a||(m=!0,i.length=0,s=0,c=void 0,u="",h=0,p=void 0,r(new Ol(`Buffered data exceeded max buffer size of ${a} characters`,{type:"max-buffer-size-exceeded"}))))}function w(y){let _=0;if(y.indexOf("\r")===-1){let k=y.indexOf(`
|
|
32
|
+
`,_);for(;k!==-1;){if(_===k){h>0&&t({id:c,event:p,data:u}),c=void 0,u="",h=0,p=void 0,_=k+1,k=y.indexOf(`
|
|
33
|
+
`,_);continue}const S=y.charCodeAt(_);if(Xh(y,_,S)){const E=y.charCodeAt(_+5)===Dn?_+6:_+5,R=y.slice(E,k);if(h===0&&y.charCodeAt(k+1)===Yh){t({id:c,event:p,data:R}),c=void 0,u="",p=void 0,_=k+2,k=y.indexOf(`
|
|
34
|
+
`,_);continue}u=h===0?R:`${u}
|
|
35
|
+
${R}`,h++}else ef(y,_,S)?p=y.slice(y.charCodeAt(_+6)===Dn?_+7:_+6,k)||void 0:C(y,_,k);_=k+1,k=y.indexOf(`
|
|
36
|
+
`,_)}return y.slice(_)}for(;_<y.length;){const k=y.indexOf("\r",_),S=y.indexOf(`
|
|
37
|
+
`,_);let E=-1;if(k!==-1&&S!==-1?E=k<S?k:S:k!==-1?k===y.length-1?E=-1:E=k:S!==-1&&(E=S),E===-1)break;C(y,_,E),_=E+1,y.charCodeAt(_-1)===r4&&y.charCodeAt(_)===Yh&&_++}return y.slice(_)}function C(y,_,k){if(_===k){g();return}const S=y.charCodeAt(_);if(Xh(y,_,S)){const z=y.charCodeAt(_+5)===Dn?_+6:_+5,ee=y.slice(z,k);u=h===0?ee:`${u}
|
|
38
|
+
${ee}`,h++;return}if(ef(y,_,S)){p=y.slice(y.charCodeAt(_+6)===Dn?_+7:_+6,k)||void 0;return}if(S===105&&y.charCodeAt(_+1)===100&&y.charCodeAt(_+2)===58){const z=y.slice(y.charCodeAt(_+3)===Dn?_+4:_+3,k);c=z.includes("\0")?void 0:z;return}if(S===58){if(o){const z=y.slice(_,k);o(z.slice(y.charCodeAt(_+1)===Dn?2:1))}return}const E=y.slice(_,k),R=E.indexOf(":");if(R===-1){v(E,"",E);return}const x=E.slice(0,R),N=E.charCodeAt(R+1)===Dn?2:1,U=E.slice(R+N);v(x,U,E)}function v(y,_,k){switch(y){case"event":p=_||void 0;break;case"data":u=h===0?_:`${u}
|
|
39
|
+
${_}`,h++;break;case"id":c=_.includes("\0")?void 0:_;break;case"retry":/^\d+$/.test(_)?n(parseInt(_,10)):r(new Ol(`Invalid \`retry\` value: "${_}"`,{type:"invalid-retry",value:_,line:k}));break;default:r(new Ol(`Unknown field "${y.length>20?`${y.slice(0,20)}…`:y}"`,{type:"unknown-field",field:y,value:_,line:k}));break}}function g(){h>0&&t({id:c,event:p,data:u}),c=void 0,u="",h=0,p=void 0}function I(y={}){if(y.consume&&i.length>0){const _=i.join("");C(_,0,_.length)}l=!0,c=void 0,u="",h=0,p=void 0,i.length=0,s=0,m=!1}return{feed:f,reset:I}}function Xh(e,t,r){return r===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function ef(e,t,r){return r===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}class _o extends TransformStream{constructor({onError:t,onRetry:r,onComment:n,maxBufferSize:o}={}){let a;super({start(i){a=Qh({onEvent:s=>{i.enqueue(s)},onError(s){typeof t=="function"&&t(s),(t==="terminate"||s.type==="max-buffer-size-exceeded")&&i.error(s)},onRetry:r,onComment:n,maxBufferSize:o})},transform(i){a.feed(i)}})}}function It(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}function n4({tools:e=[],providerToolNames:t,resolveProviderToolName:r}){var n;const o={},a={};for(const i of e)if(i.type==="provider"){const s=(n=r?.(i))!=null?n:i.id in t?t[i.id]:void 0;if(s==null)continue;o[i.name]=s,a[s]=i.name}return{toProviderToolName:i=>{var s;return(s=o[i])!=null?s:i},toCustomToolName:i=>{var s;return(s=a[i])!=null?s:i}}}async function o4(e,t){if(e==null)return Promise.resolve();const r=t?.abortSignal;return new Promise((n,o)=>{if(r?.aborted){o(tf());return}const a=setTimeout(()=>{i(),n()},e),i=()=>{clearTimeout(a),r?.removeEventListener("abort",s)},s=()=>{i(),o(tf())};r?.addEventListener("abort",s)})}function tf(){return new DOMException("Delay was aborted","AbortError")}var ra=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 yo(e){return Object.fromEntries([...e.headers])}var{btoa:a4,atob:s4}=globalThis;function Un(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=s4(t);return Uint8Array.from(r,n=>n.codePointAt(0))}function gn(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return a4(t)}function vo(e){return e instanceof Uint8Array?gn(e):e}function i4(e,t={}){const{useArrayBrackets:r=!0}=t,n=new FormData;for(const[o,a]of Object.entries(e))if(a!=null){if(Array.isArray(a)){if(a.length===1){n.append(o,a[0]);continue}const i=r?`${o}[]`:o;for(const s of a)n.append(i,s);continue}n.append(o,a)}return n}async function fs(e){var t;try{await((t=e.body)==null?void 0:t.cancel())}catch{}}var rf="AI_DownloadError",nf=`vercel.ai.error.${rf}`,l4=Symbol.for(nf),of,af,Zt=class extends(af=we,of=l4,af){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[of]=!0,this.url=e,this.statusCode=t,this.statusText=r}static isInstance(e){return we.hasMarker(e,nf)}};function c4(e=globalThis){return e.window!=null}function u4(e){let t;try{t=new URL(e)}catch{throw new Zt({url:e,message:`Invalid URL: ${e}`})}if(t.protocol==="data:")return;if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Zt({url:e,message:`URL scheme must be http, https, or data, got ${t.protocol}`});const r=t.hostname.toLowerCase().replace(/\.+$/,"");if(!r)throw new Zt({url:e,message:"URL must have a hostname"});if(r==="localhost"||r.endsWith(".local")||r.endsWith(".localhost"))throw new Zt({url:e,message:`URL with hostname ${r} is not allowed`});if(r.startsWith("[")&&r.endsWith("]")){const n=r.slice(1,-1);if(p4(n))throw new Zt({url:e,message:`URL with IPv6 address ${r} is not allowed`});return}if(sf(r)){if(lf(r))throw new Zt({url:e,message:`URL with IP address ${r} is not allowed`});return}}function sf(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 lf(e){const t=e.split(".").map(Number),[r,n,o]=t;return r===0||r===10||r===100&&n>=64&&n<=127||r===127||r===169&&n===254||r===172&&n>=16&&n<=31||r===192&&n===0&&o===0||r===192&&n===168||r===198&&(n===18||n===19)||r>=240}function d4(e){let t=e.toLowerCase();const r=t.indexOf("%");r!==-1&&(t=t.slice(0,r));const n=t.split("::");if(n.length>2)return null;const o=i=>{if(i==="")return[];const s=[],l=i.split(":");for(let c=0;c<l.length;c++){const u=l[c];if(u.includes(".")){if(c!==l.length-1||!sf(u))return null;const[h,p,m,f]=u.split(".").map(Number);s.push(h<<8|p,m<<8|f);continue}if(!/^[0-9a-f]{1,4}$/.test(u))return null;s.push(parseInt(u,16))}return s},a=o(n[0]);if(a===null)return null;if(n.length===2){const i=o(n[1]);if(i===null)return null;const s=8-a.length-i.length;return s<0?null:[...a,...new Array(s).fill(0),...i]}return a.length===8?a:null}function p4(e){const t=d4(e);if(t===null)return!0;const r=o=>t.slice(0,o).every(a=>a===0);if(r(7)&&(t[7]===0||t[7]===1)||(t[0]&65024)===64512||(t[0]&65472)===65152||(t[0]&65472)===65216||(t[0]&65280)===65280)return!0;if(r(6)||r(5)&&t[5]===65535||r(4)&&t[4]===65535&&t[5]===0||t[0]===100&&t[1]===65435&&t[2]===0&&t[3]===0&&t[4]===0&&t[5]===0||t[0]===100&&t[1]===65435&&t[2]===1){const o=t[6]>>8&255,a=t[6]&255,i=t[7]>>8&255,s=t[7]&255;return lf(`${o}.${a}.${i}.${s}`)}return!1}var h4=10;async function cf({url:e,headers:t,abortSignal:r,maxRedirects:n=h4}){const o={signal:r};t!==void 0&&(o.headers=t);let a=e;for(let i=0;i<=n;i++){u4(a);const s=await fetch(a,{...o,redirect:"manual"});if(s.type==="opaqueredirect"){if(!c4())throw new Zt({url:e,message:`Redirect from ${a} could not be validated and was blocked`});return await fetch(a,{...o,redirect:"follow"})}const l=s.headers.get("location");if(s.status>=300&&s.status<400&&l){await fs(s),a=new URL(l,a).toString();continue}return s}throw new Zt({url:e,message:`Too many redirects (max ${n})`})}var Nl=2*1024*1024*1024;async function ql({response:e,url:t,maxBytes:r=Nl}){const n=e.headers.get("content-length");if(n!=null){const u=parseInt(n,10);if(!isNaN(u)&&u>r)throw await fs(e),new Zt({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 a=o.getReader(),i=[];let s=0;try{for(;;){const{done:u,value:h}=await a.read();if(u)break;if(s+=h.length,s>r)throw new Zt({url:t,message:`Download of ${t} exceeded maximum size of ${r} bytes.`});i.push(h)}}finally{try{await a.cancel()}finally{a.releaseLock()}}const l=new Uint8Array(s);let c=0;for(const u of i)l.set(u,c),c+=u.length;return l}async function uf(e,t){var r,n;try{const o=await cf({url:e,abortSignal:t?.abortSignal});if(!o.ok)throw await fs(o),new Zt({url:e,statusCode:o.status,statusText:o.statusText});const a=await ql({response:o,url:e,maxBytes:(r=t?.maxBytes)!=null?r:Nl}),i=(n=o.headers.get("content-type"))!=null?n:void 0;return new Blob([a],i?{type:i}:void 0)}catch(o){throw Zt.isInstance(o)?o:new Zt({url:e,cause:o})}}var na=({prefix:e,size:t=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{const o=()=>{const a=r.length,i=new Array(t);for(let s=0;s<t;s++)i[s]=r[Math.random()*a|0];return i.join("")};if(e==null)return o;if(r.includes(n))throw new rp({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${e}${n}${o()}`},Kt=na();function Ll(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}function zn(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var f4=["fetch failed","failed to fetch"],m4=["ConnectionRefused","ConnectionClosed","FailedToOpenSocket","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE"];function g4(e){if(!(e instanceof Error))return!1;const t=e.code;return!!(typeof t=="string"&&m4.includes(t))}function df({error:e,url:t,requestBodyValues:r}){if(zn(e))return e;if(e instanceof TypeError&&f4.includes(e.message.toLowerCase())){const n=e.cause;if(n!=null)return new tt({message:`Cannot connect to API: ${n.message}`,cause:n,url:t,requestBodyValues:r,isRetryable:!0})}return g4(e)?new tt({message:`Cannot connect to API: ${e.message}`,cause:e,url:t,requestBodyValues:r,isRetryable:!0}):e}function oa(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 _4(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 _n(e,...t){const r=new Headers(_4(e)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var pf="4.0.33",y4=()=>globalThis.fetch,ms=async({url:e,headers:t={},successfulResponseHandler:r,failedResponseHandler:n,abortSignal:o,fetch:a=y4()})=>{try{const i=await a(e,{method:"GET",headers:_n(t,`ai-sdk/provider-utils/${pf}`,oa()),signal:o}),s=yo(i);if(!i.ok){let l;try{l=await n({response:i,url:e,requestBodyValues:{}})}catch(c){throw zn(c)||tt.isInstance(c)?c:new tt({message:"Failed to process error response",cause:c,statusCode:i.status,url:e,responseHeaders:s,requestBodyValues:{}})}throw l.value}try{return await r({response:i,url:e,requestBodyValues:{}})}catch(l){throw l instanceof Error&&(zn(l)||tt.isInstance(l))?l:new tt({message:"Failed to process successful response",cause:l,statusCode:i.status,url:e,responseHeaders:s,requestBodyValues:{}})}}catch(i){throw df({error:i,url:e,requestBodyValues:{}})}};function hf(e){return e!=null}function v4({mediaType:e,url:t,supportedUrls:r}){return t=t.toLowerCase(),e=e.toLowerCase(),Object.entries(r).map(([n,o])=>{const a=n.toLowerCase();return a==="*"||a==="*/*"?{mediaTypePrefix:"",regexes:o}:{mediaTypePrefix:a.replace(/\*/,""),regexes:o}}).filter(({mediaTypePrefix:n})=>e.startsWith(n)).flatMap(({regexes:n})=>n).some(n=>n.test(t))}function w4({apiKey:e,environmentVariableName:t,apiKeyParameterName:r="apiKey",description:n}){if(typeof e=="string")return e;if(e!=null)throw new Ka({message:`${n} API key must be a string.`});if(typeof process>"u")throw new Ka({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 Ka({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new Ka({message:`${n} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}function wo({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 b4(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 k4=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,T4=/"(?: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 ff(e){const t=JSON.parse(e);return t===null||typeof t!="object"||k4.test(e)===!1&&T4.test(e)===!1?t:C4(t)}function C4(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 a=n[o];a&&typeof a=="object"&&t.push(a)}}}return e}function jl(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return ff(e)}try{return ff(e)}finally{Error.stackTraceLimit=t}}function Dl(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]=Fn(r[n])}e.items!=null&&(e.items=Array.isArray(e.items)?e.items.map(Fn):Fn(e.items)),e.anyOf!=null&&(e.anyOf=e.anyOf.map(Fn)),e.allOf!=null&&(e.allOf=e.allOf.map(Fn)),e.oneOf!=null&&(e.oneOf=e.oneOf.map(Fn));const{definitions:t}=e;if(t!=null)for(const r of Object.keys(t))t[r]=Fn(t[r]);return e}function Fn(e){return typeof e=="boolean"?e:Dl(e)}var S4=Symbol("Let zodToJsonSchema decide on which parser to use"),mf={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"},I4=e=>typeof e=="string"?{...mf,name:e}:{...mf,...e};function or(){return{}}function x4(e,t){var r,n,o;const a={type:"array"};return(r=e.type)!=null&&r._def&&((o=(n=e.type)==null?void 0:n._def)==null?void 0:o.typeName)!==oe.ZodAny&&(a.items=Je(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&(a.minItems=e.minLength.value),e.maxLength&&(a.maxItems=e.maxLength.value),e.exactLength&&(a.minItems=e.exactLength.value,a.maxItems=e.exactLength.value),a}function E4(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 $4(){return{type:"boolean"}}function gf(e,t){return Je(e.type._def,t)}var R4=(e,t)=>Je(e.innerType._def,t);function _f(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,a)=>_f(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 P4(e)}}var P4=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 M4(e,t){return{...Je(e.innerType._def,t),default:e.defaultValue()}}function O4(e,t){return t.effectStrategy==="input"?Je(e.schema._def,t):or()}function A4(e){return{type:"string",enum:Array.from(e.values)}}var N4=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function q4(e,t){const r=[Je(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Je(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(o=>!!o),n=[];return r.forEach(o=>{if(N4(o))n.push(...o.allOf);else{let a=o;if("additionalProperties"in o&&o.additionalProperties===!1){const{additionalProperties:i,...s}=o;a=s}n.push(a)}}),n.length?{allOf:n}:void 0}function L4(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 Ul=void 0,Cr={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:()=>(Ul===void 0&&(Ul=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ul),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 yf(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":Sr(r,"email",n.message,t);break;case"format:idn-email":Sr(r,"idn-email",n.message,t);break;case"pattern:zod":Yt(r,Cr.email,n.message,t);break}break;case"url":Sr(r,"uri",n.message,t);break;case"uuid":Sr(r,"uuid",n.message,t);break;case"regex":Yt(r,n.regex,n.message,t);break;case"cuid":Yt(r,Cr.cuid,n.message,t);break;case"cuid2":Yt(r,Cr.cuid2,n.message,t);break;case"startsWith":Yt(r,RegExp(`^${zl(n.value,t)}`),n.message,t);break;case"endsWith":Yt(r,RegExp(`${zl(n.value,t)}$`),n.message,t);break;case"datetime":Sr(r,"date-time",n.message,t);break;case"date":Sr(r,"date",n.message,t);break;case"time":Sr(r,"time",n.message,t);break;case"duration":Sr(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":{Yt(r,RegExp(zl(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&Sr(r,"ipv4",n.message,t),n.version!=="v4"&&Sr(r,"ipv6",n.message,t);break}case"base64url":Yt(r,Cr.base64url,n.message,t);break;case"jwt":Yt(r,Cr.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&Yt(r,Cr.ipv4Cidr,n.message,t),n.version!=="v4"&&Yt(r,Cr.ipv6Cidr,n.message,t);break}case"emoji":Yt(r,Cr.emoji(),n.message,t);break;case"ulid":{Yt(r,Cr.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{Sr(r,"binary",n.message,t);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{Yt(r,Cr.base64,n.message,t);break}}break}case"nanoid":Yt(r,Cr.nanoid,n.message,t)}return r}function zl(e,t){return t.patternStrategy==="escape"?D4(e):e}var j4=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function D4(e){let t="";for(let r=0;r<e.length;r++)j4.has(e[r])||(t+="\\"),t+=e[r];return t}function Sr(e,t,r,n){var o;e.format||(o=e.anyOf)!=null&&o.some(a=>a.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 Yt(e,t,r,n){var o;e.pattern||(o=e.allOf)!=null&&o.some(a=>a.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern}),delete e.pattern),e.allOf.push({pattern:vf(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):e.pattern=vf(t,n)}function vf(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 a="",i=!1,s=!1,l=!1;for(let c=0;c<o.length;c++){if(i){a+=o[c],i=!1;continue}if(n.i){if(s){if(o[c].match(/[a-z]/)){l?(a+=o[c],a+=`${o[c-2]}-${o[c]}`.toUpperCase(),l=!1):o[c+1]==="-"&&((r=o[c+2])!=null&&r.match(/[a-z]/))?(a+=o[c],l=!0):a+=`${o[c]}${o[c].toUpperCase()}`;continue}}else if(o[c].match(/[a-z]/)){a+=`[${o[c]}${o[c].toUpperCase()}]`;continue}}if(n.m){if(o[c]==="^"){a+=`(^|(?<=[\r
|
|
40
|
+
]))`;continue}else if(o[c]==="$"){a+=`($|(?=[\r
|
|
41
|
+
]))`;continue}}if(n.s&&o[c]==="."){a+=s?`${o[c]}\r
|
|
37
42
|
`:`[${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=Je(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=Je(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||er(),n=Je(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||er();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:er()}}function q9(){return{type:"null"}}var xl={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 xl&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((o,s)=>{const i=xl[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)=>Je(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:[xl[e.innerType._def.typeName],"null"]};const r=Je(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=Je(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 Je(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 Je(e.innerType._def,t);const n=Je(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:er()},n]}:er()},B9=(e,t)=>{if(t.pipeStrategy==="input")return Je(e.in._def,t);if(t.pipeStrategy==="output")return Je(e.out._def,t);const r=Je(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=Je(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 Je(e.type._def,t)}function J9(e,t){const n={type:"array",uniqueItems:!0,items:Je(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 W9(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>Je(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Je(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>Je(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function G9(){return{not:er()}}function K9(){return er()}var Y9=(e,t)=>Je(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 G9();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 W9(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 er();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 Je(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"?Je(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`),er()):t.$refStrategy==="seen"?er():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=Je(f._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0))!=null?p:er()}},{}):void 0;const s=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,i=(r=Je(e._def,s===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,s]},!1))!=null?r:er(),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},El=Symbol.for("vercel.ai.schema");function ve(e){let t;return()=>(t==null&&(t=e()),t)}function Pn(e,{validate:t}={}){return{[El]:!0,_type:void 0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}function o4(e){return typeof e=="object"&&e!==null&&El in e&&e[El]===!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(()=>Cl(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(()=>Cl(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 mt({value:e,schema:t,context:r}){const n=await ur({value:e,schema:t,context:r});if(!n.success)throw Sn.wrap({value:e,cause:n.error,context:r});return n.value}async function ur({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=Tl(e);return t==null?r:mt({value:r,schema:t})}catch(r){throw Ds.isInstance(r)||Sn.isInstance(r)?r:new Ds({text:e,cause:r})}}async function dr({text:e,schema:t}){try{const r=Tl(e);return t==null?{success:!0,value:r,rawValue:r}:await ur({value:r,schema:t})}catch(r){return{success:!1,error:Ds.isInstance(r)?r:new Ds({text:e,cause:r}),rawValue:void 0}}}function Wf(e){try{return Tl(e),!0}catch{return!1}}function Gf({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new so).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await dr({text:r,schema:t}))}}))}async function Fr({provider:e,providerOptions:t,schema:r}){if(t?.[e]==null)return;const n=await ur({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,Jt=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:ln(t,`ai-sdk/provider-utils/${jf}`,Bo()),body:r.content,signal:s}),l=ao(a);if(!a.ok){let c;try{c=await o({response:a,url:e,requestBodyValues:r.values})}catch(u){throw $n(u)||lt.isInstance(u)?u:new lt({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)||lt.isInstance(c))?c:new lt({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 c$(e){return e}function $l(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 pr({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 qt(e){return typeof e=="function"&&(e=e()),Promise.resolve(e)}var Ar=({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:n,url:o,requestBodyValues:s})=>{const i=await n.text(),a=ao(n);if(i.trim()==="")return{responseHeaders:a,value:new lt({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 lt({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 lt({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:a,responseBody:i,isRetryable:r?.(n)})}}},aa=e=>async({response:t})=>{const r=ao(t);if(t.body==null)throw new Tv({});return{responseHeaders:r,value:Gf({stream:t.body,schema:e})}},Wt=e=>async({response:t,url:r,requestBodyValues:n})=>{const o=await t.text(),s=await dr({text:o,schema:e}),i=ao(t);if(!s.success)throw new lt({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=ao(e);if(!e.body)throw new lt({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 lt({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 Rl(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Pl,Xf;function h4(){if(Xf)return Pl;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}),Pl=i(a);const l=Symbol.for("@vercel/request-context");function c(){return globalThis[l]?.get?.()??{}}return Pl}var Ml,eh;function m4(){if(eh)return Ml;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}),Ml=i(a);var l=h4();async function c(){return""}function u(){return""}return Ml}var th=m4(),g4="vercel.ai.gateway.error",Nl=Symbol.for(g4),rh,nh,Ft=class gv extends(nh=Error,rh=Nl,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&&Nl in t&&t[Nl]===!0}},oh="GatewayAuthenticationError",_4=`vercel.ai.gateway.error.${oh}`,sh=Symbol.for(_4),ah,ih,Ol=class _v extends(ih=Ft,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 Ft.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.
|
|
43
|
+
]`;continue}a+=o[c],o[c]==="\\"?i=!0:s&&o[c]==="]"?s=!1:!s&&o[c]==="["&&(s=!0)}try{new RegExp(a)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return a}function wf(e,t){var r,n,o,a,i,s;const l={type:"object",additionalProperties:(r=Je(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?r:t.allowedAdditionalProperties};if(((n=e.keyType)==null?void 0:n._def.typeName)===oe.ZodString&&((o=e.keyType._def.checks)!=null&&o.length)){const{type:c,...u}=yf(e.keyType._def,t);return{...l,propertyNames:u}}else{if(((a=e.keyType)==null?void 0:a._def.typeName)===oe.ZodEnum)return{...l,propertyNames:{enum:e.keyType._def.values}};if(((i=e.keyType)==null?void 0:i._def.typeName)===oe.ZodBranded&&e.keyType._def.type._def.typeName===oe.ZodString&&((s=e.keyType._def.type._def.checks)!=null&&s.length)){const{type:c,...u}=gf(e.keyType._def,t);return{...l,propertyNames:u}}}return l}function U4(e,t){if(t.mapStrategy==="record")return wf(e,t);const r=Je(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||or(),n=Je(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||or();return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function z4(e){const t=e.values,n=Object.keys(e.values).filter(a=>typeof t[t[a]]!="number").map(a=>t[a]),o=Array.from(new Set(n.map(a=>typeof a)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function F4(){return{not:or()}}function V4(){return{type:"null"}}var Fl={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Z4(e,t){const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in Fl&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((o,a)=>{const i=Fl[a._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,a)=>{const i=typeof a._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(a._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===r.length){const o=n.filter((a,i,s)=>s.indexOf(a)===i);return{type:o.length>1?o:o[0],enum:r.reduce((a,i)=>a.includes(i._def.value)?a:[...a,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(a=>!n.includes(a))],[])};return H4(e,t)}var H4=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>Je(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 B4(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[Fl[e.innerType._def.typeName],"null"]};const r=Je(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function J4(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 G4(e,t){const r={type:"object",properties:{}},n=[],o=e.shape();for(const i in o){let s=o[i];if(s===void 0||s._def===void 0)continue;const l=K4(s),c=Je(s._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 a=W4(e,t);return a!==void 0&&(r.additionalProperties=a),r}function W4(e,t){if(e.catchall._def.typeName!=="ZodNever")return Je(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 K4(e){try{return e.isOptional()}catch{return!0}}var Y4=(e,t)=>{var r;if(t.currentPath.toString()===((r=t.propertyPath)==null?void 0:r.toString()))return Je(e.innerType._def,t);const n=Je(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:or()},n]}:or()},Q4=(e,t)=>{if(t.pipeStrategy==="input")return Je(e.in._def,t);if(t.pipeStrategy==="output")return Je(e.out._def,t);const r=Je(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=Je(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function X4(e,t){return Je(e.type._def,t)}function e6(e,t){const n={type:"array",uniqueItems:!0,items:Je(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 t6(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>Je(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Je(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>Je(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function r6(){return{not:or()}}function n6(){return or()}var o6=(e,t)=>Je(e.innerType._def,t),a6=(e,t,r)=>{switch(t){case oe.ZodString:return yf(e,r);case oe.ZodNumber:return J4(e);case oe.ZodObject:return G4(e,r);case oe.ZodBigInt:return E4(e);case oe.ZodBoolean:return $4();case oe.ZodDate:return _f(e,r);case oe.ZodUndefined:return r6();case oe.ZodNull:return V4();case oe.ZodArray:return x4(e,r);case oe.ZodUnion:case oe.ZodDiscriminatedUnion:return Z4(e,r);case oe.ZodIntersection:return q4(e,r);case oe.ZodTuple:return t6(e,r);case oe.ZodRecord:return wf(e,r);case oe.ZodLiteral:return L4(e);case oe.ZodEnum:return A4(e);case oe.ZodNativeEnum:return z4(e);case oe.ZodNullable:return B4(e,r);case oe.ZodOptional:return Y4(e,r);case oe.ZodMap:return U4(e,r);case oe.ZodSet:return e6(e,r);case oe.ZodLazy:return()=>e.getter()._def;case oe.ZodPromise:return X4(e,r);case oe.ZodNaN:case oe.ZodNever:return F4();case oe.ZodEffects:return O4(e,r);case oe.ZodAny:return or();case oe.ZodUnknown:return n6();case oe.ZodDefault:return M4(e,r);case oe.ZodBranded:return gf(e,r);case oe.ZodReadonly:return o6(e,r);case oe.ZodCatch:return R4(e,r);case oe.ZodPipeline:return Q4(e,r);case oe.ZodFunction:case oe.ZodVoid:case oe.ZodSymbol:return;default:return(n=>{})()}},s6=(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 Je(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!==S4)return l}if(o&&!r){const l=i6(o,t);if(l!==void 0)return l}const a={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,a);const i=a6(e,e.typeName,t),s=typeof i=="function"?Je(i(),t):i;if(s&&l6(e,t,s),t.postProcess){const l=t.postProcess(s,e,t);return a.jsonSchema=s,l}return a.jsonSchema=s,s}var i6=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:s6(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`),or()):t.$refStrategy==="seen"?or():void 0}},l6=(e,t,r)=>(e.description&&(r.description=e.description),r),c6=e=>{const t=I4(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}]))}},u6=(e,t)=>{var r;const n=c6(t);let o=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,h])=>{var p;return{...c,[u]:(p=Je(h._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0))!=null?p:or()}},{}):void 0;const a=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,i=(r=Je(e._def,a===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,a]},!1))!=null?r:or(),s=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;s!==void 0&&(i.title=s);const l=a===void 0?o?{...i,[n.definitionPath]:o}:i:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,a].join("/"),[n.definitionPath]:{...o,[a]:i}};return l.$schema="http://json-schema.org/draft-07/schema#",l},Vl=Symbol.for("vercel.ai.schema");function ye(e){let t;return()=>(t==null&&(t=e()),t)}function Vn(e,{validate:t}={}){return{[Vl]:!0,_type:void 0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}function d6(e){return typeof e=="object"&&e!==null&&Vl in e&&e[Vl]===!0&&"jsonSchema"in e&&"validate"in e}function yn(e){return e==null?Vn({properties:{},additionalProperties:!1}):d6(e)?e:"~standard"in e?e["~standard"].vendor==="zod"?me(e):p6(e):e()}function p6(e){return Vn(()=>Dl(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 An({value:t,cause:r.issues})}}})}function h6(e,t){var r;const n=(r=void 0)!=null?r:!1;return Vn(()=>u6(e,{$refStrategy:n?"root":"none"}),{validate:async o=>{const a=await e.safeParseAsync(o);return a.success?{success:!0,value:a.data}:{success:!1,error:a.error}}})}function f6(e,t){var r;const n=(r=void 0)!=null?r:!1;return Vn(()=>Dl(I3(e,{target:"draft-7",io:"input",reused:n?"ref":"inline"})),{validate:async o=>{const a=await _h(e,o);return a.success?{success:!0,value:a.data}:{success:!1,error:a.error}}})}function m6(e){return"_zod"in e}function me(e,t){return m6(e)?f6(e):h6(e)}async function _t({value:e,schema:t,context:r}){const n=await ar({value:e,schema:t,context:r});if(!n.success)throw An.wrap({value:e,cause:n.error,context:r});return n.value}async function ar({value:e,schema:t,context:r}){const n=yn(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:An.wrap({value:e,cause:o.error,context:r}),rawValue:e}}catch(o){return{success:!1,error:An.wrap({value:e,cause:o,context:r}),rawValue:e}}}async function gs({text:e,schema:t}){try{const r=jl(e);return t==null?r:_t({value:r,schema:t})}catch(r){throw Wa.isInstance(r)||An.isInstance(r)?r:new Wa({text:e,cause:r})}}async function gr({text:e,schema:t}){try{const r=jl(e);return t==null?{success:!0,value:r,rawValue:r}:await ar({value:r,schema:t})}catch(r){return{success:!1,error:Wa.isInstance(r)?r:new Wa({text:e,cause:r}),rawValue:void 0}}}function bf(e){try{return jl(e),!0}catch{return!1}}function kf({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new _o).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await gr({text:r,schema:t}))}}))}async function Ir({provider:e,providerOptions:t,schema:r}){if(t?.[e]==null)return;const n=await ar({value:t[e],schema:r});if(!n.success)throw new rp({argument:"providerOptions",message:`invalid ${e} provider options`,cause:n.error});return n.value}var g6=()=>globalThis.fetch,Ot=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:a,fetch:i})=>Cf({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:a,fetch:i}),Tf=async({url:e,headers:t,formData:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:a,fetch:i})=>Cf({url:e,headers:t,body:{content:r,values:Object.fromEntries(r.entries())},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:a,fetch:i}),Cf=async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:a,fetch:i=g6()})=>{try{const s=await i(e,{method:"POST",headers:_n(t,`ai-sdk/provider-utils/${pf}`,oa()),body:r.content,signal:a}),l=yo(s);if(!s.ok){let c;try{c=await o({response:s,url:e,requestBodyValues:r.values})}catch(u){throw zn(u)||tt.isInstance(u)?u:new tt({message:"Failed to process error response",cause:u,statusCode:s.status,url:e,responseHeaders:l,requestBodyValues:r.values})}throw c.value}try{return await n({response:s,url:e,requestBodyValues:r.values})}catch(c){throw c instanceof Error&&(zn(c)||tt.isInstance(c))?c:new tt({message:"Failed to process successful response",cause:c,statusCode:s.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(s){throw df({error:s,url:e,requestBodyValues:r.values})}};function VR(e){return e}function Zl(e){return{...e,type:"dynamic"}}function _6({id:e,inputSchema:t}){return({execute:r,outputSchema:n,needsApproval:o,toModelOutput:a,onInputStart:i,onInputDelta:s,onInputAvailable:l,...c})=>({type:"provider",id:e,args:c,inputSchema:t,outputSchema:n,execute:r,needsApproval:o,toModelOutput:a,onInputStart:i,onInputDelta:s,onInputAvailable:l})}function sr({id:e,inputSchema:t,outputSchema:r,supportsDeferredResults:n}){return({execute:o,needsApproval:a,toModelOutput:i,onInputStart:s,onInputDelta:l,onInputAvailable:c,...u})=>({type:"provider",id:e,args:u,inputSchema:t,outputSchema:r,execute:o,needsApproval:a,toModelOutput:i,onInputStart:s,onInputDelta:l,onInputAvailable:c,supportsDeferredResults:n})}async function yt(e){return typeof e=="function"&&(e=e()),Promise.resolve(e)}var y6=new TextDecoder;async function Sf({response:e,url:t}){return y6.decode(await ql({response:e,url:t}))}var ir=({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:n,url:o,requestBodyValues:a})=>{const i=await Sf({response:n,url:o}),s=yo(n);if(i.trim()==="")return{responseHeaders:s,value:new tt({message:n.statusText,url:o,requestBodyValues:a,statusCode:n.status,responseHeaders:s,responseBody:i,isRetryable:r?.(n)})};try{const l=await gs({text:i,schema:e});return{responseHeaders:s,value:new tt({message:t(l),url:o,requestBodyValues:a,statusCode:n.status,responseHeaders:s,responseBody:i,data:l,isRetryable:r?.(n,l)})}}catch{return{responseHeaders:s,value:new tt({message:n.statusText,url:o,requestBodyValues:a,statusCode:n.status,responseHeaders:s,responseBody:i,isRetryable:r?.(n)})}}},_s=e=>async({response:t})=>{const r=yo(t);if(t.body==null)throw new C1({});return{responseHeaders:r,value:kf({stream:t.body,schema:e})}},At=e=>async({response:t,url:r,requestBodyValues:n})=>{const o=await Sf({response:t,url:r}),a=await gr({text:o,schema:e}),i=yo(t);if(!a.success)throw new tt({message:"Invalid JSON response",cause:a.error,statusCode:t.status,responseHeaders:i,responseBody:o,url:r,requestBodyValues:n});return{responseHeaders:i,value:a.value,rawValue:a.rawValue}},v6=()=>async({response:e,url:t,requestBodyValues:r})=>{const n=yo(e);if(!e.body)throw new tt({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 tt({message:"Failed to read response as array buffer",url:t,requestBodyValues:r,statusCode:e.status,responseHeaders:n,responseBody:void 0,cause:o})}};function If(e){return e?.replace(/\/$/,"")}function w6(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*b6({execute:e,input:t,options:r}){const n=e(t,r);if(w6(n)){let o;for await(const a of n)o=a,yield{type:"preliminary",output:a};yield{type:"final",output:o}}else yield{type:"final",output:await n}}function Hl(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Bl,xf;function k6(){if(xf)return Bl;xf=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o=(u,h)=>{for(var p in h)e(u,p,{get:h[p],enumerable:!0})},a=(u,h,p,m)=>{if(h&&typeof h=="object"||typeof h=="function")for(let f of r(h))!n.call(u,f)&&f!==p&&e(u,f,{get:()=>h[f],enumerable:!(m=t(h,f))||m.enumerable});return u},i=u=>a(e({},"__esModule",{value:!0}),u),s={};o(s,{SYMBOL_FOR_REQ_CONTEXT:()=>l,getContext:()=>c}),Bl=i(s);const l=Symbol.for("@vercel/request-context");function c(){return globalThis[l]?.get?.()??{}}return Bl}var Jl,Ef;function T6(){if(Ef)return Jl;Ef=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o=(u,h)=>{for(var p in h)e(u,p,{get:h[p],enumerable:!0})},a=(u,h,p,m)=>{if(h&&typeof h=="object"||typeof h=="function")for(let f of r(h))!n.call(u,f)&&f!==p&&e(u,f,{get:()=>h[f],enumerable:!(m=t(h,f))||m.enumerable});return u},i=u=>a(e({},"__esModule",{value:!0}),u),s={};o(s,{AccessTokenMissingError:()=>l,RefreshAccessTokenFailedError:()=>c}),Jl=i(s);class l extends Error{constructor(){super("No authentication found. Please log in with the Vercel CLI (vercel login)."),this.name="AccessTokenMissingError"}}class c extends Error{constructor(h){super("Failed to refresh authentication token.",{cause:h}),this.name="RefreshAccessTokenFailedError"}}return Jl}var Gl,$f;function C6(){if($f)return Gl;$f=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o=(m,f)=>{for(var b in f)e(m,b,{get:f[b],enumerable:!0})},a=(m,f,b,w)=>{if(f&&typeof f=="object"||typeof f=="function")for(let C of r(f))!n.call(m,C)&&C!==b&&e(m,C,{get:()=>f[C],enumerable:!(w=t(f,C))||w.enumerable});return m},i=m=>a(e({},"__esModule",{value:!0}),m),s={};o(s,{AccessTokenMissingError:()=>c.AccessTokenMissingError,RefreshAccessTokenFailedError:()=>c.RefreshAccessTokenFailedError,getContext:()=>l.getContext,getVercelOidcToken:()=>u,getVercelOidcTokenSync:()=>h,getVercelToken:()=>p}),Gl=i(s);var l=k6(),c=T6();async function u(){return""}function h(){return""}async function p(){throw new Error("getVercelToken is not supported in browser environments")}return Gl}var Rf=C6(),S6="vercel.ai.gateway.error",Wl=Symbol.for(S6),Pf,Mf,kt=class _1 extends(Mf=Error,Pf=Wl,Mf){constructor({message:t,statusCode:r=500,cause:n,generationId:o,isRetryable:a=r!=null&&(r===408||r===409||r===429||r>=500)}){super(o?`${t} [${o}]`:t),this[Pf]=!0,this.statusCode=r,this.cause=n,this.generationId=o,this.isRetryable=a}static isInstance(t){return _1.hasMarker(t)}static hasMarker(t){return typeof t=="object"&&t!==null&&Wl in t&&t[Wl]===!0}},Of="GatewayAuthenticationError",I6=`vercel.ai.gateway.error.${Of}`,Af=Symbol.for(I6),Nf,qf,Kl=class y1 extends(qf=kt,Nf=Af,qf){constructor({message:t="Authentication failed",statusCode:r=401,cause:n,generationId:o}={}){super({message:t,statusCode:r,cause:n,generationId:o}),this[Nf]=!0,this.name=Of,this.type="authentication_error"}static isInstance(t){return kt.hasMarker(t)&&Af in t}static createContextualError({apiKeyProvided:t,oidcTokenProvided:r,message:n="Authentication failed",statusCode:o=401,cause:a,generationId:i}){let s;return t?s=`AI Gateway authentication failed: Invalid API key.
|
|
39
44
|
|
|
40
45
|
Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
|
|
41
46
|
|
|
42
|
-
Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`:r?
|
|
47
|
+
Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`:r?s=`AI Gateway authentication failed: Invalid OIDC token.
|
|
43
48
|
|
|
44
49
|
Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.
|
|
45
50
|
|
|
46
|
-
Alternatively, use an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys`:
|
|
51
|
+
Alternatively, use an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys`:s=`AI Gateway authentication failed: No authentication provided.
|
|
47
52
|
|
|
48
53
|
Option 1 - API key:
|
|
49
54
|
Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
|
|
50
55
|
Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
|
|
51
56
|
|
|
52
57
|
Option 2 - OIDC token:
|
|
53
|
-
Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new
|
|
58
|
+
Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new y1({message:s,statusCode:o,cause:a,generationId:i})}},Lf="GatewayInvalidRequestError",x6=`vercel.ai.gateway.error.${Lf}`,jf=Symbol.for(x6),Df,Uf,E6=class extends(Uf=kt,Df=jf,Uf){constructor({message:e="Invalid request",statusCode:t=400,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[Df]=!0,this.name=Lf,this.type="invalid_request_error"}static isInstance(e){return kt.hasMarker(e)&&jf in e}},zf="GatewayRateLimitError",$6=`vercel.ai.gateway.error.${zf}`,Ff=Symbol.for($6),Vf,Zf,R6=class extends(Zf=kt,Vf=Ff,Zf){constructor({message:e="Rate limit exceeded",statusCode:t=429,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[Vf]=!0,this.name=zf,this.type="rate_limit_exceeded"}static isInstance(e){return kt.hasMarker(e)&&Ff in e}},Hf="GatewayModelNotFoundError",P6=`vercel.ai.gateway.error.${Hf}`,Bf=Symbol.for(P6),M6=ye(()=>me(T({modelId:d()}))),Jf,Gf,O6=class extends(Gf=kt,Jf=Bf,Gf){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[Jf]=!0,this.name=Hf,this.type="model_not_found",this.modelId=r}static isInstance(e){return kt.hasMarker(e)&&Bf in e}},Wf="GatewayInternalServerError",A6=`vercel.ai.gateway.error.${Wf}`,Kf=Symbol.for(A6),Yf,Qf,Xf=class extends(Qf=kt,Yf=Kf,Qf){constructor({message:e="Internal server error",statusCode:t=500,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[Yf]=!0,this.name=Wf,this.type="internal_server_error"}static isInstance(e){return kt.hasMarker(e)&&Kf in e}},e0="GatewayFailedDependencyError",N6=`vercel.ai.gateway.error.${e0}`,t0=Symbol.for(N6),r0,n0,q6=class extends(n0=kt,r0=t0,n0){constructor({message:e="Failed dependency",statusCode:t=424,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[r0]=!0,this.name=e0,this.type="failed_dependency"}static isInstance(e){return kt.hasMarker(e)&&t0 in e}},o0="GatewayForbiddenError",L6=`vercel.ai.gateway.error.${o0}`,a0=Symbol.for(L6),s0,i0,j6=class extends(i0=kt,s0=a0,i0){constructor({message:e="Forbidden",statusCode:t=403,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[s0]=!0,this.name=o0,this.type="forbidden"}static isInstance(e){return kt.hasMarker(e)&&a0 in e}},l0="GatewayResponseError",D6=`vercel.ai.gateway.error.${l0}`,c0=Symbol.for(D6),u0,d0,U6=class extends(d0=kt,u0=c0,d0){constructor({message:e="Invalid response from Gateway",statusCode:t=502,response:r,validationError:n,cause:o,generationId:a}={}){super({message:e,statusCode:t,cause:o,generationId:a}),this[u0]=!0,this.name=l0,this.type="response_error",this.response=r,this.validationError=n}static isInstance(e){return kt.hasMarker(e)&&c0 in e}};async function p0({response:e,statusCode:t,defaultMessage:r="Gateway request failed",cause:n,authMethod:o}){var a;const i=await ar({value:e,schema:z6});if(!i.success){const h=typeof e=="object"&&e!==null&&"generationId"in e?e.generationId:void 0;return new U6({message:`Invalid error response format: ${r}`,statusCode:t,response:e,validationError:i.error,cause:n,generationId:h})}const s=i.value,l=s.error.type,c=s.error.message,u=(a=s.generationId)!=null?a:void 0;switch(l){case"authentication_error":return Kl.createContextualError({apiKeyProvided:o==="api-key",oidcTokenProvided:o==="oidc",statusCode:t,cause:n,generationId:u});case"invalid_request_error":return new E6({message:c,statusCode:t,cause:n,generationId:u});case"rate_limit_exceeded":return new R6({message:c,statusCode:t,cause:n,generationId:u});case"model_not_found":{const h=await ar({value:s.error.param,schema:M6});return new O6({message:c,statusCode:t,modelId:h.success?h.value.modelId:void 0,cause:n,generationId:u})}case"internal_server_error":return new Xf({message:c,statusCode:t,cause:n,generationId:u});case"failed_dependency":return new q6({message:c,statusCode:t,cause:n,generationId:u});case"forbidden":return new j6({message:c,statusCode:t,cause:n,generationId:u});default:return new Xf({message:c,statusCode:t,cause:n,generationId:u})}}var z6=ye(()=>me(T({error:T({message:d(),type:d().nullish(),param:Te().nullish(),code:ae([d(),q()]).nullish()}),generationId:d().nullish()})));function F6(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 h0="GatewayTimeoutError",V6=`vercel.ai.gateway.error.${h0}`,f0=Symbol.for(V6),m0,g0,_0=class v1 extends(g0=kt,m0=f0,g0){constructor({message:t="Request timed out",statusCode:r=408,cause:n,generationId:o}={}){super({message:t,statusCode:r,cause:n,generationId:o}),this[m0]=!0,this.name=h0,this.type="timeout_error"}static isInstance(t){return kt.hasMarker(t)&&f0 in t}static createTimeoutError({originalMessage:t,statusCode:r=408,cause:n,generationId:o}){const a=`Gateway request timed out: ${t}
|
|
54
59
|
|
|
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 tr(e,t){var r;return Ft.isInstance(e)?e:Ah(e)?Oh.createTimeoutError({originalMessage:e instanceof Error?e.message:"Unknown error",cause:e}):lt.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 Vr(e){const t=await ur({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 qt(this.config.headers()),successfulResponseHandler:Wt(M4),failedResponseHandler:Ar({errorSchema:yt(),errorToMessage:t=>t}),fetch:this.config.fetch});return e}catch(e){throw await tr(e)}}async getCredits(){try{const e=new URL(this.config.baseURL),{value:t}=await sa({url:`${e.origin}/v1/credits`,headers:await qt(this.config.headers()),successfulResponseHandler:Wt(N4),failedResponseHandler:Ar({errorSchema:yt(),errorToMessage:r=>r}),fetch:this.config.fetch});return t}catch(e){throw await tr(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 qt(this.config.headers()),successfulResponseHandler:Wt(A4),failedResponseHandler:Ar({errorSchema:yt(),errorToMessage:o=>o}),fetch:this.config.fetch});return n}catch(t){throw await tr(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:O(),market_cost:O().optional(),input_tokens:O().optional(),output_tokens:O().optional(),cached_input_tokens:O().optional(),cache_creation_input_tokens:O().optional(),reasoning_tokens:O().optional(),request_count:O().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 qt(this.config.headers()),successfulResponseHandler:Wt(L4),failedResponseHandler:Ar({errorSchema:yt(),errorToMessage:n=>n}),fetch:this.config.fetch});return r}catch(t){throw await tr(t)}}},L4=ve(()=>ye(k({data:k({id:d(),total_cost:O(),upstream_inference_cost:O(),usage:O(),created_at:d(),model:d(),is_byok:me(),provider_name:d(),streamed:me(),finish_reason:d(),latency:O(),generation_time:O(),native_tokens_prompt:O(),native_tokens_completion:O(),native_tokens_reasoning:O(),native_tokens_cached:O(),native_tokens_cache_creation:O(),billable_web_search_calls:O()}).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 qt(this.config.headers());try{const{responseHeaders:s,value:i,rawValue:a}=await Jt({url:this.getUrl(),headers:At(o,e.headers,this.getModelConfigHeaders(this.modelId,!1),await qt(this.config.o11yHeaders)),body:t,successfulResponseHandler:Wt(yt()),failedResponseHandler:Ar({errorSchema:yt(),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 tr(s,await Vr(o))}}async doStream(e){const{args:t,warnings:r}=await this.getArgs(e),{abortSignal:n}=e,o=await qt(this.config.headers());try{const{value:s,responseHeaders:i}=await Jt({url:this.getUrl(),headers:At(o,e.headers,this.getModelConfigHeaders(this.modelId,!0),await qt(this.config.o11yHeaders)),body:t,successfulResponseHandler:aa(yt()),failedResponseHandler:Ar({errorSchema:yt(),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 tr(s,await Vr(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 qt(this.config.headers());try{const{responseHeaders:i,value:a,rawValue:l}=await Jt({url:this.getUrl(),headers:At(s,t??{},this.getModelConfigHeaders(),await qt(this.config.o11yHeaders)),body:{values:e,...n?{providerOptions:n}:{}},successfulResponseHandler:Wt(U4),failedResponseHandler:Ar({errorSchema:yt(),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 tr(i,await Vr(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(O())),usage:k({tokens:O()}).nullish(),providerMetadata:ge(d(),ge(d(),Ce())).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 qt(this.config.headers());try{const{responseHeaders:v,value:_,rawValue:w}=await Jt({url:this.getUrl(),headers:At(g,l??{},this.getModelConfigHeaders(),await qt(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:Wt(B4),failedResponseHandler:Ar({errorSchema:yt(),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 tr(v,await Vr(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:lo(e.data)}:e}var F4=k({images:q(Ce()).optional()}).catchall(Ce()),V4=ze("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:O().nullish(),outputTokens:O().nullish(),totalTokens:O().nullish()}),B4=k({images:q(d()),warnings:q(V4).optional(),providerMetadata:ge(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 qt(this.config.headers());try{const{responseHeaders:h,value:g}=await Jt({url:this.getUrl(),headers:At(p,c??{},this.getModelConfigHeaders(),await qt(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 lt({message:"SSE response body is empty",url:_,requestBodyValues:w,statusCode:v.status});const m=Gf({stream:v.body,schema:Y4}).getReader(),{done:C,value:b}=await m.read();if(m.releaseLock(),C||!b)throw new lt({message:"SSE stream ended without a data event",url:_,requestBodyValues:w,statusCode:v.status});if(!b.success)throw new lt({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 lt({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:Ar({errorSchema:yt(),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 tr(h,await Vr(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:lo(e.data)}:e}var W4=k({videos:q(Ce()).optional()}).catchall(Ce()),G4=ae([k({type:P("url"),url:d(),mediaType:d()}),k({type:P("base64"),data:d(),mediaType:d()})]),K4=ze("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=ze("type",[k({type:P("result"),videos:q(G4),warnings:q(K4).optional(),providerMetadata:ge(d(),W4).optional()}),k({type:P("error"),message:d(),errorType:d(),statusCode:O(),param:Ce().nullable()})]),Q4=ve(()=>ye(yr({objective:et().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:an(et()).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:Or().optional().describe("Maximum number of results to return (1-20). Defaults to 10 if not specified."),source_policy:yr({include_domains:an(et()).optional().describe("List of domains to include in search results."),exclude_domains:an(et()).optional().describe("List of domains to exclude from search results."),after_date:et().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:yr({max_chars_per_result:Or().optional().describe("Maximum characters per result."),max_chars_total:Or().optional().describe("Maximum total characters across all results.")}).optional().describe("Excerpt configuration for controlling result length."),fetch_policy:yr({max_age_seconds:Or().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.")}))),X4=ve(()=>ye(yl([yr({searchId:et(),results:an(yr({url:et(),title:et(),excerpt:et(),publishDate:et().nullable().optional(),relevanceScore:Or().optional()}))}),yr({error:na(["api_error","rate_limit","timeout","invalid_input","configuration_error","unknown"]),statusCode:Or().optional(),message:et()})]))),ek=pr({id:"gateway.parallel_search",inputSchema:Q4,outputSchema:X4}),tk=(e={})=>ek(e),rk=ve(()=>ye(yr({query:yl([et(),an(et())]).describe("Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries."),max_results:Or().optional().describe("Maximum number of search results to return (1-20, default: 10)"),max_tokens_per_page:Or().optional().describe("Maximum number of tokens to extract per search result page (256-2048, default: 2048)"),max_tokens:Or().optional().describe("Maximum total tokens across all search results (default: 25000, max: 1000000)"),country:et().optional().describe("Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"),search_domain_filter:an(et()).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:an(et()).optional().describe("List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"),search_after_date:et().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:et().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:et().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:et().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.")}))),nk=ve(()=>ye(yl([yr({results:an(yr({title:et(),url:et(),snippet:et(),date:et().optional(),lastUpdated:et().optional()})),id:et()}),yr({error:na(["api_error","rate_limit","timeout","invalid_input","unknown"]),statusCode:Or().optional(),message:et()})]))),ok=pr({id:"gateway.perplexity_search",inputSchema:rk,outputSchema:nk}),sk=(e={})=>ok(e),ak={parallelSearch:tk,perplexitySearch:sk};async function ik(){var e;return(e=th.getContext().headers)==null?void 0:e["x-vercel-id"]}var lk="3.0.87",ck="0.0.1";function uk(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 w=await pk(e);return ln({Authorization:`Bearer ${w.token}`,"ai-gateway-protocol-version":ck,[qh]:w.authMethod,...e.headers},`ai-sdk/gateway/${lk}`)}catch(w){throw Ol.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:w})}},c=()=>{const w=uo({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),y=uo({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),m=uo({settingValue:void 0,environmentVariableName:"VERCEL_REGION"}),C=uo({settingValue:void 0,environmentVariableName:"VERCEL_PROJECT_ID"});return async()=>{const b=await ik();return{...w&&{"ai-o11y-deployment-id":w},...y&&{"ai-o11y-environment":y},...m&&{"ai-o11y-region":m},...b&&{"ai-o11y-request-id":b},...C&&{"ai-o11y-project-id":C}}}},u=w=>new j4(w,{provider:"gateway",baseURL:a,headers:l,fetch:e.fetch,o11yHeaders:c()}),f=async()=>{var w,y,m;const C=(m=(y=(w=e._internal)==null?void 0:w.currentDate)==null?void 0:y.call(w).getTime())!=null?m:Date.now();return(!n||C-i>s)&&(i=C,n=new Lh({baseURL:a,headers:l,fetch:e.fetch}).getAvailableModels().then(b=>(o=b,b)).catch(async b=>{throw await tr(b,await Vr(await l()))})),o?Promise.resolve(o):n},p=async()=>new Lh({baseURL:a,headers:l,fetch:e.fetch}).getCredits().catch(async w=>{throw await tr(w,await Vr(await l()))}),h=async w=>new O4({baseURL:a,headers:l,fetch:e.fetch}).getSpendReport(w).catch(async y=>{throw await tr(y,await Vr(await l()))}),g=async w=>new q4({baseURL:a,headers:l,fetch:e.fetch}).getGenerationInfo(w).catch(async y=>{throw await tr(y,await Vr(await l()))}),v=function(w){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return u(w)};v.specificationVersion="v3",v.getAvailableModels=f,v.getCredits=p,v.getSpendReport=h,v.getGenerationInfo=g,v.imageModel=w=>new z4(w,{provider:"gateway",baseURL:a,headers:l,fetch:e.fetch,o11yHeaders:c()}),v.languageModel=u;const _=w=>new D4(w,{provider:"gateway",baseURL:a,headers:l,fetch:e.fetch,o11yHeaders:c()});return v.embeddingModel=_,v.textEmbeddingModel=_,v.videoModel=w=>new H4(w,{provider:"gateway",baseURL:a,headers:l,fetch:e.fetch,o11yHeaders:c()}),v.chat=v.languageModel,v.embedding=v.embeddingModel,v.image=v.imageModel,v.video=v.videoModel,v.tools=ak,v}var dk=uk();async function pk(e){const t=uo({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});return t?{token:t,authMethod:"api-key"}:{token:await th.getVercelOidcToken(),authMethod:"oidc"}}var fk=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 hk(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 mk=hk(Nn),gk=Nn.split(".")[0],Ho=Symbol.for("opentelemetry.js.api."+gk),Jo=fk;function Wo(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||!mk(n)))return(r=Jo[Ho])===null||r===void 0?void 0:r[e]}function Go(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+Nn+".");var r=Jo[Ho];r&&delete r[e]}var _k=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},yk=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))},vk=(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,yk([],_k(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 wk(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 bk=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},kk=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))},Tk="diag",qr=(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,kk([],bk(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=wk((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 Wo("diag",f,r,!0)};r.setLogger=n,r.disable=function(){Go(Tk,r)},r.createComponentLogger=function(o){return new vk(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})(),Ck=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},Sk=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.")},Ik=(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=Ck(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=Sk(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})();qr.instance();function xk(e){return e===void 0&&(e={}),new Ik(new Map(Object.entries(e)))}function Uh(e){return Symbol.for(e)}var Ek=(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})(),$k=new Ek,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)}})(),Rk=(function(){function e(){}return e.prototype.createGauge=function(t,r){return Uk},e.prototype.createHistogram=function(t,r){return zk},e.prototype.createCounter=function(t,r){return Dk},e.prototype.createUpDownCounter=function(t,r){return Fk},e.prototype.createObservableGauge=function(t,r){return Zk},e.prototype.createObservableCounter=function(t,r){return Vk},e.prototype.createObservableUpDownCounter=function(t,r){return Bk},e.prototype.addBatchObservableCallback=function(t,r){},e.prototype.removeBatchObservableCallback=function(t){},e})(),ia=(function(){function e(){}return e})(),Pk=(function(e){An(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(r,n){},t})(ia),Mk=(function(e){An(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(r,n){},t})(ia),Nk=(function(e){An(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(r,n){},t})(ia),Ok=(function(e){An(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(r,n){},t})(ia),Al=(function(){function e(){}return e.prototype.addCallback=function(t){},e.prototype.removeCallback=function(t){},e})(),Ak=(function(e){An(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(Al),qk=(function(e){An(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(Al),Lk=(function(e){An(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(Al),jk=new Rk,Dk=new Pk,Uk=new Nk,zk=new Ok,Fk=new Mk,Vk=new Ak,Zk=new qk,Bk=new Lk,Hk={get:function(e,t){if(e!=null)return e[t]},keys:function(e){return e==null?[]:Object.keys(e)}},Jk={set:function(e,t,r){e!=null&&(e[t]=r)}},Wk=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},Gk=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))},Kk=(function(){function e(){}return e.prototype.active=function(){return $k},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,Gk([n],Wk(o),!1))},e.prototype.bind=function(t,r){return r},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e})(),Yk=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},Qk=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))},ql="context",Xk=new Kk,la=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(t){return Wo(ql,t,qr.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,Qk([t,r,n],Yk(s),!1))},e.prototype.bind=function(t,r){return this._getContextManager().bind(t,r)},e.prototype._getContextManager=function(){return On(ql)||Xk},e.prototype.disable=function(){this._getContextManager().disable(),Go(ql,qr.instance())},e})(),Ll;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(Ll||(Ll={}));var zh="0000000000000000",Fh="00000000000000000000000000000000",eT={traceId:Fh,spanId:zh,traceFlags:Ll.NONE},Yo=(function(){function e(t){t===void 0&&(t=eT),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})(),jl=Uh("OpenTelemetry Context Key SPAN");function Dl(e){return e.getValue(jl)||void 0}function tT(){return Dl(la.getInstance().active())}function Ul(e,t){return e.setValue(jl,t)}function rT(e){return e.deleteValue(jl)}function nT(e,t){return Ul(e,new Yo(t))}function Vh(e){var t;return(t=Dl(e))===null||t===void 0?void 0:t.spanContext()}var oT=/^([0-9a-f]{32})$/i,sT=/^[0-9a-f]{16}$/i;function aT(e){return oT.test(e)&&e!==Fh}function iT(e){return sT.test(e)&&e!==zh}function Zh(e){return aT(e.traceId)&&iT(e.spanId)}function lT(e){return new Yo(e)}var zl=la.getInstance(),Bh=(function(){function e(){}return e.prototype.startSpan=function(t,r,n){n===void 0&&(n=zl.active());var o=!!r?.root;if(o)return new Yo;var s=n&&Vh(n);return cT(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??zl.active(),c=this.startSpan(t,s,l),u=Ul(l,c);return zl.with(u,a,void 0,c)}},e})();function cT(e){return typeof e=="object"&&typeof e.spanId=="string"&&typeof e.traceId=="string"&&typeof e.traceFlags=="number"}var uT=new Bh,dT=(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):uT},e})(),pT=(function(){function e(){}return e.prototype.getTracer=function(t,r,n){return new Bh},e})(),fT=new pT,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 dT(this,t,r,n)},e.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:fT},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();qr.instance();var hT=(function(){function e(){}return e.prototype.getMeter=function(t,r,n){return jk},e})(),mT=new hT,Fl="metrics",gT=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalMeterProvider=function(t){return Wo(Fl,t,qr.instance())},e.prototype.getMeterProvider=function(){return On(Fl)||mT},e.prototype.getMeter=function(t,r,n){return this.getMeterProvider().getMeter(t,r,n)},e.prototype.disable=function(){Go(Fl,qr.instance())},e})();gT.getInstance();var _T=(function(){function e(){}return e.prototype.inject=function(t,r){},e.prototype.extract=function(t,r){return t},e.prototype.fields=function(){return[]},e})(),Vl=Uh("OpenTelemetry Baggage Key");function Wh(e){return e.getValue(Vl)||void 0}function yT(){return Wh(la.getInstance().active())}function vT(e,t){return e.setValue(Vl,t)}function wT(e){return e.deleteValue(Vl)}var Zl="propagation",bT=new _T,kT=(function(){function e(){this.createBaggage=xk,this.getBaggage=Wh,this.getActiveBaggage=yT,this.setBaggage=vT,this.deleteBaggage=wT}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalPropagator=function(t){return Wo(Zl,t,qr.instance())},e.prototype.inject=function(t,r,n){return n===void 0&&(n=Jk),this._getGlobalPropagator().inject(t,r,n)},e.prototype.extract=function(t,r,n){return n===void 0&&(n=Hk),this._getGlobalPropagator().extract(t,r,n)},e.prototype.fields=function(){return this._getGlobalPropagator().fields()},e.prototype.disable=function(){Go(Zl,qr.instance())},e.prototype._getGlobalPropagator=function(){return On(Zl)||bT},e})();kT.getInstance();var Bl="trace",TT=(function(){function e(){this._proxyTracerProvider=new Hh,this.wrapSpanContext=lT,this.isSpanContextValid=Zh,this.deleteSpan=rT,this.getSpan=Dl,this.getActiveSpan=tT,this.getSpanContext=Vh,this.setSpan=Ul,this.setSpanContext=nT}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(t){var r=Wo(Bl,this._proxyTracerProvider,qr.instance());return r&&this._proxyTracerProvider.setDelegate(t),r},e.prototype.getTracerProvider=function(){return On(Bl)||this._proxyTracerProvider},e.prototype.getTracer=function(t,r){return this.getTracerProvider().getTracer(t,r)},e.prototype.disable=function(){Go(Bl,qr.instance()),this._proxyTracerProvider=new Hh},e})(),CT=TT.getInstance(),ST=Object.defineProperty,IT=(e,t)=>{for(var r in t)ST(e,r,{get:t[r],enumerable:!0})},Gh="AI_InvalidArgumentError",Kh=`vercel.ai.error.${Gh}`,xT=Symbol.for(Kh),Yh,Lr=class extends we{constructor({parameter:t,value:r,message:n}){super({name:Gh,message:`Invalid argument for parameter ${t}: ${n}`}),this[Yh]=!0,this.parameter=t,this.value=r}static isInstance(t){return we.hasMarker(t,Kh)}};Yh=xT;var Qh="AI_InvalidToolApprovalError",Xh=`vercel.ai.error.${Qh}`,ET=Symbol.for(Xh),e0,$T=class extends we{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 we.hasMarker(e,Xh)}};e0=ET;var t0="AI_InvalidToolInputError",r0=`vercel.ai.error.${t0}`,RT=Symbol.for(r0),n0,Hl=class extends we{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 we.hasMarker(e,r0)}};n0=RT;var o0="AI_ToolCallNotFoundForApprovalError",s0=`vercel.ai.error.${o0}`,PT=Symbol.for(s0),a0,Jl=class extends we{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 we.hasMarker(e,s0)}};a0=PT;var i0="AI_MissingToolResultsError",l0=`vercel.ai.error.${i0}`,MT=Symbol.for(l0),c0,u0=class extends we{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 we.hasMarker(e,l0)}};c0=MT;var d0="AI_NoObjectGeneratedError",p0=`vercel.ai.error.${d0}`,NT=Symbol.for(p0),f0,cn=class extends we{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 we.hasMarker(e,p0)}};f0=NT;var h0="AI_NoOutputGeneratedError",m0=`vercel.ai.error.${h0}`,OT=Symbol.for(m0),g0,_0=class extends we{constructor({message:e="No output generated.",cause:t}={}){super({name:h0,message:e,cause:t}),this[g0]=!0}static isInstance(e){return we.hasMarker(e,m0)}};g0=OT;var y0="AI_NoSuchToolError",v0=`vercel.ai.error.${y0}`,AT=Symbol.for(v0),w0,Wl=class extends we{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 we.hasMarker(e,v0)}};w0=AT;var b0="AI_ToolCallRepairError",k0=`vercel.ai.error.${b0}`,qT=Symbol.for(k0),T0,LT=class extends we{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 we.hasMarker(e,k0)}};T0=qT;var jT=class extends we{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}`,DT=Symbol.for(S0),I0,po=class extends we{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 we.hasMarker(e,S0)}};I0=DT;var x0="AI_InvalidMessageRoleError",E0=`vercel.ai.error.${x0}`,UT=Symbol.for(E0),$0,zT=class extends we{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 we.hasMarker(e,E0)}};$0=UT;var R0="AI_RetryError",P0=`vercel.ai.error.${R0}`,FT=Symbol.for(P0),M0,N0=class extends we{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 we.hasMarker(e,P0)}};M0=FT;function qn(e){return e===void 0?[]:Array.isArray(e)?e:[e]}async function br(e){for(const t of qn(e.callbacks))if(t!=null)try{await t(e.event)}catch{}}function VT({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 ZT="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",O0=!1,Gl=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(ZT));for(const r of e.warnings)console.warn(VT({warning:r,provider:e.provider,model:e.model}))}};function BT({provider:e,modelId:t}){Gl({warnings:[{type:"compatibility",feature:"specificationVersion",details:"Using v2 specification compatibility mode. Some features may not be available."}],provider:e,model:t})}function HT(e){return e.specificationVersion==="v3"?e:(BT({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:JT(o.stream)}};default:return t[r]}}}))}function JT(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 jT({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return HT(e)}return WT().languageModel(e)}function WT(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:dk}function Kl(e){if(e!=null)return typeof e=="number"?e:e.totalMs}function L0(e){if(!(e==null||typeof e=="number"))return e.stepMs}function GT(e){if(!(e==null||typeof e=="number"))return e.chunkMs}var KT=[{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]}],YT=e=>{const t=typeof e=="string"?io(e):e,r=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(r+10)};function QT(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?YT(e):e}function XT({data:e,signatures:t}){const r=QT(e),n=typeof r=="string"?io(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.145",e6=async({url:e,maxBytes:t,abortSignal:r})=>{var n;const o=e.toString();oa(o);try{const s=await fetch(o,{headers:ln({},`ai-sdk/${j0}`,Bo()),signal:r});if(s.redirected&&oa(s.url),!s.ok)throw new Ht({url:o,statusCode:s.status,statusText:s.statusText});return{data:await Of({response:s,url:o,maxBytes:t??wl}),mediaType:(n=s.headers.get("content-type"))!=null?n:void 0}}catch(s){throw Ht.isInstance(s)?s:new Ht({url:o,cause:s})}},t6=(e=e6)=>t=>Promise.all(t.map(async r=>r.isUrlSupportedByModel?null:e(r)));function r6(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}=r6(e.toString());if(t==null||r==null)throw new we({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:r,mediaType:t}}return{data:e,mediaType:void 0}}function n6(e){return typeof e=="string"?e:e instanceof ArrayBuffer?lo(new Uint8Array(e)):lo(e)}async function z0({prompt:e,supportedUrls:t,download:r=t6()}){const n=await s6(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=>o6({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 o6({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=>a6(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 zT({role:n})}}}async function s6(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 a6(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=XT({data:l,signatures:KT}))!=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 Yl({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 Lr({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new Lr({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(t!=null&&typeof t!="number")throw new Lr({parameter:"temperature",value:t,message:"temperature must be a number"});if(r!=null&&typeof r!="number")throw new Lr({parameter:"topP",value:r,message:"topP must be a number"});if(n!=null&&typeof n!="number")throw new Lr({parameter:"topK",value:n,message:"topK must be a number"});if(o!=null&&typeof o!="number")throw new Lr({parameter:"presencePenalty",value:o,message:"presencePenalty must be a number"});if(s!=null&&typeof s!="number")throw new Lr({parameter:"frequencyPenalty",value:s,message:"frequencyPenalty must be a number"});if(i!=null&&!Number.isInteger(i))throw new Lr({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 i6(e){return e!=null&&Object.keys(e).length>0}async function Z0({tools:e,toolChoice:t,activeTools:r}){if(!i6(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(),O(),me(),ge(d(),Xo.optional()),q(Xo)])),dt=ge(d(),ge(d(),Xo.optional())),B0=k({type:P("text"),text:d(),providerOptions:dt.optional()}),l6=k({type:P("image"),image:ae([D0,Ys(URL)]),mediaType:d().optional(),providerOptions:dt.optional()}),H0=k({type:P("file"),data:ae([D0,Ys(URL)]),filename:d().optional(),mediaType:d(),providerOptions:dt.optional()}),c6=k({type:P("reasoning"),text:d(),providerOptions:dt.optional()}),u6=k({type:P("tool-call"),toolCallId:d(),toolName:d(),input:Ce(),providerOptions:dt.optional(),providerExecuted:me().optional()}),d6=ze("type",[k({type:P("text"),value:d(),providerOptions:dt.optional()}),k({type:P("json"),value:Xo,providerOptions:dt.optional()}),k({type:P("execution-denied"),reason:d().optional(),providerOptions:dt.optional()}),k({type:P("error-text"),value:d(),providerOptions:dt.optional()}),k({type:P("error-json"),value:Xo,providerOptions:dt.optional()}),k({type:P("content"),value:q(ae([k({type:P("text"),text:d(),providerOptions:dt.optional()}),k({type:P("media"),data:d(),mediaType:d()}),k({type:P("file-data"),data:d(),mediaType:d(),filename:d().optional(),providerOptions:dt.optional()}),k({type:P("file-url"),url:d(),providerOptions:dt.optional()}),k({type:P("file-id"),fileId:ae([d(),ge(d(),d())]),providerOptions:dt.optional()}),k({type:P("image-data"),data:d(),mediaType:d(),providerOptions:dt.optional()}),k({type:P("image-url"),url:d(),providerOptions:dt.optional()}),k({type:P("image-file-id"),fileId:ae([d(),ge(d(),d())]),providerOptions:dt.optional()}),k({type:P("custom"),providerOptions:dt.optional()})]))})]),J0=k({type:P("tool-result"),toolCallId:d(),toolName:d(),output:d6,providerOptions:dt.optional()}),p6=k({type:P("tool-approval-request"),approvalId:d(),toolCallId:d()}),f6=k({type:P("tool-approval-response"),approvalId:d(),approved:me(),reason:d().optional()}),h6=k({role:P("system"),content:d(),providerOptions:dt.optional()}),m6=k({role:P("user"),content:ae([d(),q(ae([B0,l6,H0]))]),providerOptions:dt.optional()}),g6=k({role:P("assistant"),content:ae([d(),q(ae([B0,H0,c6,u6,J0,p6]))]),providerOptions:dt.optional()}),_6=k({role:P("tool"),content:q(ae([J0,f6])),providerOptions:dt.optional()}),y6=ae([h6,m6,g6,_6]);async function W0(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 ur({value:t,schema:q(y6)});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 G0(e){if(!Ol.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 we({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
|
|
60
|
+
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 v1({message:a,statusCode:r,cause:n,generationId:o})}};function y0(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 Ht(e,t){var r;return kt.isInstance(e)?e:y0(e)?_0.createTimeoutError({originalMessage:e instanceof Error?e.message:"Unknown error",cause:e}):tt.isInstance(e)?e.cause&&y0(e.cause)?_0.createTimeoutError({originalMessage:e.message,cause:e}):await p0({response:F6(e),statusCode:(r=e.statusCode)!=null?r:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):await p0({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}var v0="ai-gateway-auth-method";async function _r(e){const t=await ar({value:e[v0],schema:Z6});return t.success?t.value:void 0}var Z6=ye(()=>me(ae([M("api-key"),M("oidc")]))),H6=["embedding","image","language","reranking","speech","transcription","video"],w0=class{constructor(e){this.config=e}async getAvailableModels(){try{const{value:e}=await ms({url:`${this.config.baseURL}/config`,headers:await yt(this.config.headers()),successfulResponseHandler:At(B6),failedResponseHandler:ir({errorSchema:ut(),errorToMessage:t=>t}),fetch:this.config.fetch});return e}catch(e){throw await Ht(e)}}async getCredits(){try{const e=new URL(this.config.baseURL),{value:t}=await ms({url:`${e.origin}/v1/credits`,headers:await yt(this.config.headers()),successfulResponseHandler:At(J6),failedResponseHandler:ir({errorSchema:ut(),errorToMessage:r=>r}),fetch:this.config.fetch});return t}catch(e){throw await Ht(e)}}},B6=ye(()=>me(T({models:L(T({id:d(),name:d(),description:d().nullish(),pricing:T({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:T({specificationVersion:M("v3"),provider:d(),modelId:d()}),modelType:d().nullish()})).transform(e=>e.filter(t=>t.modelType==null||H6.includes(t.modelType)))}))),J6=ye(()=>me(T({balance:d(),total_used:d()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),G6=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 ms({url:`${t.origin}/v1/report?${r.toString()}`,headers:await yt(this.config.headers()),successfulResponseHandler:At(W6),failedResponseHandler:ir({errorSchema:ut(),errorToMessage:o=>o}),fetch:this.config.fetch});return n}catch(t){throw await Ht(t)}}},W6=ye(()=>me(T({results:L(T({day:d().optional(),hour:d().optional(),user:d().optional(),model:d().optional(),tag:d().optional(),provider:d().optional(),credential_type:le(["byok","system"]).optional(),total_cost:q(),market_cost:q().optional(),input_tokens:q().optional(),output_tokens:q().optional(),cached_input_tokens:q().optional(),cache_creation_input_tokens:q().optional(),reasoning_tokens:q().optional(),request_count:q().optional()}).transform(({credential_type:e,total_cost:t,market_cost:r,input_tokens:n,output_tokens:o,cached_input_tokens:a,cache_creation_input_tokens:i,reasoning_tokens:s,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}:{},...a!==void 0?{cachedInputTokens:a}:{},...i!==void 0?{cacheCreationInputTokens:i}:{},...s!==void 0?{reasoningTokens:s}:{},...l!==void 0?{requestCount:l}:{}})))}))),K6=class{constructor(e){this.config=e}async getGenerationInfo(e){try{const t=new URL(this.config.baseURL),{value:r}=await ms({url:`${t.origin}/v1/generation?id=${encodeURIComponent(e.id)}`,headers:await yt(this.config.headers()),successfulResponseHandler:At(Y6),failedResponseHandler:ir({errorSchema:ut(),errorToMessage:n=>n}),fetch:this.config.fetch});return r}catch(t){throw await Ht(t)}}},Y6=ye(()=>me(T({data:T({id:d(),total_cost:q(),upstream_inference_cost:q(),usage:q(),created_at:d(),model:d(),is_byok:_e(),provider_name:d(),streamed:_e(),finish_reason:d(),latency:q(),generation_time:q(),native_tokens_prompt:q(),native_tokens_completion:q(),native_tokens_reasoning:q(),native_tokens_cached:q(),native_tokens_cache_creation:q(),billable_web_search_calls:q()}).transform(({total_cost:e,upstream_inference_cost:t,created_at:r,is_byok:n,provider_name:o,finish_reason:a,generation_time:i,native_tokens_prompt:s,native_tokens_completion:l,native_tokens_reasoning:c,native_tokens_cached:u,native_tokens_cache_creation:h,billable_web_search_calls:p,...m})=>({...m,totalCost:e,upstreamInferenceCost:t,createdAt:r,isByok:n,providerName:o,finishReason:a,generationTime:i,promptTokens:s,completionTokens:l,reasoningTokens:c,cachedTokens:u,cacheCreationTokens:h,billableWebSearchCalls:p}))}).transform(({data:e})=>e))),Q6=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 yt(this.config.headers());try{const{responseHeaders:a,value:i,rawValue:s}=await Ot({url:this.getUrl(),headers:It(o,e.headers,this.getModelConfigHeaders(this.modelId,!1),await yt(this.config.o11yHeaders)),body:t,successfulResponseHandler:At(ut()),failedResponseHandler:ir({errorSchema:ut(),errorToMessage:l=>l}),...n&&{abortSignal:n},fetch:this.config.fetch});return{...i,request:{body:t},response:{headers:a,body:s},warnings:r}}catch(a){throw await Ht(a,await _r(o))}}async doStream(e){const{args:t,warnings:r}=await this.getArgs(e),{abortSignal:n}=e,o=await yt(this.config.headers());try{const{value:a,responseHeaders:i}=await Ot({url:this.getUrl(),headers:It(o,e.headers,this.getModelConfigHeaders(this.modelId,!0),await yt(this.config.o11yHeaders)),body:t,successfulResponseHandler:_s(ut()),failedResponseHandler:ir({errorSchema:ut(),errorToMessage:s=>s}),...n&&{abortSignal:n},fetch:this.config.fetch});return{stream:a.pipeThrough(new TransformStream({start(s){r.length>0&&s.enqueue({type:"stream-start",warnings:r})},transform(s,l){if(s.success){const c=s.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(s.error)}})),request:{body:t},response:{headers:i}}}catch(a){throw await Ht(a,await _r(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),a=Buffer.from(o).toString("base64");n.data=new URL(`data:${n.mediaType||"application/octet-stream"};base64,${a}`)}}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)}}},X6=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,a;const i=await yt(this.config.headers());try{const{responseHeaders:s,value:l,rawValue:c}=await Ot({url:this.getUrl(),headers:It(i,t??{},this.getModelConfigHeaders(),await yt(this.config.o11yHeaders)),body:{values:e,...n?{providerOptions:n}:{}},successfulResponseHandler:At(tk),failedResponseHandler:ir({errorSchema:ut(),errorToMessage:u=>u}),...r&&{abortSignal:r},fetch:this.config.fetch});return{embeddings:l.embeddings,usage:(o=l.usage)!=null?o:void 0,providerMetadata:l.providerMetadata,response:{headers:s,body:c},warnings:(a=l.warnings)!=null?a:[]}}catch(s){throw await Ht(s,await _r(i))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"3","ai-model-id":this.modelId}}},ek=Le("type",[T({type:M("unsupported"),feature:d(),details:d().optional()}),T({type:M("compatibility"),feature:d(),details:d().optional()}),T({type:M("other"),message:d()})]),tk=ye(()=>me(T({embeddings:L(L(q())),usage:T({tokens:q()}).nullish(),warnings:L(ek).optional(),providerMetadata:pe(d(),pe(d(),Te())).optional()}))),rk=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:a,mask:i,providerOptions:s,headers:l,abortSignal:c}){var u,h,p,m;const f=await yt(this.config.headers());try{const{responseHeaders:b,value:w,rawValue:C}=await Ot({url:this.getUrl(),headers:It(f,l??{},this.getModelConfigHeaders(),await yt(this.config.o11yHeaders)),body:{prompt:e,n:t,...r&&{size:r},...n&&{aspectRatio:n},...o&&{seed:o},...s&&{providerOptions:s},...a&&{files:a.map(v=>b0(v))},...i&&{mask:b0(i)}},successfulResponseHandler:At(sk),failedResponseHandler:ir({errorSchema:ut(),errorToMessage:v=>v}),...c&&{abortSignal:c},fetch:this.config.fetch});return{images:w.images,warnings:(u=w.warnings)!=null?u:[],providerMetadata:w.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:b},...w.usage!=null&&{usage:{inputTokens:(h=w.usage.inputTokens)!=null?h:void 0,outputTokens:(p=w.usage.outputTokens)!=null?p:void 0,totalTokens:(m=w.usage.totalTokens)!=null?m:void 0}}}}catch(b){throw await Ht(b,await _r(f))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"3","ai-model-id":this.modelId}}};function b0(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:gn(e.data)}:e}var nk=T({images:L(Te()).optional()}).catchall(Te()),ok=Le("type",[T({type:M("unsupported"),feature:d(),details:d().optional()}),T({type:M("compatibility"),feature:d(),details:d().optional()}),T({type:M("other"),message:d()})]),ak=T({inputTokens:q().nullish(),outputTokens:q().nullish(),totalTokens:q().nullish()}),sk=T({images:L(d()),warnings:L(ok).optional(),providerMetadata:pe(d(),nk).optional(),usage:ak.optional()}),ik=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:a,seed:i,generateAudio:s,image:l,providerOptions:c,headers:u,abortSignal:h}){var p;const m=await yt(this.config.headers());try{const{responseHeaders:f,value:b}=await Ot({url:this.getUrl(),headers:It(m,u??{},this.getModelConfigHeaders(),await yt(this.config.o11yHeaders),{accept:"text/event-stream"}),body:{prompt:e,n:t,...r&&{aspectRatio:r},...n&&{resolution:n},...o&&{duration:o},...a&&{fps:a},...i&&{seed:i},...s!==void 0&&{generateAudio:s},...c&&{providerOptions:c},...l&&{image:lk(l)}},successfulResponseHandler:async({response:w,url:C,requestBodyValues:v})=>{if(w.body==null)throw new tt({message:"SSE response body is empty",url:C,requestBodyValues:v,statusCode:w.status});const I=kf({stream:w.body,schema:pk}).getReader(),{done:y,value:_}=await I.read();if(I.releaseLock(),y||!_)throw new tt({message:"SSE stream ended without a data event",url:C,requestBodyValues:v,statusCode:w.status});if(!_.success)throw new tt({message:"Failed to parse video SSE event",cause:_.error,url:C,requestBodyValues:v,statusCode:w.status});const k=_.value;if(k.type==="error")throw new tt({message:k.message,statusCode:k.statusCode,url:C,requestBodyValues:v,responseHeaders:Object.fromEntries([...w.headers]),responseBody:JSON.stringify(k),data:{error:{message:k.message,type:k.errorType,param:k.param}}});return{value:{videos:k.videos,warnings:k.warnings,providerMetadata:k.providerMetadata},responseHeaders:Object.fromEntries([...w.headers])}},failedResponseHandler:ir({errorSchema:ut(),errorToMessage:w=>w}),...h&&{abortSignal:h},fetch:this.config.fetch});return{videos:b.videos,warnings:(p=b.warnings)!=null?p:[],providerMetadata:b.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:f}}}catch(f){throw await Ht(f,await _r(m))}}getUrl(){return`${this.config.baseURL}/video-model`}getModelConfigHeaders(){return{"ai-video-model-specification-version":"3","ai-model-id":this.modelId}}};function lk(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:gn(e.data)}:e}var ck=T({videos:L(Te()).optional()}).catchall(Te()),uk=ae([T({type:M("url"),url:d(),mediaType:d()}),T({type:M("base64"),data:d(),mediaType:d()})]),dk=Le("type",[T({type:M("unsupported"),feature:d(),details:d().optional()}),T({type:M("compatibility"),feature:d(),details:d().optional()}),T({type:M("other"),message:d()})]),pk=Le("type",[T({type:M("result"),videos:L(uk),warnings:L(dk).optional(),providerMetadata:pe(d(),ck).optional()}),T({type:M("error"),message:d(),errorType:d(),statusCode:q(),param:Te().nullable()})]),hk=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:a}){var i;const s=await yt(this.config.headers());try{const{responseHeaders:l,value:c,rawValue:u}=await Ot({url:this.getUrl(),headers:It(s,n??{},this.getModelConfigHeaders(),await yt(this.config.o11yHeaders)),body:{documents:e,query:t,...r!=null?{topN:r}:{},...a?{providerOptions:a}:{}},successfulResponseHandler:At(mk),failedResponseHandler:ir({errorSchema:ut(),errorToMessage:h=>h}),...o&&{abortSignal:o},fetch:this.config.fetch});return{ranking:c.ranking,providerMetadata:c.providerMetadata,response:{headers:l,body:u},warnings:(i=c.warnings)!=null?i:[]}}catch(l){throw await Ht(l,await _r(s))}}getUrl(){return`${this.config.baseURL}/reranking-model`}getModelConfigHeaders(){return{"ai-reranking-model-specification-version":"3","ai-model-id":this.modelId}}},fk=Le("type",[T({type:M("unsupported"),feature:d(),details:d().optional()}),T({type:M("compatibility"),feature:d(),details:d().optional()}),T({type:M("other"),message:d()})]),mk=ye(()=>me(T({ranking:L(T({index:q(),relevanceScore:q()})),warnings:L(fk).optional(),providerMetadata:pe(d(),pe(d(),Te())).optional()}))),gk=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get provider(){return this.config.provider}async doGenerate({text:e,voice:t,outputFormat:r,instructions:n,speed:o,language:a,providerOptions:i,headers:s,abortSignal:l}){var c;const u=await yt(this.config.headers());try{const{responseHeaders:h,value:p,rawValue:m}=await Ot({url:this.getUrl(),headers:It(u,s??{},this.getModelConfigHeaders(),await yt(this.config.o11yHeaders)),body:{text:e,...t&&{voice:t},...r&&{outputFormat:r},...n&&{instructions:n},...o!=null&&{speed:o},...a&&{language:a},...i&&{providerOptions:i}},successfulResponseHandler:At(vk),failedResponseHandler:ir({errorSchema:ut(),errorToMessage:f=>f}),...l&&{abortSignal:l},fetch:this.config.fetch});return{audio:p.audio,warnings:(c=p.warnings)!=null?c:[],providerMetadata:p.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:h,body:m}}}catch(h){throw await Ht(h,await _r(u??{}))}}getUrl(){return`${this.config.baseURL}/speech-model`}getModelConfigHeaders(){return{"ai-speech-model-specification-version":"3","ai-model-id":this.modelId}}},_k=T({}).catchall(Te()),yk=Le("type",[T({type:M("unsupported"),feature:d(),details:d().optional()}),T({type:M("compatibility"),feature:d(),details:d().optional()}),T({type:M("other"),message:d()})]),vk=T({audio:d(),warnings:L(yk).optional(),providerMetadata:pe(d(),_k).optional()}),wk=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get provider(){return this.config.provider}async doGenerate({audio:e,mediaType:t,providerOptions:r,headers:n,abortSignal:o}){var a,i,s,l;const c=await yt(this.config.headers());try{const{responseHeaders:u,value:h,rawValue:p}=await Ot({url:this.getUrl(),headers:It(c,n??{},this.getModelConfigHeaders(),await yt(this.config.o11yHeaders)),body:{audio:e instanceof Uint8Array?gn(e):e,mediaType:t,...r&&{providerOptions:r}},successfulResponseHandler:At(Tk),failedResponseHandler:ir({errorSchema:ut(),errorToMessage:m=>m}),...o&&{abortSignal:o},fetch:this.config.fetch});return{text:h.text,segments:(a=h.segments)!=null?a:[],language:(i=h.language)!=null?i:void 0,durationInSeconds:(s=h.durationInSeconds)!=null?s:void 0,warnings:(l=h.warnings)!=null?l:[],providerMetadata:h.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:u,body:p}}}catch(u){throw await Ht(u,await _r(c??{}))}}getUrl(){return`${this.config.baseURL}/transcription-model`}getModelConfigHeaders(){return{"ai-transcription-model-specification-version":"3","ai-model-id":this.modelId}}},bk=T({}).catchall(Te()),kk=Le("type",[T({type:M("unsupported"),feature:d(),details:d().optional()}),T({type:M("compatibility"),feature:d(),details:d().optional()}),T({type:M("other"),message:d()})]),Tk=T({text:d(),segments:L(T({text:d(),startSecond:q(),endSecond:q()})).optional(),language:d().nullish(),durationInSeconds:q().nullish(),warnings:L(kk).optional(),providerMetadata:pe(d(),bk).optional()}),Ck=ye(()=>me(vt({query:be().describe("Natural-language web search query. This is required."),type:Vr(["auto","fast","instant"]).optional().describe("Search method. Use auto for the default balance of speed and quality."),num_results:gt().optional().describe("Maximum number of results to return (1-100, default: 10)."),category:Vr(["company","people","research paper","news","personal site","financial report"]).optional().describe("Optional content category to focus results."),user_location:be().optional().describe("Two-letter ISO country code such as 'US'."),include_domains:St(be()).optional().describe("Only return results from these domains."),exclude_domains:St(be()).optional().describe("Exclude results from these domains."),start_published_date:be().optional().describe("Only return links published after this ISO 8601 date."),end_published_date:be().optional().describe("Only return links published before this ISO 8601 date."),contents:vt({text:jn([Ml(),vt({max_characters:gt().optional(),include_html_tags:Ml().optional(),verbosity:Vr(["compact","standard","full"]).optional(),include_sections:St(Vr(["header","navigation","banner","body","sidebar","footer","metadata"])).optional(),exclude_sections:St(Vr(["header","navigation","banner","body","sidebar","footer","metadata"])).optional()})]).optional(),highlights:jn([Ml(),vt({query:be().optional(),max_characters:gt().optional()})]).optional(),max_age_hours:gt().optional(),livecrawl_timeout:gt().optional(),subpages:gt().optional(),subpage_target:jn([be(),St(be())]).optional(),extras:vt({links:gt().optional(),image_links:gt().optional()}).optional()}).optional().describe("Controls extracted page content and freshness.")}))),Sk=ye(()=>me(jn([vt({requestId:be(),searchType:be().optional(),resolvedSearchType:be().optional(),results:St(vt({title:be(),url:be(),id:be(),publishedDate:be().nullable().optional(),author:be().nullable().optional(),image:be().nullable().optional(),favicon:be().nullable().optional(),text:be().optional(),highlights:St(be()).optional(),highlightScores:St(gt()).optional(),summary:be().optional(),subpages:St(e4()).optional(),extras:vt({links:St(be()).optional(),imageLinks:St(be()).optional()}).optional()})),costDollars:vt({total:gt().optional(),search:t4(gt()).optional()}).optional()}),vt({error:Vr(["api_error","rate_limit","timeout","invalid_input","configuration_error","execution_error","unknown"]),statusCode:gt().optional(),message:be()})]))),Ik=sr({id:"gateway.exa_search",inputSchema:Ck,outputSchema:Sk}),xk=(e={})=>Ik(e),Ek=ye(()=>me(vt({objective:be().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:St(be()).optional().describe("Optional search queries to supplement the objective. Maximum 200 characters per query."),mode:Vr(["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:gt().optional().describe("Maximum number of results to return (1-20). Defaults to 10 if not specified."),source_policy:vt({include_domains:St(be()).optional().describe("Limit results to these domains. Use plain domain names only — e.g. example.com or sub.example.gov, or a bare extension like .edu. Do not include a scheme, path, or port (e.g. not https://example.com/page)."),exclude_domains:St(be()).optional().describe("Exclude results from these domains. Use plain domain names only — e.g. example.com or sub.example.gov, or a bare extension like .edu. Do not include a scheme, path, or port (e.g. not https://example.com/page)."),after_date:be().optional().describe("Only include results published after this date. Use an ISO 8601 calendar date formatted YYYY-MM-DD (e.g. 2025-01-01); do not include a time.")}).optional().describe("Source policy for controlling which domains to include/exclude and freshness."),excerpts:vt({max_chars_per_result:gt().optional().describe("Maximum characters per result."),max_chars_total:gt().optional().describe("Maximum total characters across all results.")}).optional().describe("Excerpt configuration for controlling result length."),fetch_policy:vt({max_age_seconds:gt().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.")}))),$k=ye(()=>me(jn([vt({searchId:be(),results:St(vt({url:be(),title:be(),excerpt:be(),publishDate:be().nullable().optional(),relevanceScore:gt().optional()}))}),vt({error:Vr(["api_error","rate_limit","timeout","invalid_input","configuration_error","unknown"]),statusCode:gt().optional(),message:be()})]))),Rk=sr({id:"gateway.parallel_search",inputSchema:Ek,outputSchema:$k}),Pk=(e={})=>Rk(e),Mk=ye(()=>me(vt({query:jn([be(),St(be())]).describe("Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries."),max_results:gt().optional().describe("Maximum number of search results to return (1-20, default: 10)"),max_tokens_per_page:gt().optional().describe("Maximum number of tokens to extract per search result page (256-2048, default: 2048)"),max_tokens:gt().optional().describe("Maximum total tokens across all search results (default: 25000, max: 1000000)"),country:be().optional().describe("Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"),search_domain_filter:St(be()).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:St(be()).optional().describe("List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"),search_after_date:be().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:be().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:be().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:be().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:Vr(["day","week","month","year"]).optional().describe("Filter results by relative time period. Cannot be used with search_after_date or search_before_date.")}))),Ok=ye(()=>me(jn([vt({results:St(vt({title:be(),url:be(),snippet:be(),date:be().optional(),lastUpdated:be().optional()})),id:be()}),vt({error:Vr(["api_error","rate_limit","timeout","invalid_input","unknown"]),statusCode:gt().optional(),message:be()})]))),Ak=sr({id:"gateway.perplexity_search",inputSchema:Mk,outputSchema:Ok}),Nk=(e={})=>Ak(e),qk={exaSearch:xk,parallelSearch:Pk,perplexitySearch:Nk};async function Lk(){var e;return(e=Rf.getContext().headers)==null?void 0:e["x-vercel-id"]}var jk="3.0.140",Dk="0.0.1";function Uk(e={}){var t,r;let n=null,o=null;const a=(t=e.metadataCacheRefreshMillis)!=null?t:1e3*60*5;let i=0;const s=(r=If(e.baseURL))!=null?r:"https://ai-gateway.vercel.sh/v3/ai",l=async()=>{try{const I=await Fk(e);return _n({Authorization:`Bearer ${I.token}`,"ai-gateway-protocol-version":Dk,[v0]:I.authMethod,...e.headers},`ai-sdk/gateway/${jk}`)}catch(I){throw Kl.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:I})}},c=()=>{const I=wo({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),y=wo({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),_=wo({settingValue:void 0,environmentVariableName:"VERCEL_REGION"}),k=wo({settingValue:void 0,environmentVariableName:"VERCEL_PROJECT_ID"});return async()=>{const S=await Lk();return{...I&&{"ai-o11y-deployment-id":I},...y&&{"ai-o11y-environment":y},..._&&{"ai-o11y-region":_},...S&&{"ai-o11y-request-id":S},...k&&{"ai-o11y-project-id":k}}}},u=I=>new Q6(I,{provider:"gateway",baseURL:s,headers:l,fetch:e.fetch,o11yHeaders:c()}),h=async()=>{var I,y,_;const k=(_=(y=(I=e._internal)==null?void 0:I.currentDate)==null?void 0:y.call(I).getTime())!=null?_:Date.now();return(!n||k-i>a)&&(i=k,n=new w0({baseURL:s,headers:l,fetch:e.fetch}).getAvailableModels().then(S=>(o=S,S)).catch(async S=>{throw await Ht(S,await _r(await l()))})),o?Promise.resolve(o):n},p=async()=>new w0({baseURL:s,headers:l,fetch:e.fetch}).getCredits().catch(async I=>{throw await Ht(I,await _r(await l()))}),m=async I=>new G6({baseURL:s,headers:l,fetch:e.fetch}).getSpendReport(I).catch(async y=>{throw await Ht(y,await _r(await l()))}),f=async I=>new K6({baseURL:s,headers:l,fetch:e.fetch}).getGenerationInfo(I).catch(async y=>{throw await Ht(y,await _r(await l()))}),b=function(I){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return u(I)};b.specificationVersion="v3",b.getAvailableModels=h,b.getCredits=p,b.getSpendReport=m,b.getGenerationInfo=f,b.imageModel=I=>new rk(I,{provider:"gateway",baseURL:s,headers:l,fetch:e.fetch,o11yHeaders:c()}),b.languageModel=u;const w=I=>new X6(I,{provider:"gateway",baseURL:s,headers:l,fetch:e.fetch,o11yHeaders:c()});b.embeddingModel=w,b.textEmbeddingModel=w,b.videoModel=I=>new ik(I,{provider:"gateway",baseURL:s,headers:l,fetch:e.fetch,o11yHeaders:c()});const C=I=>new hk(I,{provider:"gateway",baseURL:s,headers:l,fetch:e.fetch,o11yHeaders:c()});b.rerankingModel=C,b.reranking=C;const v=I=>new gk(I,{provider:"gateway",baseURL:s,headers:l,fetch:e.fetch,o11yHeaders:c()});b.speechModel=v,b.speech=v;const g=I=>new wk(I,{provider:"gateway",baseURL:s,headers:l,fetch:e.fetch,o11yHeaders:c()});return b.transcriptionModel=g,b.transcription=g,b.chat=b.languageModel,b.embedding=b.embeddingModel,b.image=b.imageModel,b.video=b.videoModel,b.tools=qk,b}var zk=Uk();async function Fk(e){const t=wo({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});return t?{token:t,authMethod:"api-key"}:{token:await Rf.getVercelOidcToken(),authMethod:"oidc"}}const Zn="1.9.1",k0=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function Vk(e){const t=new Set([e]),r=new Set,n=e.match(k0);if(!n)return()=>!1;const o={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(o.prerelease!=null)return function(l){return l===e};function a(s){return r.add(s),!1}function i(s){return t.add(s),!0}return function(l){if(t.has(l))return!0;if(r.has(l))return!1;const c=l.match(k0);if(!c)return a(l);const u={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return u.prerelease!=null||o.major!==u.major?a(l):o.major===0?o.minor===u.minor&&o.patch<=u.patch?i(l):a(l):o.minor<=u.minor?i(l):a(l)}}const Zk=Vk(Zn),Hk=Zn.split(".")[0],aa=Symbol.for(`opentelemetry.js.api.${Hk}`),sa=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{};function ia(e,t,r,n=!1){var o;const a=sa[aa]=(o=sa[aa])!==null&&o!==void 0?o:{version:Zn};if(!n&&a[e]){const i=new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${e}`);return r.error(i.stack||i.message),!1}if(a.version!==Zn){const i=new Error(`@opentelemetry/api: Registration of version v${a.version} for ${e} does not match previously registered API v${Zn}`);return r.error(i.stack||i.message),!1}return a[e]=t,r.debug(`@opentelemetry/api: Registered a global for ${e} v${Zn}.`),!0}function Hn(e){var t,r;const n=(t=sa[aa])===null||t===void 0?void 0:t.version;if(!(!n||!Zk(n)))return(r=sa[aa])===null||r===void 0?void 0:r[e]}function la(e,t){t.debug(`@opentelemetry/api: Unregistering a global for ${e} v${Zn}.`);const r=sa[aa];r&&delete r[e]}class Bk{constructor(t){this._namespace=t.namespace||"DiagComponentLogger"}debug(...t){return ca("debug",this._namespace,t)}error(...t){return ca("error",this._namespace,t)}info(...t){return ca("info",this._namespace,t)}warn(...t){return ca("warn",this._namespace,t)}verbose(...t){return ca("verbose",this._namespace,t)}}function ca(e,t,r){const n=Hn("diag");if(n)return n[e](t,...r)}var lr;(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"})(lr||(lr={}));function Jk(e,t){e<lr.NONE?e=lr.NONE:e>lr.ALL&&(e=lr.ALL),t=t||{};function r(n,o){const a=t[n];return typeof a=="function"&&e>=o?a.bind(t):function(){}}return{error:r("error",lr.ERROR),warn:r("warn",lr.WARN),info:r("info",lr.INFO),debug:r("debug",lr.DEBUG),verbose:r("verbose",lr.VERBOSE)}}const Gk="diag";class yr{static instance(){return this._instance||(this._instance=new yr),this._instance}constructor(){function t(o){return function(...a){const i=Hn("diag");if(i)return i[o](...a)}}const r=this,n=(o,a={logLevel:lr.INFO})=>{var i,s,l;if(o===r){const h=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=h.stack)!==null&&i!==void 0?i:h.message),!1}typeof a=="number"&&(a={logLevel:a});const c=Hn("diag"),u=Jk((s=a.logLevel)!==null&&s!==void 0?s:lr.INFO,o);if(c&&!a.suppressOverrideMessage){const h=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";c.warn(`Current logger will be overwritten from ${h}`),u.warn(`Current logger will overwrite one already registered from ${h}`)}return ia("diag",u,r,!0)};r.setLogger=n,r.disable=()=>{la(Gk,r)},r.createComponentLogger=o=>new Bk(o),r.verbose=t("verbose"),r.debug=t("debug"),r.info=t("info"),r.warn=t("warn"),r.error=t("error")}}class bo{constructor(t){this._entries=t?new Map(t):new Map}getEntry(t){const r=this._entries.get(t);if(r)return Object.assign({},r)}getAllEntries(){return Array.from(this._entries.entries())}setEntry(t,r){const n=new bo(this._entries);return n._entries.set(t,r),n}removeEntry(t){const r=new bo(this._entries);return r._entries.delete(t),r}removeEntries(...t){const r=new bo(this._entries);for(const n of t)r._entries.delete(n);return r}clear(){return new bo}}yr.instance();function Wk(e={}){return new bo(new Map(Object.entries(e)))}function T0(e){return Symbol.for(e)}class ys{constructor(t){const r=this;r._currentContext=t?new Map(t):new Map,r.getValue=n=>r._currentContext.get(n),r.setValue=(n,o)=>{const a=new ys(r._currentContext);return a._currentContext.set(n,o),a},r.deleteValue=n=>{const o=new ys(r._currentContext);return o._currentContext.delete(n),o}}}const Kk=new ys;class Yk{constructor(){}createGauge(t,r){return iT}createHistogram(t,r){return lT}createCounter(t,r){return sT}createUpDownCounter(t,r){return cT}createObservableGauge(t,r){return dT}createObservableCounter(t,r){return uT}createObservableUpDownCounter(t,r){return pT}addBatchObservableCallback(t,r){}removeBatchObservableCallback(t){}}class vs{}class Qk extends vs{add(t,r){}}class Xk extends vs{add(t,r){}}class eT extends vs{record(t,r){}}class tT extends vs{record(t,r){}}class Yl{addCallback(t){}removeCallback(t){}}class rT extends Yl{}class nT extends Yl{}class oT extends Yl{}const aT=new Yk,sT=new Qk,iT=new eT,lT=new tT,cT=new Xk,uT=new rT,dT=new nT,pT=new oT,hT={get(e,t){if(e!=null)return e[t]},keys(e){return e==null?[]:Object.keys(e)}},fT={set(e,t,r){e!=null&&(e[t]=r)}};class mT{active(){return Kk}with(t,r,n,...o){return r.call(n,...o)}bind(t,r){return r}enable(){return this}disable(){return this}}const Ql="context",gT=new mT;class ko{constructor(){}static getInstance(){return this._instance||(this._instance=new ko),this._instance}setGlobalContextManager(t){return ia(Ql,t,yr.instance())}active(){return this._getContextManager().active()}with(t,r,n,...o){return this._getContextManager().with(t,r,n,...o)}bind(t,r){return this._getContextManager().bind(t,r)}_getContextManager(){return Hn(Ql)||gT}disable(){this._getContextManager().disable(),la(Ql,yr.instance())}}var Xl;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(Xl||(Xl={}));const C0="0000000000000000",S0="00000000000000000000000000000000",_T={traceId:S0,spanId:C0,traceFlags:Xl.NONE};class ua{constructor(t=_T){this._spanContext=t}spanContext(){return this._spanContext}setAttribute(t,r){return this}setAttributes(t){return this}addEvent(t,r){return this}addLink(t){return this}addLinks(t){return this}setStatus(t){return this}updateName(t){return this}end(t){}isRecording(){return!1}recordException(t,r){}}const ec=T0("OpenTelemetry Context Key SPAN");function tc(e){return e.getValue(ec)||void 0}function yT(){return tc(ko.getInstance().active())}function rc(e,t){return e.setValue(ec,t)}function vT(e){return e.deleteValue(ec)}function wT(e,t){return rc(e,new ua(t))}function I0(e){var t;return(t=tc(e))===null||t===void 0?void 0:t.spanContext()}const ws=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1]);function x0(e,t){if(typeof e!="string"||e.length!==t)return!1;let r=0;for(let n=0;n<e.length;n+=4)r+=(ws[e.charCodeAt(n)]|0)+(ws[e.charCodeAt(n+1)]|0)+(ws[e.charCodeAt(n+2)]|0)+(ws[e.charCodeAt(n+3)]|0);return r===t}function bT(e){return x0(e,32)&&e!==S0}function kT(e){return x0(e,16)&&e!==C0}function E0(e){return bT(e.traceId)&&kT(e.spanId)}function TT(e){return new ua(e)}const nc=ko.getInstance();class $0{startSpan(t,r,n=nc.active()){if(!!r?.root)return new ua;const a=n&&I0(n);return CT(a)&&E0(a)?new ua(a):new ua}startActiveSpan(t,r,n,o){let a,i,s;if(arguments.length<2)return;arguments.length===2?s=r:arguments.length===3?(a=r,s=n):(a=r,i=n,s=o);const l=i??nc.active(),c=this.startSpan(t,a,l),u=rc(l,c);return nc.with(u,s,void 0,c)}}function CT(e){return e!==null&&typeof e=="object"&&"spanId"in e&&typeof e.spanId=="string"&&"traceId"in e&&typeof e.traceId=="string"&&"traceFlags"in e&&typeof e.traceFlags=="number"}const ST=new $0;class IT{constructor(t,r,n,o){this._provider=t,this.name=r,this.version=n,this.options=o}startSpan(t,r,n){return this._getTracer().startSpan(t,r,n)}startActiveSpan(t,r,n,o){const a=this._getTracer();return Reflect.apply(a.startActiveSpan,a,arguments)}_getTracer(){if(this._delegate)return this._delegate;const t=this._provider.getDelegateTracer(this.name,this.version,this.options);return t?(this._delegate=t,this._delegate):ST}}class xT{getTracer(t,r,n){return new $0}}const ET=new xT;class R0{getTracer(t,r,n){var o;return(o=this.getDelegateTracer(t,r,n))!==null&&o!==void 0?o:new IT(this,t,r,n)}getDelegate(){var t;return(t=this._delegate)!==null&&t!==void 0?t:ET}setDelegate(t){this._delegate=t}getDelegateTracer(t,r,n){var o;return(o=this._delegate)===null||o===void 0?void 0:o.getTracer(t,r,n)}}var bs;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(bs||(bs={}));const P0=ko.getInstance();yr.instance();class $T{getMeter(t,r,n){return aT}}const RT=new $T,oc="metrics";class ac{constructor(){}static getInstance(){return this._instance||(this._instance=new ac),this._instance}setGlobalMeterProvider(t){return ia(oc,t,yr.instance())}getMeterProvider(){return Hn(oc)||RT}getMeter(t,r,n){return this.getMeterProvider().getMeter(t,r,n)}disable(){la(oc,yr.instance())}}ac.getInstance();class PT{inject(t,r){}extract(t,r){return t}fields(){return[]}}const sc=T0("OpenTelemetry Baggage Key");function M0(e){return e.getValue(sc)||void 0}function MT(){return M0(ko.getInstance().active())}function OT(e,t){return e.setValue(sc,t)}function AT(e){return e.deleteValue(sc)}const ic="propagation",NT=new PT;class lc{constructor(){this.createBaggage=Wk,this.getBaggage=M0,this.getActiveBaggage=MT,this.setBaggage=OT,this.deleteBaggage=AT}static getInstance(){return this._instance||(this._instance=new lc),this._instance}setGlobalPropagator(t){return ia(ic,t,yr.instance())}inject(t,r,n=fT){return this._getGlobalPropagator().inject(t,r,n)}extract(t,r,n=hT){return this._getGlobalPropagator().extract(t,r,n)}fields(){return this._getGlobalPropagator().fields()}disable(){la(ic,yr.instance())}_getGlobalPropagator(){return Hn(ic)||NT}}lc.getInstance();const cc="trace";class uc{constructor(){this._proxyTracerProvider=new R0,this.wrapSpanContext=TT,this.isSpanContextValid=E0,this.deleteSpan=vT,this.getSpan=tc,this.getActiveSpan=yT,this.getSpanContext=I0,this.setSpan=rc,this.setSpanContext=wT}static getInstance(){return this._instance||(this._instance=new uc),this._instance}setGlobalTracerProvider(t){const r=ia(cc,this._proxyTracerProvider,yr.instance());return r&&this._proxyTracerProvider.setDelegate(t),r}getTracerProvider(){return Hn(cc)||this._proxyTracerProvider}getTracer(t,r){return this.getTracerProvider().getTracer(t,r)}disable(){la(cc,yr.instance()),this._proxyTracerProvider=new R0}}const qT=uc.getInstance();var LT=Object.defineProperty,jT=(e,t)=>{for(var r in t)LT(e,r,{get:t[r],enumerable:!0})},O0="AI_InvalidArgumentError",A0=`vercel.ai.error.${O0}`,DT=Symbol.for(A0),N0,Zr=class extends we{constructor({parameter:t,value:r,message:n}){super({name:O0,message:`Invalid argument for parameter ${t}: ${n}`}),this[N0]=!0,this.parameter=t,this.value=r}static isInstance(t){return we.hasMarker(t,A0)}};N0=DT;var q0="AI_InvalidToolApprovalError",L0=`vercel.ai.error.${q0}`,UT=Symbol.for(L0),j0,zT=class extends we{constructor({approvalId:e}){super({name:q0,message:`Tool approval response references unknown approvalId: "${e}". No matching tool-approval-request found in message history.`}),this[j0]=!0,this.approvalId=e}static isInstance(e){return we.hasMarker(e,L0)}};j0=UT;var D0="AI_InvalidToolApprovalSignatureError",U0=`vercel.ai.error.${D0}`,FT=Symbol.for(U0),z0,F0=class extends we{constructor({approvalId:e,toolCallId:t,reason:r}){super({name:D0,message:`Tool approval signature verification failed for approval "${e}" (tool call "${t}"): ${r}`}),this[z0]=!0,this.approvalId=e,this.toolCallId=t}static isInstance(e){return we.hasMarker(e,U0)}};z0=FT;var V0="AI_InvalidToolInputError",Z0=`vercel.ai.error.${V0}`,VT=Symbol.for(Z0),H0,ks=class extends we{constructor({toolInput:e,toolName:t,cause:r,message:n=`Invalid input for tool ${t}: ${co(r)}`}){super({name:V0,message:n,cause:r}),this[H0]=!0,this.toolInput=e,this.toolName=t}static isInstance(e){return we.hasMarker(e,Z0)}};H0=VT;var B0="AI_ToolCallNotFoundForApprovalError",J0=`vercel.ai.error.${B0}`,ZT=Symbol.for(J0),G0,dc=class extends we{constructor({toolCallId:e,approvalId:t}){super({name:B0,message:`Tool call "${e}" not found for approval request "${t}".`}),this[G0]=!0,this.toolCallId=e,this.approvalId=t}static isInstance(e){return we.hasMarker(e,J0)}};G0=ZT;var W0="AI_MissingToolResultsError",K0=`vercel.ai.error.${W0}`,HT=Symbol.for(K0),Y0,Q0=class extends we{constructor({toolCallIds:e}){super({name:W0,message:`Tool result${e.length>1?"s are":" is"} missing for tool call${e.length>1?"s":""} ${e.join(", ")}.`}),this[Y0]=!0,this.toolCallIds=e}static isInstance(e){return we.hasMarker(e,K0)}};Y0=HT;var X0="AI_NoObjectGeneratedError",em=`vercel.ai.error.${X0}`,BT=Symbol.for(em),tm,vn=class extends we{constructor({message:e="No object generated.",cause:t,text:r,response:n,usage:o,finishReason:a}){super({name:X0,message:e,cause:t}),this[tm]=!0,this.text=r,this.response=n,this.usage=o,this.finishReason=a}static isInstance(e){return we.hasMarker(e,em)}};tm=BT;var rm="AI_NoOutputGeneratedError",nm=`vercel.ai.error.${rm}`,JT=Symbol.for(nm),om,Ts=class extends we{constructor({message:e="No output generated.",cause:t}={}){super({name:rm,message:e,cause:t}),this[om]=!0}static isInstance(e){return we.hasMarker(e,nm)}};om=JT;var am="AI_NoSuchToolError",sm=`vercel.ai.error.${am}`,GT=Symbol.for(sm),im,pc=class extends we{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:am,message:r}),this[im]=!0,this.toolName=e,this.availableTools=t}static isInstance(e){return we.hasMarker(e,sm)}};im=GT;var lm="AI_ToolCallRepairError",cm=`vercel.ai.error.${lm}`,WT=Symbol.for(cm),um,KT=class extends we{constructor({cause:e,originalError:t,message:r=`Error repairing tool call: ${co(e)}`}){super({name:lm,message:r,cause:e}),this[um]=!0,this.originalError=t}static isInstance(e){return we.hasMarker(e,cm)}};um=WT;var YT=class extends we{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}},dm="AI_UIMessageStreamError",pm=`vercel.ai.error.${dm}`,QT=Symbol.for(pm),hm,To=class extends we{constructor({chunkType:e,chunkId:t,message:r}){super({name:dm,message:r}),this[hm]=!0,this.chunkType=e,this.chunkId=t}static isInstance(e){return we.hasMarker(e,pm)}};hm=QT;var fm="AI_InvalidMessageRoleError",mm=`vercel.ai.error.${fm}`,XT=Symbol.for(mm),gm,e5=class extends we{constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:fm,message:t}),this[gm]=!0,this.role=e}static isInstance(e){return we.hasMarker(e,mm)}};gm=XT;var _m="AI_RetryError",ym=`vercel.ai.error.${_m}`,t5=Symbol.for(ym),vm,wm=class extends we{constructor({message:e,reason:t,errors:r}){super({name:_m,message:e}),this[vm]=!0,this.reason=t,this.errors=r,this.lastError=r[r.length-1]}static isInstance(e){return we.hasMarker(e,ym)}};vm=t5;function Bn(e){return e===void 0?[]:Array.isArray(e)?e:[e]}async function xr(e){for(const t of Bn(e.callbacks))if(t!=null)try{await t(e.event)}catch{}}function r5({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 n5="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",bm=!1,hc=e=>{if(e.warnings.length===0)return;const t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t=="function"){t(e);return}bm||(bm=!0,console.info(n5));for(const r of e.warnings)console.warn(r5({warning:r,provider:e.provider,model:e.model}))}};function o5({provider:e,modelId:t}){hc({warnings:[{type:"compatibility",feature:"specificationVersion",details:"Using v2 specification compatibility mode. Some features may not be available."}],provider:e,model:t})}function a5(e){return e.specificationVersion==="v3"?e:(o5({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:km(o.finishReason),usage:Tm(o.usage)}};case"doStream":return async(...n)=>{const o=await t.doStream(...n);return{...o,stream:s5(o.stream)}};default:return t[r]}}}))}function s5(e){return e.pipeThrough(new TransformStream({transform(t,r){switch(t.type){case"finish":r.enqueue({...t,finishReason:km(t.finishReason),usage:Tm(t.usage)});break;default:r.enqueue(t);break}}}))}function km(e){return{unified:e==="unknown"?"other":e,raw:void 0}}function Tm(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 Cs(e){if(typeof e!="string"){if(e.specificationVersion!=="v3"&&e.specificationVersion!=="v2"){const t=e;throw new YT({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return a5(e)}return i5().languageModel(e)}function i5(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:zk}function fc(e){if(e!=null)return typeof e=="number"?e:e.totalMs}function Cm(e){if(!(e==null||typeof e=="number"))return e.stepMs}function l5(e){if(!(e==null||typeof e=="number"))return e.chunkMs}var c5=[{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]}],u5=e=>{const t=typeof e=="string"?Un(e):e,r=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(r+10)};function d5(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?u5(e):e}function p5({data:e,signatures:t}){const r=d5(e),n=typeof r=="string"?Un(r.substring(0,Math.min(r.length,24))):r;for(const o of t)if(n.length>=o.bytesPrefix.length&&o.bytesPrefix.every((a,i)=>a===null||n[i]===a))return o.mediaType}var Sm="6.0.216",h5=async({url:e,maxBytes:t,abortSignal:r})=>{var n;const o=e.toString();try{const a=_n({},`ai-sdk/${Sm}`,oa()),i=await cf({url:o,headers:a,abortSignal:r});if(!i.ok)throw await fs(i),new Zt({url:o,statusCode:i.status,statusText:i.statusText});return{data:await ql({response:i,url:o,maxBytes:t??Nl}),mediaType:(n=i.headers.get("content-type"))!=null?n:void 0}}catch(a){throw Zt.isInstance(a)?a:new Zt({url:o,cause:a})}},f5=(e=h5)=>t=>Promise.all(t.map(async r=>r.isUrlSupportedByModel?null:e(r)));function m5(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 Im=ae([d(),is(Uint8Array),is(ArrayBuffer),Rh(e=>{var t,r;return(r=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?r:!1},{message:"Must be a Buffer"})]);function mc(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}=m5(e.toString());if(t==null||r==null)throw new we({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:r,mediaType:t}}return{data:e,mediaType:void 0}}function gc(e){return typeof e=="string"?e:e instanceof ArrayBuffer?gn(new Uint8Array(e)):gn(e)}async function xm({prompt:e,supportedUrls:t,download:r=f5()}){const n=await _5(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 a=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 h=o.get(u.approvalId);h&&a.add(h)}}const i=[...e.system!=null?typeof e.system=="string"?[{role:"system",content:e.system}]:Bn(e.system).map(c=>({role:"system",content:c.content,providerOptions:c.providerOptions})):[],...e.messages.map(c=>g5({message:c,downloadedAssets:n}))],s=[];for(const c of i){if(c.role!=="tool"){s.push(c);continue}const u=s.at(-1);u?.role==="tool"?u.content.push(...c.content):s.push(c)}const l=new Set;for(const c of s)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 a)l.delete(u);if(l.size>0)throw new Q0({toolCallIds:Array.from(l)});break}for(const c of a)l.delete(c);if(l.size>0)throw new Q0({toolCallIds:Array.from(l)});return s.filter(c=>c.role!=="tool"||c.content.length>0)}function g5({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=>y5(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:a,mediaType:i}=mc(n.data);return{type:"file",data:a,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:Em({output:n.output,downloadedAssets:t}),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:Em({output:n.output,downloadedAssets:t}),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 e5({role:n})}}}async function _5(e,t,r){var n;const o=[];for(const s of e){if(s.role==="user"&&Array.isArray(s.content))for(const l of s.content)(l.type==="image"||l.type==="file")&&o.push({data:l.type==="image"?l.image:l.data,mediaType:(n=l.mediaType)!=null?n:l.type==="image"?"image/*":void 0});if(s.role==="tool"||s.role==="assistant"){if(!Array.isArray(s.content))continue;for(const l of s.content)if(l.type==="tool-result"&&l.output.type==="content")for(const c of l.output.value)(c.type==="image-url"||c.type==="file-url")&&o.push({data:new URL(c.url),mediaType:c.type==="image-url"?"image/*":void 0})}}const a=o.map(s=>{const l=s.mediaType,{data:c}=mc(s.data);return{mediaType:l,data:c}}).filter(s=>s.data instanceof URL).map(s=>({url:s.data,isUrlSupportedByModel:s.mediaType!=null&&v4({url:s.data.toString(),mediaType:s.mediaType,supportedUrls:r})})),i=await t(a);return Object.fromEntries(i.map((s,l)=>s==null?null:[a[l].url.toString(),{data:s.data,mediaType:s.mediaType}]).filter(s=>s!=null))}function y5(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:a,mediaType:i}=mc(n);let s=i??e.mediaType,l=a;if(l instanceof URL){const c=t[l.toString()];c&&(l=c.data,s??(s=c.mediaType))}switch(o){case"image":return(l instanceof Uint8Array||typeof l=="string")&&(s=(r=p5({data:l,signatures:c5}))!=null?r:s),{type:"file",mediaType:s??"image/*",filename:void 0,data:l,providerOptions:e.providerOptions};case"file":{if(s==null)throw new Error("Media type is missing for file part");return{type:"file",mediaType:s,filename:e.filename,data:l,providerOptions:e.providerOptions}}}}function Em({output:e,downloadedAssets:t}){return e.type!=="content"?e:{type:"content",value:e.value.map(r=>{var n,o;if(r.type==="image-url"){const a=t[new URL(r.url).toString()];return a?{type:"image-data",data:gc(a.data),mediaType:(n=a.mediaType)!=null?n:"image/*",providerOptions:r.providerOptions}:r}if(r.type==="file-url"){const a=t[new URL(r.url).toString()];return a?{type:"file-data",data:gc(a.data),mediaType:(o=a.mediaType)!=null?o:"application/octet-stream",providerOptions:r.providerOptions}:r}return r.type!=="media"?r:r.mediaType.startsWith("image/")?{type:"image-data",data:r.data,mediaType:r.mediaType}:{type:"file-data",data:r.data,mediaType:r.mediaType}})}}async function da({toolCallId:e,input:t,output:r,tool:n,errorMode:o}){return o==="text"?{type:"error-text",value:co(r)}:o==="json"?{type:"error-json",value:$m(r)}:n?.toModelOutput?await n.toModelOutput({toolCallId:e,input:t,output:r}):typeof r=="string"?{type:"text",value:r}:{type:"json",value:$m(r)}}function $m(e){return e===void 0?null:e}function _c({maxOutputTokens:e,temperature:t,topP:r,topK:n,presencePenalty:o,frequencyPenalty:a,seed:i,stopSequences:s}){if(e!=null){if(!Number.isInteger(e))throw new Zr({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new Zr({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(t!=null&&typeof t!="number")throw new Zr({parameter:"temperature",value:t,message:"temperature must be a number"});if(r!=null&&typeof r!="number")throw new Zr({parameter:"topP",value:r,message:"topP must be a number"});if(n!=null&&typeof n!="number")throw new Zr({parameter:"topK",value:n,message:"topK must be a number"});if(o!=null&&typeof o!="number")throw new Zr({parameter:"presencePenalty",value:o,message:"presencePenalty must be a number"});if(a!=null&&typeof a!="number")throw new Zr({parameter:"frequencyPenalty",value:a,message:"frequencyPenalty must be a number"});if(i!=null&&!Number.isInteger(i))throw new Zr({parameter:"seed",value:i,message:"seed must be an integer"});return{maxOutputTokens:e,temperature:t,topP:r,topK:n,presencePenalty:o,frequencyPenalty:a,stopSequences:s,seed:i}}function v5(e){return e!=null&&Object.keys(e).length>0}async function Rm({tools:e,toolChoice:t,activeTools:r}){if(!v5(e))return{tools:void 0,toolChoice:void 0};const n=r!=null?Object.entries(e).filter(([a])=>r.includes(a)):Object.entries(e),o=[];for(const[a,i]of n){const s=i.type;switch(s){case void 0:case"dynamic":case"function":o.push({type:"function",name:a,description:i.description,inputSchema:await yn(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:a,id:i.id,args:i.args});break;default:{const l=s;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 Jn=ss(()=>ae([Qo(),d(),q(),_e(),pe(d(),Jn.optional()),L(Jn)])),pt=pe(d(),pe(d(),Jn.optional())),Pm=T({type:M("text"),text:d(),providerOptions:pt.optional()}),w5=T({type:M("image"),image:ae([Im,is(URL)]),mediaType:d().optional(),providerOptions:pt.optional()}),Mm=T({type:M("file"),data:ae([Im,is(URL)]),filename:d().optional(),mediaType:d(),providerOptions:pt.optional()}),b5=T({type:M("reasoning"),text:d(),providerOptions:pt.optional()}),k5=T({type:M("tool-call"),toolCallId:d(),toolName:d(),input:Te(),providerOptions:pt.optional(),providerExecuted:_e().optional()}),T5=Le("type",[T({type:M("text"),value:d(),providerOptions:pt.optional()}),T({type:M("json"),value:Jn,providerOptions:pt.optional()}),T({type:M("execution-denied"),reason:d().optional(),providerOptions:pt.optional()}),T({type:M("error-text"),value:d(),providerOptions:pt.optional()}),T({type:M("error-json"),value:Jn,providerOptions:pt.optional()}),T({type:M("content"),value:L(ae([T({type:M("text"),text:d(),providerOptions:pt.optional()}),T({type:M("media"),data:d(),mediaType:d()}),T({type:M("file-data"),data:d(),mediaType:d(),filename:d().optional(),providerOptions:pt.optional()}),T({type:M("file-url"),url:d(),providerOptions:pt.optional()}),T({type:M("file-id"),fileId:ae([d(),pe(d(),d())]),providerOptions:pt.optional()}),T({type:M("image-data"),data:d(),mediaType:d(),providerOptions:pt.optional()}),T({type:M("image-url"),url:d(),providerOptions:pt.optional()}),T({type:M("image-file-id"),fileId:ae([d(),pe(d(),d())]),providerOptions:pt.optional()}),T({type:M("custom"),providerOptions:pt.optional()})]))})]),Om=T({type:M("tool-result"),toolCallId:d(),toolName:d(),output:T5,providerOptions:pt.optional()}),C5=T({type:M("tool-approval-request"),approvalId:d(),toolCallId:d()}),S5=T({type:M("tool-approval-response"),approvalId:d(),approved:_e(),reason:d().optional()}),I5=T({role:M("system"),content:d(),providerOptions:pt.optional()}),x5=T({role:M("user"),content:ae([d(),L(ae([Pm,w5,Mm]))]),providerOptions:pt.optional()}),E5=T({role:M("assistant"),content:ae([d(),L(ae([Pm,Mm,b5,k5,Om,C5]))]),providerOptions:pt.optional()}),$5=T({role:M("tool"),content:L(ae([Om,S5])),providerOptions:pt.optional()}),R5=ae([I5,x5,E5,$5]);async function Am({allowSystemInMessages:e,system:t,prompt:r,messages:n}){if(r==null&&n==null)throw new un({prompt:r,message:"prompt or messages must be defined"});if(r!=null&&n!=null)throw new un({prompt:r,message:"prompt and messages cannot be defined at the same time"});if(typeof t!="string"&&!Bn(t).every(a=>a.role==="system"))throw new un({prompt:r,message:"system must be a string, SystemModelMessage, or array of SystemModelMessage"});if(r!=null&&typeof r=="string")n=[{role:"user",content:r}];else if(r!=null&&Array.isArray(r))n=r;else if(n==null)throw new un({prompt:r,message:"prompt or messages must be defined"});if(n.length===0)throw new un({prompt:r,message:"messages must not be empty"});if(n.some(a=>a.role==="system")){if(e===!1)throw new un({prompt:r,message:"System messages are not allowed in the prompt or messages fields. Use the system option instead."});e===void 0&&console.warn("AI SDK Warning: System messages in the prompt or messages fields can be a security risk because they may enable prompt injection attacks. Use the system option instead when possible. Set allowSystemInMessages to true to suppress this warning, or false to throw an error.")}const o=await ar({value:n,schema:L(R5)});if(!o.success)throw new un({prompt:r,message:"The messages do not match the ModelMessage[] schema.",cause:o.error});return{messages:n,system:t}}function Nm(e){if(!Kl.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 we({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
61
|
|
|
57
62
|
To authenticate, set the \x1B[33mAI_GATEWAY_API_KEY\x1B[0m environment variable with your API key.
|
|
58
63
|
|
|
@@ -60,37 +65,40 @@ Alternatively, you can use a provider module instead of the AI Gateway.
|
|
|
60
65
|
|
|
61
66
|
Learn more: \x1B[34m${r}\x1B[0m
|
|
62
67
|
|
|
63
|
-
`),{name:"GatewayAuthenticationError"})}function
|
|
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=lo(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=io(this.base64Data)),this.uint8ArrayData}},C6=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 S6={};IT(S6,{array:()=>E6,choice:()=>$6,json:()=>R6,object:()=>x6,text:()=>ha});function I6(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 dr({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await dr({text:I6(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(){}}),x6=({schema:e,name:t,description:r})=>{const n=Mn(e);return{name:"object",responseFormat:qt(n.jsonSchema).then(o=>({type:"json",schema:o,...t!=null&&{name:t},...r!=null&&{description:r}})),async parseCompleteOutput({text:o},s){const i=await dr({text:o});if(!i.success)throw new cn({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 ur({value:i.value,schema:n});if(!a.success)throw new cn({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(){}}},E6=({element:e,name:t,description:r})=>{const n=Mn(e);return{name:"array",responseFormat:qt(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 dr({text:o});if(!i.success)throw new cn({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 cn({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 ur({value:l,schema:n});if(!c.success)throw new cn({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 ur({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])}})}}},$6=({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 dr({text:n});if(!s.success)throw new cn({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 cn({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(){}}),R6=({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 dr({text:r});if(!o.success)throw new cn({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)||Hl.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 LT({cause:l,originalError:i})}if(a==null)throw i;return await dm({toolCall:a,tools:t})}}catch(i){const a=await dr({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 dr({text:e.input});if(t.success===!1)throw new Hl({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 ur({value:{},schema:o}):await dr({text:e.input,schema:o});if(s.success===!1)throw new Hl({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 tc(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 rc({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.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 P6=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=tc(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=P6}={},experimental_onStart:R,experimental_onStepStart:S,experimental_onToolCallStart:j,experimental_onToolCallFinish:N,onStepFinish:L,onFinish:z,...B}){const X=ua(e),ee=em(),Q=qn(u),Z=Kl(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=Yl(B),M=ln(c??{},`ai/${j0}`),H=K0({model:X,telemetry:h,headers:M,settings:{...x,maxRetries:U}}),re={provider:X.provider,modelId:X.modelId},te=await W0({system:n,prompt:o,messages:s}),_e=ee(h?.integrations);await br({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 W=Y0(h);try{return await ts({name:"ai.generateText",attributes:fr({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:W,fn:async A=>{var V,J,Y,ue,Te,Be,it,gt,tt,nt,Lt,_t,Rr,Yt,Ge,_r,$,K,qe,Ee;const ot=te.messages,wt=[],{approvedToolApprovals:Zt,deniedToolApprovals:sr}=om({messages:ot}),ar=Zt.filter(ht=>!ht.toolCall.providerExecuted);if(sr.length>0||ar.length>0){const ht=await gm({toolCalls:ar.map(Me=>Me.toolCall),tools:t,tracer:W,telemetry:h,messages:ot,abortSignal:E,experimental_context:b,stepNumber:0,model:re,onToolCallStart:[j,_e.onToolCallStart],onToolCallFinish:[N,_e.onToolCallFinish]}),jt=[];for(const Me of ht){const Qt=await Qo({toolCallId:Me.toolCallId,input:Me.input,tool:t?.[Me.toolName],output:Me.type==="tool-result"?Me.output:Me.error,errorMode:Me.type==="tool-error"?"text":"none"});jt.push({type:"tool-result",toolCallId:Me.toolCallId,toolName:Me.toolName,output:Qt})}for(const Me of sr)jt.push({type:"tool-result",toolCallId:Me.toolCall.toolCallId,toolName:Me.toolCall.toolName,output:{type:"execution-denied",reason:Me.approvalResponse.reason,...Me.toolCall.providerExecuted&&{providerOptions:{openai:{approvalId:Me.approvalResponse.approvalId}}}}});wt.push({role:"tool",content:jt})}const ie=[...Zt,...sr].filter(ht=>ht.toolCall.providerExecuted);ie.length>0&&wt.push({role:"tool",content:ie.map(ht=>({type:"tool-approval-response",approvalId:ht.approvalResponse.approvalId,approved:ht.approvalResponse.approved,reason:ht.approvalResponse.reason,providerExecuted:!0}))});const He=Yl(B);let Le,pt=[],$e=[];const je=[],_n=new Map;do{const ht=ne!=null?setTimeout(()=>D.abort(),ne):void 0;try{const jt=[...ot,...wt],Me=await y?.({model:X,steps:je,stepNumber:je.length,messages:jt,experimental_context:b}),Qt=ua((V=Me?.model)!=null?V:X),yn={provider:Qt.provider,modelId:Qt.modelId},Qr=await z0({prompt:{system:(J=Me?.system)!=null?J:te.system,messages:(Y=Me?.messages)!=null?Y:jt},supportedUrls:await Qt.supportedUrls,download:C});b=(ue=Me?.experimental_context)!=null?ue:b;const Ji=(Te=Me?.activeTools)!=null?Te:_,{toolChoice:Gn,tools:Eo}=await Z0({tools:t,toolChoice:(Be=Me?.toolChoice)!=null?Be:r,activeTools:Ji}),vn=(it=Me?.messages)!=null?it:jt,bt=(gt=Me?.system)!=null?gt:te.system,Pr=pa(g,Me?.providerOptions);await br({event:{stepNumber:je.length,model:yn,system:bt,messages:vn,tools:t,toolChoice:Gn,activeTools:Ji,steps:[...je],providerOptions:Pr,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]}),Le=await F(()=>{var Oe;return ts({name:"ai.generateText.doGenerate",attributes:fr({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(Qr)},"ai.prompt.tools":{input:()=>Eo?.map(Dt=>JSON.stringify(Dt))},"ai.prompt.toolChoice":{input:()=>Gn!=null?JSON.stringify(Gn):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:W,fn:async Dt=>{var Yn,ir,Ps,Gi,Ki,bn,kn,Ro;const Qe=await Qt.doGenerate({...He,tools:Eo,toolChoice:Gn,responseFormat:await p?.responseFormat,prompt:Qr,providerOptions:Pr,abortSignal:E,headers:M}),lr={id:(ir=(Yn=Qe.response)==null?void 0:Yn.id)!=null?ir:I(),timestamp:(Gi=(Ps=Qe.response)==null?void 0:Ps.timestamp)!=null?Gi:new Date,modelId:(bn=(Ki=Qe.response)==null?void 0:Ki.modelId)!=null?bn:Qt.modelId,headers:(kn=Qe.response)==null?void 0:kn.headers,body:(Ro=Qe.response)==null?void 0:Ro.body},Ms=Ql(Qe.usage);return Dt.setAttributes(await fr({telemetry:h,attributes:{"ai.response.finishReason":Qe.finishReason.unified,"ai.response.text":{output:()=>am(Qe.content)},"ai.response.reasoning":{output:()=>sm(Qe.content)},"ai.response.toolCalls":{output:()=>{const Ct=_m(Qe.content);return Ct==null?void 0:JSON.stringify(Ct)}},"ai.response.id":lr.id,"ai.response.model":lr.modelId,"ai.response.timestamp":lr.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(Qe.providerMetadata),"ai.usage.inputTokens":Qe.usage.inputTokens.total,"ai.usage.inputTokenDetails.noCacheTokens":Qe.usage.inputTokens.noCache,"ai.usage.inputTokenDetails.cacheReadTokens":Qe.usage.inputTokens.cacheRead,"ai.usage.inputTokenDetails.cacheWriteTokens":Qe.usage.inputTokens.cacheWrite,"ai.usage.outputTokens":Qe.usage.outputTokens.total,"ai.usage.outputTokenDetails.textTokens":Qe.usage.outputTokens.text,"ai.usage.outputTokenDetails.reasoningTokens":Qe.usage.outputTokens.reasoning,"ai.usage.totalTokens":Ms.totalTokens,"ai.usage.reasoningTokens":Qe.usage.outputTokens.reasoning,"ai.usage.cachedInputTokens":Qe.usage.inputTokens.cacheRead,"gen_ai.response.finish_reasons":[Qe.finishReason.unified],"gen_ai.response.id":lr.id,"gen_ai.response.model":lr.modelId,"gen_ai.usage.input_tokens":Qe.usage.inputTokens.total,"gen_ai.usage.output_tokens":Qe.usage.outputTokens.total}})),{...Qe,response:lr}}})});const wn=await Promise.all(Le.content.filter(Oe=>Oe.type==="tool-call").map(Oe=>cm({toolCall:Oe,tools:t,repairToolCall:m,system:n,messages:jt}))),$o={};for(const Oe of wn){if(Oe.invalid)continue;const Dt=t?.[Oe.toolName];Dt!=null&&(Dt?.onInputAvailable!=null&&await Dt.onInputAvailable({input:Oe.input,toolCallId:Oe.toolCallId,messages:jt,abortSignal:E,experimental_context:b}),await lm({tool:Dt,toolCall:Oe,messages:jt,experimental_context:b})&&($o[Oe.toolCallId]={type:"tool-approval-request",approvalId:I(),toolCall:Oe}))}const Wi=wn.filter(Oe=>Oe.invalid&&Oe.dynamic);$e=[];for(const Oe of Wi)$e.push({type:"tool-error",toolCallId:Oe.toolCallId,toolName:Oe.toolName,input:Oe.input,error:kl(Oe.error),dynamic:!0});pt=wn.filter(Oe=>!Oe.providerExecuted),t!=null&&$e.push(...await gm({toolCalls:pt.filter(Oe=>!Oe.invalid&&$o[Oe.toolCallId]==null),tools:t,tracer:W,telemetry:h,messages:jt,abortSignal:E,experimental_context:b,stepNumber:je.length,model:yn,onToolCallStart:[j,_e.onToolCallStart],onToolCallFinish:[N,_e.onToolCallFinish]}));for(const Oe of wn){if(!Oe.providerExecuted)continue;const Dt=t?.[Oe.toolName];Dt?.type==="provider"&&Dt.supportsDeferredResults&&(Le.content.some(ir=>ir.type==="tool-result"&&ir.toolCallId===Oe.toolCallId)||_n.set(Oe.toolCallId,{toolName:Oe.toolName}))}for(const Oe of Le.content)Oe.type==="tool-result"&&_n.delete(Oe.toolCallId);const Kn=N6({content:Le.content,toolCalls:wn,toolOutputs:$e,toolApprovalRequests:Object.values($o),tools:t});wt.push(...await rc({content:Kn,tools:t}));const $s=(tt=T?.requestBody)==null||tt?(nt=Le.request)!=null?nt:{}:{...Le.request,body:void 0},ld={...Le.response,messages:structuredClone(wt),body:(Lt=T?.responseBody)==null||Lt?(_t=Le.response)==null?void 0:_t.body:void 0},cd=je.length,Rs=new pm({stepNumber:cd,model:yn,functionId:h?.functionId,metadata:h?.metadata,experimental_context:b,content:Kn,finishReason:Le.finishReason.unified,rawFinishReason:Le.finishReason.raw,usage:Ql(Le.usage),warnings:Le.warnings,providerMetadata:Le.providerMetadata,request:$s,response:ld});Gl({warnings:(Rr=Le.warnings)!=null?Rr:[],provider:yn.provider,model:yn.modelId}),je.push(Rs),await br({event:Rs,callbacks:[L,_e.onStepFinish]})}finally{ht!=null&&clearTimeout(ht)}}while((pt.length>0&&$e.length===pt.length||_n.size>0)&&!await fm({stopConditions:Q,steps:je}));A.setAttributes(await fr({telemetry:h,attributes:{"ai.response.finishReason":Le.finishReason.unified,"ai.response.text":{output:()=>am(Le.content)},"ai.response.reasoning":{output:()=>sm(Le.content)},"ai.response.toolCalls":{output:()=>{const ht=_m(Le.content);return ht==null?void 0:JSON.stringify(ht)}},"ai.response.providerMetadata":JSON.stringify(Le.providerMetadata)}}));const Se=je[je.length-1],Ye=je.reduce((ht,jt)=>tm(ht,jt.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0});A.setAttributes(await fr({telemetry:h,attributes:{"ai.usage.inputTokens":Ye.inputTokens,"ai.usage.inputTokenDetails.noCacheTokens":(Yt=Ye.inputTokenDetails)==null?void 0:Yt.noCacheTokens,"ai.usage.inputTokenDetails.cacheReadTokens":(Ge=Ye.inputTokenDetails)==null?void 0:Ge.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":(_r=Ye.inputTokenDetails)==null?void 0:_r.cacheWriteTokens,"ai.usage.outputTokens":Ye.outputTokens,"ai.usage.outputTokenDetails.textTokens":($=Ye.outputTokenDetails)==null?void 0:$.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":(K=Ye.outputTokenDetails)==null?void 0:K.reasoningTokens,"ai.usage.totalTokens":Ye.totalTokens,"ai.usage.reasoningTokens":(qe=Ye.outputTokenDetails)==null?void 0:qe.reasoningTokens,"ai.usage.cachedInputTokens":(Ee=Ye.inputTokenDetails)==null?void 0:Ee.cacheReadTokens}})),await br({event:{stepNumber:Se.stepNumber,model:Se.model,functionId:Se.functionId,metadata:Se.metadata,experimental_context:Se.experimental_context,finishReason:Se.finishReason,rawFinishReason:Se.rawFinishReason,usage:Se.usage,content:Se.content,text:Se.text,reasoningText:Se.reasoningText,reasoning:Se.reasoning,files:Se.files,sources:Se.sources,toolCalls:Se.toolCalls,staticToolCalls:Se.staticToolCalls,dynamicToolCalls:Se.dynamicToolCalls,toolResults:Se.toolResults,staticToolResults:Se.staticToolResults,dynamicToolResults:Se.dynamicToolResults,request:Se.request,response:Se.response,warnings:Se.warnings,providerMetadata:Se.providerMetadata,steps:je,totalUsage:Ye},callbacks:[z,_e.onFinish]});let ft;return Se.finishReason==="stop"&&(ft=await(p??ha()).parseCompleteOutput({text:Se.text},{response:Se.response,usage:Se.usage,finishReason:Se.finishReason})),new M6({steps:je,totalUsage:Ye,output:ft})}})}catch(A){throw G0(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=>ec({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 M6=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 N6({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 Jl({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 O6({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 A6({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)}
|
|
68
|
+
`),{name:"GatewayAuthenticationError"})}function pa({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 qm({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((a,[i,s])=>{if(i==="timeout"){const l=fc(s);l!=null&&(a[`ai.settings.${i}`]=l)}else a[`ai.settings.${i}`]=s;return a},{}),...Object.entries((o=r?.metadata)!=null?o:{}).reduce((a,[i,s])=>(a[`ai.telemetry.metadata.${i}`]=s,a),{}),...Object.entries(n??{}).reduce((a,[i,s])=>(s!==void 0&&(a[`ai.request.headers.${i}`]=s),a),{})}}var P5={startSpan(){return Ss},startActiveSpan(e,t,r,n){if(typeof t=="function")return t(Ss);if(typeof r=="function")return r(Ss);if(typeof n=="function")return n(Ss)}},Ss={spanContext(){return M5},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}},M5={traceId:"",spanId:"",traceFlags:0};function Lm({isEnabled:e=!1,tracer:t}={}){return e?t||qT.getTracer("ai"):P5}async function ha({name:e,tracer:t,attributes:r,fn:n,endWhenDone:o=!0}){return t.startActiveSpan(e,{attributes:await r},async a=>{const i=P0.active();try{const s=await P0.with(i,()=>n(a));return o&&a.end(),s}catch(s){try{jm(a,s)}finally{a.end()}throw s}})}function jm(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:bs.ERROR,message:t.message})):e.setStatus({code:bs.ERROR})}function O5(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function yc(e){if(!Array.isArray(e))return e;const t=new Set(e.filter(O5).map(n=>typeof n));if(t.size!==1)return;const[r]=t;return r==="string"?e.filter(n=>typeof n=="string"):r==="number"?e.filter(n=>typeof n=="number"):e.filter(n=>typeof n=="boolean")}async function vr({telemetry:e,attributes:t}){if(e?.isEnabled!==!0)return{};const r={};for(const[n,o]of Object.entries(t)){if(o==null)continue;if(typeof o=="object"&&"input"in o&&typeof o.input=="function"){if(e?.recordInputs===!1)continue;const i=await o.input();if(i!=null){const s=yc(i);s!=null&&(r[n]=s)}continue}if(typeof o=="object"&&"output"in o&&typeof o.output=="function"){if(e?.recordOutputs===!1)continue;const i=await o.output();if(i!=null){const s=yc(i);s!=null&&(r[n]=s)}continue}const a=yc(o);a!=null&&(r[n]=a)}return r}function Dm(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?gc(r.data):r.data}:r)})))}function A5(){var e;return(e=globalThis.AI_SDK_TELEMETRY_INTEGRATIONS)!=null?e:[]}function Um(){const e=A5();return t=>{const r=Bn(t),n=[...e,...r];function o(a){const i=n.map(a).filter(Boolean);return async s=>{for(const l of i)try{await l(s)}catch{}}}return{onStart:o(a=>a.onStart),onStepStart:o(a=>a.onStepStart),onToolCallStart:o(a=>a.onToolCallStart),onToolCallFinish:o(a=>a.onToolCallFinish),onStepFinish:o(a=>a.onStepFinish),onFinish:o(a=>a.onFinish)}}}function vc(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:Er(e.inputTokens.total,e.outputTokens.total),raw:e.raw,reasoningTokens:e.outputTokens.reasoning,cachedInputTokens:e.inputTokens.cacheRead}}function wc(){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 zm(e,t){var r,n,o,a,i,s,l,c,u,h;return{inputTokens:Er(e.inputTokens,t.inputTokens),inputTokenDetails:{noCacheTokens:Er((r=e.inputTokenDetails)==null?void 0:r.noCacheTokens,(n=t.inputTokenDetails)==null?void 0:n.noCacheTokens),cacheReadTokens:Er((o=e.inputTokenDetails)==null?void 0:o.cacheReadTokens,(a=t.inputTokenDetails)==null?void 0:a.cacheReadTokens),cacheWriteTokens:Er((i=e.inputTokenDetails)==null?void 0:i.cacheWriteTokens,(s=t.inputTokenDetails)==null?void 0:s.cacheWriteTokens)},outputTokens:Er(e.outputTokens,t.outputTokens),outputTokenDetails:{textTokens:Er((l=e.outputTokenDetails)==null?void 0:l.textTokens,(c=t.outputTokenDetails)==null?void 0:c.textTokens),reasoningTokens:Er((u=e.outputTokenDetails)==null?void 0:u.reasoningTokens,(h=t.outputTokenDetails)==null?void 0:h.reasoningTokens)},totalTokens:Er(e.totalTokens,t.totalTokens),reasoningTokens:Er(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:Er(e.cachedInputTokens,t.cachedInputTokens)}}function Er(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}function Is(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(!(n==="__proto__"||n==="constructor"||n==="prototype")&&Object.prototype.hasOwnProperty.call(t,n)){const o=t[n];if(o===void 0)continue;const a=n in e?e[n]:void 0,i=o!==null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp),s=a!=null&&typeof a=="object"&&!Array.isArray(a)&&!(a instanceof Date)&&!(a instanceof RegExp);i&&s?r[n]=Is(a,o):r[n]=o}return r}function N5({error:e,exponentialBackoffDelay:t}){const r=tt.isInstance(e)?e.responseHeaders:tt.isInstance(e.cause)?e.cause.responseHeaders:void 0;if(!r)return t;let n;const o=r["retry-after-ms"];if(o){const i=parseFloat(o);Number.isNaN(i)||(n=i)}const a=r["retry-after"];if(a&&n===void 0){const i=parseFloat(a);Number.isNaN(i)?n=Date.parse(a)-Date.now():n=i*1e3}return n!=null&&!Number.isNaN(n)&&0<=n&&(n<60*1e3||n<t)?n:t}var q5=({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:r=2,abortSignal:n}={})=>async o=>Fm(o,{maxRetries:e,delayInMs:t,backoffFactor:r,abortSignal:n});async function Fm(e,{maxRetries:t,delayInMs:r,backoffFactor:n,abortSignal:o},a=[]){try{return await e()}catch(i){if(zn(i)||t===0)throw i;const s=Ll(i),l=[...a,i],c=l.length;if(c>t)throw new wm({message:`Failed after ${c} attempts. Last error: ${s}`,reason:"maxRetriesExceeded",errors:l});if(i instanceof Error&&(tt.isInstance(i)&&i.isRetryable===!0||kt.isInstance(i)&&i.isRetryable===!0)&&c<=t)return await o4(N5({error:i,exponentialBackoffDelay:r}),{abortSignal:o}),Fm(e,{maxRetries:t,delayInMs:n*r,backoffFactor:n,abortSignal:o},l);throw c===1?i:new wm({message:`Failed after ${c} attempts with non-retryable error: '${s}'`,reason:"errorNotRetryable",errors:l})}}function Vm({maxRetries:e,abortSignal:t}){if(e!=null){if(!Number.isInteger(e))throw new Zr({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});if(e<0)throw new Zr({parameter:"maxRetries",value:e,message:"maxRetries must be >= 0"})}const r=e??2;return{maxRetries:r,retry:q5({maxRetries:r,abortSignal:t})}}function Zm({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 a=[],i=[],s=t.content.filter(l=>l.type==="tool-approval-response");for(const l of s){const c=n[l.approvalId];if(c==null)throw new zT({approvalId:l.approvalId});if(o[c.toolCallId]!=null)continue;const u=r[c.toolCallId];if(u==null)throw new dc({toolCallId:c.toolCallId,approvalId:c.approvalId});const h={approvalRequest:c,approvalResponse:l,toolCall:u};l.approved?a.push(h):i.push(h)}return{approvedToolApprovals:a,deniedToolApprovals:i}}function xs(){var e,t;return(t=(e=globalThis?.performance)==null?void 0:e.now())!=null?t:Date.now()}async function bc({toolCall:e,tools:t,tracer:r,telemetry:n,messages:o,abortSignal:a,experimental_context:i,stepNumber:s,model:l,onPreliminaryToolResult:c,onToolCallStart:u,onToolCallFinish:h}){const{toolName:p,toolCallId:m,input:f}=e,b=t?.[p];if(b?.execute==null)return;const w={stepNumber:s,model:l,toolCall:e,messages:o,abortSignal:a,functionId:n?.functionId,metadata:n?.metadata,experimental_context:i};return ha({name:"ai.toolCall",attributes:vr({telemetry:n,attributes:{...pa({operationId:"ai.toolCall",telemetry:n}),"ai.toolCall.name":p,"ai.toolCall.id":m,"ai.toolCall.args":{output:()=>JSON.stringify(f)}}}),tracer:r,fn:async C=>{let v;await xr({event:w,callbacks:u});const g=xs();try{const y=b6({execute:b.execute.bind(b),input:f,options:{toolCallId:m,messages:o,abortSignal:a,experimental_context:i}});for await(const _ of y)_.type==="preliminary"?c?.({...e,type:"tool-result",output:_.output,preliminary:!0}):v=_.output}catch(y){const _=xs()-g;return await xr({event:{...w,success:!1,error:y,durationMs:_},callbacks:h}),jm(C,y),{type:"tool-error",toolCallId:m,toolName:p,input:f,error:y,dynamic:b.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{},...e.toolMetadata!=null?{toolMetadata:e.toolMetadata}:{}}}const I=xs()-g;await xr({event:{...w,success:!0,output:v,durationMs:I},callbacks:h});try{C.setAttributes(await vr({telemetry:n,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(v)}}}))}catch{}return{type:"tool-result",toolCallId:m,toolName:p,input:f,output:v,dynamic:b.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{},...e.toolMetadata!=null?{toolMetadata:e.toolMetadata}:{}}}})}function Hm(e){const t=e.filter(r=>r.type==="reasoning");return t.length===0?void 0:t.map(r=>r.text).join(`
|
|
69
|
+
`)}function Bm(e){const t=e.filter(r=>r.type==="text");if(t.length!==0)return t.map(r=>r.text).join("")}var Jm=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=gn(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=Un(this.base64Data)),this.uint8ArrayData}},L5=class extends Jm{constructor(e){super(e),this.type="file"}};async function kc({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 Tc=new TextEncoder;function Cc(e){return e==null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(Cc).join(",")}]`:`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${Cc(e[n])}`).join(",")}}`}function Gm(e){return gn(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function j5(e){return Un(e)}async function Wm(e){const t=typeof e=="string"?Tc.encode(e):e;return crypto.subtle.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign","verify"])}async function Km(e){const t=Cc(e),r=await crypto.subtle.digest("SHA-256",Tc.encode(t));return Gm(new Uint8Array(r))}function Ym(e,t,r,n){return Tc.encode(`${e}
|
|
70
|
+
${t}
|
|
71
|
+
${r}
|
|
72
|
+
${n}`)}async function D5({secret:e,approvalId:t,toolCallId:r,toolName:n,input:o}){const a=await Wm(e),i=await Km(o),s=Ym(t,r,n,i),l=await crypto.subtle.sign("HMAC",a,s);return Gm(new Uint8Array(l))}async function U5({secret:e,signature:t,approvalId:r,toolCallId:n,toolName:o,input:a}){const i=await Wm(e),s=await Km(a),l=Ym(r,n,o,s),c=j5(t);return crypto.subtle.verify("HMAC",i,c,l)}async function Qm({secret:e,approvalId:t,toolCallId:r,toolName:n,input:o}){if(e!=null)return D5({secret:e,approvalId:t,toolCallId:r,toolName:n,input:o})}async function Xm({approvedToolApprovals:e,tools:t,messages:r,experimental_context:n,toolApprovalSecret:o}){var a;const i=[],s=[];for(const l of e){const{toolCall:c,approvalRequest:u}=l,h=t?.[c.toolName];if(o!=null){if(u.signature==null)throw new F0({approvalId:u.approvalId,toolCallId:c.toolCallId,reason:"missing signature"});if(!await U5({secret:o,signature:u.signature,approvalId:u.approvalId,toolCallId:c.toolCallId,toolName:c.toolName,input:c.input}))throw new F0({approvalId:u.approvalId,toolCallId:c.toolCallId,reason:"invalid signature"})}if(h!=null&&typeof h.execute=="function"&&h.inputSchema!=null){const m=await ar({value:c.input,schema:yn(h.inputSchema)});if(!m.success)throw new ks({toolName:c.toolName,toolInput:JSON.stringify(c.input),cause:m.error})}h!=null&&await kc({tool:h,toolCall:c,messages:r,experimental_context:n})?i.push(l):s.push({...l,approvalResponse:{...l.approvalResponse,approved:!1,reason:(a=l.approvalResponse.reason)!=null?a:`Tool "${c.toolName}" does not require approval`}})}return{approvedToolApprovals:i,deniedToolApprovals:s}}var z5={};jT(z5,{array:()=>Z5,choice:()=>H5,json:()=>B5,object:()=>V5,text:()=>Es});function F5(e){const t=["ROOT"];let r=-1,n=null,o=0;function a(u){return u>="0"&&u<="9"||u>="A"&&u<="F"||u>="a"&&u<="f"}function i(u,h,p){switch(u){case'"':{r=h,t.pop(),t.push(p),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{r=h,n=h,t.pop(),t.push(p),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(p),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=h,t.pop(),t.push(p),t.push("INSIDE_NUMBER");break}case"{":{r=h,t.pop(),t.push(p),t.push("INSIDE_OBJECT_START");break}case"[":{r=h,t.pop(),t.push(p),t.push("INSIDE_ARRAY_START");break}}}function s(u,h){switch(u){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{r=h,t.pop();break}}}function l(u,h){switch(u){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=h,t.pop();break}}}for(let u=0;u<e.length;u++){const h=e[u];switch(t[t.length-1]){case"ROOT":i(h,u,"FINISH");break;case"INSIDE_OBJECT_START":{switch(h){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{r=u,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(h){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(h){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(h){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{i(h,u,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{s(h,u);break}case"INSIDE_STRING":{switch(h){case'"':{t.pop(),r=u;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:r=u}break}case"INSIDE_ARRAY_START":{switch(h){case"]":{r=u,t.pop();break}default:{r=u,i(h,u,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(h){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=u,t.pop();break}default:{r=u;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{i(h,u,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),h==="u"?(o=0,t.push("INSIDE_STRING_UNICODE_ESCAPE")):r=u;break}case"INSIDE_STRING_UNICODE_ESCAPE":{a(h)&&(o++,o===4&&(t.pop(),r=u));break}case"INSIDE_NUMBER":{switch(h){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=u;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&l(h,u),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(h,u);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(h,u);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&l(h,u);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const m=e.substring(n,u+1);!"false".startsWith(m)&&!"true".startsWith(m)&&!"null".startsWith(m)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?s(h,u):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&l(h,u)):r=u;break}}}let c=e.slice(0,r+1);for(let u=t.length-1;u>=0;u--)switch(t[u]){case"INSIDE_STRING":{c+='"';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":{c+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{c+="]";break}case"INSIDE_LITERAL":{const p=e.substring(n,e.length);"true".startsWith(p)?c+="true".slice(p.length):"false".startsWith(p)?c+="false".slice(p.length):"null".startsWith(p)&&(c+="null".slice(p.length))}}return c}async function fa(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await gr({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await gr({text:F5(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}var Es=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:e}){return e},async parsePartialOutput({text:e}){return{partial:e}},createElementStreamTransform(){}}),V5=({schema:e,name:t,description:r})=>{const n=yn(e);return{name:"object",responseFormat:yt(n.jsonSchema).then(o=>({type:"json",schema:o,...t!=null&&{name:t},...r!=null&&{description:r}})),async parseCompleteOutput({text:o},a){const i=await gr({text:o});if(!i.success)throw new vn({message:"No object generated: could not parse the response.",cause:i.error,text:o,response:a.response,usage:a.usage,finishReason:a.finishReason});const s=await ar({value:i.value,schema:n});if(!s.success)throw new vn({message:"No object generated: response did not match schema.",cause:s.error,text:o,response:a.response,usage:a.usage,finishReason:a.finishReason});return s.value},async parsePartialOutput({text:o}){const a=await fa(o);switch(a.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:a.value}}},createElementStreamTransform(){}}},Z5=({element:e,name:t,description:r})=>{const n=yn(e);return{name:"array",responseFormat:yt(n.jsonSchema).then(o=>{const{$schema:a,...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},a){const i=await gr({text:o});if(!i.success)throw new vn({message:"No object generated: could not parse the response.",cause:i.error,text:o,response:a.response,usage:a.usage,finishReason:a.finishReason});const s=i.value;if(s==null||typeof s!="object"||!("elements"in s)||!Array.isArray(s.elements))throw new vn({message:"No object generated: response did not match schema.",cause:new An({value:s,cause:"response must be an object with an elements array"}),text:o,response:a.response,usage:a.usage,finishReason:a.finishReason});for(const l of s.elements){const c=await ar({value:l,schema:n});if(!c.success)throw new vn({message:"No object generated: response did not match schema.",cause:c.error,text:o,response:a.response,usage:a.usage,finishReason:a.finishReason})}return s.elements},async parsePartialOutput({text:o}){const a=await fa(o);switch(a.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{const i=a.value;if(i==null||typeof i!="object"||!("elements"in i)||!Array.isArray(i.elements))return;const s=a.state==="repaired-parse"&&i.elements.length>0?i.elements.slice(0,-1):i.elements,l=[];for(const c of s){const u=await ar({value:c,schema:n});u.success&&l.push(u.value)}return{partial:l}}}},createElementStreamTransform(){let o=0;return new TransformStream({transform({partialOutput:a},i){if(a!=null)for(;o<a.length;o++)i.enqueue(a[o])}})}}},H5=({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 a=await gr({text:n});if(!a.success)throw new vn({message:"No object generated: could not parse the response.",cause:a.error,text:n,response:o.response,usage:o.usage,finishReason:o.finishReason});const i=a.value;if(i==null||typeof i!="object"||!("result"in i)||typeof i.result!="string"||!e.includes(i.result))throw new vn({message:"No object generated: response did not match schema.",cause:new An({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 fa(n);switch(o.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{const a=o.value;if(a==null||typeof a!="object"||!("result"in a)||typeof a.result!="string")return;const i=e.filter(s=>s.startsWith(a.result));return o.state==="successful-parse"?i.includes(a.result)?{partial:a.result}:void 0:i.length===1?{partial:i[0]}:void 0}}},createElementStreamTransform(){}}),B5=({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 gr({text:r});if(!o.success)throw new vn({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 fa(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 e2({toolCall:e,tools:t,repairToolCall:r,system:n,messages:o}){try{if(t==null){if(e.providerExecuted&&e.dynamic)return await t2(e);throw new pc({toolName:e.toolName})}try{return await r2({toolCall:e,tools:t})}catch(a){if(r==null||!(pc.isInstance(a)||ks.isInstance(a)))throw a;let i=null;try{i=await r({toolCall:e,tools:t,inputSchema:async({toolName:s})=>{const{inputSchema:l}=t[s];return await yn(l).jsonSchema},system:n,messages:o,error:a})}catch(s){throw new KT({cause:s,originalError:a})}if(i==null)throw a;return await r2({toolCall:i,tools:t})}}catch(a){const i=await gr({text:e.input}),s=i.success?i.value:e.input,l=t?.[e.toolName];return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:s,dynamic:!0,invalid:!0,error:a,title:l?.title,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,...l?.metadata!=null?{toolMetadata:l.metadata}:{}}}}async function t2(e){const t=e.input.trim()===""?{success:!0,value:{}}:await gr({text:e.input});if(t.success===!1)throw new ks({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 r2({toolCall:e,tools:t}){const r=e.toolName,n=t[r];if(n==null){if(e.providerExecuted&&e.dynamic)return await t2(e);throw new pc({toolName:e.toolName,availableTools:Object.keys(t)})}const o=yn(n.inputSchema),a=e.input.trim()===""?await ar({value:{},schema:o}):await gr({text:e.input,schema:o});if(a.success===!1)throw new ks({toolName:r,toolInput:e.input,cause:a.error});return n.type==="dynamic"?{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:a.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,...n.metadata!=null?{toolMetadata:n.metadata}:{},dynamic:!0,title:n.title}:{type:"tool-call",toolCallId:e.toolCallId,toolName:r,input:a.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,...n.metadata!=null?{toolMetadata:n.metadata}:{},title:n.title}}var n2=class{constructor({stepNumber:e,model:t,functionId:r,metadata:n,experimental_context:o,content:a,finishReason:i,rawFinishReason:s,usage:l,warnings:c,request:u,response:h,providerMetadata:p}){this.stepNumber=e,this.model=t,this.functionId=r,this.metadata=n,this.experimental_context=o,this.content=a,this.finishReason=i,this.rawFinishReason=s,this.usage=l,this.warnings=c,this.request=u,this.response=h,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 Sc(e){return({steps:t})=>t.length===e}async function o2({stopConditions:e,steps:t}){return(await Promise.all(e.map(r=>r({steps:t})))).some(r=>r)}async function Ic({content:e,tools:t}){const r=[],n=[];for(const a of e)if(a.type!=="source"&&!((a.type==="tool-result"||a.type==="tool-error")&&!a.providerExecuted)&&!(a.type==="text"&&a.text.length===0))switch(a.type){case"text":n.push({type:"text",text:a.text,providerOptions:a.providerMetadata});break;case"reasoning":n.push({type:"reasoning",text:a.text,providerOptions:a.providerMetadata});break;case"file":n.push({type:"file",data:a.file.base64,mediaType:a.file.mediaType,providerOptions:a.providerMetadata});break;case"tool-call":n.push({type:"tool-call",toolCallId:a.toolCallId,toolName:a.toolName,input:a.invalid&&typeof a.input!="object"?{}:a.input,providerExecuted:a.providerExecuted,providerOptions:a.providerMetadata});break;case"tool-result":{const i=await da({toolCallId:a.toolCallId,input:a.input,tool:t?.[a.toolName],output:a.output,errorMode:"none"});n.push({type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,output:i,providerOptions:a.providerMetadata});break}case"tool-error":{const i=await da({toolCallId:a.toolCallId,input:a.input,tool:t?.[a.toolName],output:a.error,errorMode:"json"});n.push({type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,output:i,providerOptions:a.providerMetadata});break}case"tool-approval-request":n.push({type:"tool-approval-request",approvalId:a.approvalId,toolCallId:a.toolCall.toolCallId,...a.signature!=null?{signature:a.signature}:{}});break}n.length>0&&r.push({role:"assistant",content:n});const o=[];for(const a of e){if(!(a.type==="tool-result"||a.type==="tool-error")||a.providerExecuted)continue;const i=await da({toolCallId:a.toolCallId,input:a.input,tool:t?.[a.toolName],output:a.type==="tool-result"?a.output:a.error,errorMode:a.type==="tool-error"?"text":"none"});o.push({type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,output:i,...a.providerMetadata!=null?{providerOptions:a.providerMetadata}:{}})}return o.length>0&&r.push({role:"tool",content:o}),r}function a2(...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 J5=na({prefix:"aitxt",size:24});async function s2({model:e,tools:t,toolChoice:r,system:n,prompt:o,messages:a,allowSystemInMessages:i,maxRetries:s,abortSignal:l,timeout:c,headers:u,stopWhen:h=Sc(1),experimental_output:p,output:m=p,experimental_telemetry:f,providerOptions:b,experimental_activeTools:w,activeTools:C=w,experimental_prepareStep:v,prepareStep:g=v,experimental_repairToolCall:I,experimental_download:y,experimental_context:_,experimental_toolApprovalSecret:k,experimental_include:S,_internal:{generateId:E=J5}={},experimental_onStart:R,experimental_onStepStart:x,experimental_onToolCallStart:N,experimental_onToolCallFinish:U,onStepFinish:z,onFinish:ee,...Q}){const se=Cs(e),re=Um(),Se=Bn(h),H=fc(c),D=Cm(c),B=D!=null?new AbortController:void 0,F=a2(l,H!=null?AbortSignal.timeout(H):void 0,B?.signal),{maxRetries:$,retry:O}=Vm({maxRetries:s,abortSignal:F}),j=_c(Q),G=_n(u??{},`ai/${Sm}`),Y=qm({model:se,telemetry:f,headers:G,settings:{...j,maxRetries:$}}),W={provider:se.provider,modelId:se.modelId},V=await Am({system:n,prompt:o,messages:a,allowSystemInMessages:i}),A=re(f?.integrations);await xr({event:{model:W,system:n,prompt:o,messages:a,tools:t,toolChoice:r,activeTools:C,maxOutputTokens:j.maxOutputTokens,temperature:j.temperature,topP:j.topP,topK:j.topK,presencePenalty:j.presencePenalty,frequencyPenalty:j.frequencyPenalty,stopSequences:j.stopSequences,seed:j.seed,maxRetries:$,timeout:c,headers:u,providerOptions:b,stopWhen:h,output:m,abortSignal:l,include:S,functionId:f?.functionId,metadata:f?.metadata,experimental_context:_},callbacks:[R,A.onStart]});const Z=Lm(f);try{return await ha({name:"ai.generateText",attributes:vr({telemetry:f,attributes:{...pa({operationId:"ai.generateText",telemetry:f}),...Y,"ai.model.provider":se.provider,"ai.model.id":se.modelId,"ai.prompt":{input:()=>JSON.stringify({system:n,prompt:o,messages:a})}}}),tracer:Z,fn:async J=>{var te,de,fe,Ye,wt,st,et,Be,tr,it,qr,dr,rr,Lr,pr,P,X,Ie,We,ln;const nt=V.messages,ht=[],{approvedToolApprovals:Ut,deniedToolApprovals:hr}=Zm({messages:nt}),{approvedToolApprovals:jr,deniedToolApprovals:Dr}=await Xm({approvedToolApprovals:Ut.filter(zt=>!zt.toolCall.providerExecuted),tools:t,messages:nt,experimental_context:_,toolApprovalSecret:k}),ie=[...hr,...Dr];if(ie.length>0||jr.length>0){const zt=await i2({toolCalls:jr.map(Ne=>Ne.toolCall),tools:t,tracer:Z,telemetry:f,messages:nt,abortSignal:F,experimental_context:_,stepNumber:0,model:W,onToolCallStart:[N,A.onToolCallStart],onToolCallFinish:[U,A.onToolCallFinish]}),Bt=[];for(const Ne of zt){const nr=await da({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"});Bt.push({type:"tool-result",toolCallId:Ne.toolCallId,toolName:Ne.toolName,output:nr})}for(const Ne of ie)Bt.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}}}}});ht.push({role:"tool",content:Bt})}const Ve=_c(Q);let De,ft=[],Me=[];const Ue=[],xn=new Map;do{const zt=D!=null?setTimeout(()=>B.abort(),D):void 0;try{const Bt=[...nt,...ht],Ne=await g?.({model:se,steps:Ue,stepNumber:Ue.length,messages:Bt,experimental_context:_}),nr=Cs((te=Ne?.model)!=null?te:se),En={provider:nr.provider,modelId:nr.modelId},cn=await xm({prompt:{system:(de=Ne?.system)!=null?de:V.system,messages:(fe=Ne?.messages)!=null?fe:Bt},supportedUrls:await nr.supportedUrls,download:y});_=(Ye=Ne?.experimental_context)!=null?Ye:_;const al=(wt=Ne?.activeTools)!=null?wt:C,{toolChoice:$n,tools:so}=await Rm({tools:t,toolChoice:(st=Ne?.toolChoice)!=null?st:r,activeTools:al}),Rn=(et=Ne?.messages)!=null?et:Bt,Tt=(Be=Ne?.system)!=null?Be:V.system,Ur=Is(b,Ne?.providerOptions);await xr({event:{stepNumber:Ue.length,model:En,system:Tt,messages:Rn,tools:t,toolChoice:$n,activeTools:al,steps:[...Ue],providerOptions:Ur,timeout:c,headers:u,stopWhen:h,output:m,abortSignal:l,include:S,functionId:f?.functionId,metadata:f?.metadata,experimental_context:_},callbacks:[x,A.onStepStart]}),De=await O(()=>{var Re;return ha({name:"ai.generateText.doGenerate",attributes:vr({telemetry:f,attributes:{...pa({operationId:"ai.generateText.doGenerate",telemetry:f}),...Y,"ai.model.provider":nr.provider,"ai.model.id":nr.modelId,"ai.prompt.messages":{input:()=>Dm(cn)},"ai.prompt.tools":{input:()=>so?.map(Jt=>JSON.stringify(Jt))},"ai.prompt.toolChoice":{input:()=>$n!=null?JSON.stringify($n):void 0},"gen_ai.system":nr.provider,"gen_ai.request.model":nr.modelId,"gen_ai.request.frequency_penalty":Q.frequencyPenalty,"gen_ai.request.max_tokens":Q.maxOutputTokens,"gen_ai.request.presence_penalty":Q.presencePenalty,"gen_ai.request.stop_sequences":Q.stopSequences,"gen_ai.request.temperature":(Re=Q.temperature)!=null?Re:void 0,"gen_ai.request.top_k":Q.topK,"gen_ai.request.top_p":Q.topP}}),tracer:Z,fn:async Jt=>{var Gr,Ft,Fa,il,ll,Mn,On,zo;const Qe=await nr.doGenerate({...Ve,tools:so,toolChoice:$n,responseFormat:await m?.responseFormat,prompt:cn,providerOptions:Ur,abortSignal:F,headers:G}),fr={id:(Ft=(Gr=Qe.response)==null?void 0:Gr.id)!=null?Ft:E(),timestamp:(il=(Fa=Qe.response)==null?void 0:Fa.timestamp)!=null?il:new Date,modelId:(Mn=(ll=Qe.response)==null?void 0:ll.modelId)!=null?Mn:nr.modelId,headers:(On=Qe.response)==null?void 0:On.headers,body:(zo=Qe.response)==null?void 0:zo.body},Va=vc(Qe.usage);return Jt.setAttributes(await vr({telemetry:f,attributes:{"ai.response.finishReason":Qe.finishReason.unified,"ai.response.text":{output:()=>Bm(Qe.content)},"ai.response.reasoning":{output:()=>Hm(Qe.content)},"ai.response.toolCalls":{output:()=>{const Fo=l2(Qe.content);return Fo==null?void 0:JSON.stringify(Fo)}},"ai.response.id":fr.id,"ai.response.model":fr.modelId,"ai.response.timestamp":fr.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(Qe.providerMetadata),"ai.usage.inputTokens":Qe.usage.inputTokens.total,"ai.usage.inputTokenDetails.noCacheTokens":Qe.usage.inputTokens.noCache,"ai.usage.inputTokenDetails.cacheReadTokens":Qe.usage.inputTokens.cacheRead,"ai.usage.inputTokenDetails.cacheWriteTokens":Qe.usage.inputTokens.cacheWrite,"ai.usage.outputTokens":Qe.usage.outputTokens.total,"ai.usage.outputTokenDetails.textTokens":Qe.usage.outputTokens.text,"ai.usage.outputTokenDetails.reasoningTokens":Qe.usage.outputTokens.reasoning,"ai.usage.totalTokens":Va.totalTokens,"ai.usage.reasoningTokens":Qe.usage.outputTokens.reasoning,"ai.usage.cachedInputTokens":Qe.usage.inputTokens.cacheRead,"gen_ai.response.finish_reasons":[Qe.finishReason.unified],"gen_ai.response.id":fr.id,"gen_ai.response.model":fr.modelId,"gen_ai.usage.input_tokens":Qe.usage.inputTokens.total,"gen_ai.usage.output_tokens":Qe.usage.outputTokens.total}})),{...Qe,response:fr}}})});const Pn=await Promise.all(De.content.filter(Re=>Re.type==="tool-call").map(Re=>e2({toolCall:Re,tools:t,repairToolCall:I,system:n,messages:Bt}))),Uo={};for(const Re of Pn){if(Re.invalid)continue;const Jt=t?.[Re.toolName];if(Jt!=null&&(Jt?.onInputAvailable!=null&&await Jt.onInputAvailable({input:Re.input,toolCallId:Re.toolCallId,messages:Bt,abortSignal:F,experimental_context:_}),await kc({tool:Jt,toolCall:Re,messages:Bt,experimental_context:_}))){const Gr=E(),Ft=await Qm({secret:k,approvalId:Gr,toolCallId:Re.toolCallId,toolName:Re.toolName,input:Re.input});Uo[Re.toolCallId]={type:"tool-approval-request",approvalId:Gr,toolCall:Re,...Ft!=null?{signature:Ft}:{}}}}const sl=Pn.filter(Re=>Re.invalid&&Re.dynamic);Me=[];for(const Re of sl)Me.push({type:"tool-error",toolCallId:Re.toolCallId,toolName:Re.toolName,input:Re.input,error:Ll(Re.error),dynamic:!0});ft=Pn.filter(Re=>!Re.providerExecuted),t!=null&&Me.push(...await i2({toolCalls:ft.filter(Re=>!Re.invalid&&Uo[Re.toolCallId]==null),tools:t,tracer:Z,telemetry:f,messages:Bt,abortSignal:F,experimental_context:_,stepNumber:Ue.length,model:En,onToolCallStart:[N,A.onToolCallStart],onToolCallFinish:[U,A.onToolCallFinish]}));for(const Re of Pn){if(!Re.providerExecuted)continue;const Jt=t?.[Re.toolName];Jt?.type==="provider"&&Jt.supportsDeferredResults&&(De.content.some(Ft=>Ft.type==="tool-result"&&Ft.toolCallId===Re.toolCallId)||xn.set(Re.toolCallId,{toolName:Re.toolName}))}for(const Re of De.content)Re.type==="tool-result"&&xn.delete(Re.toolCallId);const io=W5({content:De.content,toolCalls:Pn,toolOutputs:Me,toolApprovalRequests:Object.values(Uo),tools:t});ht.push(...await Ic({content:io,tools:t}));const Ua=(tr=S?.requestBody)==null||tr?(it=De.request)!=null?it:{}:{...De.request,body:void 0},Nd={...De.response,messages:structuredClone(ht),body:(qr=S?.responseBody)==null||qr?(dr=De.response)==null?void 0:dr.body:void 0},qd=Ue.length,za=new n2({stepNumber:qd,model:En,functionId:f?.functionId,metadata:f?.metadata,experimental_context:_,content:io,finishReason:De.finishReason.unified,rawFinishReason:De.finishReason.raw,usage:vc(De.usage),warnings:De.warnings,providerMetadata:De.providerMetadata,request:Ua,response:Nd});hc({warnings:(rr=De.warnings)!=null?rr:[],provider:En.provider,model:En.modelId}),Ue.push(za),await xr({event:za,callbacks:[z,A.onStepFinish]})}finally{zt!=null&&clearTimeout(zt)}}while((ft.length>0&&Me.length===ft.length||xn.size>0)&&!await o2({stopConditions:Se,steps:Ue}));J.setAttributes(await vr({telemetry:f,attributes:{"ai.response.finishReason":De.finishReason.unified,"ai.response.text":{output:()=>Bm(De.content)},"ai.response.reasoning":{output:()=>Hm(De.content)},"ai.response.toolCalls":{output:()=>{const zt=l2(De.content);return zt==null?void 0:JSON.stringify(zt)}},"ai.response.providerMetadata":JSON.stringify(De.providerMetadata)}}));const Ee=Ue[Ue.length-1],lt=Ue.reduce((zt,Bt)=>zm(zt,Bt.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0});J.setAttributes(await vr({telemetry:f,attributes:{"ai.usage.inputTokens":lt.inputTokens,"ai.usage.inputTokenDetails.noCacheTokens":(Lr=lt.inputTokenDetails)==null?void 0:Lr.noCacheTokens,"ai.usage.inputTokenDetails.cacheReadTokens":(pr=lt.inputTokenDetails)==null?void 0:pr.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":(P=lt.inputTokenDetails)==null?void 0:P.cacheWriteTokens,"ai.usage.outputTokens":lt.outputTokens,"ai.usage.outputTokenDetails.textTokens":(X=lt.outputTokenDetails)==null?void 0:X.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":(Ie=lt.outputTokenDetails)==null?void 0:Ie.reasoningTokens,"ai.usage.totalTokens":lt.totalTokens,"ai.usage.reasoningTokens":(We=lt.outputTokenDetails)==null?void 0:We.reasoningTokens,"ai.usage.cachedInputTokens":(ln=lt.inputTokenDetails)==null?void 0:ln.cacheReadTokens}})),await xr({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:Ue,totalUsage:lt},callbacks:[ee,A.onFinish]});let mt;return Ee.finishReason==="stop"&&(mt=await(m??Es()).parseCompleteOutput({text:Ee.text},{response:Ee.response,usage:Ee.usage,finishReason:Ee.finishReason})),new G5({steps:Ue,totalUsage:lt,output:mt})}})}catch(J){throw Nm(J)}}async function i2({toolCalls:e,tools:t,tracer:r,telemetry:n,messages:o,abortSignal:a,experimental_context:i,stepNumber:s,model:l,onToolCallStart:c,onToolCallFinish:u}){return(await Promise.all(e.map(async p=>bc({toolCall:p,tools:t,tracer:r,telemetry:n,messages:o,abortSignal:a,experimental_context:i,stepNumber:s,model:l,onToolCallStart:c,onToolCallFinish:u})))).filter(p=>p!=null)}var G5=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 Ts;return this._output}};function l2(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 W5({content:e,toolCalls:t,toolOutputs:r,toolApprovalRequests:n,tools:o}){const a=[];for(const i of e)switch(i.type){case"text":case"reasoning":case"source":a.push(i);break;case"file":{a.push({type:"file",file:new Jm(i),...i.providerMetadata!=null?{providerMetadata:i.providerMetadata}:{}});break}case"tool-call":{a.push(t.find(s=>s.toolCallId===i.toolCallId));break}case"tool-result":{const s=t.find(l=>l.toolCallId===i.toolCallId);if(s==null){const l=o?.[i.toolName];if(!(l?.type==="provider"&&l.supportsDeferredResults))throw new Error(`Tool call ${i.toolCallId} not found.`);i.isError?a.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}:{},...l?.metadata!=null?{toolMetadata:l.metadata}:{}}):a.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}:{},...l?.metadata!=null?{toolMetadata:l.metadata}:{}});break}i.isError?a.push({type:"tool-error",toolCallId:i.toolCallId,toolName:i.toolName,input:s.input,error:i.result,providerExecuted:!0,dynamic:s.dynamic,...i.providerMetadata!=null?{providerMetadata:i.providerMetadata}:{},...s.toolMetadata!=null?{toolMetadata:s.toolMetadata}:{}}):a.push({type:"tool-result",toolCallId:i.toolCallId,toolName:i.toolName,input:s.input,output:i.result,providerExecuted:!0,dynamic:s.dynamic,...i.providerMetadata!=null?{providerMetadata:i.providerMetadata}:{},...s.toolMetadata!=null?{toolMetadata:s.toolMetadata}:{}});break}case"tool-approval-request":{const s=t.find(l=>l.toolCallId===i.toolCallId);if(s==null)throw new dc({toolCallId:i.toolCallId,approvalId:i.approvalId});a.push({type:"tool-approval-request",approvalId:i.approvalId,toolCall:s});break}}return[...a,...r,...n]}function $s(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 K5({status:e,statusText:t,headers:r,textStream:n}){return new Response(n.pipeThrough(new TextEncoderStream),{status:e??200,statusText:t,headers:$s(r,{"content-type":"text/plain; charset=utf-8"})})}function c2({response:e,status:t,statusText:r,headers:n,stream:o}){const a=t??200;r!==void 0?e.writeHead(a,r,n):e.writeHead(a,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(h=>{e.once("drain",h)})}}catch(l){throw l}finally{e.end()}})()}function Y5({response:e,status:t,statusText:r,headers:n,textStream:o}){c2({response:e,status:t,statusText:r,headers:Object.fromEntries($s(n,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:o.pipeThrough(new TextEncoderStream)})}var u2=class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
|
|
65
73
|
|
|
66
74
|
`)},flush(e){e.enqueue(`data: [DONE]
|
|
67
75
|
|
|
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 q6({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 L6({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 j6(e){return e.type.startsWith("data-")}function nc(e){return e.type.startsWith("tool-")}function D6(e){return e.type==="dynamic-tool"}function bm(e){return nc(e)||D6(e)}function km(e){return e.type.split("-").slice(1).join("-")}function U6({lastMessage:e,messageId:t}){return{message:e?.role==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function z6({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 po({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=>nc(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 mt({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 po({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 po({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 po({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 po({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(nc);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 po({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(j6(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 mt({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 F6({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=U6({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 z6({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 V6({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 Z6({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 B6(){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 H6({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 C6({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:Ql(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 Jl({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:kl(j.error),dynamic:!0,title:j.title});break}const N=e?.[j.toolName];if(N==null)break;if(N.onInputAvailable!=null&&await N.onInputAvailable({input:j.input,toolCallId:j.toolCallId,messages:s,abortSignal:i,experimental_context:l}),await lm({tool:N,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),N.execute!=null&&j.providerExecuted!==!0){const L=c();_.add(L),ec({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 J6=Zo({prefix:"aitxt",size:24});function oc({model:e,tools:t,toolChoice:r,system:n,prompt:o,messages:s,maxRetries:i,abortSignal:a,timeout:l,headers:c,stopWhen:u=tc(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:N,experimental_onStepStart:L,experimental_onToolCallStart:z,experimental_onToolCallFinish:B,experimental_context:X,experimental_include:ee,_internal:{now:Q=fa,generateId:Z=J6}={},...ne}){const D=Kl(l),E=L0(l),U=GT(l),F=E!=null?new AbortController:void 0,x=U!=null?new AbortController:void 0;return new G6({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:N,onStepStart:L,onToolCallStart:z,onToolCallFinish:B,now:Q,generateId:Z,experimental_context:X,download:C,include:ee})}function W6(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=JSON.stringify(u.partial);f!==s&&(i({controller:l,partialOutput:u.partial}),s=f)}}})}var G6=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:N,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,W,A,V={},J=[];const Y=[],ue=new Map;let Te,Be={},it={};const gt=new TransformStream({async transform(Ee,ot){var wt,Zt,sr,ar;ot.enqueue(Ee);const{part:ie}=Ee;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:G0(ie.error)}),ie.type==="text-start"&&(Be[ie.id]={type:"text",text:"",providerMetadata:ie.providerMetadata},re.push(Be[ie.id])),ie.type==="text-delta"){const He=Be[ie.id];if(He==null){ot.enqueue({part:{type:"error",error:`text part ${ie.id} not found`},partialOutput:void 0});return}He.text+=ie.text,He.providerMetadata=(wt=ie.providerMetadata)!=null?wt:He.providerMetadata}if(ie.type==="text-end"){const He=Be[ie.id];if(He==null){ot.enqueue({part:{type:"error",error:`text part ${ie.id} not found`},partialOutput:void 0});return}He.providerMetadata=(Zt=ie.providerMetadata)!=null?Zt:He.providerMetadata,delete Be[ie.id]}if(ie.type==="reasoning-start"&&(it[ie.id]={type:"reasoning",text:"",providerMetadata:ie.providerMetadata},re.push(it[ie.id])),ie.type==="reasoning-delta"){const He=it[ie.id];if(He==null){ot.enqueue({part:{type:"error",error:`reasoning part ${ie.id} not found`},partialOutput:void 0});return}He.text+=ie.text,He.providerMetadata=(sr=ie.providerMetadata)!=null?sr:He.providerMetadata}if(ie.type==="reasoning-end"){const He=it[ie.id];if(He==null){ot.enqueue({part:{type:"error",error:`reasoning part ${ie.id} not found`},partialOutput:void 0});return}He.providerMetadata=(ar=ie.providerMetadata)!=null?ar:He.providerMetadata,delete it[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=[],it={},Be={},V=ie.request,J=ie.warnings),ie.type==="finish-step"){const He=await rc({content:re,tools:h}),Le=new pm({stepNumber:Y.length,model:K,...qe,experimental_context:E,content:re,finishReason:ie.finishReason,rawFinishReason:ie.rawFinishReason,usage:ie.usage,warnings:J,request:V,response:{...ie.response,messages:[...te,...He]},providerMetadata:ie.providerMetadata});await br({event:Le,callbacks:[ee,M.onStepFinish]}),Gl({warnings:J,provider:K.provider,model:K.modelId}),Y.push(Le),te.push(...He),H.resolve()}ie.type==="finish"&&(A=ie.totalUsage,_e=ie.finishReason,W=ie.rawFinishReason)},async flush(Ee){var ot,wt,Zt,sr,ar,ie,He;try{if(Y.length===0){const je=s?.aborted?s.reason:new _0({message:"No output generated. Check the stream for errors."});$._finishReason.reject(je),$._rawFinishReason.reject(je),$._totalUsage.reject(je),$._steps.reject(je);return}const Le=_e??"other",pt=A??Xl();$._finishReason.resolve(Le),$._rawFinishReason.resolve(W),$._totalUsage.resolve(pt),$._steps.resolve(Y);const $e=Y[Y.length-1];await br({event:{stepNumber:$e.stepNumber,model:$e.model,functionId:$e.functionId,metadata:$e.metadata,experimental_context:$e.experimental_context,finishReason:$e.finishReason,rawFinishReason:$e.rawFinishReason,totalUsage:pt,usage:$e.usage,content:$e.content,text:$e.text,reasoningText:$e.reasoningText,reasoning:$e.reasoning,files:$e.files,sources:$e.sources,toolCalls:$e.toolCalls,staticToolCalls:$e.staticToolCalls,dynamicToolCalls:$e.dynamicToolCalls,toolResults:$e.toolResults,staticToolResults:$e.staticToolResults,dynamicToolResults:$e.dynamicToolResults,request:$e.request,response:$e.response,warnings:$e.warnings,providerMetadata:$e.providerMetadata,steps:Y},callbacks:[B,M.onFinish]}),Te.setAttributes(await fr({telemetry:t,attributes:{"ai.response.finishReason":Le,"ai.response.text":{output:()=>$e.text},"ai.response.reasoning":{output:()=>$e.reasoningText},"ai.response.toolCalls":{output:()=>{var je;return(je=$e.toolCalls)!=null&&je.length?JSON.stringify($e.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify($e.providerMetadata),"ai.usage.inputTokens":pt.inputTokens,"ai.usage.inputTokenDetails.noCacheTokens":(ot=pt.inputTokenDetails)==null?void 0:ot.noCacheTokens,"ai.usage.inputTokenDetails.cacheReadTokens":(wt=pt.inputTokenDetails)==null?void 0:wt.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":(Zt=pt.inputTokenDetails)==null?void 0:Zt.cacheWriteTokens,"ai.usage.outputTokens":pt.outputTokens,"ai.usage.outputTokenDetails.textTokens":(sr=pt.outputTokenDetails)==null?void 0:sr.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":(ar=pt.outputTokenDetails)==null?void 0:ar.reasoningTokens,"ai.usage.totalTokens":pt.totalTokens,"ai.usage.reasoningTokens":(ie=pt.outputTokenDetails)==null?void 0:ie.reasoningTokens,"ai.usage.cachedInputTokens":(He=pt.inputTokenDetails)==null?void 0:He.cacheReadTokens}}))}catch(Le){Ee.error(Le)}finally{Te.end()}}}),tt=B6();this.addStream=tt.addStream,this.closeStream=tt.close;const nt=tt.stream.getReader();let Lt=new ReadableStream({async start(Ee){Ee.enqueue({type:"start"})},async pull(Ee){function ot(){X?.({steps:Y}),Ee.enqueue({type:"abort",...s?.reason!==void 0?{reason:Tn(s.reason)}:{}}),Ee.close()}try{const{done:wt,value:Zt}=await nt.read();if(wt){Ee.close();return}if(s?.aborted){ot();return}Ee.enqueue(Zt)}catch(wt){$n(wt)&&s?.aborted?ot():Ee.error(wt)}},cancel(Ee){return tt.stream.cancel(Ee)}});for(const Ee of v)Lt=Lt.pipeThrough(Ee({tools:h,stopStream(){tt.terminate()}}));this.baseStream=Lt.pipeThrough(W6(m??ha())).pipeThrough(gt);const{maxRetries:_t,retry:Rr}=nm({maxRetries:o,abortSignal:s}),Yt=Y0(t),Ge=Yl(n),_r=K0({model:e,telemetry:t,headers:r,settings:{...Ge,maxRetries:_t}}),$=this,K={provider:e.provider,modelId:e.modelId},qe={functionId:t?.functionId,metadata:t?.metadata};ts({name:"ai.streamText",attributes:fr({telemetry:t,attributes:{...es({operationId:"ai.streamText",telemetry:t}),..._r,"ai.prompt":{input:()=>JSON.stringify({system:u,prompt:f,messages:p})}}}),tracer:Yt,endWhenDone:!1,fn:async Ee=>{Te=Ee;const ot=await W0({system:u,prompt:f,messages:p});await br({event:{model:K,system:u,prompt:f,messages:p,tools:h,toolChoice:g,activeTools:_,maxOutputTokens:Ge.maxOutputTokens,temperature:Ge.temperature,topP:Ge.topP,topK:Ge.topK,presencePenalty:Ge.presencePenalty,frequencyPenalty:Ge.frequencyPenalty,stopSequences:Ge.stopSequences,seed:Ge.seed,maxRetries:_t,timeout:S,headers:r,providerOptions:C,stopWhen:j,output:m,abortSignal:N,include:F,...qe,experimental_context:E},callbacks:[Q,M.onStart]});const wt=ot.messages,Zt=[],{approvedToolApprovals:sr,deniedToolApprovals:ar}=om({messages:wt});if(ar.length>0||sr.length>0){const He=[...sr,...ar].filter(Se=>Se.toolCall.providerExecuted),Le=sr.filter(Se=>!Se.toolCall.providerExecuted),pt=ar.filter(Se=>!Se.toolCall.providerExecuted),$e=ar.filter(Se=>Se.toolCall.providerExecuted);let je;const _n=new ReadableStream({start(Se){je=Se}});$.addStream(_n);try{for(const Ye of[...pt,...$e])je?.enqueue({type:"tool-output-denied",toolCallId:Ye.toolCall.toolCallId,toolName:Ye.toolCall.toolName});const Se=[];if(await Promise.all(Le.map(async Ye=>{const ft=await ec({toolCall:Ye.toolCall,tools:h,tracer:Yt,telemetry:t,messages:wt,abortSignal:s,experimental_context:E,stepNumber:Y.length,model:K,onToolCallStart:[ne,M.onToolCallStart],onToolCallFinish:[D,M.onToolCallFinish],onPreliminaryToolResult:ht=>{je?.enqueue(ht)}});ft!=null&&(je?.enqueue(ft),Se.push(ft))})),He.length>0&&Zt.push({role:"tool",content:He.map(Ye=>({type:"tool-approval-response",approvalId:Ye.approvalResponse.approvalId,approved:Ye.approvalResponse.approved,reason:Ye.approvalResponse.reason,providerExecuted:!0}))}),Se.length>0||pt.length>0){const Ye=[];for(const ft of Se)Ye.push({type:"tool-result",toolCallId:ft.toolCallId,toolName:ft.toolName,output:await Qo({toolCallId:ft.toolCallId,input:ft.input,tool:h?.[ft.toolName],output:ft.type==="tool-result"?ft.output:ft.error,errorMode:ft.type==="tool-error"?"text":"none"})});for(const ft of pt)Ye.push({type:"tool-result",toolCallId:ft.toolCall.toolCallId,toolName:ft.toolCall.toolName,output:{type:"execution-denied",reason:ft.approvalResponse.reason}});Zt.push({role:"tool",content:Ye})}}finally{je?.close()}}te.push(...Zt);async function ie({currentStep:He,responseMessages:Le,usage:pt}){var $e,je,_n,Se,Ye,ft,ht,jt,Me;const Qt=$.includeRawChunks,yn=i!=null?setTimeout(()=>a.abort(),i):void 0;let Qr;function Ji(){l!=null&&(Qr!=null&&clearTimeout(Qr),Qr=setTimeout(()=>c.abort(),l))}function Gn(){Qr!=null&&(clearTimeout(Qr),Qr=void 0)}function Eo(){yn!=null&&clearTimeout(yn)}try{H=new Vo;const vn=[...wt,...Le],bt=await b?.({model:e,steps:Y,stepNumber:Y.length,messages:vn,experimental_context:E}),Pr=ua(($e=bt?.model)!=null?$e:e),wn={provider:Pr.provider,modelId:Pr.modelId},$o=await z0({prompt:{system:(je=bt?.system)!=null?je:ot.system,messages:(_n=bt?.messages)!=null?_n:vn},supportedUrls:await Pr.supportedUrls,download:U}),Wi=(Se=bt?.activeTools)!=null?Se:_,{toolChoice:Kn,tools:$s}=await Z0({tools:h,toolChoice:(Ye=bt?.toolChoice)!=null?Ye:g,activeTools:Wi});E=(ft=bt?.experimental_context)!=null?ft:E;const ld=(ht=bt?.messages)!=null?ht:vn,cd=(jt=bt?.system)!=null?jt:ot.system,Rs=pa(C,bt?.providerOptions);await br({event:{stepNumber:Y.length,model:wn,system:cd,messages:ld,tools:h,toolChoice:Kn,activeTools:Wi,steps:[...Y],providerOptions:Rs,timeout:S,headers:r,stopWhen:j,output:m,abortSignal:N,include:F,...qe,experimental_context:E},callbacks:[Z,M.onStepStart]});const{result:{stream:Oe,response:Dt,request:Yn},doStreamSpan:ir,startTimestampMs:Ps}=await Rr(()=>ts({name:"ai.streamText.doStream",attributes:fr({telemetry:t,attributes:{...es({operationId:"ai.streamText.doStream",telemetry:t}),..._r,"ai.model.provider":Pr.provider,"ai.model.id":Pr.modelId,"ai.prompt.messages":{input:()=>X0($o)},"ai.prompt.tools":{input:()=>$s?.map(be=>JSON.stringify(be))},"ai.prompt.toolChoice":{input:()=>Kn!=null?JSON.stringify(Kn):void 0},"gen_ai.system":Pr.provider,"gen_ai.request.model":Pr.modelId,"gen_ai.request.frequency_penalty":Ge.frequencyPenalty,"gen_ai.request.max_tokens":Ge.maxOutputTokens,"gen_ai.request.presence_penalty":Ge.presencePenalty,"gen_ai.request.stop_sequences":Ge.stopSequences,"gen_ai.request.temperature":Ge.temperature,"gen_ai.request.top_k":Ge.topK,"gen_ai.request.top_p":Ge.topP}}),tracer:Yt,endWhenDone:!1,fn:async be=>({startTimestampMs:I(),doStreamSpan:be,result:await Pr.doStream({...Ge,tools:$s,toolChoice:Kn,responseFormat:await m?.responseFormat,prompt:$o,providerOptions:Rs,abortSignal:s,headers:r,includeRawChunks:Qt})})})),Gi=H6({tools:h,generatorStream:Oe,tracer:Yt,telemetry:t,system:u,messages:vn,repairToolCall:w,abortSignal:s,experimental_context:E,generateId:R,stepNumber:Y.length,model:wn,onToolCallStart:[ne,M.onToolCallStart],onToolCallFinish:[D,M.onToolCallFinish]}),Ki=(Me=F?.requestBody)==null||Me?Yn??{}:{...Yn,body:void 0},bn=[],kn=[];let Ro;const Qe={};let lr="other",Ms,Ct=Xl(),pv,fv=!0,Dr={id:R(),timestamp:new Date,modelId:K.modelId},a$="";$.addStream(Gi.pipeThrough(new TransformStream({async transform(be,Et){var Ns,Os,As,qs,Ls;if(Ji(),be.type==="stream-start"){Ro=be.warnings;return}if(fv){const St=I()-Ps;fv=!1,ir.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":St}),ir.setAttributes({"ai.response.msToFirstChunk":St}),Et.enqueue({type:"start-step",request:Ki,warnings:Ro??[]})}const js=be.type;switch(js){case"tool-approval-request":case"text-start":case"text-end":{Et.enqueue(be);break}case"text-delta":{be.delta.length>0&&(Et.enqueue({type:"text-delta",id:be.id,text:be.delta,providerMetadata:be.providerMetadata}),a$+=be.delta);break}case"reasoning-start":case"reasoning-end":{Et.enqueue(be);break}case"reasoning-delta":{Et.enqueue({type:"reasoning-delta",id:be.id,text:be.delta,providerMetadata:be.providerMetadata});break}case"tool-call":{Et.enqueue(be),bn.push(be);break}case"tool-result":{Et.enqueue(be),be.preliminary||kn.push(be);break}case"tool-error":{Et.enqueue(be),kn.push(be);break}case"response-metadata":{Dr={id:(Ns=be.id)!=null?Ns:Dr.id,timestamp:(Os=be.timestamp)!=null?Os:Dr.timestamp,modelId:(As=be.modelId)!=null?As:Dr.modelId};break}case"finish":{Ct=be.usage,lr=be.finishReason,Ms=be.rawFinishReason,pv=be.providerMetadata;const St=I()-Ps;ir.addEvent("ai.stream.finish"),ir.setAttributes({"ai.response.msToFinish":St,"ai.response.avgOutputTokensPerSecond":1e3*((qs=Ct.outputTokens)!=null?qs:0)/St});break}case"file":{Et.enqueue(be);break}case"source":{Et.enqueue(be);break}case"tool-input-start":{Qe[be.id]=be.toolName;const St=h?.[be.toolName];St?.onInputStart!=null&&await St.onInputStart({toolCallId:be.id,messages:vn,abortSignal:s,experimental_context:E}),Et.enqueue({...be,dynamic:(Ls=be.dynamic)!=null?Ls:St?.type==="dynamic",title:St?.title});break}case"tool-input-end":{delete Qe[be.id],Et.enqueue(be);break}case"tool-input-delta":{const St=Qe[be.id],Po=h?.[St];Po?.onInputDelta!=null&&await Po.onInputDelta({inputTextDelta:be.delta,toolCallId:be.id,messages:vn,abortSignal:s,experimental_context:E}),Et.enqueue(be);break}case"error":{Et.enqueue(be),lr="error";break}case"raw":{Qt&&Et.enqueue(be);break}default:{const St=js;throw new Error(`Unknown chunk type: ${St}`)}}},async flush(be){var Et,Ns,Os,As,qs,Ls,js;const St=bn.length>0?JSON.stringify(bn):void 0;try{ir.setAttributes(await fr({telemetry:t,attributes:{"ai.response.finishReason":lr,"ai.response.toolCalls":{output:()=>St},"ai.response.id":Dr.id,"ai.response.model":Dr.modelId,"ai.response.timestamp":Dr.timestamp.toISOString(),"ai.usage.inputTokens":Ct.inputTokens,"ai.usage.inputTokenDetails.noCacheTokens":(Et=Ct.inputTokenDetails)==null?void 0:Et.noCacheTokens,"ai.usage.inputTokenDetails.cacheReadTokens":(Ns=Ct.inputTokenDetails)==null?void 0:Ns.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":(Os=Ct.inputTokenDetails)==null?void 0:Os.cacheWriteTokens,"ai.usage.outputTokens":Ct.outputTokens,"ai.usage.outputTokenDetails.textTokens":(As=Ct.outputTokenDetails)==null?void 0:As.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":(qs=Ct.outputTokenDetails)==null?void 0:qs.reasoningTokens,"ai.usage.totalTokens":Ct.totalTokens,"ai.usage.reasoningTokens":(Ls=Ct.outputTokenDetails)==null?void 0:Ls.reasoningTokens,"ai.usage.cachedInputTokens":(js=Ct.inputTokenDetails)==null?void 0:js.cacheReadTokens,"gen_ai.response.finish_reasons":[lr],"gen_ai.response.id":Dr.id,"gen_ai.response.model":Dr.modelId,"gen_ai.usage.input_tokens":Ct.inputTokens,"gen_ai.usage.output_tokens":Ct.outputTokens}}))}catch{}be.enqueue({type:"finish-step",finishReason:lr,rawFinishReason:Ms,usage:Ct,providerMetadata:pv,response:{...Dr,headers:Dt?.headers}});const Po=tm(pt,Ct);await H.promise;const ud=Y[Y.length-1];try{ir.setAttributes(await fr({telemetry:t,attributes:{"ai.response.text":{output:()=>ud.text},"ai.response.reasoning":{output:()=>ud.reasoningText},"ai.response.providerMetadata":JSON.stringify(ud.providerMetadata)}}))}catch{}finally{ir.end()}const hv=bn.filter(Ot=>Ot.providerExecuted!==!0),i$=kn.filter(Ot=>Ot.providerExecuted!==!0);for(const Ot of bn){if(Ot.providerExecuted!==!0)continue;const dd=h?.[Ot.toolName];dd?.type==="provider"&&dd.supportsDeferredResults&&(kn.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 kn)(Ot.type==="tool-result"||Ot.type==="tool-error")&&ue.delete(Ot.toolCallId);if(Eo(),Gn(),(hv.length>0&&i$.length===hv.length||ue.size>0)&&!await fm({stopConditions:y,steps:Y})){Le.push(...await rc({content:Y[Y.length-1].content,tools:h}));try{await ie({currentStep:He+1,responseMessages:Le,usage:Po})}catch(Ot){be.enqueue({type:"error",error:Ot}),$.closeStream()}}else be.enqueue({type:"finish",finishReason:lr,rawFinishReason:Ms,totalUsage:Po}),$.closeStream()}})))}finally{Eo(),Gn()}}await ie({currentStep:0,responseMessages:Zt,usage:Xl()})}}).catch(Ee=>{$.addStream(new ReadableStream({start(ot){ot.enqueue({type:"error",error:Ee}),ot.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 Z6({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 Mr({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?L6({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(F6({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}={}){V6({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){A6({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 q6({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 O6({textStream:this.textStream,...e})}};Zo({prefix:"aiobj",size:24}),Zo({prefix:"aiobj",size:24});let sc;sc=globalThis.crypto;async function K6(e){return(await sc).getRandomValues(new Uint8Array(e))}async function Y6(e){const t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length;let n="";for(;n.length<e;){const o=await K6(e-n.length);for(const s of o)s<r&&(n+=t[s%t.length])}return n}async function Q6(e){return await Y6(e)}async function X6(e){const t=await(await sc).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 Q6(e),r=await X6(t);return{code_verifier:t,code_challenge:r}}var eC="AI_MCPClientError",Sm=`vercel.ai.error.${eC}`,tC=Symbol.for(Sm),Im,xm,Ve=class extends(xm=we,Im=tC,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 we.hasMarker(e,Sm)}},fo="2025-11-25",rC=[fo,"2025-06-18","2025-03-26","2024-11-05"],nC=de(ge(d(),Ce())),oC=ut({name:d(),version:d()}),ga=ut({_meta:de(k({}).loose())}),Zr=ga,Em=k({method:d(),params:de(ga)}),$m=k({applyDefaults:de(me())}).loose(),sC=ut({experimental:de(k({}).loose()),logging:de(k({}).loose()),prompts:de(ut({listChanged:de(me())})),resources:de(ut({subscribe:de(me()),listChanged:de(me())})),tools:de(ut({listChanged:de(me())})),elicitation:de($m)});k({elicitation:de($m)}).loose();var aC=Zr.extend({protocolVersion:d(),capabilities:sC,serverInfo:oC,instructions:de(d())}),ac=Zr.extend({nextCursor:de(d())}),iC=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:nC}).loose(),lC=ac.extend({tools:q(iC)}),Rm=k({type:P("text"),text:d()}).loose(),Pm=k({type:P("image"),data:Gp(),mimeType:d()}).loose(),cC=k({uri:d(),name:d(),title:de(d()),description:de(d()),mimeType:de(d()),size:de(O())}).loose(),uC=ac.extend({resources:q(cC)}),Mm=k({uri:d(),name:de(d()),title:de(d()),mimeType:de(d())}).loose(),Nm=Mm.extend({text:d()}),Om=Mm.extend({blob:Gp()}),Am=k({type:P("resource"),resource:ae([Nm,Om])}).loose(),dC=Zr.extend({content:q(ae([Rm,Pm,Am])),structuredContent:de(Ce()),isError:me().default(!1).optional()}).or(Zr.extend({toolResult:Ce()})),pC=k({uriTemplate:d(),name:d(),title:de(d()),description:de(d()),mimeType:de(d())}).loose(),fC=Zr.extend({resourceTemplates:q(pC)}),hC=Zr.extend({contents:q(ae([Nm,Om]))}),mC=k({name:d(),description:de(d()),required:de(me())}).loose(),gC=k({name:d(),title:de(d()),description:de(d()),arguments:de(q(mC))}).loose(),_C=ac.extend({prompts:q(gC)}),yC=k({role:ae([P("user"),P("assistant")]),content:ae([Rm,Pm,Am])}).loose(),vC=Zr.extend({description:de(d()),messages:q(yC)}),wC=ga.extend({message:d(),requestedSchema:Ce()}),qm=Em.extend({method:P("elicitation/create"),params:wC}),bC=Zr.extend({action:ae([P("accept"),P("decline"),P("cancel")]),content:de(ge(d(),Ce()))}),_a="2.0",kC=k({jsonrpc:P(_a),id:ae([d(),O().int()])}).merge(Em).strict(),TC=k({jsonrpc:P(_a),id:ae([d(),O().int()]),result:Zr}).strict(),CC=k({jsonrpc:P(_a),id:ae([d(),O().int()]),error:k({code:O().int(),message:d(),data:de(Ce())})}).strict(),SC=k({jsonrpc:P(_a)}).merge(k({method:d(),params:de(ga)})).strict(),os=ae([kC,SC,TC,CC]),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:O().optional(),scope:d().optional(),refresh_token:d().optional()}).strip(),Gt=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"}),IC=k({resource:d().url(),authorization_servers:q(Gt).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:me().optional(),authorization_details_types_supported:q(d()).optional(),dpop_signing_alg_values_supported:q(d()).optional(),dpop_bound_access_tokens_required:me().optional()}).passthrough(),Dm=k({issuer:d(),authorization_endpoint:Gt,token_endpoint:Gt,registration_endpoint:Gt.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(),xC=k({issuer:d(),authorization_endpoint:Gt,token_endpoint:Gt,userinfo_endpoint:Gt.optional(),jwks_uri:Gt,registration_endpoint:Gt.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(),EC=xC.merge(Dm.pick({code_challenge_methods_supported:!0})),$C=k({client_id:d(),client_secret:d().optional(),client_id_issued_at:O().optional(),client_secret_expires_at:O().optional()}).strip(),RC=k({redirect_uris:q(Gt),token_endpoint_auth_method:d().optional(),grant_types:q(d()).optional(),response_types:q(d()).optional(),client_name:d().optional(),client_uri:Gt.optional(),logo_uri:Gt.optional(),scope:d().optional(),contacts:q(d()).optional(),tos_uri:Gt.optional(),policy_uri:d().optional(),jwks_uri:Gt.optional(),jwks:yt().optional(),software_id:d().optional(),software_version:d().optional(),software_statement:d().optional()}).strip(),PC=k({error:d(),error_description:d().optional(),error_uri:d().optional()}),MC=RC.merge($C),NC="AI_MCPClientOAuthError",Um=`vercel.ai.error.${NC}`,OC=Symbol.for(Um),zm,Fm,ss=class extends(Fm=we,zm=OC,Fm){constructor({name:e="MCPClientOAuthError",message:t,cause:r}){super({name:e,message:t,cause:r}),this[zm]=!0}static isInstance(e){return we.hasMarker(e,Um)}},ho=class extends ss{};ho.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 AC={[ho.errorCode]:ho,[ya.errorCode]:ya,[va.errorCode]:va,[wa.errorCode]:wa};function qC(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function ic(e){const t=e.href;return e.pathname==="/"&&t.endsWith("/")?t.slice(0,-1):t}function LC({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 jC(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function lc(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?lc(e,void 0,r):void 0;throw n}}async function Vm(e,t,r=fetch){return await lc(e,{"MCP-Protocol-Version":t},r)}function DC(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function UC(e,t,r,n){var o,s;const i=new URL(e),a=(o=n?.protocolVersion)!=null?o:fo;let l;if(n?.metadataUrl)l=new URL(n.metadataUrl);else{const u=jC(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&&DC(c,i.pathname)){const u=new URL(`/.well-known/${t}`,i);c=await Vm(u,a,r)}return c}async function zC(e,t,r=fetch){const n=await UC(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 IC.parse(await n.json())}function FC(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 VC(e,{fetchFn:t=fetch,protocolVersion:r=fo}={}){var n;const o={"MCP-Protocol-Version":r},s=FC(e);for(const{url:i,type:a}of s){const l=await lc(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=EC.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 ZC(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",ic(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":BC(o,s,r);return;case"client_secret_post":HC(o,s,n);return;case"none":JC(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function BC(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 HC(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function JC(e,t){t.set("client_id",e)}async function cc(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=PC.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:i}=n,a=AC[o]||ho;return new a({message:s||"",cause:i})}catch(n){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new ho({message:o})}}async function WC(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",ic(i));const g=await(l??fetch)(f,{method:"POST",headers:p,body:h});if(!g.ok)throw await cc(g);return jm.parse(await g.json())}async function GC(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",ic(o));const p=await(i??fetch)(c,{method:"POST",headers:u,body:f});if(!p.ok)throw await cc(p);return jm.parse({refresh_token:n,...await p.json()})}async function KC(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 cc(s);return MC.parse(await s.json())}async function Ta(e,t){var r,n;try{return await uc(e,t)}catch(o){if(o instanceof ya||o instanceof wa)return await((r=e.invalidateCredentials)==null?void 0:r.call(e,"all")),await uc(e,t);if(o instanceof va)return await((n=e.invalidateCredentials)==null?void 0:n.call(e,"tokens")),await uc(e,t);throw o}}async function YC(e,t,r){const n=qC(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!LC({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 uc(e,{serverUrl:t,authorizationCode:r,callbackState:n,scope:o,resourceMetadataUrl:s,fetchFn:i}){let a,l;try{a=await zC(t,{resourceMetadataUrl:s},i),a.authorization_servers&&a.authorization_servers.length>0&&(l=a.authorization_servers[0])}catch{}l||(l=t);const c=await YC(t,e,a),u=await VC(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 KC(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 WC(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 GC(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 ho))throw _}const h=e.state?await e.state():void 0;h&&e.saveState&&await e.saveState(h);const{authorizationUrl:g,codeVerifier:v}=await ZC(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 QC=class{constructor({url:e,headers:t,authProvider:r,redirect:n="follow"}){this.connected=!1,this.url=new URL(e),this.headers=t,this.authProvider=r,this.redirectMode=n}async commonHeaders(e){const t={...this.headers,...e,"mcp-protocol-version":fo};if(this.authProvider){const r=await this.authProvider.tokens();r?.access_token&&(t.Authorization=`Bearer ${r.access_token}`)}return ln(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 fetch(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})!=="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 Ve({message:g});return(a=this.onerror)==null||a.call(this,v),t(v)}const p=u.body.pipeThrough(new TextDecoderStream).pipeThrough(new so).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 Ve({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 Ve({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${this.endpoint.origin}`});this.connected=!0,e()}else if(m==="message")try{const b=os.parse(JSON.parse(C));(g=this.onmessage)==null||g.call(this,b)}catch(b){const T=new Ve({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 Ve({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 fetch(t,u);if(f.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=ka(f);try{if(await Ta(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="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 Ve({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()}},XC=class{constructor({url:e,headers:t,authProvider:r,redirect:n="follow"}){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}async commonHeaders(e){const t={...this.headers,...e,"mcp-protocol-version":fo};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 ln(t,`ai-sdk/${Lm}`,Bo())}async start(){if(this.abortController)throw new Ve({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 fetch(this.url,{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 fetch(this.url,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})!=="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 Ve({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 Ve({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 so).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 N=os.parse(JSON.parse(j));(C=this.onmessage)==null||C.call(this,N)}catch(N){const L=new Ve({message:"MCP HTTP Transport Error: Failed to parse message",cause:N});(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 Ve({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 Ve({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 fetch(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})!=="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 Ve({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 so).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 Ve({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 e5(e){switch(e.type){case"sse":return new QC(e);case"http":return new XC(e);default:throw new Ve({message:"Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface."})}}function t5(e){return"start"in e&&typeof e.start=="function"&&"send"in e&&typeof e.send=="function"&&"close"in e&&typeof e.close=="function"}var r5="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 n5(e){const t=new o5(e);return await t.init(),t}var o5=class{constructor({transport:e,name:t="ai-sdk-mcp-client",version:r=r5,onUncaughtError:n,capabilities:o}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this.isClosed=!0,this.onUncaughtError=n,this.clientCapabilities=o??{},t5(e)?this.transport=e:this.transport=e5(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 Ve({message:"Unsupported message type"}));return}this.onResponse(s)},this.clientInfo={name:t,version:r}}async init(){try{await this.transport.start(),this.isClosed=!1;const e=await this.request({request:{method:"initialize",params:{protocolVersion:fo,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:aC});if(e===void 0)throw new Ve({message:"Server sent invalid initialize result"});if(!rC.includes(e.protocolVersion))throw new Ve({message:`Server's protocol version is not supported: ${e.protocolVersion}`});return this.serverCapabilities=e.capabilities,await this.notification({method:"notifications/initialized"}),this}catch(e){throw await this.close(),e}}async close(){var e;this.isClosed||(await((e=this.transport)==null?void 0:e.close()),this.onClose())}assertCapability(e){switch(e){case"initialize":break;case"tools/list":case"tools/call":if(!this.serverCapabilities.tools)throw new Ve({message:"Server does not support tools"});break;case"resources/list":case"resources/read":case"resources/templates/list":if(!this.serverCapabilities.resources)throw new Ve({message:"Server does not support resources"});break;case"prompts/list":case"prompts/get":if(!this.serverCapabilities.prompts)throw new Ve({message:"Server does not support prompts"});break;default:throw new Ve({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:r}){return new Promise((n,o)=>{if(this.isClosed)return o(new Ve({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 Ve({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 Ve({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:lC,options:t})}async callTool({name:e,args:t,options:r}){try{return this.request({request:{method:"tools/call",params:{name:e,arguments:t}},resultSchema:dC,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:uC,options:t})}catch(r){throw r}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:"resources/read",params:{uri:e}},resultSchema:hC,options:t})}catch(r){throw r}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:"resources/templates/list"},resultSchema:fC,options:e})}catch(t){throw t}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:"prompts/list",params:e},resultSchema:_C,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:vC,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 h!=null?p.extractStructuredContent(m,h,s):m},v=t==="automatic"?$l({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 ur({value:e.structuredContent,schema:Mn(t)});if(!n.success)throw new Ve({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 dr({text:n.text,schema:t});if(!o.success)throw new Ve({message:`Tool "${r}" returned content that does not match the expected outputSchema`,cause:o.error});return o.value}}throw new Ve({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 Ve({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=bC.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 Ve({message:"Connection closed"});for(const t of this.responseHandlers.values())t(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){const t=Number(e.id),r=this.responseHandlers.get(t);if(r===void 0)throw new Ve({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),r("result"in e?e:new Ve({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",s5=[Sa,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Ln="io.modelcontextprotocol/related-task",Ia="2.0",$t=nf(e=>e!==null&&(typeof e=="object"||typeof e=="function")),Wm=ae([d(),O().int()]),Gm=d();ut({ttl:ae([O(),Do()]).optional(),pollInterval:O().optional()});const a5=k({ttl:O().optional()}),i5=k({taskId:d()}),dc=ut({progressToken:Wm.optional(),[Ln]:i5.optional()}),nr=k({_meta:dc.optional()}),as=nr.extend({task:a5.optional()}),l5=e=>as.safeParse(e).success,Rt=k({method:d(),params:nr.loose().optional()}),hr=k({_meta:dc.optional()}),mr=k({method:d(),params:hr.loose().optional()}),Pt=ut({_meta:dc.optional()}),xa=ae([d(),O().int()]),Km=k({jsonrpc:P(Ia),id:xa,...Rt.shape}).strict(),pc=e=>Km.safeParse(e).success,Ym=k({jsonrpc:P(Ia),...mr.shape}).strict(),c5=e=>Ym.safeParse(e).success,fc=k({jsonrpc:P(Ia),id:xa,result:Pt}).strict(),is=e=>fc.safeParse(e).success;var xe;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(xe||(xe={}));const hc=k({jsonrpc:P(Ia),id:xa.optional(),error:k({code:O().int(),message:d(),data:Ce().optional()})}).strict(),u5=e=>hc.safeParse(e).success,jn=ae([Km,Ym,fc,hc]);ae([fc,hc]);const Dn=Pt.strict(),d5=hr.extend({requestId:xa.optional(),reason:d().optional()}),mc=mr.extend({method:P("notifications/cancelled"),params:d5}),p5=k({src:d(),mimeType:d().optional(),sizes:q(d()).optional(),theme:ce(["light","dark"]).optional()}),ls=k({icons:q(p5).optional()}),mo=k({name:d(),title:d().optional()}),Qm=mo.extend({...mo.shape,...ls.shape,version:d(),websiteUrl:d().optional(),description:d().optional()}),f5=il(k({applyDefaults:me().optional()}),ge(d(),Ce())),h5=of(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,il(k({form:f5.optional(),url:$t.optional()}),ge(d(),Ce()).optional())),m5=ut({list:$t.optional(),cancel:$t.optional(),requests:ut({sampling:ut({createMessage:$t.optional()}).optional(),elicitation:ut({create:$t.optional()}).optional()}).optional()}),g5=ut({list:$t.optional(),cancel:$t.optional(),requests:ut({tools:ut({call:$t.optional()}).optional()}).optional()}),_5=k({experimental:ge(d(),$t).optional(),sampling:k({context:$t.optional(),tools:$t.optional()}).optional(),elicitation:h5.optional(),roots:k({listChanged:me().optional()}).optional(),tasks:m5.optional()}),y5=nr.extend({protocolVersion:d(),capabilities:_5,clientInfo:Qm}),v5=Rt.extend({method:P("initialize"),params:y5}),w5=k({experimental:ge(d(),$t).optional(),logging:$t.optional(),completions:$t.optional(),prompts:k({listChanged:me().optional()}).optional(),resources:k({subscribe:me().optional(),listChanged:me().optional()}).optional(),tools:k({listChanged:me().optional()}).optional(),tasks:g5.optional()}),Xm=Pt.extend({protocolVersion:d(),capabilities:w5,serverInfo:Qm,instructions:d().optional()}),e2=mr.extend({method:P("notifications/initialized"),params:hr.optional()}),b5=e=>e2.safeParse(e).success,gc=Rt.extend({method:P("ping"),params:nr.optional()}),k5=k({progress:O(),total:de(O()),message:de(d())}),T5=k({...hr.shape,...k5.shape,progressToken:Wm}),_c=mr.extend({method:P("notifications/progress"),params:T5}),C5=nr.extend({cursor:Gm.optional()}),cs=Rt.extend({params:C5.optional()}),us=Pt.extend({nextCursor:Gm.optional()}),S5=ce(["working","input_required","completed","failed","cancelled"]),ds=k({taskId:d(),status:S5,ttl:ae([O(),Do()]),createdAt:d(),lastUpdatedAt:d(),pollInterval:de(O()),statusMessage:de(d())}),ps=Pt.extend({task:ds}),I5=hr.merge(ds),Ea=mr.extend({method:P("notifications/tasks/status"),params:I5}),yc=Rt.extend({method:P("tasks/get"),params:nr.extend({taskId:d()})}),vc=Pt.merge(ds),wc=Rt.extend({method:P("tasks/result"),params:nr.extend({taskId:d()})});Pt.loose();const bc=cs.extend({method:P("tasks/list")}),kc=us.extend({tasks:q(ds)}),Tc=Rt.extend({method:P("tasks/cancel"),params:nr.extend({taskId:d()})}),x5=Pt.merge(ds),t2=k({uri:d(),mimeType:de(d()),_meta:ge(d(),Ce()).optional()}),r2=t2.extend({text:d()}),Cc=d().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),n2=t2.extend({blob:Cc}),fs=ce(["user","assistant"]),go=k({audience:q(fs).optional(),priority:O().min(0).max(1).optional(),lastModified:Vp({offset:!0}).optional()}),o2=k({...mo.shape,...ls.shape,uri:d(),description:de(d()),mimeType:de(d()),annotations:go.optional(),_meta:de(ut({}))}),E5=k({...mo.shape,...ls.shape,uriTemplate:d(),description:de(d()),mimeType:de(d()),annotations:go.optional(),_meta:de(ut({}))}),$5=cs.extend({method:P("resources/list")}),s2=us.extend({resources:q(o2)}),R5=cs.extend({method:P("resources/templates/list")}),a2=us.extend({resourceTemplates:q(E5)}),Sc=nr.extend({uri:d()}),P5=Sc,M5=Rt.extend({method:P("resources/read"),params:P5}),i2=Pt.extend({contents:q(ae([r2,n2]))}),Ic=mr.extend({method:P("notifications/resources/list_changed"),params:hr.optional()}),N5=Sc,O5=Rt.extend({method:P("resources/subscribe"),params:N5}),A5=Sc,q5=Rt.extend({method:P("resources/unsubscribe"),params:A5}),L5=hr.extend({uri:d()}),l2=mr.extend({method:P("notifications/resources/updated"),params:L5}),j5=k({name:d(),description:de(d()),required:de(me())}),D5=k({...mo.shape,...ls.shape,description:de(d()),arguments:de(q(j5)),_meta:de(ut({}))}),U5=cs.extend({method:P("prompts/list")}),c2=us.extend({prompts:q(D5)}),z5=nr.extend({name:d(),arguments:ge(d(),d()).optional()}),F5=Rt.extend({method:P("prompts/get"),params:z5}),xc=k({type:P("text"),text:d(),annotations:go.optional(),_meta:ge(d(),Ce()).optional()}),Ec=k({type:P("image"),data:Cc,mimeType:d(),annotations:go.optional(),_meta:ge(d(),Ce()).optional()}),$c=k({type:P("audio"),data:Cc,mimeType:d(),annotations:go.optional(),_meta:ge(d(),Ce()).optional()}),V5=k({type:P("tool_use"),name:d(),id:d(),input:ge(d(),Ce()),_meta:ge(d(),Ce()).optional()}),Z5=k({type:P("resource"),resource:ae([r2,n2]),annotations:go.optional(),_meta:ge(d(),Ce()).optional()}),B5=o2.extend({type:P("resource_link")}),Rc=ae([xc,Ec,$c,B5,Z5]),H5=k({role:fs,content:Rc}),u2=Pt.extend({description:d().optional(),messages:q(H5)}),Pc=mr.extend({method:P("notifications/prompts/list_changed"),params:hr.optional()}),J5=k({title:d().optional(),readOnlyHint:me().optional(),destructiveHint:me().optional(),idempotentHint:me().optional(),openWorldHint:me().optional()}),W5=k({taskSupport:ce(["required","optional","forbidden"]).optional()}),d2=k({...mo.shape,...ls.shape,description:d().optional(),inputSchema:k({type:P("object"),properties:ge(d(),$t).optional(),required:q(d()).optional()}).catchall(Ce()),outputSchema:k({type:P("object"),properties:ge(d(),$t).optional(),required:q(d()).optional()}).catchall(Ce()).optional(),annotations:J5.optional(),execution:W5.optional(),_meta:ge(d(),Ce()).optional()}),G5=cs.extend({method:P("tools/list")}),p2=us.extend({tools:q(d2)}),hs=Pt.extend({content:q(Rc).default([]),structuredContent:ge(d(),Ce()).optional(),isError:me().optional()});hs.or(Pt.extend({toolResult:Ce()}));const K5=as.extend({name:d(),arguments:ge(d(),Ce()).optional()}),Y5=Rt.extend({method:P("tools/call"),params:K5}),Mc=mr.extend({method:P("notifications/tools/list_changed"),params:hr.optional()}),Q5=k({autoRefresh:me().default(!0),debounceMs:O().int().nonnegative().default(300)}),f2=ce(["debug","info","notice","warning","error","critical","alert","emergency"]),X5=nr.extend({level:f2}),eS=Rt.extend({method:P("logging/setLevel"),params:X5}),tS=hr.extend({level:f2,logger:d().optional(),data:Ce()}),h2=mr.extend({method:P("notifications/message"),params:tS}),rS=k({name:d().optional()}),nS=k({hints:q(rS).optional(),costPriority:O().min(0).max(1).optional(),speedPriority:O().min(0).max(1).optional(),intelligencePriority:O().min(0).max(1).optional()}),oS=k({mode:ce(["auto","required","none"]).optional()}),sS=k({type:P("tool_result"),toolUseId:d().describe("The unique identifier for the corresponding tool call."),content:q(Rc).default([]),structuredContent:k({}).loose().optional(),isError:me().optional(),_meta:ge(d(),Ce()).optional()}),aS=ze("type",[xc,Ec,$c]),$a=ze("type",[xc,Ec,$c,V5,sS]),iS=k({role:fs,content:ae([$a,q($a)]),_meta:ge(d(),Ce()).optional()}),lS=as.extend({messages:q(iS),modelPreferences:nS.optional(),systemPrompt:d().optional(),includeContext:ce(["none","thisServer","allServers"]).optional(),temperature:O().optional(),maxTokens:O().int(),stopSequences:q(d()).optional(),metadata:$t.optional(),tools:q(d2).optional(),toolChoice:oS.optional()}),Nc=Rt.extend({method:P("sampling/createMessage"),params:lS}),Oc=Pt.extend({model:d(),stopReason:de(ce(["endTurn","stopSequence","maxTokens"]).or(d())),role:fs,content:aS}),m2=Pt.extend({model:d(),stopReason:de(ce(["endTurn","stopSequence","maxTokens","toolUse"]).or(d())),role:fs,content:ae([$a,q($a)])}),cS=k({type:P("boolean"),title:d().optional(),description:d().optional(),default:me().optional()}),uS=k({type:P("string"),title:d().optional(),description:d().optional(),minLength:O().optional(),maxLength:O().optional(),format:ce(["email","uri","date","date-time"]).optional(),default:d().optional()}),dS=k({type:ce(["number","integer"]),title:d().optional(),description:d().optional(),minimum:O().optional(),maximum:O().optional(),default:O().optional()}),pS=k({type:P("string"),title:d().optional(),description:d().optional(),enum:q(d()),default:d().optional()}),fS=k({type:P("string"),title:d().optional(),description:d().optional(),oneOf:q(k({const:d(),title:d()})),default:d().optional()}),hS=k({type:P("string"),title:d().optional(),description:d().optional(),enum:q(d()),enumNames:q(d()).optional(),default:d().optional()}),mS=ae([pS,fS]),gS=k({type:P("array"),title:d().optional(),description:d().optional(),minItems:O().optional(),maxItems:O().optional(),items:k({type:P("string"),enum:q(d())}),default:q(d()).optional()}),_S=k({type:P("array"),title:d().optional(),description:d().optional(),minItems:O().optional(),maxItems:O().optional(),items:k({anyOf:q(k({const:d(),title:d()}))}),default:q(d()).optional()}),yS=ae([gS,_S]),vS=ae([hS,mS,yS]),wS=ae([vS,cS,uS,dS]),bS=as.extend({mode:P("form").optional(),message:d(),requestedSchema:k({type:P("object"),properties:ge(d(),wS),required:q(d()).optional()})}),kS=as.extend({mode:P("url"),message:d(),elicitationId:d(),url:d().url()}),TS=ae([bS,kS]),Ac=Rt.extend({method:P("elicitation/create"),params:TS}),CS=hr.extend({elicitationId:d()}),SS=mr.extend({method:P("notifications/elicitation/complete"),params:CS}),qc=Pt.extend({action:ce(["accept","decline","cancel"]),content:of(e=>e===null?void 0:e,ge(d(),ae([d(),O(),me(),q(d())])).optional())}),IS=k({type:P("ref/resource"),uri:d()}),xS=k({type:P("ref/prompt"),name:d()}),ES=nr.extend({ref:ae([xS,IS]),argument:k({name:d(),value:d()}),context:k({arguments:ge(d(),d()).optional()}).optional()}),$S=Rt.extend({method:P("completion/complete"),params:ES}),g2=Pt.extend({completion:ut({values:q(d()).max(100),total:de(O().int()),hasMore:de(me())})}),RS=k({uri:d().startsWith("file://"),name:d().optional(),_meta:ge(d(),Ce()).optional()}),_2=Rt.extend({method:P("roots/list"),params:nr.optional()}),y2=Pt.extend({roots:q(RS)}),PS=mr.extend({method:P("notifications/roots/list_changed"),params:hr.optional()});ae([gc,v5,$S,eS,F5,U5,$5,R5,M5,O5,q5,Y5,G5,yc,wc,bc,Tc]),ae([mc,_c,e2,PS,Ea]),ae([Dn,Oc,m2,qc,y2,vc,kc,ps]),ae([gc,Nc,Ac,_2,yc,wc,bc,Tc]),ae([mc,_c,h2,l2,Ic,Mc,Pc,Ea,SS]),ae([Dn,Xm,g2,u2,c2,s2,a2,i2,hs,p2,vc,kc,ps]);class ke 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===xe.UrlElicitationRequired&&n){const o=n;if(o.elicitations)return new MS(o.elicitations,r)}return new ke(t,r,n)}}class MS extends ke{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(xe.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}}const Mt=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"}),NS=ut({resource:d().url(),authorization_servers:q(Mt).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:me().optional(),authorization_details_types_supported:q(d()).optional(),dpop_signing_alg_values_supported:q(d()).optional(),dpop_bound_access_tokens_required:me().optional()}),v2=ut({issuer:d(),authorization_endpoint:Mt,token_endpoint:Mt,registration_endpoint:Mt.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:Mt.optional(),revocation_endpoint:Mt.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:me().optional()}),OS=ut({issuer:d(),authorization_endpoint:Mt,token_endpoint:Mt,userinfo_endpoint:Mt.optional(),jwks_uri:Mt,registration_endpoint:Mt.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:me().optional(),request_parameter_supported:me().optional(),request_uri_parameter_supported:me().optional(),require_request_uri_registration:me().optional(),op_policy_uri:Mt.optional(),op_tos_uri:Mt.optional(),client_id_metadata_document_supported:me().optional()}),AS=k({...OS.shape,...v2.pick({code_challenge_methods_supported:!0}).shape}),qS=k({access_token:d(),id_token:d().optional(),token_type:d(),expires_in:af().optional(),scope:d().optional(),refresh_token:d().optional()}).strip(),LS=k({error:d(),error_description:d().optional(),error_uri:d().optional()}),w2=Mt.optional().or(P("").transform(()=>{})),jS=k({redirect_uris:q(Mt),token_endpoint_auth_method:d().optional(),grant_types:q(d()).optional(),response_types:q(d()).optional(),client_name:d().optional(),client_uri:Mt.optional(),logo_uri:w2,scope:d().optional(),contacts:q(d()).optional(),tos_uri:w2,policy_uri:d().optional(),jwks_uri:Mt.optional(),jwks:yt().optional(),software_id:d().optional(),software_version:d().optional(),software_statement:d().optional()}).strip(),DS=k({client_id:d(),client_secret:d().optional(),client_id_issued_at:O().optional(),client_secret_expires_at:O().optional()}).strip(),US=jS.merge(DS);k({error:d(),error_description:d().optional()}).strip(),k({token:d(),token_type_hint:d().optional()}).strip();function zS(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function FS({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 It 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 Lc extends It{}Lc.errorCode="invalid_request";class Ra extends It{}Ra.errorCode="invalid_client";class Pa extends It{}Pa.errorCode="invalid_grant";class Ma extends It{}Ma.errorCode="unauthorized_client";class jc extends It{}jc.errorCode="unsupported_grant_type";class Dc extends It{}Dc.errorCode="invalid_scope";class Uc extends It{}Uc.errorCode="access_denied";class _o extends It{}_o.errorCode="server_error";class zc extends It{}zc.errorCode="temporarily_unavailable";class Fc extends It{}Fc.errorCode="unsupported_response_type";class Vc extends It{}Vc.errorCode="unsupported_token_type";class Zc extends It{}Zc.errorCode="invalid_token";class Bc extends It{}Bc.errorCode="method_not_allowed";class Hc extends It{}Hc.errorCode="too_many_requests";class Na extends It{}Na.errorCode="invalid_client_metadata";class Jc extends It{}Jc.errorCode="insufficient_scope";class Wc extends It{}Wc.errorCode="invalid_target";const VS={[Lc.errorCode]:Lc,[Ra.errorCode]:Ra,[Pa.errorCode]:Pa,[Ma.errorCode]:Ma,[jc.errorCode]:jc,[Dc.errorCode]:Dc,[Uc.errorCode]:Uc,[_o.errorCode]:_o,[zc.errorCode]:zc,[Fc.errorCode]:Fc,[Vc.errorCode]:Vc,[Zc.errorCode]:Zc,[Bc.errorCode]:Bc,[Hc.errorCode]:Hc,[Na.errorCode]:Na,[Jc.errorCode]:Jc,[Wc.errorCode]:Wc};class gr extends Error{constructor(t){super(t??"Unauthorized")}}function ZS(e){return["client_secret_basic","client_secret_post","none"].includes(e)}const Gc="code",Kc="S256";function BS(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&&ZS(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 HS(e,t,r,n){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":JS(o,s,r);return;case"client_secret_post":WS(o,s,n);return;case"none":GS(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function JS(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 WS(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function GS(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=LS.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:i}=n,a=VS[o]||_o;return new a(s||"",i)}catch(n){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new _o(o)}}async function Un(e,t){try{return await Yc(e,t)}catch(r){if(r instanceof Ra||r instanceof Ma)return await e.invalidateCredentials?.("all"),await Yc(e,t);if(r instanceof Pa)return await e.invalidateCredentials?.("tokens"),await Yc(e,t);throw r}}async function Yc(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){let i,a;try{i=await QS(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 YS(t,e,i),c=await nI(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&&!KS(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 lI(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 iI(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 aI(a,{metadata:c,clientInformation:u,refreshToken:p.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(_),"AUTHORIZED"}catch(_){if(!(!(_ instanceof It)||_ instanceof _o))throw _}const h=e.state?await e.state():void 0,{authorizationUrl:g,codeVerifier:v}=await oI(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 KS(e){if(!e)return!1;try{const t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function YS(e,t,r){const n=zS(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!FS({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=Qc(e,"resource_metadata")||void 0;let s;if(o)try{s=new URL(o)}catch{}const i=Qc(e,"scope")||void 0,a=Qc(e,"error")||void 0;return{resourceMetadataUrl:s,scope:i,error:a}}function Qc(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 QS(e,t,r=fetch){const n=await tI(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 NS.parse(await n.json())}async function Xc(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?Xc(e,void 0,r):void 0;throw n}}function XS(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 Xc(e,{"MCP-Protocol-Version":t},r)}function eI(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function tI(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=XS(t,o.pathname);i=new URL(l,n?.metadataServerUrl??o),i.search=o.search}let a=await k2(i,s,r);if(!n?.metadataUrl&&eI(a,o.pathname)){const l=new URL(`/.well-known/${t}`,o);a=await k2(l,s,r)}return a}function rI(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 nI(e,{fetchFn:t=fetch,protocolVersion:r=Sa}={}){const n={"MCP-Protocol-Version":r,Accept:"application/json"},o=rI(e);for(const{url:s,type:i}of o){const a=await Xc(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()):AS.parse(await a.json())}}}async function oI(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(Gc))throw new Error(`Incompatible auth server: does not support response type ${Gc}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Kc))throw new Error(`Incompatible auth server: does not support code challenge method ${Kc}`)}else a=new URL("/authorize",e);const l=await Cm(),c=l.code_verifier,u=l.code_challenge;return a.searchParams.set("response_type",Gc),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",u),a.searchParams.set("code_challenge_method",Kc),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 sI(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=BS(n,u);HS(f,n,l,r)}const c=await(i??fetch)(a,{method:"POST",headers:l,body:r});if(!c.ok)throw await b2(c);return qS.parse(await c.json())}async function aI(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 iI(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=sI(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 lI(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 US.parse(await s.json())}const cI={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class yo 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??cI}async _authThenStart(){if(!this._authProvider)throw new gr("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 gr;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 yo(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 so({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 gr("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 gr("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:pc(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 yo(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 gr;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 yo(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 gr;return this.send(t)}}throw new yo(a.status,`Error POSTing to endpoint: ${p}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,a.status===202){await a.body?.cancel(),b5(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 yo(-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 yo(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 uI(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function eu(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(eu).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${eu(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)},tu=(e,t,r)=>t.has(e)||I2("Cannot "+r),Ae=(e,t,r)=>(tu(e,t,"read from private field"),r?r.call(e):t.get(e)),Tt=(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),at=(e,t,r,n)=>(tu(e,t,"write to private field"),t.set(e,r),r),Br=(e,t,r)=>(tu(e,t,"access private method"),r),Kt,zn,vo,qa,La,ms,wo,gs,un,bo,ko,To,_s,Tr,ru,nu,ou,x2,su,au,ys,iu,lu;class ja extends EventTarget{constructor(t,r){var n,o;super(),Tt(this,Tr),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Tt(this,Kt),Tt(this,zn),Tt(this,vo),Tt(this,qa),Tt(this,La),Tt(this,ms),Tt(this,wo),Tt(this,gs,null),Tt(this,un),Tt(this,bo),Tt(this,ko,null),Tt(this,To,null),Tt(this,_s,null),Tt(this,nu,async s=>{var i;Ae(this,bo).reset();const{body:a,redirected:l,status:c,headers:u}=s;if(c===204){Br(this,Tr,ys).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?at(this,vo,new URL(s.url)):at(this,vo,void 0),c!==200){Br(this,Tr,ys).call(this,`Non-200 status code (${c})`,c);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){Br(this,Tr,ys).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(Ae(this,Kt)===this.CLOSED)return;at(this,Kt,this.OPEN);const f=new Event("open");if((i=Ae(this,_s))==null||i.call(this,f),this.dispatchEvent(f),typeof a!="object"||!a||!("getReader"in a)){Br(this,Tr,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();_&&Ae(this,bo).feed(p.decode(_,{stream:!v})),v&&(g=!1,Ae(this,bo).reset(),Br(this,Tr,iu).call(this))}while(g)}),Tt(this,ou,s=>{at(this,un,void 0),!(s.name==="AbortError"||s.type==="aborted")&&Br(this,Tr,iu).call(this,eu(s))}),Tt(this,su,s=>{typeof s.id=="string"&&at(this,gs,s.id);const i=new MessageEvent(s.event||"message",{data:s.data,origin:Ae(this,vo)?Ae(this,vo).origin:Ae(this,zn).origin,lastEventId:s.id||""});Ae(this,To)&&(!s.event||s.event==="message")&&Ae(this,To).call(this,i),this.dispatchEvent(i)}),Tt(this,au,s=>{at(this,ms,s)}),Tt(this,lu,()=>{at(this,wo,void 0),Ae(this,Kt)===this.CONNECTING&&Br(this,Tr,ru).call(this)});try{if(t instanceof URL)at(this,zn,t);else if(typeof t=="string")at(this,zn,new URL(t,dI()));else throw new Error("Invalid URL")}catch{throw uI("An invalid or illegal string was specified")}at(this,bo,Ef({onEvent:Ae(this,su),onRetry:Ae(this,au)})),at(this,Kt,this.CONNECTING),at(this,ms,3e3),at(this,La,(n=r?.fetch)!=null?n:globalThis.fetch),at(this,qa,(o=r?.withCredentials)!=null?o:!1),Br(this,Tr,ru).call(this)}get readyState(){return Ae(this,Kt)}get url(){return Ae(this,zn).href}get withCredentials(){return Ae(this,qa)}get onerror(){return Ae(this,ko)}set onerror(t){at(this,ko,t)}get onmessage(){return Ae(this,To)}set onmessage(t){at(this,To,t)}get onopen(){return Ae(this,_s)}set onopen(t){at(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(){Ae(this,wo)&&clearTimeout(Ae(this,wo)),Ae(this,Kt)!==this.CLOSED&&(Ae(this,un)&&Ae(this,un).abort(),at(this,Kt,this.CLOSED),at(this,un,void 0))}}Kt=new WeakMap,zn=new WeakMap,vo=new WeakMap,qa=new WeakMap,La=new WeakMap,ms=new WeakMap,wo=new WeakMap,gs=new WeakMap,un=new WeakMap,bo=new WeakMap,ko=new WeakMap,To=new WeakMap,_s=new WeakMap,Tr=new WeakSet,ru=function(){at(this,Kt,this.CONNECTING),at(this,un,new AbortController),Ae(this,La)(Ae(this,zn),Br(this,Tr,x2).call(this)).then(Ae(this,nu)).catch(Ae(this,ou))},nu=new WeakMap,ou=new WeakMap,x2=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Ae(this,gs)?{"Last-Event-ID":Ae(this,gs)}:void 0},cache:"no-store",signal:(e=Ae(this,un))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},su=new WeakMap,au=new WeakMap,ys=function(e,t){var r;Ae(this,Kt)!==this.CLOSED&&at(this,Kt,this.CLOSED);const n=new C2("error",{code:t,message:e});(r=Ae(this,ko))==null||r.call(this,n),this.dispatchEvent(n)},iu=function(e,t){var r;if(Ae(this,Kt)===this.CLOSED)return;at(this,Kt,this.CONNECTING);const n=new C2("error",{code:t,message:e});(r=Ae(this,ko))==null||r.call(this,n),this.dispatchEvent(n),at(this,wo,setTimeout(Ae(this,lu),Ae(this,ms)))},lu=new WeakMap,ja.CONNECTING=0,ja.OPEN=1,ja.CLOSED=2;function dI(){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 pI 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 gr("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 gr;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 pI(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 gr("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 gr("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 gr;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 cu=k({error:k({message:d(),type:d().nullish(),param:yt().nullish(),code:ae([d(),O()]).nullish()})}),Cr=Ar({errorSchema:cu,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 fI({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,${co(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 Mr({functionality:"audio file parts with URLs"});switch(a.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:co(a.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:co(a.data),format:"mp3"}};default:throw new Mr({functionality:`audio content parts with media type ${a.mediaType}`})}}else if(a.mediaType==="application/pdf"){if(a.data instanceof URL)throw new Mr({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,${co(a.data)}`}}}else throw new Mr({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 uu({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 hI=ve(()=>ye(k({id:d().nullish(),created:O().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:O(),end_index:O(),url:d(),title:d()})})).nullish()}),index:O(),logprobs:k({content:q(k({token:d(),logprob:O(),top_logprobs:q(k({token:d(),logprob:O()}))})).nullish()}).nullish(),finish_reason:d().nullish()})),usage:k({prompt_tokens:O().nullish(),completion_tokens:O().nullish(),total_tokens:O().nullish(),prompt_tokens_details:k({cached_tokens:O().nullish()}).nullish(),completion_tokens_details:k({reasoning_tokens:O().nullish(),accepted_prediction_tokens:O().nullish(),rejected_prediction_tokens:O().nullish()}).nullish()}).nullish()}))),mI=ve(()=>ye(ae([k({id:d().nullish(),created:O().nullish(),model:d().nullish(),choices:q(k({delta:k({role:ce(["assistant"]).nullish(),content:d().nullish(),tool_calls:q(k({index:O(),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:O(),end_index:O(),url:d(),title:d()})})).nullish()}).nullish(),logprobs:k({content:q(k({token:d(),logprob:O(),top_logprobs:q(k({token:d(),logprob:O()}))})).nullish()}).nullish(),finish_reason:d().nullish(),index:O()})),usage:k({prompt_tokens:O().nullish(),completion_tokens:O().nullish(),total_tokens:O().nullish(),prompt_tokens_details:k({cached_tokens:O().nullish()}).nullish(),completion_tokens_details:k({reasoning_tokens:O().nullish(),accepted_prediction_tokens:O().nullish(),rejected_prediction_tokens:O().nullish()}).nullish()}).nullish()}),cu]))),gI=ve(()=>ye(k({logitBias:ge(af(),O()).optional(),logprobs:ae([me(),O()]).optional(),parallelToolCalls:me().optional(),user:d().optional(),reasoningEffort:ce(["none","minimal","low","medium","high","xhigh"]).optional(),maxCompletionTokens:O().optional(),store:me().optional(),metadata:ge(d().max(64),d().max(512)).optional(),prediction:ge(d(),yt()).optional(),serviceTier:ce(["auto","flex","priority","default"]).optional(),strictJsonSchema:me().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:me().optional()})));function _I({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 Mr({functionality:`tool choice type: ${s}`})}}}var yI=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 Fr({provider:"openai",providerOptions:p,schema:gI}))!=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}=fI({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:N,toolWarnings:L}=_I({tools:u,toolChoice:f});return{args:{...S,tools:j,tool_choice:N},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 Jt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:At(this.config.headers(),e.headers),body:l,failedResponseHandler:Cr,successfulResponseHandler:Wt(hI),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:Ut(),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:Ut(),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:{...uu(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 Jt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:At(this.config.headers(),e.headers),body:n,failedResponseHandler:Cr,successfulResponseHandler:aa(mI),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,N,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=uu(X);Object.values(Z).some(Boolean)&&(c=!0,h.enqueue({type:"response-metadata",...uu(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 Yi({data:Z,message:"Expected 'function' type."});if(Z.id==null)throw new Yi({data:Z,message:"Expected 'id' to be a string."});if(((m=Z.function)==null?void 0:m.name)==null)throw new Yi({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}),Wf(E.function.arguments)&&(h.enqueue({type:"tool-input-end",id:E.id}),h.enqueue({type:"tool-call",toolCallId:(I=E.id)!=null?I:Ut(),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:(N=Z.function.arguments)!=null?N:""}),((L=D.function)==null?void 0:L.name)!=null&&((z=D.function)==null?void 0:z.arguments)!=null&&Wf(D.function.arguments)&&(h.enqueue({type:"tool-input-end",id:D.id}),h.enqueue({type:"tool-call",toolCallId:(B=D.id)!=null?B:Ut(),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:Ut(),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 vI({prompt:e,user:t="user",assistant:r="assistant"}){let n="";e[0].role==="system"&&(n+=`${e[0].content}
|
|
76
|
+
`)}})}},d2={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function Q5({status:e,statusText:t,headers:r,stream:n,consumeSseStream:o}){let a=n.pipeThrough(new u2);if(o){const[i,s]=a.tee();a=i,o({stream:s})}return new Response(a.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:$s(r,d2)})}function X5({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}pe(d(),Jn.optional());function eC(e){return e.type.startsWith("data-")}function Xr(){return Object.create(null)}function xc(e){return e.type.startsWith("tool-")}function tC(e){return e.type==="dynamic-tool"}function p2(e){return xc(e)||tC(e)}function h2(e){return e.type.split("-").slice(1).join("-")}function rC({lastMessage:e,messageId:t}){return{message:e?.role==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:Xr(),activeReasoningParts:Xr(),partialToolCalls:Xr()}}function nC({stream:e,messageMetadataSchema:t,dataPartSchemas:r,runUpdateMessageJob:n,onError:o,onToolCall:a,onData:i}){return e.pipeThrough(new TransformStream({async transform(s,l){await n(async({state:c,write:u})=>{var h,p,m,f;function b(g){const y=c.message.parts.filter(p2).find(_=>_.toolCallId===g);if(y==null)throw new To({chunkType:"tool-invocation",chunkId:g,message:`No tool invocation found for tool call ID "${g}".`});return y}function w(g){var I;const y=c.message.parts.find(S=>xc(S)&&S.toolCallId===g.toolCallId),_=g,k=y;if(y!=null){y.state=g.state,k.input=_.input,k.output=_.output,k.errorText=_.errorText,k.rawInput=_.rawInput,k.preliminary=_.preliminary,g.title!==void 0&&(k.title=g.title),g.toolMetadata!==void 0&&(k.toolMetadata=g.toolMetadata),k.providerExecuted=(I=_.providerExecuted)!=null?I:y.providerExecuted;const S=_.providerMetadata;if(S!=null)if(g.state==="output-available"||g.state==="output-error"){const E=y;E.resultProviderMetadata=S}else y.callProviderMetadata=S}else c.message.parts.push({type:`tool-${g.toolName}`,toolCallId:g.toolCallId,state:g.state,title:g.title,...g.toolMetadata!==void 0?{toolMetadata:g.toolMetadata}:{},input:_.input,output:_.output,rawInput:_.rawInput,errorText:_.errorText,providerExecuted:_.providerExecuted,preliminary:_.preliminary,..._.providerMetadata!=null&&(g.state==="output-available"||g.state==="output-error")?{resultProviderMetadata:_.providerMetadata}:{},..._.providerMetadata!=null&&!(g.state==="output-available"||g.state==="output-error")?{callProviderMetadata:_.providerMetadata}:{}})}function C(g){var I,y;const _=c.message.parts.find(E=>E.type==="dynamic-tool"&&E.toolCallId===g.toolCallId),k=g,S=_;if(_!=null){_.state=g.state,S.toolName=g.toolName,S.input=k.input,S.output=k.output,S.errorText=k.errorText,S.rawInput=(I=k.rawInput)!=null?I:S.rawInput,S.preliminary=k.preliminary,g.title!==void 0&&(S.title=g.title),g.toolMetadata!==void 0&&(S.toolMetadata=g.toolMetadata),S.providerExecuted=(y=k.providerExecuted)!=null?y:_.providerExecuted;const E=k.providerMetadata;if(E!=null)if(g.state==="output-available"||g.state==="output-error"){const R=_;R.resultProviderMetadata=E}else _.callProviderMetadata=E}else c.message.parts.push({type:"dynamic-tool",toolName:g.toolName,toolCallId:g.toolCallId,state:g.state,input:k.input,output:k.output,errorText:k.errorText,preliminary:k.preliminary,providerExecuted:k.providerExecuted,title:g.title,...g.toolMetadata!==void 0?{toolMetadata:g.toolMetadata}:{},...k.providerMetadata!=null&&(g.state==="output-available"||g.state==="output-error")?{resultProviderMetadata:k.providerMetadata}:{},...k.providerMetadata!=null&&!(g.state==="output-available"||g.state==="output-error")?{callProviderMetadata:k.providerMetadata}:{}})}async function v(g){if(g!=null){const I=c.message.metadata!=null?Is(c.message.metadata,g):g;t!=null&&await _t({value:I,schema:t,context:{field:"message.metadata",entityId:c.message.id}}),c.message.metadata=I}}switch(s.type){case"text-start":{const g={type:"text",text:"",providerMetadata:s.providerMetadata,state:"streaming"};c.activeTextParts[s.id]=g,c.message.parts.push(g),u();break}case"text-delta":{const g=c.activeTextParts[s.id];if(g==null)throw new To({chunkType:"text-delta",chunkId:s.id,message:`Received text-delta for missing text part with ID "${s.id}". Ensure a "text-start" chunk is sent before any "text-delta" chunks.`});g.text+=s.delta,g.providerMetadata=(h=s.providerMetadata)!=null?h:g.providerMetadata,u();break}case"text-end":{const g=c.activeTextParts[s.id];if(g==null)throw new To({chunkType:"text-end",chunkId:s.id,message:`Received text-end for missing text part with ID "${s.id}". Ensure a "text-start" chunk is sent before any "text-end" chunks.`});g.state="done",g.providerMetadata=(p=s.providerMetadata)!=null?p:g.providerMetadata,delete c.activeTextParts[s.id],u();break}case"reasoning-start":{const g={type:"reasoning",text:"",providerMetadata:s.providerMetadata,state:"streaming"};c.activeReasoningParts[s.id]=g,c.message.parts.push(g),u();break}case"reasoning-delta":{const g=c.activeReasoningParts[s.id];if(g==null)throw new To({chunkType:"reasoning-delta",chunkId:s.id,message:`Received reasoning-delta for missing reasoning part with ID "${s.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-delta" chunks.`});g.text+=s.delta,g.providerMetadata=(m=s.providerMetadata)!=null?m:g.providerMetadata,u();break}case"reasoning-end":{const g=c.activeReasoningParts[s.id];if(g==null)throw new To({chunkType:"reasoning-end",chunkId:s.id,message:`Received reasoning-end for missing reasoning part with ID "${s.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-end" chunks.`});g.providerMetadata=(f=s.providerMetadata)!=null?f:g.providerMetadata,g.state="done",delete c.activeReasoningParts[s.id],u();break}case"file":{c.message.parts.push({type:"file",mediaType:s.mediaType,url:s.url,...s.providerMetadata!=null?{providerMetadata:s.providerMetadata}:{}}),u();break}case"source-url":{c.message.parts.push({type:"source-url",sourceId:s.sourceId,url:s.url,title:s.title,providerMetadata:s.providerMetadata}),u();break}case"source-document":{c.message.parts.push({type:"source-document",sourceId:s.sourceId,mediaType:s.mediaType,title:s.title,filename:s.filename,providerMetadata:s.providerMetadata}),u();break}case"tool-input-start":{const g=c.message.parts.filter(xc);c.partialToolCalls[s.toolCallId]={text:"",toolName:s.toolName,index:g.length,dynamic:s.dynamic,title:s.title,toolMetadata:s.toolMetadata},s.dynamic?C({toolCallId:s.toolCallId,toolName:s.toolName,state:"input-streaming",input:void 0,providerExecuted:s.providerExecuted,title:s.title,toolMetadata:s.toolMetadata,providerMetadata:s.providerMetadata}):w({toolCallId:s.toolCallId,toolName:s.toolName,state:"input-streaming",input:void 0,providerExecuted:s.providerExecuted,title:s.title,toolMetadata:s.toolMetadata,providerMetadata:s.providerMetadata}),u();break}case"tool-input-delta":{const g=c.partialToolCalls[s.toolCallId];if(g==null)throw new To({chunkType:"tool-input-delta",chunkId:s.toolCallId,message:`Received tool-input-delta for missing tool call with ID "${s.toolCallId}". Ensure a "tool-input-start" chunk is sent before any "tool-input-delta" chunks.`});g.text+=s.inputTextDelta;const{value:I}=await fa(g.text);g.dynamic?C({toolCallId:s.toolCallId,toolName:g.toolName,state:"input-streaming",input:I,title:g.title,toolMetadata:g.toolMetadata}):w({toolCallId:s.toolCallId,toolName:g.toolName,state:"input-streaming",input:I,title:g.title,toolMetadata:g.toolMetadata}),u();break}case"tool-input-available":{s.dynamic?C({toolCallId:s.toolCallId,toolName:s.toolName,state:"input-available",input:s.input,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata,title:s.title,toolMetadata:s.toolMetadata}):w({toolCallId:s.toolCallId,toolName:s.toolName,state:"input-available",input:s.input,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata,title:s.title,toolMetadata:s.toolMetadata}),u(),a&&!s.providerExecuted&&await a({toolCall:s});break}case"tool-input-error":{const g=c.message.parts.filter(p2).find(y=>y.toolCallId===s.toolCallId);(g!=null?g.type==="dynamic-tool":!!s.dynamic)?C({toolCallId:s.toolCallId,toolName:s.toolName,state:"output-error",input:s.input,errorText:s.errorText,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata,toolMetadata:s.toolMetadata}):w({toolCallId:s.toolCallId,toolName:s.toolName,state:"output-error",input:void 0,rawInput:s.input,errorText:s.errorText,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata,toolMetadata:s.toolMetadata}),u();break}case"tool-approval-request":{const g=b(s.toolCallId);g.state="approval-requested",g.approval={id:s.approvalId,...s.signature!=null?{signature:s.signature}:{}},u();break}case"tool-output-denied":{const g=b(s.toolCallId);g.state="output-denied",u();break}case"tool-output-available":{const g=b(s.toolCallId);g.type==="dynamic-tool"?C({toolCallId:s.toolCallId,toolName:g.toolName,state:"output-available",input:g.input,output:s.output,preliminary:s.preliminary,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata,title:g.title,toolMetadata:g.toolMetadata}):w({toolCallId:s.toolCallId,toolName:h2(g),state:"output-available",input:g.input,output:s.output,providerExecuted:s.providerExecuted,preliminary:s.preliminary,providerMetadata:s.providerMetadata,title:g.title,toolMetadata:g.toolMetadata}),u();break}case"tool-output-error":{const g=b(s.toolCallId);g.type==="dynamic-tool"?C({toolCallId:s.toolCallId,toolName:g.toolName,state:"output-error",input:g.input,errorText:s.errorText,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata,title:g.title,toolMetadata:g.toolMetadata}):w({toolCallId:s.toolCallId,toolName:h2(g),state:"output-error",input:g.input,rawInput:g.rawInput,errorText:s.errorText,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata,title:g.title,toolMetadata:g.toolMetadata}),u();break}case"start-step":{c.message.parts.push({type:"step-start"});break}case"finish-step":{c.activeTextParts=Xr(),c.activeReasoningParts=Xr();break}case"start":{s.messageId!=null&&(c.message.id=s.messageId),await v(s.messageMetadata),(s.messageId!=null||s.messageMetadata!=null)&&u();break}case"finish":{s.finishReason!=null&&(c.finishReason=s.finishReason),await v(s.messageMetadata),s.messageMetadata!=null&&u();break}case"message-metadata":{await v(s.messageMetadata),s.messageMetadata!=null&&u();break}case"error":{o?.(new Error(s.errorText));break}default:if(eC(s)){if(r?.[s.type]!=null){const y=c.message.parts.findIndex(k=>"id"in k&&"data"in k&&k.id===s.id&&k.type===s.type),_=y>=0?y:c.message.parts.length;await _t({value:s.data,schema:r[s.type],context:{field:`message.parts[${_}].data`,entityName:s.type,entityId:s.id}})}const g=s;if(g.transient){i?.(g);break}const I=g.id!=null?c.message.parts.find(y=>g.type===y.type&&g.id===y.id):void 0;I!=null?I.data=g.data:c.message.parts.push(g),i?.(g),u()}}l.enqueue(s)})}}))}function oC({messageId:e,originalMessages:t=[],onStepFinish:r,onFinish:n,onError:o,stream:a}){let i=t?.[t.length-1];i?.role!=="assistant"?i=void 0:e=i.id;let s=!1;const l=a.pipeThrough(new TransformStream({transform(f,b){if(f.type==="start"){const w=f;w.messageId==null&&e!=null&&(w.messageId=e)}f.type==="abort"&&(s=!0),b.enqueue(f)}}));if(n==null&&r==null)return l;const c=rC({lastMessage:i?structuredClone(i):void 0,messageId:e??""}),u=async f=>{await f({state:c,write:()=>{}})};let h=!1;const p=async()=>{if(h||!n)return;h=!0;const f=c.message.id===i?.id;await n({isAborted:s,isContinuation:f,responseMessage:c.message,messages:[...f?t.slice(0,-1):t,c.message],finishReason:c.finishReason})},m=async()=>{if(!r)return;const f=c.message.id===i?.id;try{await r({isContinuation:f,responseMessage:structuredClone(c.message),messages:[...f?t.slice(0,-1):t,structuredClone(c.message)]})}catch(b){o(b)}};return nC({stream:l,runUpdateMessageJob:u,onError:o}).pipeThrough(new TransformStream({async transform(f,b){f.type==="finish-step"&&await m(),b.enqueue(f)},async cancel(){await p()},async flush(){await p()}}))}function aC({response:e,status:t,statusText:r,headers:n,stream:o,consumeSseStream:a}){let i=o.pipeThrough(new u2);if(a){const[s,l]=i.tee();i=s,a({stream:l})}c2({response:e,status:t,statusText:r,headers:Object.fromEntries($s(n,d2).entries()),stream:i.pipeThrough(new TextEncoderStream)})}function ma(e){const t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=function(){const r=this.getReader();let n=!1;async function o(a){var i;if(!n){n=!0;try{a&&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:a,value:i}=await r.read();return a?(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(a){throw await o(!0),a}}},t}async function sC({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 f2(){let e,t;return{promise:new Promise((n,o)=>{e=n,t=o}),resolve:e,reject:t}}function iC(){let e=[],t=null,r=!1,n=f2();const o=()=>{r=!0,n.resolve(),e.forEach(i=>i.cancel()),e=[],t?.close()},a=async()=>{if(r&&e.length===0){t?.close();return}if(e.length===0)return n=f2(),await n.promise,a();try{const{value:i,done:s}=await e[0].read();s?(e.shift(),e.length===0&&r?t?.close():await a()):t?.enqueue(i)}catch(i){t?.error(i),e.shift(),o()}};return{stream:new ReadableStream({start(i){t=i},pull:a,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 lC({tools:e,generatorStream:t,tracer:r,telemetry:n,system:o,messages:a,abortSignal:i,repairToolCall:s,experimental_context:l,toolApprovalSecret:c,generateId:u,stepNumber:h,model:p,onToolCallStart:m,onToolCallFinish:f}){let b=null;const w=new ReadableStream({start(S){b=S}}),C=new Set,v=new Map,g=new Map;let I=!1,y;function _(){I&&C.size===0&&(y!=null&&b.enqueue(y),b.close())}const k=new TransformStream({async transform(S,E){const R=S.type;switch(R){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":{E.enqueue(S);break}case"file":{E.enqueue({type:"file",file:new L5({data:S.data,mediaType:S.mediaType}),...S.providerMetadata!=null?{providerMetadata:S.providerMetadata}:{}});break}case"finish":{y={type:"finish",finishReason:S.finishReason.unified,rawFinishReason:S.finishReason.raw,usage:vc(S.usage),providerMetadata:S.providerMetadata};break}case"tool-approval-request":{const x=g.get(S.toolCallId);if(x==null){b.enqueue({type:"error",error:new dc({toolCallId:S.toolCallId,approvalId:S.approvalId})});break}E.enqueue({type:"tool-approval-request",approvalId:S.approvalId,toolCall:x});break}case"tool-call":{try{const x=await e2({toolCall:S,tools:e,repairToolCall:s,system:o,messages:a});if(g.set(x.toolCallId,x),E.enqueue(x),x.invalid){b.enqueue({type:"tool-error",toolCallId:x.toolCallId,toolName:x.toolName,input:x.input,error:Ll(x.error),dynamic:!0,title:x.title,...x.toolMetadata!=null?{toolMetadata:x.toolMetadata}:{}});break}const N=e?.[x.toolName];if(N==null)break;if(N.onInputAvailable!=null&&await N.onInputAvailable({input:x.input,toolCallId:x.toolCallId,messages:a,abortSignal:i,experimental_context:l}),await kc({tool:N,toolCall:x,messages:a,experimental_context:l})){const U=u(),z=await Qm({secret:c,approvalId:U,toolCallId:x.toolCallId,toolName:x.toolName,input:x.input});b.enqueue({type:"tool-approval-request",approvalId:U,toolCall:x,...z!=null?{signature:z}:{}});break}if(v.set(x.toolCallId,x.input),N.execute!=null&&x.providerExecuted!==!0){const U=u();C.add(U),bc({toolCall:x,tools:e,tracer:r,telemetry:n,messages:a,abortSignal:i,experimental_context:l,stepNumber:h,model:p,onToolCallStart:m,onToolCallFinish:f,onPreliminaryToolResult:z=>{b.enqueue(z)}}).then(z=>{b.enqueue(z)}).catch(z=>{b.enqueue({type:"error",error:z})}).finally(()=>{C.delete(U),_()})}}catch(x){b.enqueue({type:"error",error:x})}break}case"tool-result":{const x=S.toolName,N=g.get(S.toolCallId);S.isError?b.enqueue({type:"tool-error",toolCallId:S.toolCallId,toolName:x,input:v.get(S.toolCallId),providerExecuted:!0,error:S.result,dynamic:S.dynamic,...S.providerMetadata!=null?{providerMetadata:S.providerMetadata}:{},...N?.toolMetadata!=null?{toolMetadata:N.toolMetadata}:{}}):E.enqueue({type:"tool-result",toolCallId:S.toolCallId,toolName:x,input:v.get(S.toolCallId),output:S.result,providerExecuted:!0,dynamic:S.dynamic,...S.providerMetadata!=null?{providerMetadata:S.providerMetadata}:{},...N?.toolMetadata!=null?{toolMetadata:N.toolMetadata}:{}});break}default:{const x=R;throw new Error(`Unhandled chunk type: ${x}`)}}},flush(){I=!0,_()}});return new ReadableStream({async start(S){return Promise.all([t.pipeThrough(k).pipeTo(new WritableStream({write(E){S.enqueue(E)},close(){}})),w.pipeTo(new WritableStream({write(E){S.enqueue(E)},close(){S.close()}}))])}})}var cC=na({prefix:"aitxt",size:24}),uC={file:!0,source:!0,"text-start":!0,"text-end":!0,"text-delta":!0,"reasoning-start":!0,"reasoning-end":!0,"reasoning-delta":!0,"tool-input-start":!0,"tool-input-end":!0,"tool-input-delta":!0,"tool-approval-request":!0,"tool-call":!0,"tool-result":!0,"tool-error":!0,"stream-start":!1,"response-metadata":!1,finish:!1,error:!1,raw:!1};function Ec({model:e,tools:t,toolChoice:r,system:n,prompt:o,messages:a,allowSystemInMessages:i,maxRetries:s,abortSignal:l,timeout:c,headers:u,stopWhen:h=Sc(1),experimental_output:p,output:m=p,experimental_telemetry:f,prepareStep:b,providerOptions:w,experimental_activeTools:C,activeTools:v=C,experimental_repairToolCall:g,experimental_transform:I,experimental_download:y,includeRawChunks:_=!1,onChunk:k,onError:S=({error:B})=>{console.error(B)},onFinish:E,onAbort:R,onStepFinish:x,experimental_onStart:N,experimental_onStepStart:U,experimental_onToolCallStart:z,experimental_onToolCallFinish:ee,experimental_context:Q,experimental_toolApprovalSecret:se,experimental_include:re,_internal:{now:Se=xs,generateId:H=cC}={},...D}){const B=fc(c),F=Cm(c),$=l5(c),O=F!=null?new AbortController:void 0,j=$!=null?new AbortController:void 0;return new pC({model:Cs(e),telemetry:f,headers:u,settings:D,maxRetries:s,abortSignal:a2(l,B!=null?AbortSignal.timeout(B):void 0,O?.signal,j?.signal),stepTimeoutMs:F,stepAbortController:O,chunkTimeoutMs:$,chunkAbortController:j,system:n,prompt:o,messages:a,allowSystemInMessages:i,tools:t,toolChoice:r,transforms:Bn(I),activeTools:v,repairToolCall:g,stopConditions:Bn(h),output:m,providerOptions:w,prepareStep:b,includeRawChunks:_,timeout:c,stopWhen:h,originalAbortSignal:l,onChunk:k,onError:S,onFinish:E,onAbort:R,onStepFinish:x,onStart:N,onStepStart:U,onToolCallStart:z,onToolCallFinish:ee,now:Se,generateId:H,experimental_context:Q,experimental_toolApprovalSecret:se,download:y,include:re})}function dC(e){let t,r="",n="",o,a="";function i({controller:s,partialOutput:l=void 0}){s.enqueue({part:{type:"text-delta",id:t,text:n,providerMetadata:o},partialOutput:l}),n=""}return new TransformStream({async transform(s,l){var c;if(s.type==="finish-step"&&n.length>0&&i({controller:l}),s.type!=="text-delta"&&s.type!=="text-start"&&s.type!=="text-end"){l.enqueue({part:s,partialOutput:void 0});return}if(t==null)t=s.id;else if(s.id!==t){l.enqueue({part:s,partialOutput:void 0});return}if(s.type==="text-start"){l.enqueue({part:s,partialOutput:void 0});return}if(s.type==="text-end"){n.length>0&&i({controller:l}),l.enqueue({part:s,partialOutput:void 0});return}r+=s.text,n+=s.text,o=(c=s.providerMetadata)!=null?c:o;const u=await e.parsePartialOutput({text:r});if(u!==void 0){const h=typeof u.partial=="string"?u.partial:JSON.stringify(u.partial);h!==a&&(i({controller:l,partialOutput:u.partial}),a=h)}}})}var pC=class{constructor({model:e,telemetry:t,headers:r,settings:n,maxRetries:o,abortSignal:a,stepTimeoutMs:i,stepAbortController:s,chunkTimeoutMs:l,chunkAbortController:c,system:u,prompt:h,messages:p,allowSystemInMessages:m,tools:f,toolChoice:b,transforms:w,activeTools:C,repairToolCall:v,stopConditions:g,output:I,providerOptions:y,prepareStep:_,includeRawChunks:k,now:S,generateId:E,timeout:R,stopWhen:x,originalAbortSignal:N,onChunk:U,onError:z,onFinish:ee,onAbort:Q,onStepFinish:se,onStart:re,onStepStart:Se,onToolCallStart:H,onToolCallFinish:D,experimental_context:B,experimental_toolApprovalSecret:F,download:$,include:O}){this._totalUsage=new ra,this._finishReason=new ra,this._rawFinishReason=new ra,this._steps=new ra,this.outputSpecification=I,this.includeRawChunks=k,this.tools=f;const G=Um()(t?.integrations);let Y,W=[];const V=[];let A,Z,J,te={},de=[];const fe=[];let Ye;const wt=new Map;let st,et=Xr(),Be=Xr();const tr=new TransformStream({async transform(nt,ht){var Ut,hr,jr,Dr;ht.enqueue(nt);const{part:ie}=nt;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 U?.({chunk:ie}),ie.type==="error"){const Ve=Nm(ie.error);Ts.isInstance(Ve)&&(Ye=Ve),await z({error:Ve})}if(ie.type==="text-start"&&(et[ie.id]={type:"text",text:"",providerMetadata:ie.providerMetadata},W.push(et[ie.id])),ie.type==="text-delta"){const Ve=et[ie.id];if(Ve==null){ht.enqueue({part:{type:"error",error:`text part ${ie.id} not found`},partialOutput:void 0});return}Ve.text+=ie.text,Ve.providerMetadata=(Ut=ie.providerMetadata)!=null?Ut:Ve.providerMetadata}if(ie.type==="text-end"){const Ve=et[ie.id];if(Ve==null){ht.enqueue({part:{type:"error",error:`text part ${ie.id} not found`},partialOutput:void 0});return}Ve.providerMetadata=(hr=ie.providerMetadata)!=null?hr:Ve.providerMetadata,delete et[ie.id]}if(ie.type==="reasoning-start"&&(Be[ie.id]={type:"reasoning",text:"",providerMetadata:ie.providerMetadata},W.push(Be[ie.id])),ie.type==="reasoning-delta"){const Ve=Be[ie.id];if(Ve==null){ht.enqueue({part:{type:"error",error:`reasoning part ${ie.id} not found`},partialOutput:void 0});return}Ve.text+=ie.text,Ve.providerMetadata=(jr=ie.providerMetadata)!=null?jr:Ve.providerMetadata}if(ie.type==="reasoning-end"){const Ve=Be[ie.id];if(Ve==null){ht.enqueue({part:{type:"error",error:`reasoning part ${ie.id} not found`},partialOutput:void 0});return}Ve.providerMetadata=(Dr=ie.providerMetadata)!=null?Dr:Ve.providerMetadata,delete Be[ie.id]}if(ie.type==="file"&&W.push({type:"file",file:ie.file,...ie.providerMetadata!=null?{providerMetadata:ie.providerMetadata}:{}}),ie.type==="source"&&W.push(ie),ie.type==="tool-call"&&W.push(ie),ie.type==="tool-result"&&!ie.preliminary&&W.push(ie),ie.type==="tool-approval-request"&&W.push(ie),ie.type==="tool-error"&&W.push(ie),ie.type==="start-step"&&(W=[],Be=Xr(),et=Xr(),te=ie.request,de=ie.warnings),ie.type==="finish-step"){const Ve=await Ic({content:W,tools:f}),De=new n2({stepNumber:fe.length,model:We,...ln,experimental_context:B,content:W,finishReason:ie.finishReason,rawFinishReason:ie.rawFinishReason,usage:ie.usage,warnings:de,request:te,response:{...ie.response,messages:[...V,...Ve]},providerMetadata:ie.providerMetadata});await xr({event:De,callbacks:[se,G.onStepFinish]}),hc({warnings:de,provider:We.provider,model:We.modelId}),fe.push(De),V.push(...Ve),Y.resolve()}ie.type==="finish"&&(J=ie.totalUsage,A=ie.finishReason,Z=ie.rawFinishReason)},async flush(nt){var ht,Ut,hr,jr,Dr,ie,Ve;try{if(fe.length===0||Ye!=null){const Ue=a?.aborted?a.reason:Ye??new Ts({message:"No output generated. Check the stream for errors."});Ie._finishReason.reject(Ue),Ie._rawFinishReason.reject(Ue),Ie._totalUsage.reject(Ue),Ie._steps.reject(Ue);return}const De=A??"other",ft=J??wc();Ie._finishReason.resolve(De),Ie._rawFinishReason.resolve(Z),Ie._totalUsage.resolve(ft),Ie._steps.resolve(fe);const Me=fe[fe.length-1];await xr({event:{stepNumber:Me.stepNumber,model:Me.model,functionId:Me.functionId,metadata:Me.metadata,experimental_context:Me.experimental_context,finishReason:Me.finishReason,rawFinishReason:Me.rawFinishReason,totalUsage:ft,usage:Me.usage,content:Me.content,text:Me.text,reasoningText:Me.reasoningText,reasoning:Me.reasoning,files:Me.files,sources:Me.sources,toolCalls:Me.toolCalls,staticToolCalls:Me.staticToolCalls,dynamicToolCalls:Me.dynamicToolCalls,toolResults:Me.toolResults,staticToolResults:Me.staticToolResults,dynamicToolResults:Me.dynamicToolResults,request:Me.request,response:Me.response,warnings:Me.warnings,providerMetadata:Me.providerMetadata,steps:fe},callbacks:[ee,G.onFinish]}),st.setAttributes(await vr({telemetry:t,attributes:{"ai.response.finishReason":De,"ai.response.text":{output:()=>Me.text},"ai.response.reasoning":{output:()=>Me.reasoningText},"ai.response.toolCalls":{output:()=>{var Ue;return(Ue=Me.toolCalls)!=null&&Ue.length?JSON.stringify(Me.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(Me.providerMetadata),"ai.usage.inputTokens":ft.inputTokens,"ai.usage.inputTokenDetails.noCacheTokens":(ht=ft.inputTokenDetails)==null?void 0:ht.noCacheTokens,"ai.usage.inputTokenDetails.cacheReadTokens":(Ut=ft.inputTokenDetails)==null?void 0:Ut.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":(hr=ft.inputTokenDetails)==null?void 0:hr.cacheWriteTokens,"ai.usage.outputTokens":ft.outputTokens,"ai.usage.outputTokenDetails.textTokens":(jr=ft.outputTokenDetails)==null?void 0:jr.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":(Dr=ft.outputTokenDetails)==null?void 0:Dr.reasoningTokens,"ai.usage.totalTokens":ft.totalTokens,"ai.usage.reasoningTokens":(ie=ft.outputTokenDetails)==null?void 0:ie.reasoningTokens,"ai.usage.cachedInputTokens":(Ve=ft.inputTokenDetails)==null?void 0:Ve.cacheReadTokens}}))}catch(De){nt.error(De)}finally{st.end()}}}),it=iC();this.addStream=it.addStream,this.closeStream=it.close;const qr=it.stream.getReader();let dr=new ReadableStream({async start(nt){nt.enqueue({type:"start"})},async pull(nt){function ht(){Q?.({steps:fe}),nt.enqueue({type:"abort",...a?.reason!==void 0?{reason:co(a.reason)}:{}}),nt.close()}try{const{done:Ut,value:hr}=await qr.read();if(Ut){nt.close();return}if(a?.aborted){ht();return}nt.enqueue(hr)}catch(Ut){zn(Ut)&&a?.aborted?ht():nt.error(Ut)}},cancel(nt){return it.stream.cancel(nt)}});for(const nt of w)dr=dr.pipeThrough(nt({tools:f,stopStream(){it.terminate()}}));this.baseStream=dr.pipeThrough(dC(I??Es())).pipeThrough(tr);const{maxRetries:rr,retry:Lr}=Vm({maxRetries:o,abortSignal:a}),pr=Lm(t),P=_c(n),X=qm({model:e,telemetry:t,headers:r,settings:{...P,maxRetries:rr}}),Ie=this,We={provider:e.provider,modelId:e.modelId},ln={functionId:t?.functionId,metadata:t?.metadata};ha({name:"ai.streamText",attributes:vr({telemetry:t,attributes:{...pa({operationId:"ai.streamText",telemetry:t}),...X,"ai.prompt":{input:()=>JSON.stringify({system:u,prompt:h,messages:p})}}}),tracer:pr,endWhenDone:!1,fn:async nt=>{st=nt;const ht=await Am({system:u,prompt:h,messages:p,allowSystemInMessages:m});await xr({event:{model:We,system:u,prompt:h,messages:p,tools:f,toolChoice:b,activeTools:C,maxOutputTokens:P.maxOutputTokens,temperature:P.temperature,topP:P.topP,topK:P.topK,presencePenalty:P.presencePenalty,frequencyPenalty:P.frequencyPenalty,stopSequences:P.stopSequences,seed:P.seed,maxRetries:rr,timeout:R,headers:r,providerOptions:y,stopWhen:x,output:I,abortSignal:N,include:O,...ln,experimental_context:B},callbacks:[re,G.onStart]});const Ut=ht.messages,hr=[],{approvedToolApprovals:jr,deniedToolApprovals:Dr}=Zm({messages:Ut});if(Dr.length>0||jr.length>0){const{approvedToolApprovals:Ve,deniedToolApprovals:De}=await Xm({approvedToolApprovals:jr.filter(Ee=>!Ee.toolCall.providerExecuted),tools:f,messages:Ut,experimental_context:B,toolApprovalSecret:F}),ft=[...Dr.filter(Ee=>!Ee.toolCall.providerExecuted),...De],Me=Dr.filter(Ee=>Ee.toolCall.providerExecuted);let Ue;const xn=new ReadableStream({start(Ee){Ue=Ee}});Ie.addStream(xn);try{for(const lt of[...ft,...Me])Ue?.enqueue({type:"tool-output-denied",toolCallId:lt.toolCall.toolCallId,toolName:lt.toolCall.toolName});const Ee=[];if(await Promise.all(Ve.map(async lt=>{const mt=await bc({toolCall:lt.toolCall,tools:f,tracer:pr,telemetry:t,messages:Ut,abortSignal:a,experimental_context:B,stepNumber:fe.length,model:We,onToolCallStart:[H,G.onToolCallStart],onToolCallFinish:[D,G.onToolCallFinish],onPreliminaryToolResult:zt=>{Ue?.enqueue(zt)}});mt!=null&&(Ue?.enqueue(mt),Ee.push(mt))})),Ee.length>0||ft.length>0){const lt=[];for(const mt of Ee)lt.push({type:"tool-result",toolCallId:mt.toolCallId,toolName:mt.toolName,output:await da({toolCallId:mt.toolCallId,input:mt.input,tool:f?.[mt.toolName],output:mt.type==="tool-result"?mt.output:mt.error,errorMode:mt.type==="tool-error"?"text":"none"})});for(const mt of ft)lt.push({type:"tool-result",toolCallId:mt.toolCall.toolCallId,toolName:mt.toolCall.toolName,output:{type:"execution-denied",reason:mt.approvalResponse.reason}});hr.push({role:"tool",content:lt})}}finally{Ue?.close()}}V.push(...hr);async function ie({currentStep:Ve,responseMessages:De,usage:ft}){var Me,Ue,xn,Ee,lt,mt,zt,Bt,Ne;const nr=Ie.includeRawChunks,En=i!=null?setTimeout(()=>s.abort(),i):void 0;let cn;function al(){l!=null&&(cn!=null&&clearTimeout(cn),cn=setTimeout(()=>c.abort(),l))}function $n(){cn!=null&&(clearTimeout(cn),cn=void 0)}function so(){En!=null&&clearTimeout(En)}try{Y=new ra;const Rn=[...Ut,...De],Tt=await _?.({model:e,steps:fe,stepNumber:fe.length,messages:Rn,experimental_context:B}),Ur=Cs((Me=Tt?.model)!=null?Me:e),Pn={provider:Ur.provider,modelId:Ur.modelId},Uo=await xm({prompt:{system:(Ue=Tt?.system)!=null?Ue:ht.system,messages:(xn=Tt?.messages)!=null?xn:Rn},supportedUrls:await Ur.supportedUrls,download:$}),sl=(Ee=Tt?.activeTools)!=null?Ee:C,{toolChoice:io,tools:Ua}=await Rm({tools:f,toolChoice:(lt=Tt?.toolChoice)!=null?lt:b,activeTools:sl});B=(mt=Tt?.experimental_context)!=null?mt:B;const Nd=(zt=Tt?.messages)!=null?zt:Rn,qd=(Bt=Tt?.system)!=null?Bt:ht.system,za=Is(y,Tt?.providerOptions);await xr({event:{stepNumber:fe.length,model:Pn,system:qd,messages:Nd,tools:f,toolChoice:io,activeTools:sl,steps:[...fe],providerOptions:za,timeout:R,headers:r,stopWhen:x,output:I,abortSignal:N,include:O,...ln,experimental_context:B},callbacks:[Se,G.onStepStart]});const{result:{stream:Re,response:Jt,request:Gr},doStreamSpan:Ft,startTimestampMs:Fa}=await Lr(()=>ha({name:"ai.streamText.doStream",attributes:vr({telemetry:t,attributes:{...pa({operationId:"ai.streamText.doStream",telemetry:t}),...X,"ai.model.provider":Ur.provider,"ai.model.id":Ur.modelId,"ai.prompt.messages":{input:()=>Dm(Uo)},"ai.prompt.tools":{input:()=>Ua?.map(ke=>JSON.stringify(ke))},"ai.prompt.toolChoice":{input:()=>io!=null?JSON.stringify(io):void 0},"gen_ai.system":Ur.provider,"gen_ai.request.model":Ur.modelId,"gen_ai.request.frequency_penalty":P.frequencyPenalty,"gen_ai.request.max_tokens":P.maxOutputTokens,"gen_ai.request.presence_penalty":P.presencePenalty,"gen_ai.request.stop_sequences":P.stopSequences,"gen_ai.request.temperature":P.temperature,"gen_ai.request.top_k":P.topK,"gen_ai.request.top_p":P.topP}}),tracer:pr,endWhenDone:!1,fn:async ke=>({startTimestampMs:S(),doStreamSpan:ke,result:await Ur.doStream({...P,tools:Ua,toolChoice:io,responseFormat:await I?.responseFormat,prompt:Uo,providerOptions:za,abortSignal:a,headers:r,includeRawChunks:nr})})})),il=lC({tools:f,generatorStream:Re,tracer:pr,telemetry:t,system:u,messages:Rn,repairToolCall:v,abortSignal:a,experimental_context:B,toolApprovalSecret:F,generateId:E,stepNumber:fe.length,model:Pn,onToolCallStart:[H,G.onToolCallStart],onToolCallFinish:[D,G.onToolCallFinish]}),ll=(Ne=O?.requestBody)==null||Ne?Gr??{}:{...Gr,body:void 0},Mn=[],On=[];let zo;const Qe={};let fr="other",Va,Fo=!1,p1=!1,Gt=wc(),h1,f1=!0,Wr={id:E(),timestamp:new Date,modelId:We.modelId},UR="";Ie.addStream(il.pipeThrough(new TransformStream({async transform(ke,Mt){var Za,Ha,Ba,Ja,Ga;if(al(),ke.type==="stream-start"){zo=ke.warnings;return}if(f1){const Et=S()-Fa;f1=!1,Ft.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":Et}),Ft.setAttributes({"ai.response.msToFirstChunk":Et}),Mt.enqueue({type:"start-step",request:ll,warnings:zo??[]})}const Vo=ke.type;switch(uC[Vo]&&(p1=!0),Vo){case"tool-approval-request":case"text-start":case"text-end":{Mt.enqueue(ke);break}case"text-delta":{ke.delta.length>0&&(Mt.enqueue({type:"text-delta",id:ke.id,text:ke.delta,providerMetadata:ke.providerMetadata}),UR+=ke.delta);break}case"reasoning-start":case"reasoning-end":{Mt.enqueue(ke);break}case"reasoning-delta":{Mt.enqueue({type:"reasoning-delta",id:ke.id,text:ke.delta,providerMetadata:ke.providerMetadata});break}case"tool-call":{Mt.enqueue(ke),Mn.push(ke);break}case"tool-result":{Mt.enqueue(ke),ke.preliminary||On.push(ke);break}case"tool-error":{Mt.enqueue(ke),On.push(ke);break}case"response-metadata":{Wr={id:(Za=ke.id)!=null?Za:Wr.id,timestamp:(Ha=ke.timestamp)!=null?Ha:Wr.timestamp,modelId:(Ba=ke.modelId)!=null?Ba:Wr.modelId};break}case"finish":{Fo=!0,Gt=ke.usage,fr=ke.finishReason,Va=ke.rawFinishReason,h1=ke.providerMetadata;const Et=S()-Fa;Ft.addEvent("ai.stream.finish"),Ft.setAttributes({"ai.response.msToFinish":Et,"ai.response.avgOutputTokensPerSecond":1e3*((Ja=Gt.outputTokens)!=null?Ja:0)/Et});break}case"file":{Mt.enqueue(ke);break}case"source":{Mt.enqueue(ke);break}case"tool-input-start":{Qe[ke.id]=ke.toolName;const Et=f?.[ke.toolName];Et?.onInputStart!=null&&await Et.onInputStart({toolCallId:ke.id,messages:Rn,abortSignal:a,experimental_context:B}),Mt.enqueue({...ke,dynamic:(Ga=ke.dynamic)!=null?Ga:Et?.type==="dynamic",title:Et?.title});break}case"tool-input-end":{delete Qe[ke.id],Mt.enqueue(ke);break}case"tool-input-delta":{const Et=Qe[ke.id],Zo=f?.[Et];Zo?.onInputDelta!=null&&await Zo.onInputDelta({inputTextDelta:ke.delta,toolCallId:ke.id,messages:Rn,abortSignal:a,experimental_context:B}),Mt.enqueue(ke);break}case"error":{Fo=!0,Mt.enqueue(ke),fr="error";break}case"raw":{nr&&Mt.enqueue(ke);break}default:{const Et=Vo;throw new Error(`Unknown chunk type: ${Et}`)}}},async flush(ke){var Mt,Za,Ha,Ba,Ja,Ga,Vo;if(!Fo&&!p1){ke.enqueue({type:"error",error:new Ts({message:"No output generated. The model stream ended without a finish chunk."})}),Ft.end(),so(),$n(),Ie.closeStream();return}const Et=Mn.length>0?JSON.stringify(Mn):void 0;try{Ft.setAttributes(await vr({telemetry:t,attributes:{"ai.response.finishReason":fr,"ai.response.toolCalls":{output:()=>Et},"ai.response.id":Wr.id,"ai.response.model":Wr.modelId,"ai.response.timestamp":Wr.timestamp.toISOString(),"ai.usage.inputTokens":Gt.inputTokens,"ai.usage.inputTokenDetails.noCacheTokens":(Mt=Gt.inputTokenDetails)==null?void 0:Mt.noCacheTokens,"ai.usage.inputTokenDetails.cacheReadTokens":(Za=Gt.inputTokenDetails)==null?void 0:Za.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":(Ha=Gt.inputTokenDetails)==null?void 0:Ha.cacheWriteTokens,"ai.usage.outputTokens":Gt.outputTokens,"ai.usage.outputTokenDetails.textTokens":(Ba=Gt.outputTokenDetails)==null?void 0:Ba.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":(Ja=Gt.outputTokenDetails)==null?void 0:Ja.reasoningTokens,"ai.usage.totalTokens":Gt.totalTokens,"ai.usage.reasoningTokens":(Ga=Gt.outputTokenDetails)==null?void 0:Ga.reasoningTokens,"ai.usage.cachedInputTokens":(Vo=Gt.inputTokenDetails)==null?void 0:Vo.cacheReadTokens,"gen_ai.response.finish_reasons":[fr],"gen_ai.response.id":Wr.id,"gen_ai.response.model":Wr.modelId,"gen_ai.usage.input_tokens":Gt.inputTokens,"gen_ai.usage.output_tokens":Gt.outputTokens}}))}catch{}ke.enqueue({type:"finish-step",finishReason:fr,rawFinishReason:Va,usage:Gt,providerMetadata:h1,response:{...Wr,headers:Jt?.headers}});const Zo=zm(ft,Gt);await Y.promise;const Ld=fe[fe.length-1];try{Ft.setAttributes(await vr({telemetry:t,attributes:{"ai.response.text":{output:()=>Ld.text},"ai.response.reasoning":{output:()=>Ld.reasoningText},"ai.response.providerMetadata":JSON.stringify(Ld.providerMetadata)}}))}catch{}finally{Ft.end()}const m1=Mn.filter(Vt=>Vt.providerExecuted!==!0),zR=On.filter(Vt=>Vt.providerExecuted!==!0);for(const Vt of Mn){if(Vt.providerExecuted!==!0)continue;const jd=f?.[Vt.toolName];jd?.type==="provider"&&jd.supportsDeferredResults&&(On.some(Dd=>(Dd.type==="tool-result"||Dd.type==="tool-error")&&Dd.toolCallId===Vt.toolCallId)||wt.set(Vt.toolCallId,{toolName:Vt.toolName}))}for(const Vt of On)(Vt.type==="tool-result"||Vt.type==="tool-error")&&wt.delete(Vt.toolCallId);if(so(),$n(),(m1.length>0&&zR.length===m1.length||wt.size>0)&&!await o2({stopConditions:g,steps:fe})){De.push(...await Ic({content:fe[fe.length-1].content,tools:f}));try{await ie({currentStep:Ve+1,responseMessages:De,usage:Zo})}catch(Vt){ke.enqueue({type:"error",error:Vt}),Ie.closeStream()}}else ke.enqueue({type:"finish",finishReason:fr,rawFinishReason:Va,totalUsage:Zo}),Ie.closeStream()}})))}finally{so(),$n()}}await ie({currentStep:0,responseMessages:hr,usage:wc()})}}).catch(nt=>{Ie.addStream(new ReadableStream({start(ht){ht.enqueue({type:"error",error:nt}),ht.close()}})),Ie.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 ma(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){e.type==="text-delta"&&t.enqueue(e.text)}})))}get fullStream(){return ma(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){t.enqueue(e)}})))}rejectResultPromises(e){this._finishReason.isPending()&&this._finishReason.reject(e),this._rawFinishReason.isPending()&&this._rawFinishReason.reject(e),this._totalUsage.isPending()&&this._totalUsage.reject(e),this._steps.isPending()&&this._steps.reject(e)}async consumeStream(e){var t;try{await sC({stream:this.fullStream,onError:r=>{var n;this.rejectResultPromises(r),(n=e?.onError)==null||n.call(e,r)}})}catch(r){this.rejectResultPromises(r),(t=e?.onError)==null||t.call(e,r)}}get experimental_partialOutputStream(){return this.partialOutputStream}get partialOutputStream(){return ma(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 Tr({functionality:`element streams in ${(r=(t=this.outputSpecification)==null?void 0:t.name)!=null?r:"text"} mode`});return ma(this.teeStream().pipeThrough(n))}get output(){return this.finalStep.then(e=>{var t;return((t=this.outputSpecification)!=null?t:Es()).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:a=!1,sendStart:i=!0,sendFinish:s=!0,onError:l=()=>"An error occurred."}={}){const c=t!=null?X5({originalMessages:e,responseMessageId:t}):void 0,u=p=>{var m;const f=(m=this.tools)==null?void 0:m[p.toolName];return f==null?p.dynamic:f?.type==="dynamic"?!0:void 0},h=this.fullStream.pipeThrough(new TransformStream({transform:async(p,m)=>{const f=n?.({part:p}),b=p.type;switch(b){case"text-start":{m.enqueue({type:"text-start",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"text-delta":{m.enqueue({type:"text-delta",id:p.id,delta:p.text,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"text-end":{m.enqueue({type:"text-end",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-start":case"reasoning-end":{o&&m.enqueue({type:b,id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-delta":{o&&m.enqueue({type:"reasoning-delta",id:p.id,delta:p.text,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"file":{m.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":{a&&p.sourceType==="url"&&m.enqueue({type:"source-url",sourceId:p.id,url:p.url,title:p.title,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}}),a&&p.sourceType==="document"&&m.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 w=u(p);m.enqueue({type:"tool-input-start",toolCallId:p.id,toolName:p.toolName,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...p.toolMetadata!=null?{toolMetadata:p.toolMetadata}:{},...w!=null?{dynamic:w}:{},...p.title!=null?{title:p.title}:{}});break}case"tool-input-delta":{m.enqueue({type:"tool-input-delta",toolCallId:p.id,inputTextDelta:p.delta});break}case"tool-call":{const w=u(p);p.invalid?m.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}:{},...p.toolMetadata!=null?{toolMetadata:p.toolMetadata}:{},...w!=null?{dynamic:w}:{},errorText:l(p.error),...p.title!=null?{title:p.title}:{}}):m.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}:{},...p.toolMetadata!=null?{toolMetadata:p.toolMetadata}:{},...w!=null?{dynamic:w}:{},...p.title!=null?{title:p.title}:{}});break}case"tool-approval-request":{m.enqueue({type:"tool-approval-request",approvalId:p.approvalId,toolCallId:p.toolCall.toolCallId,...p.signature!=null?{signature:p.signature}:{}});break}case"tool-result":{const w=u(p);m.enqueue({type:"tool-output-available",toolCallId:p.toolCallId,output:p.output===void 0?null:p.output,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...p.toolMetadata!=null?{toolMetadata:p.toolMetadata}:{},...p.preliminary!=null?{preliminary:p.preliminary}:{},...w!=null?{dynamic:w}:{}});break}case"tool-error":{const w=u(p);m.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}:{},...p.toolMetadata!=null?{toolMetadata:p.toolMetadata}:{},...w!=null?{dynamic:w}:{}});break}case"tool-output-denied":{m.enqueue({type:"tool-output-denied",toolCallId:p.toolCallId});break}case"error":{m.enqueue({type:"error",errorText:l(p.error)});break}case"start-step":{m.enqueue({type:"start-step"});break}case"finish-step":{m.enqueue({type:"finish-step"});break}case"start":{i&&m.enqueue({type:"start",...f!=null?{messageMetadata:f}:{},...c!=null?{messageId:c}:{}});break}case"finish":{s&&m.enqueue({type:"finish",finishReason:p.finishReason,...f!=null?{messageMetadata:f}:{}});break}case"abort":{m.enqueue(p);break}case"tool-input-end":break;case"raw":break;default:{const w=b;throw new Error(`Unknown chunk type: ${w}`)}}f!=null&&b!=="start"&&b!=="finish"&&m.enqueue({type:"message-metadata",messageMetadata:f})}}));return ma(oC({stream:h,messageId:c??t?.(),originalMessages:e,onFinish:r,onError:l}))}pipeUIMessageStreamToResponse(e,{originalMessages:t,generateMessageId:r,onFinish:n,messageMetadata:o,sendReasoning:a,sendSources:i,sendFinish:s,sendStart:l,onError:c,...u}={}){aC({response:e,stream:this.toUIMessageStream({originalMessages:t,generateMessageId:r,onFinish:n,messageMetadata:o,sendReasoning:a,sendSources:i,sendFinish:s,sendStart:l,onError:c}),...u})}pipeTextStreamToResponse(e,t){Y5({response:e,textStream:this.textStream,...t})}toUIMessageStreamResponse({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:o,sendSources:a,sendFinish:i,sendStart:s,onError:l,...c}={}){return Q5({stream:this.toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:o,sendSources:a,sendFinish:i,sendStart:s,onError:l}),...c})}toTextStreamResponse(e){return K5({textStream:this.textStream,...e})}};pe(d(),Jn.optional()),na({prefix:"aiobj",size:24}),na({prefix:"aiobj",size:24});let $c;$c=globalThis.crypto;async function hC(e){return(await $c).getRandomValues(new Uint8Array(e))}async function fC(e){const t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length;let n="";for(;n.length<e;){const o=await hC(e-n.length);for(const a of o)a<r&&(n+=t[a%t.length])}return n}async function mC(e){return await fC(e)}async function gC(e){const t=await(await $c).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function m2(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;const t=await mC(e),r=await gC(t);return{code_verifier:t,code_challenge:r}}var _C="AI_MCPClientError",g2=`vercel.ai.error.${_C}`,yC=Symbol.for(g2),_2,y2,ze=class extends(y2=we,_2=yC,y2){constructor({name:e="MCPClientError",message:t,cause:r,data:n,code:o,statusCode:a,url:i,responseBody:s}){super({name:e,message:t,cause:r}),this[_2]=!0,this.data=n,this.code=o,this.statusCode=a,this.url=i,this.responseBody=s}static isInstance(e){return we.hasMarker(e,g2)}},Co="2025-11-25",vC=[Co,"2025-06-18","2025-03-26","2024-11-05"],wC=ce(pe(d(),Te())),bC=dt({name:d(),version:d(),title:ce(d())}),ga=dt({_meta:ce(T({}).loose())}),Hr=ga,v2=T({method:d(),params:ce(ga)}),w2=T({applyDefaults:ce(_e())}).loose(),kC=dt({experimental:ce(T({}).loose()),logging:ce(T({}).loose()),completions:ce(T({}).loose()),prompts:ce(dt({listChanged:ce(_e())})),resources:ce(dt({subscribe:ce(_e()),listChanged:ce(_e())})),tools:ce(dt({listChanged:ce(_e())})),elicitation:ce(w2)});T({elicitation:ce(w2)}).loose();var TC=Hr.extend({protocolVersion:d(),capabilities:kC,serverInfo:bC,instructions:ce(d())}),Rc=Hr.extend({nextCursor:ce(d())}),CC=T({name:d(),title:ce(d()),description:ce(d()),inputSchema:T({type:M("object"),properties:ce(T({}).loose())}).loose(),outputSchema:ce(T({}).loose()),annotations:ce(T({title:ce(d())}).loose()),_meta:wC}).loose(),SC=Rc.extend({tools:L(CC)}),b2=T({type:M("text"),text:d()}).loose(),k2=T({type:M("image"),data:kh(),mimeType:d()}).loose(),IC=T({uri:d(),name:d(),title:ce(d()),description:ce(d()),mimeType:ce(d()),size:ce(q())}).loose(),xC=Rc.extend({resources:L(IC)}),T2=T({uri:d(),name:ce(d()),title:ce(d()),mimeType:ce(d())}).loose(),C2=T2.extend({text:d()}),S2=T2.extend({blob:kh()}),I2=T({type:M("resource"),resource:ae([C2,S2])}).loose(),x2=T({type:M("resource_link"),uri:d(),name:d(),description:ce(d()),mimeType:ce(d())}).loose(),EC=Hr.extend({content:L(ae([b2,k2,I2,x2])),structuredContent:ce(Te()),isError:_e().default(!1).optional()}).or(Hr.extend({toolResult:Te()})),$C=T({uriTemplate:d(),name:d(),title:ce(d()),description:ce(d()),mimeType:ce(d())}).loose(),RC=Hr.extend({resourceTemplates:L($C)}),PC=Hr.extend({contents:L(ae([C2,S2]))}),MC=T({type:M("ref/prompt"),name:d()}).loose(),OC=T({type:M("ref/resource"),uri:d()}).loose(),AC=T({name:d(),value:d()}).loose();ga.extend({ref:ae([MC,OC]),argument:AC,context:ce(T({arguments:pe(d(),d())}).loose())});var NC=Hr.extend({completion:T({values:L(d()).max(100),total:ce(q().int()),hasMore:ce(_e())}).loose()}),qC=T({name:d(),description:ce(d()),required:ce(_e())}).loose(),LC=T({name:d(),title:ce(d()),description:ce(d()),arguments:ce(L(qC))}).loose(),jC=Rc.extend({prompts:L(LC)}),DC=T({role:ae([M("user"),M("assistant")]),content:ae([b2,k2,I2,x2])}).loose(),UC=Hr.extend({description:ce(d()),messages:L(DC)}),zC=ga.extend({message:d(),requestedSchema:Te()}),E2=v2.extend({method:M("elicitation/create"),params:zC}),FC=Hr.extend({action:ae([M("accept"),M("decline"),M("cancel")]),content:ce(pe(d(),Te()))}),Rs="2.0",VC=T({jsonrpc:M(Rs),id:ae([d(),q().int()])}).merge(v2).strict(),ZC=T({jsonrpc:M(Rs),id:ae([d(),q().int()]),result:Hr}).strict(),HC=T({jsonrpc:M(Rs),id:ae([d(),q().int()]),error:T({code:q().int(),message:d(),data:ce(Te())})}).strict(),BC=T({jsonrpc:M(Rs)}).merge(T({method:d(),params:ce(ga)})).strict(),Pc=ae([VC,BC,ZC,HC]);async function Mc(e){return Pc.parse(await gs({text:e}))}var $2=typeof __PACKAGE_VERSION__<"u"?__PACKAGE_VERSION__:"0.0.0-test",$t=d().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Mh.custom,message:"URL must be parseable",fatal:!0}),Pp}).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"}),R2=T({access_token:d(),id_token:d().optional(),token_type:d(),expires_in:q().optional(),scope:d().optional(),refresh_token:d().optional(),authorization_server:$t.optional(),token_endpoint:$t.optional()}).strip(),JC=T({resource:d().url(),authorization_servers:L($t).optional(),jwks_uri:d().url().optional(),scopes_supported:L(d()).optional(),bearer_methods_supported:L(d()).optional(),resource_signing_alg_values_supported:L(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:_e().optional(),authorization_details_types_supported:L(d()).optional(),dpop_signing_alg_values_supported:L(d()).optional(),dpop_bound_access_tokens_required:_e().optional()}).passthrough(),P2=T({issuer:d(),authorization_endpoint:$t,token_endpoint:$t,registration_endpoint:$t.optional(),scopes_supported:L(d()).optional(),response_types_supported:L(d()),grant_types_supported:L(d()).optional(),code_challenge_methods_supported:L(d()),token_endpoint_auth_methods_supported:L(d()).optional(),token_endpoint_auth_signing_alg_values_supported:L(d()).optional()}).passthrough(),GC=T({issuer:d(),authorization_endpoint:$t,token_endpoint:$t,userinfo_endpoint:$t.optional(),jwks_uri:$t,registration_endpoint:$t.optional(),scopes_supported:L(d()).optional(),response_types_supported:L(d()),grant_types_supported:L(d()).optional(),subject_types_supported:L(d()),id_token_signing_alg_values_supported:L(d()),claims_supported:L(d()).optional(),token_endpoint_auth_methods_supported:L(d()).optional()}).passthrough(),WC=GC.merge(P2.pick({code_challenge_methods_supported:!0})),KC=T({client_id:d(),client_secret:d().optional(),client_id_issued_at:q().optional(),client_secret_expires_at:q().optional(),authorization_server:$t.optional(),token_endpoint:$t.optional()}).strip(),YC=T({redirect_uris:L($t),token_endpoint_auth_method:d().optional(),grant_types:L(d()).optional(),response_types:L(d()).optional(),client_name:d().optional(),client_uri:$t.optional(),logo_uri:$t.optional(),scope:d().optional(),contacts:L(d()).optional(),tos_uri:$t.optional(),policy_uri:d().optional(),jwks_uri:$t.optional(),jwks:ut().optional(),software_id:d().optional(),software_version:d().optional(),software_statement:d().optional()}).strip(),QC=T({error:d(),error_description:d().optional(),error_uri:d().optional()}),XC=YC.merge(KC),eS="AI_MCPClientOAuthError",M2=`vercel.ai.error.${eS}`,tS=Symbol.for(M2),O2,A2,Br=class extends(A2=we,O2=tS,A2){constructor({name:e="MCPClientOAuthError",message:t,cause:r}){super({name:e,message:t,cause:r}),this[O2]=!0}static isInstance(e){return we.hasMarker(e,M2)}},So=class extends Br{};So.errorCode="server_error";var Ps=class extends Br{};Ps.errorCode="invalid_client";var Ms=class extends Br{};Ms.errorCode="invalid_grant";var Os=class extends Br{};Os.errorCode="unauthorized_client";var rS={[So.errorCode]:So,[Ps.errorCode]:Ps,[Ms.errorCode]:Ms,[Os.errorCode]:Os};function nS(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function Oc(e){const t=e.href;return e.pathname==="/"&&t.endsWith("/")?t.slice(0,-1):t}function oS({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+"/",a=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return o.startsWith(a)}var As=class extends Error{constructor(t="Unauthorized"){super(t),this.name="UnauthorizedError"}};function Io(e){return new URL(e).href}function aS(e,t){return{authorizationServerUrl:Io(e),tokenEndpoint:Io(t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e))}}function N2(e,t){return{...e,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function q2(e,t){return{...e,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function L2(e){if(!(!e?.authorization_server||!e.token_endpoint))return{authorizationServerUrl:Io(e.authorization_server),tokenEndpoint:Io(e.token_endpoint)}}async function j2({provider:e,clientInformation:t,tokens:r}){var n;const o=L2(r);if(o)return o;const a=await((n=e.authorizationServerInformation)==null?void 0:n.call(e));return a?{authorizationServerUrl:Io(a.authorizationServerUrl),tokenEndpoint:Io(a.tokenEndpoint)}:L2(t)}async function sS({provider:e,clientInformation:t,authorizationServerInformation:r}){return e.saveAuthorizationServerInformation?(await e.saveAuthorizationServerInformation(r),!0):e.saveClientInformation?(await e.saveClientInformation(q2(t,r)),!0):!1}function iS(e,t){if(!t)return;const r=new URL(e).origin;if(t.origin!==r)throw new Br({message:`OAuth protected resource metadata URL ${t.href} must have the same origin as the MCP server URL ${r}`})}function D2({storedAuthorizationServerInformation:e,currentAuthorizationServerInformation:t}){if(e.authorizationServerUrl!==t.authorizationServerUrl||e.tokenEndpoint!==t.tokenEndpoint)throw new Br({message:"OAuth authorization server metadata does not match the metadata that issued the stored credentials"})}function Ns(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 a=/resource_metadata="([^"]*)"/,i=r.match(a);if(i)try{return new URL(i[1])}catch{return}}function lS(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Ac(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?Ac(e,void 0,r):void 0;throw n}}async function U2(e,t,r=fetch){return await Ac(e,{"MCP-Protocol-Version":t},r)}function cS(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function uS(e,t,r,n){var o,a;const i=new URL(e),s=(o=n?.protocolVersion)!=null?o:Co;let l;if(n?.metadataUrl)l=new URL(n.metadataUrl);else{const u=lS(t,i.pathname);l=new URL(u,(a=n?.metadataServerUrl)!=null?a:i),l.search=i.search}let c=await U2(l,s,r);if(!n?.metadataUrl&&cS(c,i.pathname)){const u=new URL(`/.well-known/${t}`,i);c=await U2(u,s,r)}return c}async function dS(e,t,r=fetch){const n=await uS(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 JC.parse(await n.json())}function pS(e){const t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",n=t.origin,o=[];if(!r)return o.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth",expectedIssuer:n}),o.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc",expectedIssuer:n}),o;let a=t.pathname;a.endsWith("/")&&(a=a.slice(0,-1));const i=`${t.origin}${a}`;return o.push({url:new URL(`/.well-known/oauth-authorization-server${a}`,t.origin),type:"oauth",expectedIssuer:i}),o.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth",expectedIssuer:n}),o.push({url:new URL(`/.well-known/openid-configuration${a}`,t.origin),type:"oidc",expectedIssuer:i}),o.push({url:new URL(`${a}/.well-known/openid-configuration`,t.origin),type:"oidc",expectedIssuer:i}),o}function z2(e,t){if(e.issuer!==t)throw new Br({message:`OAuth authorization server metadata issuer ${e.issuer} does not match expected issuer ${t}`})}async function hS(e,{fetchFn:t=fetch,protocolVersion:r=Co}={}){var n;const o={"MCP-Protocol-Version":r},a=pS(e);for(const{url:i,type:s,expectedIssuer:l}of a){const c=await Ac(i,o,t);if(c){if(!c.ok){if(c.status>=400&&c.status<500)continue;throw new Error(`HTTP ${c.status} trying to load ${s==="oauth"?"OAuth":"OpenID provider"} metadata from ${i}`)}if(s==="oauth"){const u=P2.parse(await c.json());return z2(u,l),u}else{const u=WC.parse(await c.json());if(z2(u,l),!((n=u.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 u}}}}async function fS(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:o,state:a,resource:i}){const s="code",l="S256";let c;if(t){if(c=new URL(t.authorization_endpoint),!t.response_types_supported.includes(s))throw new Error(`Incompatible auth server: does not support response type ${s}`);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 m2(),h=u.code_verifier,p=u.code_challenge;return c.searchParams.set("response_type",s),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)),a&&c.searchParams.set("state",a),o&&c.searchParams.set("scope",o),o?.includes("offline_access")&&c.searchParams.append("prompt","consent"),i&&c.searchParams.set("resource",Oc(i)),{authorizationUrl:c,codeVerifier:h}}function F2(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 V2(e,t,r,n){const{client_id:o,client_secret:a}=t;switch(e){case"client_secret_basic":mS(o,a,r);return;case"client_secret_post":gS(o,a,n);return;case"none":_S(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function mS(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 gS(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function _S(e,t){t.set("client_id",e)}async function Nc(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=QC.parse(await gs({text:r})),{error:o,error_description:a,error_uri:i}=n,s=rS[o]||So;return new s({message:a||"",cause:i})}catch(n){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new So({message:o})}}async function yS(e,{metadata:t,clientInformation:r,authorizationCode:n,codeVerifier:o,redirectUri:a,resource:i,addClientAuthentication:s,fetchFn:l}){var c;const u="authorization_code",h=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"}),m=new URLSearchParams({grant_type:u,code:n,code_verifier:o,redirect_uri:String(a)});if(s)await s(p,m,e,t);else{const b=(c=t?.token_endpoint_auth_methods_supported)!=null?c:[],w=F2(r,b);V2(w,r,p,m)}i&&m.set("resource",Oc(i));const f=await(l??fetch)(h,{method:"POST",headers:p,body:m});if(!f.ok)throw await Nc(f);return R2.parse(await f.json())}async function vS(e,{metadata:t,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:a,fetchFn:i}){var s;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"}),h=new URLSearchParams({grant_type:l,refresh_token:n});if(a)await a(u,h,e,t);else{const m=(s=t?.token_endpoint_auth_methods_supported)!=null?s:[],f=F2(r,m);V2(f,r,u,h)}o&&h.set("resource",Oc(o));const p=await(i??fetch)(c,{method:"POST",headers:u,body:h});if(!p.ok)throw await Nc(p);return R2.parse({refresh_token:n,...await p.json()})}async function wS(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 a=await(n??fetch)(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!a.ok)throw await Nc(a);return XC.parse(await a.json())}async function qc(e,t){var r,n;try{return await Lc(e,t)}catch(o){if(o instanceof Ps||o instanceof Os)return await((r=e.invalidateCredentials)==null?void 0:r.call(e,"all")),await Lc(e,t);if(o instanceof Ms)return await((n=e.invalidateCredentials)==null?void 0:n.call(e,"tokens")),await Lc(e,t);throw o}}async function bS(e,t,r){const n=nS(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!oS({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 Lc(e,{serverUrl:t,authorizationCode:r,callbackState:n,scope:o,resourceMetadataUrl:a,fetchFn:i}){var s,l;let c,u;iS(t,a);try{c=await dS(t,{resourceMetadataUrl:a},i),c.authorization_servers&&c.authorization_servers.length>0&&(u=c.authorization_servers[0])}catch{}u||(u=t);const h=await bS(t,e,c);await((s=e.validateAuthorizationServerURL)==null?void 0:s.call(e,t,u));const p=await hS(u,{fetchFn:i}),m=aS(u,p);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 I=await wS(u,{metadata:p,clientMetadata:e.clientMetadata,fetchFn:i});f=q2(I,m),await e.saveClientInformation(f)}if(r!==void 0){if(e.storedState){const k=await e.storedState();if(k!==void 0&&k!==n)throw new Error("OAuth state parameter mismatch - possible CSRF attack")}const I=await j2({provider:e,clientInformation:f});if(!I)throw new Br({message:"Stored OAuth authorization server metadata is required when exchanging an authorization code"});D2({storedAuthorizationServerInformation:I,currentAuthorizationServerInformation:m});const y=await e.codeVerifier(),_=await yS(u,{metadata:p,clientInformation:f,authorizationCode:r,codeVerifier:y,redirectUri:e.redirectUrl,resource:h,addClientAuthentication:e.addClientAuthentication,fetchFn:i});return await e.saveTokens(N2(_,m)),"AUTHORIZED"}const b=await e.tokens();if(b?.refresh_token){const I=await j2({provider:e,clientInformation:f,tokens:b});I?D2({storedAuthorizationServerInformation:I,currentAuthorizationServerInformation:m}):await((l=e.invalidateCredentials)==null?void 0:l.call(e,"tokens"));try{if(I){const y=await vS(u,{metadata:p,clientInformation:f,refreshToken:b.refresh_token,resource:h,addClientAuthentication:e.addClientAuthentication,fetchFn:i});return await e.saveTokens(N2(y,m)),"AUTHORIZED"}}catch(y){if(!(!(y instanceof Br)||y instanceof So))throw y}}const w=e.state?await e.state():void 0;w&&e.saveState&&await e.saveState(w);const{authorizationUrl:C,codeVerifier:v}=await fS(u,{metadata:p,clientInformation:f,state:w,redirectUrl:e.redirectUrl,scope:o||e.clientMetadata.scope,resource:h});if(!await sS({provider:e,clientInformation:f,authorizationServerInformation:m}))throw new Br({message:"OAuth authorization server metadata must be saveable before starting authorization"});return await e.saveCodeVerifier(v),await e.redirectToAuthorization(C),"REDIRECT"}function kS(e){return e===void 0||e==="message"}var TS=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}setProtocolVersion(e){this.protocolVersion=e}async commonHeaders(e){var t;const r={...this.headers,...e,"mcp-protocol-version":(t=this.protocolVersion)!=null?t:Co};if(this.authProvider){const n=await this.authProvider.tokens();n?.access_token&&(r.Authorization=`Bearer ${n.access_token}`)}return _n(r,`ai-sdk/${$2}`,oa())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;const r=async(n=!1)=>{var o,a,i,s,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=Ns(u);try{if(await qc(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!=="AUTHORIZED"){const b=new As;return(a=this.onerror)==null||a.call(this,b),t(b)}}catch(f){return(i=this.onerror)==null||i.call(this,f),t(f)}return r(!0)}if(!u.ok||!u.body){let f=`MCP SSE Transport Error: ${u.status} ${u.statusText}`;u.status===405&&(f+=". This server does not support SSE transport. Try using `http` transport instead");const b=new ze({message:f});return(s=this.onerror)==null||s.call(this,b),t(b)}const p=u.body.pipeThrough(new TextDecoderStream).pipeThrough(new _o).getReader(),m=async()=>{var f,b,w,C,v;try{for(;;){const{done:g,value:I}=await p.read();if(g){if(this.connected)throw this.connected=!1,new ze({message:"MCP SSE Transport Error: Connection closed unexpectedly"});return}const{event:y,data:_}=I;if(y==="endpoint"){if(this.endpoint)continue;const k=new URL(_,this.url);if(k.origin!==this.url.origin)throw this.connected=!1,this.endpoint=void 0,(f=this.sseConnection)==null||f.close(),(b=this.abortController)==null||b.abort(),new ze({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${k.origin}`});this.endpoint=k,this.connected=!0,e()}else if(kS(y))try{const k=await Mc(_);(w=this.onmessage)==null||w.call(this,k)}catch(k){const S=new ze({message:"MCP SSE Transport Error: Failed to parse message",cause:k});(C=this.onerror)==null||C.call(this,S)}}}catch(g){if(g instanceof Error&&g.name==="AbortError")return;(v=this.onerror)==null||v.call(this,g),t(g)}};this.sseConnection={close:()=>p.cancel()},m()}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,this.endpoint=void 0,(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 ze({message:"MCP SSE Transport Error: Not connected"});const t=this.endpoint,r=async(n=!1)=>{var o,a,i,s,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},h=await this.fetchFn(t.href,u);if(h.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=Ns(h);try{if(await qc(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!=="AUTHORIZED"){const m=new As;(a=this.onerror)==null||a.call(this,m);return}}catch(p){(i=this.onerror)==null||i.call(this,p);return}return r(!0)}if(!h.ok){const p=await h.text().catch(()=>null),m=new ze({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${h.status}): ${p}`});(s=this.onerror)==null||s.call(this,m);return}}catch(c){(l=this.onerror)==null||l.call(this,c);return}};await r()}};function Z2(e){return e===void 0||e==="message"}var CS=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}setProtocolVersion(e){this.protocolVersion=e}async commonHeaders(e){var t;const r={...this.headers,...e,"mcp-protocol-version":(t=this.protocolVersion)!=null?t:Co};if(this.sessionId&&(r["mcp-session-id"]=this.sessionId),this.authProvider){const n=await this.authProvider.tokens();n?.access_token&&(r.Authorization=`Bearer ${n.access_token}`)}return _n(r,`ai-sdk/${$2}`,oa())}authorizeOnce(e){return this.authProvider?(this.authPromise||(this.authPromise=qc(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:e,fetchFn:this.fetchFn}).finally(()=>{this.authPromise=void 0})),this.authPromise):Promise.resolve("REDIRECT")}async start(){if(this.abortController)throw new ze({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,a,i,s,l,c;try{const h={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,h),m=p.headers.get("mcp-session-id");if(m&&(this.sessionId=m),p.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=Ns(p);try{if(await this.authorizeOnce(this.resourceMetadataUrl)!=="AUTHORIZED")throw new As}catch(C){throw(o=this.onerror)==null||o.call(this,C),C}return t(!0)}if(p.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!p.ok){const C=await p.text().catch(()=>null);let v=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${p.status}): ${C}`;p.status===404&&(v+=". This server does not support HTTP transport. Try using `sse` transport instead");const g=new ze({message:v,statusCode:p.status,url:this.url.href,responseBody:C??void 0});throw(a=this.onerror)==null||a.call(this,g),g}if(!("id"in e))return;const b=p.headers.get("content-type")||"";if(b.includes("application/json")){const C=await p.json(),v=Array.isArray(C)?C.map(g=>Pc.parse(g)):[Pc.parse(C)];for(const g of v)(i=this.onmessage)==null||i.call(this,g);return}if(b.includes("text/event-stream")){if(!p.body){const I=new ze({message:"MCP HTTP Transport Error: text/event-stream response without body",statusCode:p.status,url:this.url.href});throw(s=this.onerror)==null||s.call(this,I),I}const v=p.body.pipeThrough(new TextDecoderStream).pipeThrough(new _o).getReader();(async()=>{var I,y,_;try{for(;;){const{done:k,value:S}=await v.read();if(k)return;const{event:E,data:R}=S;if(Z2(E))try{const x=await Mc(R);(I=this.onmessage)==null||I.call(this,x)}catch(x){const N=new ze({message:"MCP HTTP Transport Error: Failed to parse message",cause:x});(y=this.onerror)==null||y.call(this,N)}}}catch(k){if(k instanceof Error&&k.name==="AbortError")return;(_=this.onerror)==null||_.call(this,k)}})();return}const w=new ze({message:`MCP HTTP Transport Error: Unexpected content type: ${b}`,statusCode:p.status,url:this.url.href});throw(l=this.onerror)==null||l.call(this,w),w}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 ze({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,a,i,s;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=Ns(c);try{if(await this.authorizeOnce(this.resourceMetadataUrl)!=="AUTHORIZED"){const b=new As;(n=this.onerror)==null||n.call(this,b);return}}catch(f){(o=this.onerror)==null||o.call(this,f);return}return this.openInboundSse(!0,t)}if(c.status===405)return;if(!c.ok||!c.body){const f=new ze({message:`MCP HTTP Transport Error: GET SSE failed: ${c.status} ${c.statusText}`,statusCode:c.status,url:this.url.href});(a=this.onerror)==null||a.call(this,f);return}const p=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new _o).getReader(),m=async()=>{var f,b,w,C;try{for(;;){const{done:v,value:g}=await p.read();if(v)return;const{event:I,data:y,id:_}=g;if(_&&(this.lastInboundEventId=_),Z2(I))try{const k=await Mc(y);(f=this.onmessage)==null||f.call(this,k)}catch(k){const S=new ze({message:"MCP HTTP Transport Error: Failed to parse message",cause:k});(b=this.onerror)==null||b.call(this,S)}}}catch(v){if(v instanceof Error&&v.name==="AbortError")return;(w=this.onerror)==null||w.call(this,v),(C=this.abortController)!=null&&C.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>p.cancel()},this.inboundReconnectAttempts=0,m()}catch(l){if(l instanceof Error&&l.name==="AbortError")return;(i=this.onerror)==null||i.call(this,l),(s=this.abortController)!=null&&s.signal.aborted||this.scheduleInboundSseReconnection()}}};function SS(e){switch(e.type){case"sse":return new TS(e);case"http":return new CS(e);default:throw new ze({message:"Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface."})}}function IS(e){return"start"in e&&typeof e.start=="function"&&"send"in e&&typeof e.send=="function"&&"close"in e&&typeof e.close=="function"}var xS="1.0.0";function H2({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 ES(e){const t=new $S(e);return await t.init(),t}var $S=class{constructor({transport:e,name:t,clientName:r=t??"ai-sdk-mcp-client",version:n=xS,onUncaughtError:o,capabilities:a}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this._serverInfo={name:"",version:""},this.isClosed=!0,this.onUncaughtError=o,this.clientCapabilities=a??{},IS(e)?this.transport=e:this.transport=SS(e),this.transport.onclose=()=>this.onClose(),this.transport.onerror=i=>this.onError(i),this.transport.onmessage=i=>{if("method"in i){"id"in i?this.onRequestMessage(i):this.onError(new ze({message:"Unsupported message type"}));return}this.onResponse(i)},this.clientInfo={name:r,version:n}}get serverInfo(){return this._serverInfo}get instructions(){return this._serverInstructions}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:TC});if(e===void 0)throw new ze({message:"Server sent invalid initialize result"});if(!vC.includes(e.protocolVersion))throw new ze({message:`Server's protocol version is not supported: ${e.protocolVersion}`});return this.serverCapabilities=e.capabilities,this._serverInfo=e.serverInfo,this.transport.setProtocolVersion?this.transport.setProtocolVersion(e.protocolVersion):this.transport.protocolVersion=e.protocolVersion,this._serverInstructions=e.instructions,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"completion/complete":if(!this.serverCapabilities.completions)throw new ze({message:"Server does not support completions"});break;case"tools/list":case"tools/call":if(!this.serverCapabilities.tools)throw new ze({message:"Server does not support tools"});break;case"resources/list":case"resources/read":case"resources/templates/list":if(!this.serverCapabilities.resources)throw new ze({message:"Server does not support resources"});break;case"prompts/list":case"prompts/get":if(!this.serverCapabilities.prompts)throw new ze({message:"Server does not support prompts"});break;default:throw new ze({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:r}){return new Promise((n,o)=>{if(this.isClosed)return o(new ze({message:"Attempted to send a request from a closed client"}));this.assertCapability(e.method);const a=r?.signal;a?.throwIfAborted();const i=this.requestMessageId++,s={...e,jsonrpc:"2.0",id:i},l=()=>{this.responseHandlers.delete(i)};this.responseHandlers.set(i,c=>{if(a?.aborted)return o(new ze({message:"Request was aborted",cause:a.reason}));if(c instanceof Error)return o(c);try{const u=t.parse(c.result);n(u)}catch(u){const h=new ze({message:"Failed to parse server response",cause:u});o(h)}}),this.transport.send(s).catch(c=>{l(),o(c)})})}async listTools({params:e,options:t}={}){return this.request({request:{method:"tools/list",params:e},resultSchema:SC,options:t})}async callTool({name:e,args:t,options:r}){try{return this.request({request:{method:"tools/call",params:{name:e,arguments:t}},resultSchema:EC,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:xC,options:t})}catch(r){throw r}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:"resources/read",params:{uri:e}},resultSchema:PC,options:t})}catch(r){throw r}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:"resources/templates/list"},resultSchema:RC,options:e})}catch(t){throw t}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:"prompts/list",params:e},resultSchema:jC,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:UC,options:r})}catch(n){throw n}}async completeInternal({options:e,...t}){return this.request({request:{method:"completion/complete",params:t},resultSchema:NC,options:e})}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:a,title:i,description:s,inputSchema:l,annotations:c,_meta:u}of e.tools){const h=i??c?.title;if(t!=="automatic"&&!Object.prototype.hasOwnProperty.call(t,a))continue;const p=this,m=t!=="automatic"?(r=t[a])==null?void 0:r.outputSchema:void 0,f=async(w,C)=>{var v;(v=C?.abortSignal)==null||v.throwIfAborted();const g=await p.callTool({name:a,args:w,options:C});return g.isError?g:m!=null?p.extractStructuredContent(g,m,a):g},b=t==="automatic"?Zl({description:s,title:h,metadata:{clientName:this.clientInfo.name},inputSchema:Vn({...l,properties:(n=l.properties)!=null?n:{},additionalProperties:!1}),execute:f,toModelOutput:H2}):{description:s,title:h,metadata:{clientName:this.clientInfo.name},inputSchema:t[a].inputSchema,...m!=null?{outputSchema:m}:{},execute:f,toModelOutput:H2};o[a]={...b,_meta:u}}return o}async extractStructuredContent(e,t,r){if("structuredContent"in e&&e.structuredContent!=null){const n=await ar({value:e.structuredContent,schema:yn(t)});if(!n.success)throw new ze({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 gr({text:n.text,schema:t});if(!o.success)throw new ze({message:`Tool "${r}" returned content that does not match the expected outputSchema`,cause:o.error});return o.value}}throw new ze({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})}complete(e){return this.completeInternal(e)}onElicitationRequest(e,t){if(e!==E2)throw new ze({message:"Unsupported request schema. Only ElicitationRequestSchema is supported."});this.elicitationRequestHandler=t}async onRequestMessage(e){try{if(e.method==="ping"){await this.transport.send({jsonrpc:"2.0",id:e.id,result:{}});return}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=E2.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=FC.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 ze({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 ze({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),r("result"in e?e:new ze({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}};function qs(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function B2(e=fetch,t){return t?async(r,n)=>{const o={...t,...n,headers:n?.headers?{...qs(t.headers),...qs(n.headers)}:t.headers};return e(r,o)}:e}const Ls="2025-11-25",RS=[Ls,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Gn="io.modelcontextprotocol/related-task",js="2.0",Nt=Rh(e=>e!==null&&(typeof e=="object"||typeof e=="function")),J2=ae([d(),q().int()]),G2=d();dt({ttl:ae([q(),Qo()]).optional(),pollInterval:q().optional()});const PS=T({ttl:q().optional()}),MS=T({taskId:d()}),jc=dt({progressToken:J2.optional(),[Gn]:MS.optional()}),cr=T({_meta:jc.optional()}),_a=cr.extend({task:PS.optional()}),OS=e=>_a.safeParse(e).success,qt=T({method:d(),params:cr.loose().optional()}),wr=T({_meta:jc.optional()}),br=T({method:d(),params:wr.loose().optional()}),Lt=dt({_meta:jc.optional()}),Ds=ae([d(),q().int()]),W2=T({jsonrpc:M(js),id:Ds,...qt.shape}).strict(),Dc=e=>W2.safeParse(e).success,K2=T({jsonrpc:M(js),...br.shape}).strict(),AS=e=>K2.safeParse(e).success,Uc=T({jsonrpc:M(js),id:Ds,result:Lt}).strict(),ya=e=>Uc.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 zc=T({jsonrpc:M(js),id:Ds.optional(),error:T({code:q().int(),message:d(),data:Te().optional()})}).strict(),NS=e=>zc.safeParse(e).success,Wn=ae([W2,K2,Uc,zc]);ae([Uc,zc]);const Kn=Lt.strict(),qS=wr.extend({requestId:Ds.optional(),reason:d().optional()}),Fc=br.extend({method:M("notifications/cancelled"),params:qS}),LS=T({src:d(),mimeType:d().optional(),sizes:L(d()).optional(),theme:le(["light","dark"]).optional()}),va=T({icons:L(LS).optional()}),xo=T({name:d(),title:d().optional()}),Y2=xo.extend({...xo.shape,...va.shape,version:d(),websiteUrl:d().optional(),description:d().optional()}),jS=vl(T({applyDefaults:_e().optional()}),pe(d(),Te())),DS=Ph(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,vl(T({form:jS.optional(),url:Nt.optional()}),pe(d(),Te()).optional())),US=dt({list:Nt.optional(),cancel:Nt.optional(),requests:dt({sampling:dt({createMessage:Nt.optional()}).optional(),elicitation:dt({create:Nt.optional()}).optional()}).optional()}),zS=dt({list:Nt.optional(),cancel:Nt.optional(),requests:dt({tools:dt({call:Nt.optional()}).optional()}).optional()}),FS=T({experimental:pe(d(),Nt).optional(),sampling:T({context:Nt.optional(),tools:Nt.optional()}).optional(),elicitation:DS.optional(),roots:T({listChanged:_e().optional()}).optional(),tasks:US.optional()}),VS=cr.extend({protocolVersion:d(),capabilities:FS,clientInfo:Y2}),ZS=qt.extend({method:M("initialize"),params:VS}),HS=T({experimental:pe(d(),Nt).optional(),logging:Nt.optional(),completions:Nt.optional(),prompts:T({listChanged:_e().optional()}).optional(),resources:T({subscribe:_e().optional(),listChanged:_e().optional()}).optional(),tools:T({listChanged:_e().optional()}).optional(),tasks:zS.optional()}),Q2=Lt.extend({protocolVersion:d(),capabilities:HS,serverInfo:Y2,instructions:d().optional()}),X2=br.extend({method:M("notifications/initialized"),params:wr.optional()}),BS=e=>X2.safeParse(e).success,Vc=qt.extend({method:M("ping"),params:cr.optional()}),JS=T({progress:q(),total:ce(q()),message:ce(d())}),GS=T({...wr.shape,...JS.shape,progressToken:J2}),Zc=br.extend({method:M("notifications/progress"),params:GS}),WS=cr.extend({cursor:G2.optional()}),wa=qt.extend({params:WS.optional()}),ba=Lt.extend({nextCursor:G2.optional()}),KS=le(["working","input_required","completed","failed","cancelled"]),ka=T({taskId:d(),status:KS,ttl:ae([q(),Qo()]),createdAt:d(),lastUpdatedAt:d(),pollInterval:ce(q()),statusMessage:ce(d())}),Ta=Lt.extend({task:ka}),YS=wr.merge(ka),Us=br.extend({method:M("notifications/tasks/status"),params:YS}),Hc=qt.extend({method:M("tasks/get"),params:cr.extend({taskId:d()})}),Bc=Lt.merge(ka),Jc=qt.extend({method:M("tasks/result"),params:cr.extend({taskId:d()})});Lt.loose();const Gc=wa.extend({method:M("tasks/list")}),Wc=ba.extend({tasks:L(ka)}),Kc=qt.extend({method:M("tasks/cancel"),params:cr.extend({taskId:d()})}),QS=Lt.merge(ka),eg=T({uri:d(),mimeType:ce(d()),_meta:pe(d(),Te()).optional()}),tg=eg.extend({text:d()}),Yc=d().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),rg=eg.extend({blob:Yc}),Ca=le(["user","assistant"]),Eo=T({audience:L(Ca).optional(),priority:q().min(0).max(1).optional(),lastModified:gh({offset:!0}).optional()}),ng=T({...xo.shape,...va.shape,uri:d(),description:ce(d()),mimeType:ce(d()),annotations:Eo.optional(),_meta:ce(dt({}))}),XS=T({...xo.shape,...va.shape,uriTemplate:d(),description:ce(d()),mimeType:ce(d()),annotations:Eo.optional(),_meta:ce(dt({}))}),eI=wa.extend({method:M("resources/list")}),og=ba.extend({resources:L(ng)}),tI=wa.extend({method:M("resources/templates/list")}),ag=ba.extend({resourceTemplates:L(XS)}),Qc=cr.extend({uri:d()}),rI=Qc,nI=qt.extend({method:M("resources/read"),params:rI}),sg=Lt.extend({contents:L(ae([tg,rg]))}),Xc=br.extend({method:M("notifications/resources/list_changed"),params:wr.optional()}),oI=Qc,aI=qt.extend({method:M("resources/subscribe"),params:oI}),sI=Qc,iI=qt.extend({method:M("resources/unsubscribe"),params:sI}),lI=wr.extend({uri:d()}),ig=br.extend({method:M("notifications/resources/updated"),params:lI}),cI=T({name:d(),description:ce(d()),required:ce(_e())}),uI=T({...xo.shape,...va.shape,description:ce(d()),arguments:ce(L(cI)),_meta:ce(dt({}))}),dI=wa.extend({method:M("prompts/list")}),lg=ba.extend({prompts:L(uI)}),pI=cr.extend({name:d(),arguments:pe(d(),d()).optional()}),hI=qt.extend({method:M("prompts/get"),params:pI}),eu=T({type:M("text"),text:d(),annotations:Eo.optional(),_meta:pe(d(),Te()).optional()}),tu=T({type:M("image"),data:Yc,mimeType:d(),annotations:Eo.optional(),_meta:pe(d(),Te()).optional()}),ru=T({type:M("audio"),data:Yc,mimeType:d(),annotations:Eo.optional(),_meta:pe(d(),Te()).optional()}),fI=T({type:M("tool_use"),name:d(),id:d(),input:pe(d(),Te()),_meta:pe(d(),Te()).optional()}),mI=T({type:M("resource"),resource:ae([tg,rg]),annotations:Eo.optional(),_meta:pe(d(),Te()).optional()}),gI=ng.extend({type:M("resource_link")}),nu=ae([eu,tu,ru,gI,mI]),_I=T({role:Ca,content:nu}),cg=Lt.extend({description:d().optional(),messages:L(_I)}),ou=br.extend({method:M("notifications/prompts/list_changed"),params:wr.optional()}),yI=T({title:d().optional(),readOnlyHint:_e().optional(),destructiveHint:_e().optional(),idempotentHint:_e().optional(),openWorldHint:_e().optional()}),vI=T({taskSupport:le(["required","optional","forbidden"]).optional()}),ug=T({...xo.shape,...va.shape,description:d().optional(),inputSchema:T({type:M("object"),properties:pe(d(),Nt).optional(),required:L(d()).optional()}).catchall(Te()),outputSchema:T({type:M("object"),properties:pe(d(),Nt).optional(),required:L(d()).optional()}).catchall(Te()).optional(),annotations:yI.optional(),execution:vI.optional(),_meta:pe(d(),Te()).optional()}),wI=wa.extend({method:M("tools/list")}),dg=ba.extend({tools:L(ug)}),Sa=Lt.extend({content:L(nu).default([]),structuredContent:pe(d(),Te()).optional(),isError:_e().optional()});Sa.or(Lt.extend({toolResult:Te()}));const bI=_a.extend({name:d(),arguments:pe(d(),Te()).optional()}),kI=qt.extend({method:M("tools/call"),params:bI}),au=br.extend({method:M("notifications/tools/list_changed"),params:wr.optional()}),TI=T({autoRefresh:_e().default(!0),debounceMs:q().int().nonnegative().default(300)}),pg=le(["debug","info","notice","warning","error","critical","alert","emergency"]),CI=cr.extend({level:pg}),SI=qt.extend({method:M("logging/setLevel"),params:CI}),II=wr.extend({level:pg,logger:d().optional(),data:Te()}),hg=br.extend({method:M("notifications/message"),params:II}),xI=T({name:d().optional()}),EI=T({hints:L(xI).optional(),costPriority:q().min(0).max(1).optional(),speedPriority:q().min(0).max(1).optional(),intelligencePriority:q().min(0).max(1).optional()}),$I=T({mode:le(["auto","required","none"]).optional()}),RI=T({type:M("tool_result"),toolUseId:d().describe("The unique identifier for the corresponding tool call."),content:L(nu).default([]),structuredContent:T({}).loose().optional(),isError:_e().optional(),_meta:pe(d(),Te()).optional()}),PI=Le("type",[eu,tu,ru]),zs=Le("type",[eu,tu,ru,fI,RI]),MI=T({role:Ca,content:ae([zs,L(zs)]),_meta:pe(d(),Te()).optional()}),OI=_a.extend({messages:L(MI),modelPreferences:EI.optional(),systemPrompt:d().optional(),includeContext:le(["none","thisServer","allServers"]).optional(),temperature:q().optional(),maxTokens:q().int(),stopSequences:L(d()).optional(),metadata:Nt.optional(),tools:L(ug).optional(),toolChoice:$I.optional()}),su=qt.extend({method:M("sampling/createMessage"),params:OI}),iu=Lt.extend({model:d(),stopReason:ce(le(["endTurn","stopSequence","maxTokens"]).or(d())),role:Ca,content:PI}),fg=Lt.extend({model:d(),stopReason:ce(le(["endTurn","stopSequence","maxTokens","toolUse"]).or(d())),role:Ca,content:ae([zs,L(zs)])}),AI=T({type:M("boolean"),title:d().optional(),description:d().optional(),default:_e().optional()}),NI=T({type:M("string"),title:d().optional(),description:d().optional(),minLength:q().optional(),maxLength:q().optional(),format:le(["email","uri","date","date-time"]).optional(),default:d().optional()}),qI=T({type:le(["number","integer"]),title:d().optional(),description:d().optional(),minimum:q().optional(),maximum:q().optional(),default:q().optional()}),LI=T({type:M("string"),title:d().optional(),description:d().optional(),enum:L(d()),default:d().optional()}),jI=T({type:M("string"),title:d().optional(),description:d().optional(),oneOf:L(T({const:d(),title:d()})),default:d().optional()}),DI=T({type:M("string"),title:d().optional(),description:d().optional(),enum:L(d()),enumNames:L(d()).optional(),default:d().optional()}),UI=ae([LI,jI]),zI=T({type:M("array"),title:d().optional(),description:d().optional(),minItems:q().optional(),maxItems:q().optional(),items:T({type:M("string"),enum:L(d())}),default:L(d()).optional()}),FI=T({type:M("array"),title:d().optional(),description:d().optional(),minItems:q().optional(),maxItems:q().optional(),items:T({anyOf:L(T({const:d(),title:d()}))}),default:L(d()).optional()}),VI=ae([zI,FI]),ZI=ae([DI,UI,VI]),HI=ae([ZI,AI,NI,qI]),BI=_a.extend({mode:M("form").optional(),message:d(),requestedSchema:T({type:M("object"),properties:pe(d(),HI),required:L(d()).optional()})}),JI=_a.extend({mode:M("url"),message:d(),elicitationId:d(),url:d().url()}),GI=ae([BI,JI]),lu=qt.extend({method:M("elicitation/create"),params:GI}),WI=wr.extend({elicitationId:d()}),KI=br.extend({method:M("notifications/elicitation/complete"),params:WI}),cu=Lt.extend({action:le(["accept","decline","cancel"]),content:Ph(e=>e===null?void 0:e,pe(d(),ae([d(),q(),_e(),L(d())])).optional())}),YI=T({type:M("ref/resource"),uri:d()}),QI=T({type:M("ref/prompt"),name:d()}),XI=cr.extend({ref:ae([QI,YI]),argument:T({name:d(),value:d()}),context:T({arguments:pe(d(),d()).optional()}).optional()}),e8=qt.extend({method:M("completion/complete"),params:XI}),mg=Lt.extend({completion:dt({values:L(d()).max(100),total:ce(q().int()),hasMore:ce(_e())})}),t8=T({uri:d().startsWith("file://"),name:d().optional(),_meta:pe(d(),Te()).optional()}),gg=qt.extend({method:M("roots/list"),params:cr.optional()}),_g=Lt.extend({roots:L(t8)}),r8=br.extend({method:M("notifications/roots/list_changed"),params:wr.optional()});ae([Vc,ZS,e8,SI,hI,dI,eI,tI,nI,aI,iI,kI,wI,Hc,Jc,Gc,Kc]),ae([Fc,Zc,X2,r8,Us]),ae([Kn,iu,fg,cu,_g,Bc,Wc,Ta]),ae([Vc,su,lu,gg,Hc,Jc,Gc,Kc]),ae([Fc,Zc,hg,ig,Xc,au,ou,Us,KI]),ae([Kn,Q2,mg,cg,lg,og,ag,sg,Sa,dg,Bc,Wc,Ta]);class Ce 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 n8(o.elicitations,r)}return new Ce(t,r,n)}}class n8 extends Ce{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super($e.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}}const jt=D3().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Mh.custom,message:"URL must be parseable",fatal:!0}),Pp}).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"}),o8=dt({resource:d().url(),authorization_servers:L(jt).optional(),jwks_uri:d().url().optional(),scopes_supported:L(d()).optional(),bearer_methods_supported:L(d()).optional(),resource_signing_alg_values_supported:L(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:_e().optional(),authorization_details_types_supported:L(d()).optional(),dpop_signing_alg_values_supported:L(d()).optional(),dpop_bound_access_tokens_required:_e().optional()}),yg=dt({issuer:d(),authorization_endpoint:jt,token_endpoint:jt,registration_endpoint:jt.optional(),scopes_supported:L(d()).optional(),response_types_supported:L(d()),response_modes_supported:L(d()).optional(),grant_types_supported:L(d()).optional(),token_endpoint_auth_methods_supported:L(d()).optional(),token_endpoint_auth_signing_alg_values_supported:L(d()).optional(),service_documentation:jt.optional(),revocation_endpoint:jt.optional(),revocation_endpoint_auth_methods_supported:L(d()).optional(),revocation_endpoint_auth_signing_alg_values_supported:L(d()).optional(),introspection_endpoint:d().optional(),introspection_endpoint_auth_methods_supported:L(d()).optional(),introspection_endpoint_auth_signing_alg_values_supported:L(d()).optional(),code_challenge_methods_supported:L(d()).optional(),client_id_metadata_document_supported:_e().optional()}),a8=dt({issuer:d(),authorization_endpoint:jt,token_endpoint:jt,userinfo_endpoint:jt.optional(),jwks_uri:jt,registration_endpoint:jt.optional(),scopes_supported:L(d()).optional(),response_types_supported:L(d()),response_modes_supported:L(d()).optional(),grant_types_supported:L(d()).optional(),acr_values_supported:L(d()).optional(),subject_types_supported:L(d()),id_token_signing_alg_values_supported:L(d()),id_token_encryption_alg_values_supported:L(d()).optional(),id_token_encryption_enc_values_supported:L(d()).optional(),userinfo_signing_alg_values_supported:L(d()).optional(),userinfo_encryption_alg_values_supported:L(d()).optional(),userinfo_encryption_enc_values_supported:L(d()).optional(),request_object_signing_alg_values_supported:L(d()).optional(),request_object_encryption_alg_values_supported:L(d()).optional(),request_object_encryption_enc_values_supported:L(d()).optional(),token_endpoint_auth_methods_supported:L(d()).optional(),token_endpoint_auth_signing_alg_values_supported:L(d()).optional(),display_values_supported:L(d()).optional(),claim_types_supported:L(d()).optional(),claims_supported:L(d()).optional(),service_documentation:d().optional(),claims_locales_supported:L(d()).optional(),ui_locales_supported:L(d()).optional(),claims_parameter_supported:_e().optional(),request_parameter_supported:_e().optional(),request_uri_parameter_supported:_e().optional(),require_request_uri_registration:_e().optional(),op_policy_uri:jt.optional(),op_tos_uri:jt.optional(),client_id_metadata_document_supported:_e().optional()}),s8=T({...a8.shape,...yg.pick({code_challenge_methods_supported:!0}).shape}),i8=T({access_token:d(),id_token:d().optional(),token_type:d(),expires_in:Oh().optional(),scope:d().optional(),refresh_token:d().optional()}).strip(),l8=T({error:d(),error_description:d().optional(),error_uri:d().optional()}),vg=jt.optional().or(M("").transform(()=>{})),c8=T({redirect_uris:L(jt),token_endpoint_auth_method:d().optional(),grant_types:L(d()).optional(),response_types:L(d()).optional(),client_name:d().optional(),client_uri:jt.optional(),logo_uri:vg,scope:d().optional(),contacts:L(d()).optional(),tos_uri:vg,policy_uri:d().optional(),jwks_uri:jt.optional(),jwks:ut().optional(),software_id:d().optional(),software_version:d().optional(),software_statement:d().optional()}).strip(),u8=T({client_id:d(),client_secret:d().optional(),client_id_issued_at:q().optional(),client_secret_expires_at:q().optional()}).strip(),d8=c8.merge(u8);T({error:d(),error_description:d().optional()}).strip(),T({token:d(),token_type_hint:d().optional()}).strip();function p8(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function h8({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+"/",a=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return o.startsWith(a)}class Rt 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 uu extends Rt{}uu.errorCode="invalid_request";class Fs extends Rt{}Fs.errorCode="invalid_client";class Vs extends Rt{}Vs.errorCode="invalid_grant";class Zs extends Rt{}Zs.errorCode="unauthorized_client";class du extends Rt{}du.errorCode="unsupported_grant_type";class pu extends Rt{}pu.errorCode="invalid_scope";class hu extends Rt{}hu.errorCode="access_denied";class $o extends Rt{}$o.errorCode="server_error";class fu extends Rt{}fu.errorCode="temporarily_unavailable";class mu extends Rt{}mu.errorCode="unsupported_response_type";class gu extends Rt{}gu.errorCode="unsupported_token_type";class _u extends Rt{}_u.errorCode="invalid_token";class yu extends Rt{}yu.errorCode="method_not_allowed";class vu extends Rt{}vu.errorCode="too_many_requests";class Hs extends Rt{}Hs.errorCode="invalid_client_metadata";class wu extends Rt{}wu.errorCode="insufficient_scope";class bu extends Rt{}bu.errorCode="invalid_target";const f8={[uu.errorCode]:uu,[Fs.errorCode]:Fs,[Vs.errorCode]:Vs,[Zs.errorCode]:Zs,[du.errorCode]:du,[pu.errorCode]:pu,[hu.errorCode]:hu,[$o.errorCode]:$o,[fu.errorCode]:fu,[mu.errorCode]:mu,[gu.errorCode]:gu,[_u.errorCode]:_u,[yu.errorCode]:yu,[vu.errorCode]:vu,[Hs.errorCode]:Hs,[wu.errorCode]:wu,[bu.errorCode]:bu};class kr extends Error{constructor(t){super(t??"Unauthorized")}}function m8(e){return["client_secret_basic","client_secret_post","none"].includes(e)}const ku="code",Tu="S256";function g8(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&&m8(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 _8(e,t,r,n){const{client_id:o,client_secret:a}=t;switch(e){case"client_secret_basic":y8(o,a,r);return;case"client_secret_post":v8(o,a,n);return;case"none":w8(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function y8(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 v8(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function w8(e,t){t.set("client_id",e)}async function wg(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=l8.parse(JSON.parse(r)),{error:o,error_description:a,error_uri:i}=n,s=f8[o]||$o;return new s(a||"",i)}catch(n){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new $o(o)}}async function Yn(e,t){try{return await Cu(e,t)}catch(r){if(r instanceof Fs||r instanceof Zs)return await e.invalidateCredentials?.("all"),await Cu(e,t);if(r instanceof Vs)return await e.invalidateCredentials?.("tokens"),await Cu(e,t);throw r}}async function Cu(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:a}){let i,s;try{i=await T8(t,{resourceMetadataUrl:o},a),i.authorization_servers&&i.authorization_servers.length>0&&(s=i.authorization_servers[0])}catch{}s||(s=new URL("/",t));const l=await k8(t,e,i),c=await E8(s,{fetchFn:a});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 w=c?.client_id_metadata_document_supported===!0,C=e.clientMetadataUrl;if(C&&!b8(C))throw new Hs(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${C}`);if(w&&C)u={client_id:C},await e.saveClientInformation?.(u);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const g=await O8(s,{metadata:c,clientMetadata:e.clientMetadata,fetchFn:a});await e.saveClientInformation(g),u=g}}const h=!e.redirectUrl;if(r!==void 0||h){const w=await M8(e,s,{metadata:c,resource:l,authorizationCode:r,fetchFn:a});return await e.saveTokens(w),"AUTHORIZED"}const p=await e.tokens();if(p?.refresh_token)try{const w=await P8(s,{metadata:c,clientInformation:u,refreshToken:p.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(w),"AUTHORIZED"}catch(w){if(!(!(w instanceof Rt)||w instanceof $o))throw w}const m=e.state?await e.state():void 0,{authorizationUrl:f,codeVerifier:b}=await $8(s,{metadata:c,clientInformation:u,state:m,redirectUrl:e.redirectUrl,scope:n||i?.scopes_supported?.join(" ")||e.clientMetadata.scope,resource:l});return await e.saveCodeVerifier(b),await e.redirectToAuthorization(f),"REDIRECT"}function b8(e){if(!e)return!1;try{const t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function k8(e,t,r){const n=p8(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!h8({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 Bs(e){const t=e.headers.get("WWW-Authenticate");if(!t)return{};const[r,n]=t.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};const o=Su(e,"resource_metadata")||void 0;let a;if(o)try{a=new URL(o)}catch{}const i=Su(e,"scope")||void 0,s=Su(e,"error")||void 0;return{resourceMetadataUrl:a,scope:i,error:s}}function Su(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 T8(e,t,r=fetch){const n=await I8(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 o8.parse(await n.json())}async function Iu(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?Iu(e,void 0,r):void 0;throw n}}function C8(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function bg(e,t,r=fetch){return await Iu(e,{"MCP-Protocol-Version":t},r)}function S8(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function I8(e,t,r,n){const o=new URL(e),a=n?.protocolVersion??Ls;let i;if(n?.metadataUrl)i=new URL(n.metadataUrl);else{const l=C8(t,o.pathname);i=new URL(l,n?.metadataServerUrl??o),i.search=o.search}let s=await bg(i,a,r);if(!n?.metadataUrl&&S8(s,o.pathname)){const l=new URL(`/.well-known/${t}`,o);s=await bg(l,a,r)}return s}function x8(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 E8(e,{fetchFn:t=fetch,protocolVersion:r=Ls}={}){const n={"MCP-Protocol-Version":r,Accept:"application/json"},o=x8(e);for(const{url:a,type:i}of o){const s=await Iu(a,n,t);if(s){if(!s.ok){if(await s.body?.cancel(),s.status>=400&&s.status<500)continue;throw new Error(`HTTP ${s.status} trying to load ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`)}return i==="oauth"?yg.parse(await s.json()):s8.parse(await s.json())}}}async function $8(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:o,state:a,resource:i}){let s;if(t){if(s=new URL(t.authorization_endpoint),!t.response_types_supported.includes(ku))throw new Error(`Incompatible auth server: does not support response type ${ku}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Tu))throw new Error(`Incompatible auth server: does not support code challenge method ${Tu}`)}else s=new URL("/authorize",e);const l=await m2(),c=l.code_verifier,u=l.code_challenge;return s.searchParams.set("response_type",ku),s.searchParams.set("client_id",r.client_id),s.searchParams.set("code_challenge",u),s.searchParams.set("code_challenge_method",Tu),s.searchParams.set("redirect_uri",String(n)),a&&s.searchParams.set("state",a),o&&s.searchParams.set("scope",o),o?.includes("offline_access")&&s.searchParams.append("prompt","consent"),i&&s.searchParams.set("resource",i.href),{authorizationUrl:s,codeVerifier:c}}function R8(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function kg(e,{metadata:t,tokenRequestParams:r,clientInformation:n,addClientAuthentication:o,resource:a,fetchFn:i}){const s=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(a&&r.set("resource",a.href),o)await o(l,r,s,t);else if(n){const u=t?.token_endpoint_auth_methods_supported??[],h=g8(n,u);_8(h,n,l,r)}const c=await(i??fetch)(s,{method:"POST",headers:l,body:r});if(!c.ok)throw await wg(c);return i8.parse(await c.json())}async function P8(e,{metadata:t,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:a,fetchFn:i}){const s=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),l=await kg(e,{metadata:t,tokenRequestParams:s,clientInformation:r,addClientAuthentication:a,resource:o,fetchFn:i});return{refresh_token:n,...l}}async function M8(e,t,{metadata:r,resource:n,authorizationCode:o,fetchFn:a}={}){const i=e.clientMetadata.scope;let s;if(e.prepareTokenRequest&&(s=await e.prepareTokenRequest(i)),!s){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();s=R8(o,c,e.redirectUrl)}const l=await e.clientInformation();return kg(t,{metadata:r,tokenRequestParams:s,clientInformation:l??void 0,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:a})}async function O8(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 a=await(n??fetch)(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!a.ok)throw await wg(a);return d8.parse(await a.json())}const A8={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class Ro extends Error{constructor(t,r){super(`Streamable HTTP error: ${r}`),this.code=t}}class Js{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=B2(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??A8}async _authThenStart(){if(!this._authProvider)throw new kr("No auth provider");let t;try{t=await Yn(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 kr;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=qs(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 Ro(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(a=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${a instanceof Error?a.message:String(a)}`)),this._scheduleReconnection(t,r+1)})},o)}_handleSseStream(t,r,n){if(!t)return;const{onresumptiontoken:o,replayMessageId:a}=r;let i,s=!1,l=!1;(async()=>{try{const u=t.pipeThrough(new TextDecoderStream).pipeThrough(new _o({onRetry:m=>{this._serverRetryMs=m}})).getReader();for(;;){const{value:m,done:f}=await u.read();if(f)break;if(m.id&&(i=m.id,s=!0,o?.(m.id)),!!m.data&&(!m.event||m.event==="message"))try{const b=Wn.parse(JSON.parse(m.data));ya(b)&&(l=!0,a!==void 0&&(b.id=a)),this.onmessage?.(b)}catch(b){this.onerror?.(b)}}(n||s)&&!l&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:i,onresumptiontoken:o,replayMessageId:a},0)}catch(u){if(this.onerror?.(new Error(`SSE stream disconnected: ${u}`)),(n||s)&&!l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:i,onresumptiontoken:o,replayMessageId:a},0)}catch(m){this.onerror?.(new Error(`Failed to reconnect: ${m instanceof Error?m.message:String(m)}`))}}})()}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 kr("No auth provider");if(await Yn(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new kr("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:Dc(t)?t.id:void 0}).catch(p=>this.onerror?.(p));return}const a=await this._commonHeaders();a.set("content-type","application/json"),a.set("accept","application/json, text/event-stream");const i={...this._requestInit,method:"POST",headers:a,body:JSON.stringify(t),signal:this._abortController?.signal},s=await(this._fetch??fetch)(this._url,i),l=s.headers.get("mcp-session-id");if(l&&(this._sessionId=l),!s.ok){const p=await s.text().catch(()=>null);if(s.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Ro(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:m,scope:f}=Bs(s);if(this._resourceMetadataUrl=m,this._scope=f,await Yn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new kr;return this._hasCompletedAuthFlow=!0,this.send(t)}if(s.status===403&&this._authProvider){const{resourceMetadataUrl:m,scope:f,error:b}=Bs(s);if(b==="insufficient_scope"){const w=s.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===w)throw new Ro(403,"Server returned 403 after trying upscoping");if(f&&(this._scope=f),m&&(this._resourceMetadataUrl=m),this._lastUpscopingHeader=w??void 0,await Yn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new kr;return this.send(t)}}throw new Ro(s.status,`Error POSTing to endpoint: ${p}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,s.status===202){await s.body?.cancel(),BS(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,h=s.headers.get("content-type");if(u)if(h?.includes("text/event-stream"))this._handleSseStream(s.body,{onresumptiontoken:o},!1);else if(h?.includes("application/json")){const p=await s.json(),m=Array.isArray(p)?p.map(f=>Wn.parse(f)):[Wn.parse(p)];for(const f of m)this.onmessage?.(f)}else throw await s.body?.cancel(),new Ro(-1,`Unexpected content type: ${h}`);else await s.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 Ro(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 Tg 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(Cg(this),r)}[Symbol.for("Deno.customInspect")](t,r){return t(Cg(this),r)}}function N8(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function xu(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(xu).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${xu(e.cause)}`:e.message:`${e}`}function Cg(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var Sg=e=>{throw TypeError(e)},Eu=(e,t,r)=>t.has(e)||Sg("Cannot "+r),qe=(e,t,r)=>(Eu(e,t,"read from private field"),r?r.call(e):t.get(e)),xt=(e,t,r)=>t.has(e)?Sg("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),at=(e,t,r,n)=>(Eu(e,t,"write to private field"),t.set(e,r),r),en=(e,t,r)=>(Eu(e,t,"access private method"),r),er,Qn,Po,Gs,Ws,Ia,Mo,xa,wn,Oo,Ao,No,Ea,$r,$u,Ru,Pu,Ig,Mu,Ou,$a,Au,Nu;class Ks extends EventTarget{constructor(t,r){var n,o;super(),xt(this,$r),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,xt(this,er),xt(this,Qn),xt(this,Po),xt(this,Gs),xt(this,Ws),xt(this,Ia),xt(this,Mo),xt(this,xa,null),xt(this,wn),xt(this,Oo),xt(this,Ao,null),xt(this,No,null),xt(this,Ea,null),xt(this,Ru,async a=>{var i;qe(this,Oo).reset();const{body:s,redirected:l,status:c,headers:u}=a;if(c===204){en(this,$r,$a).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?at(this,Po,new URL(a.url)):at(this,Po,void 0),c!==200){en(this,$r,$a).call(this,`Non-200 status code (${c})`,c);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){en(this,$r,$a).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(qe(this,er)===this.CLOSED)return;at(this,er,this.OPEN);const h=new Event("open");if((i=qe(this,Ea))==null||i.call(this,h),this.dispatchEvent(h),typeof s!="object"||!s||!("getReader"in s)){en(this,$r,$a).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}const p=new TextDecoder,m=s.getReader();let f=!0;do{const{done:b,value:w}=await m.read();w&&qe(this,Oo).feed(p.decode(w,{stream:!b})),b&&(f=!1,qe(this,Oo).reset(),en(this,$r,Au).call(this))}while(f)}),xt(this,Pu,a=>{at(this,wn,void 0),!(a.name==="AbortError"||a.type==="aborted")&&en(this,$r,Au).call(this,xu(a))}),xt(this,Mu,a=>{typeof a.id=="string"&&at(this,xa,a.id);const i=new MessageEvent(a.event||"message",{data:a.data,origin:qe(this,Po)?qe(this,Po).origin:qe(this,Qn).origin,lastEventId:a.id||""});qe(this,No)&&(!a.event||a.event==="message")&&qe(this,No).call(this,i),this.dispatchEvent(i)}),xt(this,Ou,a=>{at(this,Ia,a)}),xt(this,Nu,()=>{at(this,Mo,void 0),qe(this,er)===this.CONNECTING&&en(this,$r,$u).call(this)});try{if(t instanceof URL)at(this,Qn,t);else if(typeof t=="string")at(this,Qn,new URL(t,q8()));else throw new Error("Invalid URL")}catch{throw N8("An invalid or illegal string was specified")}at(this,Oo,Qh({onEvent:qe(this,Mu),onRetry:qe(this,Ou)})),at(this,er,this.CONNECTING),at(this,Ia,3e3),at(this,Ws,(n=r?.fetch)!=null?n:globalThis.fetch),at(this,Gs,(o=r?.withCredentials)!=null?o:!1),en(this,$r,$u).call(this)}get readyState(){return qe(this,er)}get url(){return qe(this,Qn).href}get withCredentials(){return qe(this,Gs)}get onerror(){return qe(this,Ao)}set onerror(t){at(this,Ao,t)}get onmessage(){return qe(this,No)}set onmessage(t){at(this,No,t)}get onopen(){return qe(this,Ea)}set onopen(t){at(this,Ea,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,Mo)&&clearTimeout(qe(this,Mo)),qe(this,er)!==this.CLOSED&&(qe(this,wn)&&qe(this,wn).abort(),at(this,er,this.CLOSED),at(this,wn,void 0))}}er=new WeakMap,Qn=new WeakMap,Po=new WeakMap,Gs=new WeakMap,Ws=new WeakMap,Ia=new WeakMap,Mo=new WeakMap,xa=new WeakMap,wn=new WeakMap,Oo=new WeakMap,Ao=new WeakMap,No=new WeakMap,Ea=new WeakMap,$r=new WeakSet,$u=function(){at(this,er,this.CONNECTING),at(this,wn,new AbortController),qe(this,Ws)(qe(this,Qn),en(this,$r,Ig).call(this)).then(qe(this,Ru)).catch(qe(this,Pu))},Ru=new WeakMap,Pu=new WeakMap,Ig=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...qe(this,xa)?{"Last-Event-ID":qe(this,xa)}:void 0},cache:"no-store",signal:(e=qe(this,wn))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},Mu=new WeakMap,Ou=new WeakMap,$a=function(e,t){var r;qe(this,er)!==this.CLOSED&&at(this,er,this.CLOSED);const n=new Tg("error",{code:t,message:e});(r=qe(this,Ao))==null||r.call(this,n),this.dispatchEvent(n)},Au=function(e,t){var r;if(qe(this,er)===this.CLOSED)return;at(this,er,this.CONNECTING);const n=new Tg("error",{code:t,message:e});(r=qe(this,Ao))==null||r.call(this,n),this.dispatchEvent(n),at(this,Mo,setTimeout(qe(this,Nu),qe(this,Ia)))},Nu=new WeakMap,Ks.CONNECTING=0,Ks.OPEN=1,Ks.CLOSED=2;function q8(){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 L8 extends Error{constructor(t,r,n){super(`SSE error: ${r}`),this.code=t,this.event=n}}class Ys{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=B2(r?.fetch,r?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new kr("No auth provider");let t;try{t=await Yn(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 kr;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=qs(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 Ks(this._url.href,{...this._eventSourceInit,fetch:async(o,a)=>{const i=await this._commonHeaders();i.set("Accept","text/event-stream");const s=await t(o,{...a,headers:i});if(s.status===401&&s.headers.has("www-authenticate")){const{resourceMetadataUrl:l,scope:c}=Bs(s);this._resourceMetadataUrl=l,this._scope=c}return s}}),this._abortController=new AbortController,this._eventSource.onerror=o=>{if(o.code===401&&this._authProvider){this._authThenStart().then(r,n);return}const a=new L8(o.code,o.message,o);n(a),this.onerror?.(a)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",o=>{const a=o;try{if(this._endpoint=new URL(a.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 a=o;let i;try{i=Wn.parse(JSON.parse(a.data))}catch(s){this.onerror?.(s);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 kr("No auth provider");if(await Yn(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new kr("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 a=await o.text().catch(()=>null);if(o.status===401&&this._authProvider){const{resourceMetadataUrl:i,scope:s}=Bs(o);if(this._resourceMetadataUrl=i,this._scope=s,await Yn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new kr;return this.send(t)}throw new Error(`Error POSTing to endpoint (HTTP ${o.status}): ${a}`)}await o.body?.cancel()}catch(r){throw this.onerror?.(r),r}}setProtocolVersion(t){this._protocolVersion=t}}class Qs{constructor(){this._messageQueue=[]}static createLinkedPair(){const t=new Qs,r=new Qs;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 qu=T({error:T({message:d(),type:d().nullish(),param:ut().nullish(),code:ae([d(),q()]).nullish()})}),Rr=ir({errorSchema:qu,errorToMessage:e=>e.error.message});function xg(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")||e.startsWith("gpt-5.5");return{supportsFlexProcessing:t,supportsPriorityProcessing:r,isReasoningModel:n,systemMessageMode:n?"developer":"system",supportsNonReasoningParameters:o}}function Eg(e){var t,r,n,o,a,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 s=(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=(a=e.completion_tokens_details)==null?void 0:a.reasoning_tokens)!=null?i:0;return{inputTokens:{total:s,noCache:s-c,cacheRead:c,cacheWrite:void 0},outputTokens:{total:l,text:l-u,reasoning:u},raw:e}}function j8(e){return JSON.stringify(e===void 0?{}:e)}function D8({prompt:e,systemMessageMode:t="system"}){var r;const n=[],o=[];for(const{role:a,content:i}of e)switch(a){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 s=t;throw new Error(`Unsupported system message mode: ${s}`)}}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((s,l)=>{var c,u,h;switch(s.type){case"text":return{type:"text",text:s.text};case"file":if(s.mediaType.startsWith("image/")){const p=s.mediaType==="image/*"?"image/jpeg":s.mediaType;return{type:"image_url",image_url:{url:s.data instanceof URL?s.data.toString():`data:${p};base64,${vo(s.data)}`,detail:(u=(c=s.providerOptions)==null?void 0:c.openai)==null?void 0:u.imageDetail}}}else if(s.mediaType.startsWith("audio/")){if(s.data instanceof URL)throw new Tr({functionality:"audio file parts with URLs"});switch(s.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:vo(s.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:vo(s.data),format:"mp3"}};default:throw new Tr({functionality:`audio content parts with media type ${s.mediaType}`})}}else if(s.mediaType==="application/pdf"){if(s.data instanceof URL)throw new Tr({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof s.data=="string"&&s.data.startsWith("file-")?{file_id:s.data}:{filename:(h=s.filename)!=null?h:`part-${l}.pdf`,file_data:`data:application/pdf;base64,${vo(s.data)}`}}}else throw new Tr({functionality:`file part media type ${s.mediaType}`})}})});break}case"assistant":{let s="";const l=[];for(const c of i)switch(c.type){case"text":{s+=c.text;break}case"tool-call":{l.push({id:c.toolCallId,type:"function",function:{name:c.toolName,arguments:j8(c.input)}});break}}n.push({role:"assistant",content:l.length>0?s||null:s,tool_calls:l.length>0?l:void 0});break}case"tool":{for(const s of i){if(s.type==="tool-approval-response")continue;const l=s.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:s.toolCallId,content:c})}break}default:{const s=a;throw new Error(`Unsupported role: ${s}`)}}return{messages:n,warnings:o}}function Lu({id:e,model:t,created:r}){return{id:e??void 0,modelId:t??void 0,timestamp:r?new Date(r*1e3):void 0}}function $g(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 U8=ye(()=>me(T({id:d().nullish(),created:q().nullish(),model:d().nullish(),choices:L(T({message:T({role:M("assistant").nullish(),content:d().nullish(),tool_calls:L(T({id:d().nullish(),type:M("function"),function:T({name:d(),arguments:d()})})).nullish(),annotations:L(T({type:M("url_citation"),url_citation:T({start_index:q(),end_index:q(),url:d(),title:d()})})).nullish()}),index:q(),logprobs:T({content:L(T({token:d(),logprob:q(),top_logprobs:L(T({token:d(),logprob:q()}))})).nullish()}).nullish(),finish_reason:d().nullish()})),usage:T({prompt_tokens:q().nullish(),completion_tokens:q().nullish(),total_tokens:q().nullish(),prompt_tokens_details:T({cached_tokens:q().nullish()}).nullish(),completion_tokens_details:T({reasoning_tokens:q().nullish(),accepted_prediction_tokens:q().nullish(),rejected_prediction_tokens:q().nullish()}).nullish()}).nullish()}))),z8=ye(()=>me(ae([T({id:d().nullish(),created:q().nullish(),model:d().nullish(),choices:L(T({delta:T({role:le(["assistant"]).nullish(),content:d().nullish(),tool_calls:L(T({index:q(),id:d().nullish(),type:M("function").nullish(),function:T({name:d().nullish(),arguments:d().nullish()})})).nullish(),annotations:L(T({type:M("url_citation"),url_citation:T({start_index:q(),end_index:q(),url:d(),title:d()})})).nullish()}).nullish(),logprobs:T({content:L(T({token:d(),logprob:q(),top_logprobs:L(T({token:d(),logprob:q()}))})).nullish()}).nullish(),finish_reason:d().nullish(),index:q()})),usage:T({prompt_tokens:q().nullish(),completion_tokens:q().nullish(),total_tokens:q().nullish(),prompt_tokens_details:T({cached_tokens:q().nullish()}).nullish(),completion_tokens_details:T({reasoning_tokens:q().nullish(),accepted_prediction_tokens:q().nullish(),rejected_prediction_tokens:q().nullish()}).nullish()}).nullish()}),qu]))),F8=ye(()=>me(T({logitBias:pe(Oh(),q()).optional(),logprobs:ae([_e(),q()]).optional(),parallelToolCalls:_e().optional(),user:d().optional(),reasoningEffort:le(["none","minimal","low","medium","high","xhigh"]).optional(),maxCompletionTokens:q().optional(),store:_e().optional(),metadata:pe(d().max(64),d().max(512)).optional(),prediction:pe(d(),ut()).optional(),serviceTier:le(["auto","flex","priority","default"]).optional(),strictJsonSchema:_e().optional(),textVerbosity:le(["low","medium","high"]).optional(),promptCacheKey:d().optional(),promptCacheRetention:le(["in_memory","24h"]).optional(),safetyIdentifier:d().optional(),systemMessageMode:le(["system","developer","remove"]).optional(),forceReasoning:_e().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 a of e)switch(a.type){case"function":n.push({type:"function",function:{name:a.name,description:a.description,parameters:a.inputSchema,...a.strict!=null?{strict:a.strict}:{}}});break;default:r.push({type:"unsupported",feature:`tool type: ${a.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 a=o;throw new Tr({functionality:`tool choice type: ${a}`})}}}var Z8=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:a,presencePenalty:i,stopSequences:s,responseFormat:l,seed:c,tools:u,toolChoice:h,providerOptions:p}){var m,f,b,w,C;const v=[],g=(m=await Ir({provider:"openai",providerOptions:p,schema:F8}))!=null?m:{},I=xg(this.modelId),y=(f=g.forceReasoning)!=null?f:I.isReasoningModel;o!=null&&v.push({type:"unsupported",feature:"topK"});const{messages:_,warnings:k}=D8({prompt:e,systemMessageMode:(b=g.systemMessageMode)!=null?b:y?"developer":I.systemMessageMode});v.push(...k);const S=(w=g.strictJsonSchema)!=null?w:!0,E={model:this.modelId,logit_bias:g.logitBias,logprobs:g.logprobs===!0||typeof g.logprobs=="number"?!0:void 0,top_logprobs:typeof g.logprobs=="number"?g.logprobs:typeof g.logprobs=="boolean"&&g.logprobs?0:void 0,user:g.user,parallel_tool_calls:g.parallelToolCalls,max_tokens:t,temperature:r,top_p:n,frequency_penalty:a,presence_penalty:i,response_format:l?.type==="json"?l.schema!=null?{type:"json_schema",json_schema:{schema:l.schema,strict:S,name:(C=l.name)!=null?C:"response",description:l.description}}:{type:"json_object"}:void 0,stop:s,seed:c,verbosity:g.textVerbosity,max_completion_tokens:g.maxCompletionTokens,store:g.store,metadata:g.metadata,prediction:g.prediction,reasoning_effort:g.reasoningEffort,service_tier:g.serviceTier,prompt_cache_key:g.promptCacheKey,prompt_cache_retention:g.promptCacheRetention,safety_identifier:g.safetyIdentifier,messages:_};y?((g.reasoningEffort!=="none"||!I.supportsNonReasoningParameters)&&(E.temperature!=null&&(E.temperature=void 0,v.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),E.top_p!=null&&(E.top_p=void 0,v.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"})),E.logprobs!=null&&(E.logprobs=void 0,v.push({type:"other",message:"logprobs is not supported for reasoning models"}))),E.frequency_penalty!=null&&(E.frequency_penalty=void 0,v.push({type:"unsupported",feature:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),E.presence_penalty!=null&&(E.presence_penalty=void 0,v.push({type:"unsupported",feature:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),E.logit_bias!=null&&(E.logit_bias=void 0,v.push({type:"other",message:"logitBias is not supported for reasoning models"})),E.top_logprobs!=null&&(E.top_logprobs=void 0,v.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),E.max_tokens!=null&&(E.max_completion_tokens==null&&(E.max_completion_tokens=E.max_tokens),E.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&E.temperature!=null&&(E.temperature=void 0,v.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),g.serviceTier==="flex"&&!I.supportsFlexProcessing&&(v.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),E.service_tier=void 0),g.serviceTier==="priority"&&!I.supportsPriorityProcessing&&(v.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"}),E.service_tier=void 0);const{tools:R,toolChoice:x,toolWarnings:N}=V8({tools:u,toolChoice:h});return{args:{...E,tools:R,tool_choice:x},warnings:[...v,...N]}}async doGenerate(e){var t,r,n,o,a,i,s;const{args:l,warnings:c}=await this.getArgs(e),{responseHeaders:u,value:h,rawValue:p}=await Ot({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:It(this.config.headers(),e.headers),body:l,failedResponseHandler:Rr,successfulResponseHandler:At(U8),abortSignal:e.abortSignal,fetch:this.config.fetch}),m=h.choices[0],f=[],b=m.message.content;b!=null&&b.length>0&&f.push({type:"text",text:b});for(const v of(t=m.message.tool_calls)!=null?t:[])f.push({type:"tool-call",toolCallId:(r=v.id)!=null?r:Kt(),toolName:v.function.name,input:v.function.arguments});for(const v of(n=m.message.annotations)!=null?n:[])f.push({type:"source",sourceType:"url",id:Kt(),url:v.url_citation.url,title:v.url_citation.title});const w=(o=h.usage)==null?void 0:o.completion_tokens_details;(a=h.usage)==null||a.prompt_tokens_details;const C={openai:{}};return w?.accepted_prediction_tokens!=null&&(C.openai.acceptedPredictionTokens=w?.accepted_prediction_tokens),w?.rejected_prediction_tokens!=null&&(C.openai.rejectedPredictionTokens=w?.rejected_prediction_tokens),((i=m.logprobs)==null?void 0:i.content)!=null&&(C.openai.logprobs=m.logprobs.content),{content:f,finishReason:{unified:$g(m.finish_reason),raw:(s=m.finish_reason)!=null?s:void 0},usage:Eg(h.usage),request:{body:l},response:{...Lu(h),headers:u,body:p},warnings:c,providerMetadata:C}}async doStream(e){const{args:t,warnings:r}=await this.getArgs(e),n={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:o,value:a}=await Ot({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:It(this.config.headers(),e.headers),body:n,failedResponseHandler:Rr,successfulResponseHandler:_s(z8),abortSignal:e.abortSignal,fetch:this.config.fetch}),i=[];let s={unified:"other",raw:void 0},l,c=!1,u=!1;const h={openai:{}};return{stream:a.pipeThrough(new TransformStream({start(p){p.enqueue({type:"stream-start",warnings:r})},transform(p,m){var f,b,w,C,v,g,I,y,_,k,S,E,R,x,N,U,z;if(e.includeRawChunks&&m.enqueue({type:"raw",rawValue:p.rawValue}),!p.success){s={unified:"error",raw:void 0},m.enqueue({type:"error",error:p.error});return}const ee=p.value;if("error"in ee){s={unified:"error",raw:void 0},m.enqueue({type:"error",error:ee.error});return}if(!c){const re=Lu(ee);Object.values(re).some(Boolean)&&(c=!0,m.enqueue({type:"response-metadata",...Lu(ee)}))}ee.usage!=null&&(l=ee.usage,((f=ee.usage.completion_tokens_details)==null?void 0:f.accepted_prediction_tokens)!=null&&(h.openai.acceptedPredictionTokens=(b=ee.usage.completion_tokens_details)==null?void 0:b.accepted_prediction_tokens),((w=ee.usage.completion_tokens_details)==null?void 0:w.rejected_prediction_tokens)!=null&&(h.openai.rejectedPredictionTokens=(C=ee.usage.completion_tokens_details)==null?void 0:C.rejected_prediction_tokens));const Q=ee.choices[0];if(Q?.finish_reason!=null&&(s={unified:$g(Q.finish_reason),raw:Q.finish_reason}),((v=Q?.logprobs)==null?void 0:v.content)!=null&&(h.openai.logprobs=Q.logprobs.content),Q?.delta==null)return;const se=Q.delta;if(se.content!=null&&(u||(m.enqueue({type:"text-start",id:"0"}),u=!0),m.enqueue({type:"text-delta",id:"0",delta:se.content})),se.tool_calls!=null)for(const re of se.tool_calls){const Se=re.index;if(i[Se]==null){if(re.type!=null&&re.type!=="function")throw new cl({data:re,message:"Expected 'function' type."});if(re.id==null)throw new cl({data:re,message:"Expected 'id' to be a string."});if(((g=re.function)==null?void 0:g.name)==null)throw new cl({data:re,message:"Expected 'function.name' to be a string."});m.enqueue({type:"tool-input-start",id:re.id,toolName:re.function.name}),i[Se]={id:re.id,type:"function",function:{name:re.function.name,arguments:(I=re.function.arguments)!=null?I:""},hasFinished:!1};const D=i[Se];((y=D.function)==null?void 0:y.name)!=null&&((_=D.function)==null?void 0:_.arguments)!=null&&(D.function.arguments.length>0&&m.enqueue({type:"tool-input-delta",id:D.id,delta:D.function.arguments}),bf(D.function.arguments)&&(m.enqueue({type:"tool-input-end",id:D.id}),m.enqueue({type:"tool-call",toolCallId:(k=D.id)!=null?k:Kt(),toolName:D.function.name,input:D.function.arguments}),D.hasFinished=!0));continue}const H=i[Se];H.hasFinished||(((S=re.function)==null?void 0:S.arguments)!=null&&(H.function.arguments+=(R=(E=re.function)==null?void 0:E.arguments)!=null?R:""),m.enqueue({type:"tool-input-delta",id:H.id,delta:(x=re.function.arguments)!=null?x:""}),((N=H.function)==null?void 0:N.name)!=null&&((U=H.function)==null?void 0:U.arguments)!=null&&bf(H.function.arguments)&&(m.enqueue({type:"tool-input-end",id:H.id}),m.enqueue({type:"tool-call",toolCallId:(z=H.id)!=null?z:Kt(),toolName:H.function.name,input:H.function.arguments}),H.hasFinished=!0))}if(se.annotations!=null)for(const re of se.annotations)m.enqueue({type:"source",sourceType:"url",id:Kt(),url:re.url_citation.url,title:re.url_citation.title})},flush(p){u&&p.enqueue({type:"text-end",id:"0"}),p.enqueue({type:"finish",finishReason:s,usage:Eg(l),...h!=null?{providerMetadata:h}:{}})}})),request:{body:n},response:{headers:o}}}};function Rg(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 a=(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:a,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:(o=e.completion_tokens)!=null?o:void 0,text:i,reasoning:void 0},raw:e}}function H8({prompt:e,user:t="user",assistant:r="assistant"}){let n="";e[0].role==="system"&&(n+=`${e[0].content}
|
|
69
77
|
|
|
70
|
-
`,e=e.slice(1));for(const{role:o,content:
|
|
78
|
+
`,e=e.slice(1));for(const{role:o,content:a}of e)switch(o){case"system":throw new un({message:"Unexpected system message in prompt: ${content}",prompt:e});case"user":{const i=a.map(s=>{switch(s.type){case"text":return s.text}}).filter(Boolean).join("");n+=`${t}:
|
|
71
79
|
${i}
|
|
72
80
|
|
|
73
|
-
`;break}case"assistant":{const i=
|
|
81
|
+
`;break}case"assistant":{const i=a.map(s=>{switch(s.type){case"text":return s.text;case"tool-call":throw new Tr({functionality:"tool-call messages"})}}).join("");n+=`${r}:
|
|
74
82
|
${i}
|
|
75
83
|
|
|
76
|
-
`;break}case"tool":throw new
|
|
84
|
+
`;break}case"tool":throw new Tr({functionality:"tool messages"});default:{const i=o;throw new Error(`Unsupported role: ${i}`)}}return n+=`${r}:
|
|
77
85
|
`,{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 wI=ve(()=>ye(k({id:d().nullish(),created:O().nullish(),model:d().nullish(),choices:q(k({text:d(),finish_reason:d(),logprobs:k({tokens:q(d()),token_logprobs:q(O()),top_logprobs:q(ge(d(),O())).nullish()}).nullish()})),usage:k({prompt_tokens:O(),completion_tokens:O(),total_tokens:O()}).nullish()}))),bI=ve(()=>ye(ae([k({id:d().nullish(),created:O().nullish(),model:d().nullish(),choices:q(k({text:d(),finish_reason:d().nullish(),index:O(),logprobs:k({tokens:q(d()),token_logprobs:q(O()),top_logprobs:q(ge(d(),O())).nullish()}).nullish()})),usage:k({prompt_tokens:O(),completion_tokens:O(),total_tokens:O()}).nullish()}),cu]))),O2=ve(()=>ye(k({echo:me().optional(),logitBias:ge(d(),O()).optional(),suffix:d().optional(),user:d().optional(),logprobs:ae([me(),O()]).optional()}))),kI=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 Fr({provider:"openai",providerOptions:p,schema:O2}),...await Fr({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:_}=vI({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 Jt({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:At(this.config.headers(),e.headers),body:r,failedResponseHandler:Cr,successfulResponseHandler:Wt(wI),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 Jt({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:At(this.config.headers(),e.headers),body:n,failedResponseHandler:Cr,successfulResponseHandler:aa(bI),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}}}},TI=ve(()=>ye(k({dimensions:O().optional(),user:d().optional()}))),CI=ve(()=>ye(k({data:q(k({embedding:q(O())})),usage:k({prompt_tokens:O()}).nullish()}))),SI=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 Fr({provider:"openai",providerOptions:n,schema:TI}))!=null?o:{},{responseHeaders:i,value:a,rawValue:l}=await Jt({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:At(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:"float",dimensions:s.dimensions,user:s.user},failedResponseHandler:Cr,successfulResponseHandler:Wt(CI),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:O().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:O().nullish(),output_tokens:O().nullish(),total_tokens:O().nullish(),input_tokens_details:k({image_tokens:O().nullish(),text_tokens:O().nullish()}).nullish()}).nullish()}))),II={"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},xI=["chatgpt-image-","gpt-image-1-mini","gpt-image-1.5","gpt-image-1"];function EI(e){return xI.some(t=>e.startsWith(t))}var $I=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get maxImagesPerCall(){var e;return(e=II[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:At(this.config.headers(),l),formData:o9({model:this.modelId,prompt:e,image:await Promise.all(t.map(N=>N.type==="file"?new Blob([N.data instanceof Uint8Array?new Blob([N.data],{type:N.mediaType}):new Blob([io(N.data)],{type:N.mediaType})],{type:N.mediaType}):qf(N.url))),mask:r!=null?await RI(r):void 0,n,size:o,...(h=a.openai)!=null?h:{}}),failedResponseHandler:Cr,successfulResponseHandler:Wt(A2),abortSignal:c,fetch:this.config.fetch});return{images:S.data.map(N=>N.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((N,L)=>{var z,B,X,ee,Q,Z;return{...N.revised_prompt?{revisedPrompt:N.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 Jt({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:At(this.config.headers(),l),body:{model:this.modelId,prompt:e,n,size:o,...(w=a.openai)!=null?w:{},...EI(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:Cr,successfulResponseHandler:Wt(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 N,L,z,B,X,ee;return{...S.revised_prompt?{revisedPrompt:S.revised_prompt}:{},created:(N=I.created)!=null?N: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 RI(e){if(!e)return;if(e.type==="url")return qf(e.url);const t=e.data instanceof Uint8Array?e.data:io(e.data);return new Blob([t],{type:e.mediaType})}var L2=ve(()=>ye(k({callId:d(),operation:ze("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()}))),PI=pr({id:"openai.apply_patch",inputSchema:L2,outputSchema:j2}),MI=PI,NI=ve(()=>ye(k({code:d().nullish(),containerId:d()}))),OI=ve(()=>ye(k({outputs:q(ze("type",[k({type:P("logs"),logs:d()}),k({type:P("image"),url:d()})])).nullish()}))),AI=ve(()=>ye(k({container:ae([d(),k({fileIds:q(d()).optional()})]).optional()}))),qI=pr({id:"openai.code_interpreter",inputSchema:NI,outputSchema:OI}),LI=(e={})=>qI(e),jI=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()}))),DI=ve(()=>ye(d())),UI=u4({id:"openai.custom",inputSchema:DI}),zI=e=>UI(e),D2=k({key:d(),type:ce(["eq","ne","gt","gte","lt","lte","in","nin"]),value:ae([d(),O(),me(),q(d())])}),U2=k({type:ce(["and","or"]),filters:q(ae([D2,Ks(()=>U2)]))}),FI=ve(()=>ye(k({vectorStoreIds:q(d()),maxNumResults:O().optional(),ranking:k({ranker:d().optional(),scoreThreshold:O().optional()}).optional(),filters:ae([D2,U2]).optional()}))),VI=ve(()=>ye(k({queries:q(d()),results:q(k({attributes:ge(d(),Ce()),fileId:d(),filename:d(),score:O(),text:d()})).nullable()}))),ZI=pr({id:"openai.file_search",inputSchema:k({}),outputSchema:VI}),BI=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:O().int().min(0).max(100).optional(),outputFormat:ce(["png","jpeg","webp"]).optional(),partialImages:O().int().min(0).max(3).optional(),quality:ce(["auto","low","medium","high"]).optional(),size:ce(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),HI=ve(()=>ye(k({}))),JI=ve(()=>ye(k({result:d()}))),WI=pr({id:"openai.image_generation",inputSchema:HI,outputSchema:JI}),GI=(e={})=>WI(e),z2=ve(()=>ye(k({action:k({type:P("exec"),command:q(d()),timeoutMs:O().optional(),user:d().optional(),workingDirectory:d().optional(),env:ge(d(),d()).optional()})}))),F2=ve(()=>ye(k({output:d()}))),KI=pr({id:"openai.local_shell",inputSchema:z2,outputSchema:F2}),V2=ve(()=>ye(k({action:k({commands:q(d()),timeoutMs:O().optional(),maxOutputLength:O().optional()})}))),du=ve(()=>ye(k({output:q(k({stdout:d(),stderr:d(),outcome:ze("type",[k({type:P("timeout")}),k({type:P("exit"),exitCode:O()})])}))}))),YI=q(ze("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(),QI=ve(()=>ye(k({environment:ae([k({type:P("containerAuto"),fileIds:q(d()).optional(),memoryLimit:ce(["1g","4g","16g","64g"]).optional(),networkPolicy:ze("type",[k({type:P("disabled")}),k({type:P("allowlist"),allowedDomains:q(d()),domainSecrets:q(k({domain:d(),name:d(),value:d()})).optional()})]).optional(),skills:YI}),k({type:P("containerReference"),containerId:d()}),k({type:P("local").optional(),skills:q(k({name:d(),description:d(),path:d()})).optional()})]).optional()}))),XI=pr({id:"openai.shell",inputSchema:V2,outputSchema:du}),e8=ve(()=>ye(k({execution:ce(["server","client"]).optional(),description:d().optional(),parameters:ge(d(),Ce()).optional()}))),pu=ve(()=>ye(k({arguments:Ce().optional(),call_id:d().nullish()}))),fu=ve(()=>ye(k({tools:q(ge(d(),Ce()))}))),t8=pr({id:"openai.tool_search",inputSchema:pu,outputSchema:fu}),r8=(e={})=>t8(e),n8=ve(()=>ye(k({externalWebAccess:me().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()}))),o8=ve(()=>ye(k({}))),s8=ve(()=>ye(k({action:ze("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(ze("type",[k({type:P("url"),url:d()}),k({type:P("api"),name:d()})])).optional()}))),a8=pr({id:"openai.web_search",inputSchema:o8,outputSchema:s8}),i8=(e={})=>a8(e),l8=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()}))),c8=ve(()=>ye(k({}))),u8=ve(()=>ye(k({action:ze("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()}))),d8=pr({id:"openai.web_search_preview",inputSchema:c8,outputSchema:u8}),hu=Ks(()=>ae([d(),O(),me(),Do(),q(hu),ge(d(),hu)])),p8=ve(()=>ye(k({serverLabel:d(),allowedTools:ae([q(d()),k({readOnly:me().optional(),toolNames:q(d()).optional()})]).optional(),authorization:d().optional(),connectorId:d().optional(),headers:ge(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."))),f8=ve(()=>ye(k({}))),h8=ve(()=>ye(k({type:P("call"),serverLabel:d(),name:d(),arguments:d(),output:d().nullish(),error:ae([d(),hu]).optional()}))),m8=pr({id:"openai.mcp",inputSchema:f8,outputSchema:h8}),g8=e=>m8(e),_8={applyPatch:MI,customTool:zI,codeInterpreter:LI,fileSearch:ZI,imageGeneration:GI,localShell:KI,shell:XI,webSearchPreview:d8,webSearch:i8,mcp:g8,toolSearch:r8};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 y8({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,N;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,${co(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,${co(Q.data)}`}};throw new Mr({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:pu}):await mt({value:Z.input,schema:pu}),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 mt({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 mt({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 mt({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 mt({value:Z.output.value,schema:fu});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 mt({value:Z.output.value,schema:du});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 Fr({provider:n,providerOptions:Z.providerOptions,schema:v8}),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 mt({value:Z.value,schema:fu});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 mt({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 mt({value:Z.value,schema:du});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 mt({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=(N=Z.reason)!=null?N:"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 v8=k({itemId:d().nullish(),reasoningEncryptedContent:d().nullish()});function mu({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(),O(),me(),Do(),q(vs),ge(d(),vs.optional())])),w8=ve(()=>ye(ae([k({type:P("response.output_text.delta"),item_id:d(),delta:d(),logprobs:q(k({token:d(),logprob:O(),top_logprobs:q(k({token:d(),logprob:O()}))})).nullish()}),k({type:ce(["response.completed","response.incomplete"]),response:k({incomplete_details:k({reason:d()}).nullish(),usage:k({input_tokens:O(),input_tokens_details:k({cached_tokens:O().nullish()}).nullish(),output_tokens:O(),output_tokens_details:k({reasoning_tokens:O().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:O(),input_tokens_details:k({cached_tokens:O().nullish()}).nullish(),output_tokens:O(),output_tokens_details:k({reasoning_tokens:O().nullish()}).nullish()}).nullish(),service_tier:d().nullish()})}),k({type:P("response.created"),response:k({id:d(),created_at:O(),model:d(),service_tier:d().nullish()})}),k({type:P("response.output_item.added"),output_index:O(),item:ze("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(ze("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:ze("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:ze("type",[k({type:P("timeout")}),k({type:P("exit"),exit_code:O()})])}))}),k({type:P("tool_search_call"),id:d(),execution:ce(["server","client"]),call_id:d().nullable(),status:ce(["in_progress","completed","incomplete"]),arguments:Ce()}),k({type:P("tool_search_output"),id:d(),execution:ce(["server","client"]),call_id:d().nullable(),status:ce(["in_progress","completed","incomplete"]),tools:q(ge(d(),vs.optional()))})])}),k({type:P("response.output_item.done"),output_index:O(),item:ze("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(ze("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:ze("type",[k({type:P("search"),query:d().nullish(),sources:q(ze("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:ge(d(),ae([d(),O(),me()])),file_id:d(),filename:d(),score:O(),text:d()})).nullish()}),k({type:P("local_shell_call"),id:d(),call_id:d(),action:k({type:P("exec"),command:q(d()),timeout_ms:O().optional(),user:d().optional(),working_directory:d().optional(),env:ge(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([O(),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:yt(),annotations:ge(d(),Ce()).optional()})),error:ae([d(),k({type:d().optional(),code:ae([O(),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:ze("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:ze("type",[k({type:P("timeout")}),k({type:P("exit"),exit_code:O()})])}))}),k({type:P("tool_search_call"),id:d(),execution:ce(["server","client"]),call_id:d().nullable(),status:ce(["in_progress","completed","incomplete"]),arguments:Ce()}),k({type:P("tool_search_output"),id:d(),execution:ce(["server","client"]),call_id:d().nullable(),status:ce(["in_progress","completed","incomplete"]),tools:q(ge(d(),vs.optional()))})])}),k({type:P("response.function_call_arguments.delta"),item_id:d(),output_index:O(),delta:d()}),k({type:P("response.custom_tool_call_input.delta"),item_id:d(),output_index:O(),delta:d()}),k({type:P("response.image_generation_call.partial_image"),item_id:d(),output_index:O(),partial_image_b64:d()}),k({type:P("response.code_interpreter_call_code.delta"),item_id:d(),output_index:O(),delta:d()}),k({type:P("response.code_interpreter_call_code.done"),item_id:d(),output_index:O(),code:d()}),k({type:P("response.output_text.annotation.added"),annotation:ze("type",[k({type:P("url_citation"),start_index:O(),end_index:O(),url:d(),title:d()}),k({type:P("file_citation"),file_id:d(),filename:d(),index:O()}),k({type:P("container_file_citation"),container_id:d(),file_id:d(),filename:d(),start_index:O(),end_index:O()}),k({type:P("file_path"),file_id:d(),index:O()})])}),k({type:P("response.reasoning_summary_part.added"),item_id:d(),summary_index:O()}),k({type:P("response.reasoning_summary_text.delta"),item_id:d(),summary_index:O(),delta:d()}),k({type:P("response.reasoning_summary_part.done"),item_id:d(),summary_index:O()}),k({type:P("response.apply_patch_call_operation_diff.delta"),item_id:d(),output_index:O(),delta:d(),obfuscation:d().nullish()}),k({type:P("response.apply_patch_call_operation_diff.done"),item_id:d(),output_index:O(),diff:d()}),k({type:P("error"),sequence_number:O(),error:k({type:d(),code:d(),message:d(),param:d().nullish()})}),k({type:d()}).loose().transform(e=>({type:"unknown_chunk",message:e.type}))]))),b8=ve(()=>ye(k({id:d().optional(),created_at:O().optional(),error:k({message:d(),type:d(),param:d().nullish(),code:d()}).nullish(),model:d().optional(),output:q(ze("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:O(),top_logprobs:q(k({token:d(),logprob:O()}))})).nullish(),annotations:q(ze("type",[k({type:P("url_citation"),start_index:O(),end_index:O(),url:d(),title:d()}),k({type:P("file_citation"),file_id:d(),filename:d(),index:O()}),k({type:P("container_file_citation"),container_id:d(),file_id:d(),filename:d(),start_index:O(),end_index:O()}),k({type:P("file_path"),file_id:d(),index:O()})]))}))}),k({type:P("web_search_call"),id:d(),status:d(),action:ze("type",[k({type:P("search"),query:d().nullish(),sources:q(ze("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:ge(d(),ae([d(),O(),me()])),file_id:d(),filename:d(),score:O(),text:d()})).nullish()}),k({type:P("code_interpreter_call"),id:d(),code:d().nullable(),container_id:d(),outputs:q(ze("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:O().optional(),user:d().optional(),working_directory:d().optional(),env:ge(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([O(),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:yt(),annotations:ge(d(),Ce()).optional()})),error:ae([d(),k({type:d().optional(),code:ae([O(),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:ze("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:ze("type",[k({type:P("timeout")}),k({type:P("exit"),exit_code:O()})])}))}),k({type:P("tool_search_call"),id:d(),execution:ce(["server","client"]),call_id:d().nullable(),status:ce(["in_progress","completed","incomplete"]),arguments:Ce()}),k({type:P("tool_search_output"),id:d(),execution:ce(["server","client"]),call_id:d().nullable(),status:ce(["in_progress","completed","incomplete"]),tools:q(ge(d(),vs.optional()))})])).optional(),service_tier:d().nullish(),incomplete_details:k({reason:d()}).nullish(),usage:k({input_tokens:O(),input_tokens_details:k({cached_tokens:O().nullish()}).nullish(),output_tokens:O(),output_tokens_details:k({reasoning_tokens:O().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([me(),O().min(1).max(H2)]).optional(),maxToolCalls:O().nullish(),metadata:yt().nullish(),parallelToolCalls:me().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:me().nullish(),strictJsonSchema:me().nullish(),textVerbosity:ce(["low","medium","high"]).nullish(),truncation:ce(["auto","disabled"]).nullish(),user:d().nullish(),systemMessageMode:ce(["system","developer","remove"]).optional(),forceReasoning:me().optional()})));async function k8({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 mt({value:u.args,schema:FI});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 mt({value:u.args,schema:QI});a.push({type:"shell",...f.environment&&{environment:T8(f.environment)}});break}case"openai.apply_patch":{a.push({type:"apply_patch"});break}case"openai.web_search_preview":{const f=await mt({value:u.args,schema:l8});a.push({type:"web_search_preview",search_context_size:f.searchContextSize,user_location:f.userLocation});break}case"openai.web_search":{const f=await mt({value:u.args,schema:n8});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 mt({value:u.args,schema:AI});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 mt({value:u.args,schema:BI});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 mt({value:u.args,schema:p8}),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 mt({value:u.args,schema:jI});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 mt({value:u.args,schema:e8});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 Mr({functionality:`tool choice type: ${u}`})}}}function T8(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:C8(r.skills)}}return{type:"local",skills:e.skills}}function C8(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 W2(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 S8=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 Fr({provider:R,providerOptions:c,schema:J2});S==null&&R!=="openai"&&(S=await Fr({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 N=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 k8({tools:u,toolChoice:f,toolNameMapping:N,customProviderToolNames:L}),{input:ee,warnings:Q}=await y8({prompt:l,toolNameMapping:N,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:N,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,N,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=W2(e.prompt),{responseHeaders:E,value:U,rawValue:F}=await Jt({url:ne,headers:At(this.config.headers(),e.headers),body:z,failedResponseHandler:Cr,successfulResponseHandler:Wt(b8),abortSignal:e.abortSignal,fetch:this.config.fetch});if(U.error)throw new lt({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 W of U.output)switch(W.type){case"reasoning":{W.summary.length===0&&W.summary.push({type:"summary_text",text:""});for(const A of W.summary)x.push({type:"reasoning",text:A.text,providerMetadata:{[Q]:{itemId:W.id,reasoningEncryptedContent:(t=W.encrypted_content)!=null?t:null}}});break}case"image_generation_call":{x.push({type:"tool-call",toolCallId:W.id,toolName:ee.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),x.push({type:"tool-result",toolCallId:W.id,toolName:ee.toCustomToolName("image_generation"),result:{result:W.result}});break}case"tool_search_call":{const A=(r=W.call_id)!=null?r:W.id,V=W.execution==="server";V&&re.push(A),x.push({type:"tool-call",toolCallId:A,toolName:ee.toCustomToolName("tool_search"),input:JSON.stringify({arguments:W.arguments,call_id:W.call_id}),...V?{providerExecuted:!0}:{},providerMetadata:{[Q]:{itemId:W.id}}});break}case"tool_search_output":{const A=(o=(n=W.call_id)!=null?n:re.shift())!=null?o:W.id;x.push({type:"tool-result",toolCallId:A,toolName:ee.toCustomToolName("tool_search"),result:{tools:W.tools},providerMetadata:{[Q]:{itemId:W.id}}});break}case"local_shell_call":{x.push({type:"tool-call",toolCallId:W.call_id,toolName:ee.toCustomToolName("local_shell"),input:JSON.stringify({action:W.action}),providerMetadata:{[Q]:{itemId:W.id}}});break}case"shell_call":{x.push({type:"tool-call",toolCallId:W.call_id,toolName:ee.toCustomToolName("shell"),input:JSON.stringify({action:{commands:W.action.commands}}),...Z&&{providerExecuted:!0},providerMetadata:{[Q]:{itemId:W.id}}});break}case"shell_call_output":{x.push({type:"tool-result",toolCallId:W.call_id,toolName:ee.toCustomToolName("shell"),result:{output:W.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 W.content){(i=(s=e.providerOptions)==null?void 0:s[Q])!=null&&i.logprobs&&A.logprobs&&M.push(A.logprobs);const V={itemId:W.id,...W.phase!=null&&{phase:W.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:Ut(),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:Ut(),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:Ut(),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:Ut(),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:W.call_id,toolName:W.name,input:W.arguments,providerMetadata:{[Q]:{itemId:W.id}}});break}case"custom_tool_call":{H=!0;const A=ee.toCustomToolName(W.name);x.push({type:"tool-call",toolCallId:W.call_id,toolName:A,input:JSON.stringify(W.input),providerMetadata:{[Q]:{itemId:W.id}}});break}case"web_search_call":{x.push({type:"tool-call",toolCallId:W.id,toolName:ee.toCustomToolName(X??"web_search"),input:JSON.stringify({}),providerExecuted:!0}),x.push({type:"tool-result",toolCallId:W.id,toolName:ee.toCustomToolName(X??"web_search"),result:K2(W.action)});break}case"mcp_call":{const A=W.approval_request_id!=null&&(m=D[W.approval_request_id])!=null?m:W.id,V=`mcp.${W.name}`;x.push({type:"tool-call",toolCallId:A,toolName:V,input:W.arguments,providerExecuted:!0,dynamic:!0}),x.push({type:"tool-result",toolCallId:A,toolName:V,result:{type:"call",serverLabel:W.server_label,name:W.name,arguments:W.arguments,...W.output!=null?{output:W.output}:{},...W.error!=null?{error:W.error}:{}},providerMetadata:{[Q]:{itemId:W.id}}});break}case"mcp_list_tools":break;case"mcp_approval_request":{const A=(C=W.approval_request_id)!=null?C:W.id,V=(I=(T=(b=this.config).generateId)==null?void 0:T.call(b))!=null?I:Ut(),J=`mcp.${W.name}`;x.push({type:"tool-call",toolCallId:V,toolName:J,input:W.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:W.id,toolName:ee.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),x.push({type:"tool-result",toolCallId:W.id,toolName:ee.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:W.status||"completed"}});break}case"file_search_call":{x.push({type:"tool-call",toolCallId:W.id,toolName:ee.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),x.push({type:"tool-result",toolCallId:W.id,toolName:ee.toCustomToolName("file_search"),result:{queries:W.queries,results:(S=(R=W.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:W.id,toolName:ee.toCustomToolName("code_interpreter"),input:JSON.stringify({code:W.code,containerId:W.container_id}),providerExecuted:!0}),x.push({type:"tool-result",toolCallId:W.id,toolName:ee.toCustomToolName("code_interpreter"),result:{outputs:W.outputs}});break}case"apply_patch_call":{x.push({type:"tool-call",toolCallId:W.call_id,toolName:ee.toCustomToolName("apply_patch"),input:JSON.stringify({callId:W.call_id,operation:W.operation}),providerMetadata:{[Q]:{itemId:W.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:mu({finishReason:(j=U.incomplete_details)==null?void 0:j.reason,hasFunctionCall:H}),raw:(L=(N=U.incomplete_details)==null?void 0:N.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 Jt({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:At(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:Cr,successfulResponseHandler:aa(w8),abortSignal:e.abortSignal,fetch:this.config.fetch}),u=this,f=W2(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,N,L,z,B,X,ee,Q,Z,ne,D,E,U,F,x,M,H,re,te,_e,W,A,V,J,Y,ue,Te,Be,it,gt,tt,nt,Lt,_t,Rr,Yt,Ge,_r;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(G2($)){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,qe=o.toCustomToolName("tool_search"),Ee=$.item.execution==="server";w[$.output_index]={toolName:qe,toolCallId:K,toolSearchExecution:(j=$.item.execution)!=null?j:"server"},Ee&&S.enqueue({type:"tool-input-start",id:K,toolName:qe,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:qe}=$.item;if(w[$.output_index]={toolName:o.toCustomToolName("apply_patch"),toolCallId:K,applyPatch:{hasDiff:qe.type==="delete_file",endEmitted:qe.type==="delete_file"}},S.enqueue({type:"tool-input-start",id:K,toolName:o.toCustomToolName("apply_patch")}),qe.type==="delete_file"){const Ee=JSON.stringify({callId:K,operation:qe});S.enqueue({type:"tool-input-delta",id:K,delta:Ee}),S.enqueue({type:"tool-input-end",id:K})}else S.enqueue({type:"tool-input-delta",id:K,delta:`{"callId":"${Fn(K)}","operation":{"type":"${Fn(qe.type)}","path":"${Fn(qe.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=(N=$.item.phase)!=null?N:void 0,S.enqueue({type:"text-start",id:$.item.id,providerMetadata:{[i]:{itemId:$.item.id,...$.item.phase!=null&&{phase:$.item.phase}}}})):G2($)&&$.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(x8($)){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],qe=$.item.execution==="server";if(K!=null){const Ee=qe?K.toolCallId:(ee=$.item.call_id)!=null?ee:$.item.id;qe?I.push(Ee):S.enqueue({type:"tool-input-start",id:Ee,toolName:K.toolName}),S.enqueue({type:"tool-input-end",id:Ee}),S.enqueue({type:"tool-call",toolCallId:Ee,toolName:K.toolName,input:JSON.stringify({arguments:$.item.arguments,call_id:qe?null:Ee}),...qe?{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,qe=K!=null&&(E=(D=p.get(K))!=null?D:f[K])!=null?E:$.item.id,Ee=`mcp.${$.item.name}`;S.enqueue({type:"tool-call",toolCallId:qe,toolName:Ee,input:$.item.arguments,providerExecuted:!0,dynamic:!0}),S.enqueue({type:"tool-result",toolCallId:qe,toolName:Ee,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:Ut(),qe=(M=$.item.approval_request_id)!=null?M:$.item.id;p.set(qe,K);const Ee=`mcp.${$.item.name}`;S.enqueue({type:"tool-call",toolCallId:K,toolName:Ee,input:$.item.arguments,providerExecuted:!0,dynamic:!0}),S.enqueue({type:"tool-approval-request",approvalId:qe,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],qe=Object.entries(K.summaryParts).filter(([Ee,ot])=>ot==="active"||ot==="can-conclude").map(([Ee])=>Ee);for(const Ee of qe)S.enqueue({type:"reasoning-end",id:`${$.item.id}:${Ee}`,providerMetadata:{[i]:{itemId:$.item.id,reasoningEncryptedContent:(H=$.item.encrypted_content)!=null?H:null}}});delete b[$.item.id]}}else if(P8($)){const K=w[$.output_index];K!=null&&S.enqueue({type:"tool-input-delta",id:K.toolCallId,delta:$.delta})}else if(M8($)){const K=w[$.output_index];K!=null&&S.enqueue({type:"tool-input-delta",id:K.toolCallId,delta:$.delta})}else if(q8($)){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(L8($)){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(N8($))S.enqueue({type:"tool-result",toolCallId:$.item_id,toolName:o.toCustomToolName("image_generation"),result:{result:$.partial_image_b64},preliminary:!0});else if(O8($)){const K=w[$.output_index];K!=null&&S.enqueue({type:"tool-input-delta",id:K.toolCallId,delta:Fn($.delta)})}else if(A8($)){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(R8($))_=$.response.id,S.enqueue({type:"response-metadata",id:$.response.id,timestamp:new Date($.response.created_at*1e3),modelId:$.response.model});else if(I8($))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 qe of Object.keys(K.summaryParts))K.summaryParts[qe]==="can-conclude"&&(S.enqueue({type:"reasoning-end",id:`${$.item_id}:${qe}`,providerMetadata:{[i]:{itemId:$.item_id}}}),K.summaryParts[qe]="concluded");S.enqueue({type:"reasoning-start",id:`${$.item_id}:${$.summary_index}`,providerMetadata:{[i]:{itemId:$.item_id,reasoningEncryptedContent:(W=(_e=b[$.item_id])==null?void 0:_e.encryptedContent)!=null?W: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(E8($))h={unified:mu({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($8($)){const K=(Y=$.response.incomplete_details)==null?void 0:Y.reason;h={unified:K?mu({finishReason:K,hasFunctionCall:C}):"error",raw:K??"error"},g=(ue=$.response.usage)!=null?ue:void 0}else j8($)?(y.push($.annotation),$.annotation.type==="url_citation"?S.enqueue({type:"source",sourceType:"url",id:(it=(Be=(Te=u.config).generateId)==null?void 0:Be.call(Te))!=null?it:Ut(),url:$.annotation.url,title:$.annotation.title}):$.annotation.type==="file_citation"?S.enqueue({type:"source",sourceType:"document",id:(nt=(tt=(gt=u.config).generateId)==null?void 0:tt.call(gt))!=null?nt:Ut(),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:(Rr=(_t=(Lt=u.config).generateId)==null?void 0:_t.call(Lt))!=null?Rr:Ut(),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:(_r=(Ge=(Yt=u.config).generateId)==null?void 0:Ge.call(Yt))!=null?_r:Ut(),mediaType:"application/octet-stream",title:$.annotation.file_id,filename:$.annotation.file_id,providerMetadata:{[i]:{type:$.annotation.type,fileId:$.annotation.file_id,index:$.annotation.index}}})):D8($)&&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 I8(e){return e.type==="response.output_text.delta"}function x8(e){return e.type==="response.output_item.done"}function E8(e){return e.type==="response.completed"||e.type==="response.incomplete"}function $8(e){return e.type==="response.failed"}function R8(e){return e.type==="response.created"}function P8(e){return e.type==="response.function_call_arguments.delta"}function M8(e){return e.type==="response.custom_tool_call_input.delta"}function N8(e){return e.type==="response.image_generation_call.partial_image"}function O8(e){return e.type==="response.code_interpreter_call_code.delta"}function A8(e){return e.type==="response.code_interpreter_call_code.done"}function q8(e){return e.type==="response.apply_patch_call_operation_diff.delta"}function L8(e){return e.type==="response.apply_patch_call_operation_diff.done"}function G2(e){return e.type==="response.output_item.added"}function j8(e){return e.type==="response.output_text.annotation.added"}function D8(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 U8=ve(()=>ye(k({instructions:d().nullish(),speed:O().min(.25).max(4).default(1).nullish()}))),z8=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 Fr({provider:"openai",providerOptions:i,schema:U8}),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 Jt({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:At(this.config.headers(),e.headers),body:s,failedResponseHandler:Cr,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}}}},F8=ve(()=>ye(k({text:d(),language:d().nullish(),duration:O().nullish(),words:q(k({word:d(),start:O(),end:O()})).nullish(),segments:q(k({id:O(),seek:O(),start:O(),end:O(),text:d(),tokens:q(O()),temperature:O(),avg_logprob:O(),compression_ratio:O(),no_speech_prob:O()})).nullish()}))),V8=ve(()=>ye(k({include:q(d()).optional(),language:d().optional(),prompt:d().optional(),temperature:O().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"},Z8=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 Fr({provider:"openai",providerOptions:r,schema:V8}),s=new FormData,i=e instanceof Uint8Array?new Blob([e]):new Blob([io(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:At(this.config.headers(),e.headers),formData:u,failedResponseHandler:Cr,successfulResponseHandler:Wt(F8),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}}}},B8="3.0.50";function Q2(e={}){var t,r;const n=(t=Qf(uo({settingValue:e.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?t:"https://api.openai.com/v1",o=(r=e.name)!=null?r:"openai",s=()=>ln({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/${B8}`),i=v=>new yI(v,{provider:`${o}.chat`,url:({path:_})=>`${n}${_}`,headers:s,fetch:e.fetch}),a=v=>new kI(v,{provider:`${o}.completion`,url:({path:_})=>`${n}${_}`,headers:s,fetch:e.fetch}),l=v=>new SI(v,{provider:`${o}.embedding`,url:({path:_})=>`${n}${_}`,headers:s,fetch:e.fetch}),c=v=>new $I(v,{provider:`${o}.image`,url:({path:_})=>`${n}${_}`,headers:s,fetch:e.fetch}),u=v=>new Z8(v,{provider:`${o}.transcription`,url:({path:_})=>`${n}${_}`,headers:s,fetch:e.fetch}),f=v=>new z8(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 S8(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=_8,g}Q2();var X2="vercel.ai.error",H8=Symbol.for(X2),eg,J8=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=H8;var xt=J8,tg="AI_APICallError",rg=`vercel.ai.error.${tg}`,W8=Symbol.for(rg),ng,Hr=class extends xt{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 xt.hasMarker(e,rg)}};ng=W8;var og="AI_EmptyResponseBodyError",sg=`vercel.ai.error.${og}`,G8=Symbol.for(sg),ag,K8=class extends xt{constructor({message:e="Empty response body"}={}){super({name:og,message:e}),this[ag]=!0}static isInstance(e){return xt.hasMarker(e,sg)}};ag=G8;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}`,Y8=Symbol.for(cg),ug,dg=class extends xt{constructor({message:e,cause:t,argument:r}){super({name:lg,message:e,cause:t}),this[ug]=!0,this.argument=r}static isInstance(e){return xt.hasMarker(e,cg)}};ug=Y8;var pg="AI_InvalidResponseDataError",fg=`vercel.ai.error.${pg}`,Q8=Symbol.for(fg),hg,mg=class extends xt{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 xt.hasMarker(e,fg)}};hg=Q8;var gg="AI_JSONParseError",_g=`vercel.ai.error.${gg}`,X8=Symbol.for(_g),yg,za=class extends xt{constructor({text:e,cause:t}){super({name:gg,message:`JSON parsing failed: Text: ${e}.
|
|
79
|
-
Error message: ${
|
|
80
|
-
Error message: ${ig(r)}`,cause:r}),this[Eg]=!0,this.value=t}static isInstance(t){return xt.hasMarker(t,xg)}static wrap({value:t,cause:r}){return hd.isInstance(r)&&r.value===t?r:new hd({value:t,cause:r})}};Eg=rx;var ws=nx,$g="AI_UnsupportedFunctionalityError",Rg=`vercel.ai.error.${$g}`,ox=Symbol.for(Rg),Pg,Mg=class extends xt{constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:$g,message:t}),this[Pg]=!0,this.functionality=e}static isInstance(e){return xt.hasMarker(e,Rg)}};Pg=ox;function Ng(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}function Va(e){return Object.fromEntries([...e.headers])}var sx=({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=sx();function gu(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var ax=["fetch failed","failed to fetch"];function ix({error:e,url:t,requestBodyValues:r}){if(gu(e))return e;if(e instanceof TypeError&&ax.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 lx(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 cx(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(cx(e)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var ux="3.0.18";function dx({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 px=/"__proto__"\s*:/,fx=/"constructor"\s*:/;function Ag(e){const t=JSON.parse(e);return t===null||typeof t!="object"||px.test(e)===!1&&fx.test(e)===!1?t:hx(t)}function hx(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 _u(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return Ag(e)}try{return Ag(e)}finally{Error.stackTraceLimit=t}}var yu=Symbol.for("vercel.ai.validator");function mx(e){return{[yu]:!0,validate:e}}function gx(e){return typeof e=="object"&&e!==null&&yu in e&&e[yu]===!0&&"validate"in e}function _x(e){return gx(e)?e:typeof e=="function"?e():yx(e)}function yx(e){return mx(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 vx({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=_x(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 wx({text:e,schema:t}){try{const r=_u(e);return t==null?r:vx({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=_u(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 _u(e),!0}catch{return!1}}function bx({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new so).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 kx=()=>globalThis.fetch,Dg=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i})=>Tx({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i}),Tx=async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:s,fetch:i=kx()})=>{try{const a=await i(e,{method:"POST",headers:Og(t,`ai-sdk/provider-utils/${ux}`,lx()),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 gu(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&&(gu(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 ix({error:a,url:e,requestBodyValues:r.values})}},Cx=({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 wx({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)})}}},Sx=e=>async({response:t})=>{const r=Va(t);if(t.body==null)throw new K8({});return{responseHeaders:r,value:bx({stream:t.body,schema:e})}},Ix=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:xx}=globalThis;function Ex(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return xx(t)}function $x(e){return e instanceof Uint8Array?Ex(e):e}function Rx(e){return e?.replace(/\/$/,"")}function ks(e){var t,r;return(r=(t=e?.providerOptions)==null?void 0:t.openaiCompatible)!=null?r:{}}function Px(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,${$x(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 vu=k({user:d().optional(),reasoningEffort:d().optional(),textVerbosity:d().optional()}),Mx=k({error:k({message:d(),type:d().nullish(),param:yt().nullish(),code:ae([d(),O()]).nullish()})}),Nx={errorSchema:Mx,errorToMessage:e=>e.error.message};function Ox({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 Ax=class{constructor(e,t){this.specificationVersion="v2";var r,n;this.modelId=e,this.config=t;const o=(r=t.errorStructure)!=null?r:Nx;this.chunkSchema=Lx(o.errorSchema),this.failedResponseHandler=Cx(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:vu}))!=null?h:{},(g=await jg({provider:this.providerOptionsName,providerOptions:a,schema:vu}))!=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}=Ox({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(vu.shape).includes(T))),reasoning_effort:y.reasoningEffort,verbosity:y.textVerbosity,messages:Px(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:Ix(qx),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 N=(t=R.message.reasoning_content)!=null?t:R.message.reasoning;if(N!=null&&N.length>0&&S.push({type:"reasoning",text:N}),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:Sx(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,N,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:""}),((N=D.function)==null?void 0:N.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:O().nullish(),completion_tokens:O().nullish(),total_tokens:O().nullish(),prompt_tokens_details:k({cached_tokens:O().nullish()}).nullish(),completion_tokens_details:k({reasoning_tokens:O().nullish(),accepted_prediction_tokens:O().nullish(),rejected_prediction_tokens:O().nullish()}).nullish()}).nullish(),qx=k({id:d().nullish(),created:O().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}),Lx=e=>ae([k({id:d().nullish(),created:O().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:O(),id:d().nullish(),function:k({name:d().nullish(),arguments:d().nullish()})})).nullish()}).nullish(),finish_reason:d().nullish()})),usage:Fg}),e]);k({echo:me().optional(),logitBias:ge(d(),O()).optional(),suffix:d().optional(),user:d().optional()});var jx=k({prompt_tokens:O(),completion_tokens:O(),total_tokens:O()});k({id:d().nullish(),created:O().nullish(),model:d().nullish(),choices:q(k({text:d(),finish_reason:d()})),usage:jx.nullish()}),k({dimensions:O().optional(),user:d().optional()}),k({data:q(k({embedding:q(O())})),usage:k({prompt_tokens:O()}).nullish(),providerMetadata:ge(d(),ge(d(),yt())).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}}},Dx={extractMetadata:async({parsedBody:e})=>{const t=await bs({value:e,schema:Ux});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:zx});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:O().nullish(),prompt_cache_miss_tokens:O().nullish()}),Ux=k({usage:Zg.nullish()}),zx=k({choices:q(k({finish_reason:d().nullish()})).nullish(),usage:Zg.nullish()}),Fx="1.0.30";function Bg(e={}){var t;const r=Rx((t=e.baseURL)!=null?t:"https://api.deepseek.com/v1"),n=()=>Og({Authorization:`Bearer ${dx({apiKey:e.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...e.headers},`ai-sdk/deepseek/${Fx}`);class o extends Ax{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:Dx}),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 Vx=(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})},Zx=(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 Bx{constructor(t){this._isStarted=!1,this._isClosed=!1,this.targetSessionId=t,this._messageListener=Zx("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}`),Vx("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 dn(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 Hx(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=Hx(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Wg(e,t){const r=dn(e,t);if(!r.success)throw r.error;return r.data}const Jx=6e4;class Wx{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(mc,r=>{this._oncancel(r)}),this.setNotificationHandler(_c,r=>{this._onprogress(r)}),this.setRequestHandler(gc,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(yc,async(r,n)=>{const o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new ke(xe.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(wc,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 ke(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 ke(xe.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(bc,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 ke(xe.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Tc,async(r,n)=>{try{const o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new ke(xe.InvalidParams,`Task not found: ${r.params.taskId}`);if(Vn(o.status))throw new ke(xe.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 ke(xe.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof ke?o:new ke(xe.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),ke.fromError(xe.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)||u5(s)?this._onresponse(s):pc(s)?this._onrequest(s,i):c5(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=ke.fromError(xe.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:xe.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=l5(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:xe.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 ke(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=ke.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 ke?i:new ke(xe.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 ke(xe.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 ke(xe.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new ke(xe.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 ke?i:new ke(xe.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 ke?y:new ke(xe.RequestTimeout,String(y));u(m)};this._responseHandlers.set(p,y=>{if(!n?.signal?.aborted){if(y instanceof Error)return u(y);try{const m=dn(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??Jx,_=()=>g(ke.fromError(xe.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},vc,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},kc,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},x5,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=Wg(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=Wg(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"&&pc(o.message)){const s=o.message.id,i=this._requestResolvers.get(s);i?(i(new ke(xe.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 ke(xe.InvalidRequest,"Request cancelled"));return}const i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new ke(xe.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 ke(xe.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 ke(xe.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Vn(a.status))throw new ke(xe.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 Gg(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Gx(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];Gg(i)&&Gg(s)?r[o]={...i,...s}:r[o]=s}return r}var Ha={exports:{}},wu={},Jr={},Zn={},bu={},ku={},Tu={},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=_})(Tu)),Tu}var Cu={},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})(Cu)),Cu}var Xg;function Re(){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 N{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`,W=>{this.var(te,(0,t._)`${_e}[${W}]`),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=N;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})`}})(ku)),ku}var Pe={},e_;function Ue(){if(e_)return Pe;e_=1,Object.defineProperty(Pe,"__esModule",{value:!0}),Pe.checkStrictMode=Pe.getErrorPath=Pe.Type=Pe.useFunc=Pe.setEvaluated=Pe.evaluatedPropsToName=Pe.mergeEvaluated=Pe.eachItem=Pe.unescapeJsonPointer=Pe.escapeJsonPointer=Pe.escapeFragment=Pe.unescapeFragment=Pe.schemaRefOrVal=Pe.schemaHasRulesButRef=Pe.schemaHasRules=Pe.checkUnknownRules=Pe.alwaysValidSchema=Pe.toHash=void 0;const e=Re(),t=Ja();function r(b){const T={};for(const I of b)T[I]=!0;return T}Pe.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))}Pe.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}"`)}Pe.checkUnknownRules=o;function s(b,T){if(typeof b=="boolean")return!b;for(const I in b)if(T[I])return!0;return!1}Pe.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}Pe.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)}`}Pe.schemaRefOrVal=a;function l(b){return f(decodeURIComponent(b))}Pe.unescapeFragment=l;function c(b){return encodeURIComponent(u(b))}Pe.escapeFragment=c;function u(b){return typeof b=="number"?`${b}`:b.replace(/~/g,"~0").replace(/\//g,"~1")}Pe.escapeJsonPointer=u;function f(b){return b.replace(/~1/g,"/").replace(/~0/g,"~")}Pe.unescapeJsonPointer=f;function p(b,T){if(Array.isArray(b))for(const I of b)T(I);else T(b)}Pe.eachItem=p;function h({mergeNames:b,mergeToName:T,mergeValues:I,resultToName:R}){return(S,j,N,L)=>{const z=N===void 0?j:N instanceof e.Name?(j instanceof e.Name?b(S,j,N):T(S,j,N),N):j instanceof e.Name?(T(S,N,j),j):I(j,N);return L===e.Name&&!(z instanceof e.Name)?R(S,z):z}}Pe.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}Pe.evaluatedPropsToName=g;function v(b,T,I){Object.keys(I).forEach(R=>b.assign((0,e._)`${T}${(0,e.getProperty)(R)}`,!0))}Pe.setEvaluated=v;const _={};function w(b,T){return b.scopeValue("func",{ref:T,code:_[T.code]||(_[T.code]=new t._Code(T.code))})}Pe.useFunc=w;var y;(function(b){b[b.Num=0]="Num",b[b.Str=1]="Str"})(y||(Pe.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)}Pe.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 Pe.checkStrictMode=C,Pe}var Wa={},t_;function pn(){if(t_)return Wa;t_=1,Object.defineProperty(Wa,"__esModule",{value:!0});const e=Re(),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 Wa.default=t,Wa}var r_;function Ga(){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=Re(),r=Ue(),n=pn();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:N}=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}${N}`],[n.default.data,b]),S&&m.push([u.propertyName,S])}})(bu)),bu}var n_;function Kx(){if(n_)return Zn;n_=1,Object.defineProperty(Zn,"__esModule",{value:!0}),Zn.boolOrEmptySchema=Zn.topBoolOrEmptySchema=void 0;const e=Ga(),t=Re(),r=pn(),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 Nt={},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 Wr={},a_;function i_(){if(a_)return Wr;a_=1,Object.defineProperty(Wr,"__esModule",{value:!0}),Wr.shouldUseRule=Wr.shouldUseGroup=Wr.schemaHasRulesForType=void 0;function e({schema:n,self:o},s){const i=o.RULES.types[s];return i&&i!==!0&&t(n,i)}Wr.schemaHasRulesForType=e;function t(n,o){return o.rules.some(s=>r(n,s))}Wr.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 Wr.shouldUseRule=r,Wr}var l_;function Ka(){if(l_)return Nt;l_=1,Object.defineProperty(Nt,"__esModule",{value:!0}),Nt.reportTypeError=Nt.checkDataTypes=Nt.checkDataType=Nt.coerceAndCheckDataType=Nt.getJSONTypes=Nt.getSchemaTypes=Nt.DataType=void 0;const e=s_(),t=i_(),r=Ga(),n=Re(),o=Ue();var s;(function(y){y[y.Correct=0]="Correct",y[y.Wrong=1]="Wrong"})(s||(Nt.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}Nt.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(","))}Nt.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}Nt.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 N of C)(c.has(N)||N==="array"&&I.coerceTypes==="array")&&j(N);b.else(),_(y),b.endIf(),b.if((0,n._)`${S} !== undefined`,()=>{b.assign(T,S),p(y,S)});function j(N){switch(N){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
|
-
|| (${
|
|
83
|
-
|| (${
|
|
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)}}Nt.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}Nt.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)}Nt.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 Nt}var Ts={},c_;function Yx(){if(c_)return Ts;c_=1,Object.defineProperty(Ts,"__esModule",{value:!0}),Ts.assignDefaults=void 0;const e=Re(),t=Ue();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 Sr={},We={},u_;function Ir(){if(u_)return We;u_=1,Object.defineProperty(We,"__esModule",{value:!0}),We.validateUnion=We.validateArray=We.usePattern=We.callValidateCode=We.schemaProperties=We.allSchemaProperties=We.noPropertyInData=We.propertyInData=We.isOwnProperty=We.hasPropFunc=We.reportMissingProp=We.checkMissingProp=We.checkReportMissingProp=void 0;const e=Re(),t=Ue(),r=pn(),n=Ue();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()})}We.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}`)))}We.checkMissingProp=s;function i(y,m){y.setParams({missingProperty:m},!0),y.error()}We.reportMissingProp=i;function a(y){return y.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,e._)`Object.prototype.hasOwnProperty`})}We.hasPropFunc=a;function l(y,m,C){return(0,e._)`${a(y)}.call(${m}, ${C})`}We.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}We.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}We.noPropertyInData=u;function f(y){return y?Object.keys(y).filter(m=>m!=="__proto__"):[]}We.allSchemaProperties=f;function p(y,m){return f(m).filter(C=>!(0,t.alwaysValidSchema)(y,m[C]))}We.schemaProperties=p;function h({schemaCode:y,data:m,it:{gen:C,topSchemaRef:b,schemaPath:T,errorPath:I},it:R},S,j,N){const L=N?(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})`}We.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})`})}We.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,N=>{y.subschema({keyword:b,dataProp:N,dataPropType:t.Type.Num},I),m.if((0,e.not)(I),S)})}}We.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,N)=>{const L=y.subschema({keyword:b,schemaProp:N,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 We.validateUnion=w,We}var d_;function Qx(){if(d_)return Sr;d_=1,Object.defineProperty(Sr,"__esModule",{value:!0}),Sr.validateKeywordUsage=Sr.validSchemaType=Sr.funcKeywordCode=Sr.macroKeywordCode=void 0;const e=Re(),t=pn(),r=Ir(),n=Ga();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))}Sr.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)N(),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(()=>N((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),N(e.nil),z}function N(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)}}Sr.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")}Sr.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 Sr.validateKeywordUsage=f,Sr}var Gr={},p_;function Xx(){if(p_)return Gr;p_=1,Object.defineProperty(Gr,"__esModule",{value:!0}),Gr.extendSubschemaMode=Gr.extendSubschemaData=Gr.getSubschema=void 0;const e=Re(),t=Ue();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')}Gr.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]}}Gr.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 Gr.extendSubschemaMode=o,Gr}var Vt={},Su,f_;function h_(){return f_||(f_=1,Su=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}),Su}var Iu={exports:{}},m_;function e7(){if(m_)return Iu.exports;m_=1;var e=Iu.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 Iu.exports}var g_;function Ya(){if(g_)return Vt;g_=1,Object.defineProperty(Vt,"__esModule",{value:!0}),Vt.getSchemaRefs=Vt.resolveUrl=Vt.normalizeId=Vt._getFullPath=Vt.getFullPath=Vt.inlineRef=void 0;const e=Ue(),t=h_(),r=e7(),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}Vt.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)}Vt.getFullPath=l;function c(v,_){return v.serialize(_).split("#")[0]+"#"}Vt._getFullPath=c;const u=/#\/?$/;function f(v){return v?v.replace(u,""):""}Vt.normalizeId=f;function p(v,_,w){return w=f(w),v.resolve(_,w)}Vt.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,N,L,z)=>{if(z===void 0)return;const B=b+N;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[N]=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,N,L){if(N!==void 0&&!t(j,N))throw S(L)}function S(j){return new Error(`reference "${j}" resolves to more than one schema`)}}return Vt.getSchemaRefs=g,Vt}var __;function Qa(){if(__)return Jr;__=1,Object.defineProperty(Jr,"__esModule",{value:!0}),Jr.getData=Jr.KeywordCxt=Jr.validateFunctionCode=void 0;const e=Kx(),t=Ka(),r=i_(),n=Ka(),o=Yx(),s=Qx(),i=Xx(),a=Re(),l=pn(),c=Ya(),u=Ue(),f=Ga();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},Te){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(Te)}):A.func(V,(0,a._)`${l.default.data}, ${g(ue)}`,Y.$async,()=>A.code(y(J,ue)).code(Te))}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),N(A),L(A);const Te=Y.const("_errs",l.default.errors);R(A,Te),Y.var(V,(0,a._)`${Te} === ${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 N(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 Te=J.$comment;if(ue.$comment===!0)A.code((0,a._)`${l.default.self}.logger.log(${Te})`);else if(typeof ue.$comment=="function"){const Be=(0,a.str)`${Y}/$comment`,it=A.scopeValue("root",{ref:V.root});A.code((0,a._)`${l.default.self}.opts.$comment(${Te}, ${Be}, ${it}.schema)`)}}function B(A){const{gen:V,schemaEnv:J,validateName:Y,ValidationError:ue,opts:Te}=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),Te.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:Te,data:Be,allErrors:it,opts:gt,self:tt}=A,{RULES:nt}=tt;if(Te.$ref&&(gt.ignoreKeywordsWithRef||!(0,u.schemaHasRulesButRef)(Te,nt))){ue.block(()=>re(A,"$ref",nt.all.$ref.definition));return}gt.jtd||Z(A,V),ue.block(()=>{for(const _t of nt.rules)Lt(_t);Lt(nt.post)});function Lt(_t){(0,r.shouldUseGroup)(Te,_t)&&(_t.type?(ue.if((0,n.checkDataType)(_t.type,Be,gt.strictNumbers)),Q(A,_t),V.length===1&&V[0]===_t.type&&J&&(ue.else(),(0,n.reportTypeError)(A)),ue.endIf()):Q(A,_t),it||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 Te of V.rules)(0,r.shouldUseRule)(Y,Te)&&re(A,Te.keyword,Te.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:Te}=ue.definition;Te.length&&!Te.some(Be=>U(V,Be))&&M(A,`missing type "${Te.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",W(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:Te,def:Be}=this;Y.if((0,a.or)((0,a._)`${ue} === undefined`,J)),V!==a.nil&&Y.assign(V,!0),(Te.length||Be.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:Te}=this;return(0,a.or)(Be(),it());function Be(){if(Y.length){if(!(J instanceof a.Name))throw new Error("ajv implementation error");const gt=Array.isArray(Y)?Y:[Y];return(0,a._)`${(0,n.checkDataTypes)(gt,J,Te.opts.strictNumbers,n.DataType.Wrong)}`}return a.nil}function it(){if(ue.validateSchema){const gt=V.scopeValue("validate$data",{ref:ue.validateSchema});return(0,a._)`!${gt}(${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 W(A,{dataLevel:V,dataNames:J,dataPathArr:Y}){let ue,Te;if(A==="")return l.default.rootData;if(A[0]==="/"){if(!te.test(A))throw new Error(`Invalid JSON-pointer: ${A}`);ue=A,Te=l.default.rootData}else{const tt=_e.exec(A);if(!tt)throw new Error(`Invalid JSON-pointer: ${A}`);const nt=+tt[1];if(ue=tt[2],ue==="#"){if(nt>=V)throw new Error(gt("property/index",nt));return Y[V-nt]}if(nt>V)throw new Error(gt("data",nt));if(Te=J[V-nt],!ue)return Te}let Be=Te;const it=ue.split("/");for(const tt of it)tt&&(Te=(0,a._)`${Te}${(0,a.getProperty)((0,u.unescapeJsonPointer)(tt))}`,Be=(0,a._)`${Be} && ${Te}`);return Be;function gt(tt,nt){return`Cannot access ${tt} ${nt} levels up, current level is ${V}`}}return Jr.getData=W,Jr}var Xa={},y_;function xu(){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 Eu(){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=Re(),t=xu(),r=pn(),n=Ya(),o=Ue(),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 N=T.toString();j=`${T.scopeRefs(r.default.scope)}return ${N}`,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:N,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(N){throw delete _.validate,delete _.validateName,j&&this.logger.error("Error compiling schema, function code:",j),N}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 t7={$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:{}},$u,b_;function k_(){if(b_)return $u;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 $u={nonSimpleDomain:n,recomposeAuthority:f,normalizeComponentEncoding:u,removeDotSegments:c,isIPv4:t,isUUID:e,normalizeIPv6:a,stringArrayToHexStripped:r},$u}var Ru,T_;function r7(){if(T_)return Ru;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 N=b,L=b.nss;return N.path=`${R||T.nid}:${L}`,T.skipEscape=!0,N}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 Ru={wsIsSecure:o,SCHEMES:m,isValidSchemeName:n,getSchemeHandler:C},Ru}var C_;function n7(){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}=r7();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 o7(){if(S_)return ri;S_=1,Object.defineProperty(ri,"__esModule",{value:!0});const e=n7();return e.code='require("ajv/dist/runtime/uri").default',ri.default=e,ri}var I_;function s7(){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=Re();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=xu(),o=ti(),s=s_(),i=Eu(),a=Re(),l=Ya(),c=Ka(),u=Ue(),f=t7,p=o7(),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,W,A,V,J,Y,ue,Te,Be,it,gt,tt,nt,Lt,_t,Rr,Yt;const Ge=D.strict,_r=(E=D.code)===null||E===void 0?void 0:E.optimize,$=_r===!0||_r===void 0?1:_r||0,K=(F=(U=D.code)===null||U===void 0?void 0:U.regExp)!==null&&F!==void 0?F:h,qe=(x=D.uriResolver)!==null&&x!==void 0?x:p.default;return{strictSchema:(H=(M=D.strictSchema)!==null&&M!==void 0?M:Ge)!==null&&H!==void 0?H:!0,strictNumbers:(te=(re=D.strictNumbers)!==null&&re!==void 0?re:Ge)!==null&&te!==void 0?te:!0,strictTypes:(W=(_e=D.strictTypes)!==null&&_e!==void 0?_e:Ge)!==null&&W!==void 0?W:"log",strictTuples:(V=(A=D.strictTuples)!==null&&A!==void 0?A:Ge)!==null&&V!==void 0?V:"log",strictRequired:(Y=(J=D.strictRequired)!==null&&J!==void 0?J:Ge)!==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:(Te=D.loopEnum)!==null&&Te!==void 0?Te:y,meta:(Be=D.meta)!==null&&Be!==void 0?Be:!0,messages:(it=D.messages)!==null&&it!==void 0?it:!0,inlineRefs:(gt=D.inlineRefs)!==null&>!==void 0?gt:!0,schemaId:(tt=D.schemaId)!==null&&tt!==void 0?tt:"$id",addUsedSchema:(nt=D.addUsedSchema)!==null&&nt!==void 0?nt:!0,validateSchema:(Lt=D.validateSchema)!==null&&Lt!==void 0?Lt:!0,validateFormats:(_t=D.validateFormats)!==null&&_t!==void 0?_t:!0,unicodeRegExp:(Rr=D.unicodeRegExp)!==null&&Rr!==void 0?Rr:!0,int32range:(Yt=D.int32range)!==null&&Yt!==void 0?Yt:!0,uriResolver:qe}}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(W,A){await M.call(this,W.$schema);const V=this._addSchema(W,A);return V.validate||H.call(this,V)}async function M(W){W&&!this.getSchema(W)&&await x.call(this,{$ref:W},!0)}async function H(W){try{return this._compileSchemaEnv(W)}catch(A){if(!(A instanceof o.default))throw A;return re.call(this,A),await te.call(this,A.missingSchema),H.call(this,W)}}function re({missingSchema:W,missingRef:A}){if(this.refs[W])throw new Error(`AnySchema ${W} is loaded but ${A} cannot be resolved`)}async function te(W){const A=await _e.call(this,W);this.refs[W]||await M.call(this,A.$schema),this.refs[W]||this.addSchema(A,W,U)}async function _e(W){const A=this._loading[W];if(A)return A;try{return await(this._loading[W]=F(W))}finally{delete this._loading[W]}}}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,W=H[re];_e&&W&&(H[re]=ne(W))}}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 N={log(){},warn(){},error(){}};function L(D){if(D===!1)return N;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]}}})(wu)),wu}var ni={},oi={},si={},x_;function a7(){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 fn={},E_;function i7(){if(E_)return fn;E_=1,Object.defineProperty(fn,"__esModule",{value:!0}),fn.callRef=fn.getValidate=void 0;const e=ti(),t=Ir(),r=Re(),n=pn(),o=Eu(),s=Ue(),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`}fn.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 fn.callRef=l,fn.default=i,fn}var $_;function l7(){if($_)return oi;$_=1,Object.defineProperty(oi,"__esModule",{value:!0});const e=a7(),t=i7(),r=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",e.default,t.default];return oi.default=r,oi}var ai={},ii={},R_;function c7(){if(R_)return ii;R_=1,Object.defineProperty(ii,"__esModule",{value:!0});const e=Re(),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 u7(){if(P_)return li;P_=1,Object.defineProperty(li,"__esModule",{value:!0});const e=Re(),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 d7(){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 p7(){if(N_)return ci;N_=1,Object.defineProperty(ci,"__esModule",{value:!0});const e=Re(),t=Ue(),r=d7(),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 f7(){if(O_)return di;O_=1,Object.defineProperty(di,"__esModule",{value:!0});const e=Ir(),t=Ue(),r=Re(),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 h7(){if(A_)return pi;A_=1,Object.defineProperty(pi,"__esModule",{value:!0});const e=Re(),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 m7(){if(q_)return fi;q_=1,Object.defineProperty(fi,"__esModule",{value:!0});const e=Ir(),t=Re(),r=Ue(),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 g7(){if(L_)return hi;L_=1,Object.defineProperty(hi,"__esModule",{value:!0});const e=Re(),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 Pu(){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 _7(){if(D_)return mi;D_=1,Object.defineProperty(mi,"__esModule",{value:!0});const e=Ka(),t=Re(),r=Ue(),n=Pu(),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 y7(){if(U_)return _i;U_=1,Object.defineProperty(_i,"__esModule",{value:!0});const e=Re(),t=Ue(),r=Pu(),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 v7(){if(z_)return yi;z_=1,Object.defineProperty(yi,"__esModule",{value:!0});const e=Re(),t=Ue(),r=Pu(),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 w7(){if(F_)return ai;F_=1,Object.defineProperty(ai,"__esModule",{value:!0});const e=c7(),t=u7(),r=p7(),n=f7(),o=h7(),s=m7(),i=g7(),a=_7(),l=y7(),c=v7(),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={},Co={},V_;function Z_(){if(V_)return Co;V_=1,Object.defineProperty(Co,"__esModule",{value:!0}),Co.validateAdditionalItems=void 0;const e=Re(),t=Ue(),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 Co.validateAdditionalItems=o,Co.default=n,Co}var wi={},So={},B_;function H_(){if(B_)return So;B_=1,Object.defineProperty(So,"__esModule",{value:!0}),So.validateTuple=void 0;const e=Re(),t=Ue(),r=Ir(),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 So.validateTuple=o,So.default=n,So}var J_;function b7(){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={},W_;function k7(){if(W_)return bi;W_=1,Object.defineProperty(bi,"__esModule",{value:!0});const e=Re(),t=Ue(),r=Ir(),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={},G_;function T7(){if(G_)return ki;G_=1,Object.defineProperty(ki,"__esModule",{value:!0});const e=Re(),t=Ue(),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 Mu={},K_;function C7(){return K_||(K_=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=Re(),r=Ue(),n=Ir();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: ${
|
|
86
|
+
${t}:`]}}function Pg({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 Mg(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 B8=ye(()=>me(T({id:d().nullish(),created:q().nullish(),model:d().nullish(),choices:L(T({text:d(),finish_reason:d(),logprobs:T({tokens:L(d()),token_logprobs:L(q()),top_logprobs:L(pe(d(),q())).nullish()}).nullish()})),usage:T({prompt_tokens:q(),completion_tokens:q(),total_tokens:q()}).nullish()}))),J8=ye(()=>me(ae([T({id:d().nullish(),created:q().nullish(),model:d().nullish(),choices:L(T({text:d(),finish_reason:d().nullish(),index:q(),logprobs:T({tokens:L(d()),token_logprobs:L(q()),top_logprobs:L(pe(d(),q())).nullish()}).nullish()})),usage:T({prompt_tokens:q(),completion_tokens:q(),total_tokens:q()}).nullish()}),qu]))),Og=ye(()=>me(T({echo:_e().optional(),logitBias:pe(d(),q()).optional(),suffix:d().optional(),user:d().optional(),logprobs:ae([_e(),q()]).optional()}))),G8=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:a,presencePenalty:i,stopSequences:s,responseFormat:l,tools:c,toolChoice:u,seed:h,providerOptions:p}){const m=[],f={...await Ir({provider:"openai",providerOptions:p,schema:Og}),...await Ir({provider:this.providerOptionsName,providerOptions:p,schema:Og})};o!=null&&m.push({type:"unsupported",feature:"topK"}),c?.length&&m.push({type:"unsupported",feature:"tools"}),u!=null&&m.push({type:"unsupported",feature:"toolChoice"}),l!=null&&l.type!=="text"&&m.push({type:"unsupported",feature:"responseFormat",details:"JSON response format is not supported."});const{prompt:b,stopSequences:w}=H8({prompt:e}),C=[...w??[],...s??[]];return{args:{model:this.modelId,echo:f.echo,logit_bias:f.logitBias,logprobs:f?.logprobs===!0?0:f?.logprobs===!1?void 0:f?.logprobs,suffix:f.suffix,user:f.user,max_tokens:t,temperature:r,top_p:n,frequency_penalty:a,presence_penalty:i,seed:h,prompt:b,stop:C.length>0?C:void 0},warnings:m}}async doGenerate(e){var t;const{args:r,warnings:n}=await this.getArgs(e),{responseHeaders:o,value:a,rawValue:i}=await Ot({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:It(this.config.headers(),e.headers),body:r,failedResponseHandler:Rr,successfulResponseHandler:At(B8),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=a.choices[0],l={openai:{}};return s.logprobs!=null&&(l.openai.logprobs=s.logprobs),{content:[{type:"text",text:s.text}],usage:Rg(a.usage),finishReason:{unified:Mg(s.finish_reason),raw:(t=s.finish_reason)!=null?t:void 0},request:{body:r},response:{...Pg(a),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:a}=await Ot({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:It(this.config.headers(),e.headers),body:n,failedResponseHandler:Rr,successfulResponseHandler:_s(J8),abortSignal:e.abortSignal,fetch:this.config.fetch});let i={unified:"other",raw:void 0};const s={openai:{}};let l,c=!0;return{stream:a.pipeThrough(new TransformStream({start(u){u.enqueue({type:"stream-start",warnings:r})},transform(u,h){if(e.includeRawChunks&&h.enqueue({type:"raw",rawValue:u.rawValue}),!u.success){i={unified:"error",raw:void 0},h.enqueue({type:"error",error:u.error});return}const p=u.value;if("error"in p){i={unified:"error",raw:void 0},h.enqueue({type:"error",error:p.error});return}c&&(c=!1,h.enqueue({type:"response-metadata",...Pg(p)}),h.enqueue({type:"text-start",id:"0"})),p.usage!=null&&(l=p.usage);const m=p.choices[0];m?.finish_reason!=null&&(i={unified:Mg(m.finish_reason),raw:m.finish_reason}),m?.logprobs!=null&&(s.openai.logprobs=m.logprobs),m?.text!=null&&m.text.length>0&&h.enqueue({type:"text-delta",id:"0",delta:m.text})},flush(u){c||u.enqueue({type:"text-end",id:"0"}),u.enqueue({type:"finish",finishReason:i,providerMetadata:s,usage:Rg(l)})}})),request:{body:n},response:{headers:o}}}},W8=ye(()=>me(T({dimensions:q().optional(),user:d().optional()}))),K8=ye(()=>me(T({data:L(T({embedding:L(q())})),usage:T({prompt_tokens:q()}).nullish()}))),Y8=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 P1({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const a=(o=await Ir({provider:"openai",providerOptions:n,schema:W8}))!=null?o:{},{responseHeaders:i,value:s,rawValue:l}=await Ot({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:It(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:"float",dimensions:a.dimensions,user:a.user},failedResponseHandler:Rr,successfulResponseHandler:At(K8),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:s.data.map(c=>c.embedding),usage:s.usage?{tokens:s.usage.prompt_tokens}:void 0,response:{headers:i,body:l}}}},Ag=ye(()=>me(T({created:q().nullish(),data:L(T({b64_json:d(),revised_prompt:d().nullish()})),background:d().nullish(),output_format:d().nullish(),size:d().nullish(),quality:d().nullish(),usage:T({input_tokens:q().nullish(),output_tokens:q().nullish(),total_tokens:q().nullish(),input_tokens_details:T({image_tokens:q().nullish(),text_tokens:q().nullish()}).nullish()}).nullish()}))),Q8={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10,"gpt-image-2":10,"chatgpt-image-latest":10},X8=["chatgpt-image-","gpt-image-1-mini","gpt-image-1.5","gpt-image-1","gpt-image-2"];function ex(e){return X8.some(t=>e.startsWith(t))}var Ng=T({quality:le(["standard","hd","low","medium","high","auto"]).optional(),background:le(["transparent","opaque","auto"]).optional(),outputFormat:le(["png","jpeg","webp"]).optional(),outputCompression:q().int().min(0).max(100).optional(),user:d().optional()}),tx=ye(()=>me(Ng.extend({style:le(["vivid","natural"]).optional(),moderation:le(["auto","low"]).optional()}))),rx=ye(()=>me(Ng.extend({inputFidelity:le(["high","low"]).optional()}))),nx=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get maxImagesPerCall(){var e;return(e=Q8[this.modelId])!=null?e:1}get provider(){return this.config.provider}async doGenerate({prompt:e,files:t,mask:r,n,size:o,aspectRatio:a,seed:i,providerOptions:s,headers:l,abortSignal:c}){var u,h,p,m,f,b,w,C,v,g,I;const y=[];a!=null&&y.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),i!=null&&y.push({type:"unsupported",feature:"seed"});const _=(p=(h=(u=this.config._internal)==null?void 0:u.currentDate)==null?void 0:h.call(u))!=null?p:new Date;if(t!=null){const R=(m=await Ir({provider:"openai",providerOptions:s,schema:rx}))!=null?m:{},{value:x,responseHeaders:N}=await Tf({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:It(this.config.headers(),l),formData:i4({model:this.modelId,prompt:e,image:await Promise.all(t.map(U=>U.type==="file"?new Blob([U.data instanceof Uint8Array?new Blob([U.data],{type:U.mediaType}):new Blob([Un(U.data)],{type:U.mediaType})],{type:U.mediaType}):uf(U.url))),mask:r!=null?await ox(r):void 0,n,size:o,quality:R.quality,background:R.background,output_format:R.outputFormat,output_compression:R.outputCompression,input_fidelity:R.inputFidelity,user:R.user}),failedResponseHandler:Rr,successfulResponseHandler:At(Ag),abortSignal:c,fetch:this.config.fetch});return{images:x.data.map(U=>U.b64_json),warnings:y,usage:x.usage!=null?{inputTokens:(f=x.usage.input_tokens)!=null?f:void 0,outputTokens:(b=x.usage.output_tokens)!=null?b:void 0,totalTokens:(w=x.usage.total_tokens)!=null?w:void 0}:void 0,response:{timestamp:_,modelId:this.modelId,headers:N},providerMetadata:{openai:{images:x.data.map((U,z)=>{var ee,Q,se,re,Se,H;return{...U.revised_prompt?{revisedPrompt:U.revised_prompt}:{},created:(ee=x.created)!=null?ee:void 0,size:(Q=x.size)!=null?Q:void 0,quality:(se=x.quality)!=null?se:void 0,background:(re=x.background)!=null?re:void 0,outputFormat:(Se=x.output_format)!=null?Se:void 0,...qg((H=x.usage)==null?void 0:H.input_tokens_details,z,x.data.length)}})}}}}const k=(C=await Ir({provider:"openai",providerOptions:s,schema:tx}))!=null?C:{},{value:S,responseHeaders:E}=await Ot({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:It(this.config.headers(),l),body:{model:this.modelId,prompt:e,n,size:o,quality:k.quality,style:k.style,background:k.background,moderation:k.moderation,output_format:k.outputFormat,output_compression:k.outputCompression,user:k.user,...ex(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:Rr,successfulResponseHandler:At(Ag),abortSignal:c,fetch:this.config.fetch});return{images:S.data.map(R=>R.b64_json),warnings:y,usage:S.usage!=null?{inputTokens:(v=S.usage.input_tokens)!=null?v:void 0,outputTokens:(g=S.usage.output_tokens)!=null?g:void 0,totalTokens:(I=S.usage.total_tokens)!=null?I:void 0}:void 0,response:{timestamp:_,modelId:this.modelId,headers:E},providerMetadata:{openai:{images:S.data.map((R,x)=>{var N,U,z,ee,Q,se;return{...R.revised_prompt?{revisedPrompt:R.revised_prompt}:{},created:(N=S.created)!=null?N:void 0,size:(U=S.size)!=null?U:void 0,quality:(z=S.quality)!=null?z:void 0,background:(ee=S.background)!=null?ee:void 0,outputFormat:(Q=S.output_format)!=null?Q:void 0,...qg((se=S.usage)==null?void 0:se.input_tokens_details,x,S.data.length)}})}}}}};function qg(e,t,r){if(e==null)return{};const n={};if(e.image_tokens!=null){const o=Math.floor(e.image_tokens/r),a=e.image_tokens-o*(r-1);n.imageTokens=t===r-1?a:o}if(e.text_tokens!=null){const o=Math.floor(e.text_tokens/r),a=e.text_tokens-o*(r-1);n.textTokens=t===r-1?a:o}return n}async function ox(e){if(!e)return;if(e.type==="url")return uf(e.url);const t=e.data instanceof Uint8Array?e.data:Un(e.data);return new Blob([t],{type:e.mediaType})}var Lg=ye(()=>me(T({callId:d(),operation:Le("type",[T({type:M("create_file"),path:d(),diff:d()}),T({type:M("delete_file"),path:d()}),T({type:M("update_file"),path:d(),diff:d()})])}))),jg=ye(()=>me(T({status:le(["completed","failed"]),output:d().optional()}))),ax=sr({id:"openai.apply_patch",inputSchema:Lg,outputSchema:jg}),sx=ax,ix=ye(()=>me(T({code:d().nullish(),containerId:d()}))),lx=ye(()=>me(T({outputs:L(Le("type",[T({type:M("logs"),logs:d()}),T({type:M("image"),url:d()})])).nullish()}))),cx=ye(()=>me(T({container:ae([d(),T({fileIds:L(d()).optional()})]).optional()}))),ux=sr({id:"openai.code_interpreter",inputSchema:ix,outputSchema:lx}),dx=(e={})=>ux(e),px=ye(()=>me(T({name:d(),description:d().optional(),format:ae([T({type:M("grammar"),syntax:le(["regex","lark"]),definition:d()}),T({type:M("text")})]).optional()}))),hx=ye(()=>me(d())),fx=_6({id:"openai.custom",inputSchema:hx}),mx=e=>fx(e),Dg=T({key:d(),type:le(["eq","ne","gt","gte","lt","lte","in","nin"]),value:ae([d(),q(),_e(),L(d())])}),Ug=T({type:le(["and","or"]),filters:L(ae([Dg,ss(()=>Ug)]))}),gx=ye(()=>me(T({vectorStoreIds:L(d()),maxNumResults:q().optional(),ranking:T({ranker:d().optional(),scoreThreshold:q().optional()}).optional(),filters:ae([Dg,Ug]).optional()}))),_x=ye(()=>me(T({queries:L(d()),results:L(T({attributes:pe(d(),Te()),fileId:d(),filename:d(),score:q(),text:d()})).nullable()}))),yx=sr({id:"openai.file_search",inputSchema:T({}),outputSchema:_x}),vx=ye(()=>me(T({background:le(["auto","opaque","transparent"]).optional(),inputFidelity:le(["low","high"]).optional(),inputImageMask:T({fileId:d().optional(),imageUrl:d().optional()}).optional(),model:d().optional(),moderation:le(["auto"]).optional(),outputCompression:q().int().min(0).max(100).optional(),outputFormat:le(["png","jpeg","webp"]).optional(),partialImages:q().int().min(0).max(3).optional(),quality:le(["auto","low","medium","high"]).optional(),size:le(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),wx=ye(()=>me(T({}))),bx=ye(()=>me(T({result:d()}))),kx=sr({id:"openai.image_generation",inputSchema:wx,outputSchema:bx}),Tx=(e={})=>kx(e),zg=ye(()=>me(T({action:T({type:M("exec"),command:L(d()),timeoutMs:q().optional(),user:d().optional(),workingDirectory:d().optional(),env:pe(d(),d()).optional()})}))),Fg=ye(()=>me(T({output:d()}))),Cx=sr({id:"openai.local_shell",inputSchema:zg,outputSchema:Fg}),Vg=ye(()=>me(T({action:T({commands:L(d()),timeoutMs:q().optional(),maxOutputLength:q().optional()})}))),ju=ye(()=>me(T({output:L(T({stdout:d(),stderr:d(),outcome:Le("type",[T({type:M("timeout")}),T({type:M("exit"),exitCode:q()})])}))}))),Sx=L(Le("type",[T({type:M("skillReference"),skillId:d(),version:d().optional()}),T({type:M("inline"),name:d(),description:d(),source:T({type:M("base64"),mediaType:M("application/zip"),data:d()})})])).optional(),Ix=ye(()=>me(T({environment:ae([T({type:M("containerAuto"),fileIds:L(d()).optional(),memoryLimit:le(["1g","4g","16g","64g"]).optional(),networkPolicy:Le("type",[T({type:M("disabled")}),T({type:M("allowlist"),allowedDomains:L(d()),domainSecrets:L(T({domain:d(),name:d(),value:d()})).optional()})]).optional(),skills:Sx}),T({type:M("containerReference"),containerId:d()}),T({type:M("local").optional(),skills:L(T({name:d(),description:d(),path:d()})).optional()})]).optional()}))),xx=sr({id:"openai.shell",inputSchema:Vg,outputSchema:ju}),Ex=ye(()=>me(T({execution:le(["server","client"]).optional(),description:d().optional(),parameters:pe(d(),Te()).optional()}))),Du=ye(()=>me(T({arguments:Te().optional(),call_id:d().nullish()}))),Uu=ye(()=>me(T({tools:L(pe(d(),Te()))}))),$x=sr({id:"openai.tool_search",inputSchema:Du,outputSchema:Uu}),Rx=(e={})=>$x(e),Px=ye(()=>me(T({externalWebAccess:_e().optional(),filters:T({allowedDomains:L(d()).optional()}).optional(),searchContextSize:le(["low","medium","high"]).optional(),userLocation:T({type:M("approximate"),country:d().optional(),city:d().optional(),region:d().optional(),timezone:d().optional()}).optional()}))),Mx=ye(()=>me(T({}))),Ox=ye(()=>me(T({action:Le("type",[T({type:M("search"),query:d().optional(),queries:L(d()).optional()}),T({type:M("openPage"),url:d().nullish()}),T({type:M("findInPage"),url:d().nullish(),pattern:d().nullish()})]).optional(),sources:L(Le("type",[T({type:M("url"),url:d()}),T({type:M("api"),name:d()})])).optional()}))),Ax=sr({id:"openai.web_search",inputSchema:Mx,outputSchema:Ox}),Nx=(e={})=>Ax(e),qx=ye(()=>me(T({searchContextSize:le(["low","medium","high"]).optional(),userLocation:T({type:M("approximate"),country:d().optional(),city:d().optional(),region:d().optional(),timezone:d().optional()}).optional()}))),Lx=ye(()=>me(T({}))),jx=ye(()=>me(T({action:Le("type",[T({type:M("search"),query:d().optional()}),T({type:M("openPage"),url:d().nullish()}),T({type:M("findInPage"),url:d().nullish(),pattern:d().nullish()})]).optional()}))),Dx=sr({id:"openai.web_search_preview",inputSchema:Lx,outputSchema:jx}),zu=ss(()=>ae([d(),q(),_e(),Qo(),L(zu),pe(d(),zu)])),Ux=ye(()=>me(T({serverLabel:d(),allowedTools:ae([L(d()),T({readOnly:_e().optional(),toolNames:L(d()).optional()})]).optional(),authorization:d().optional(),connectorId:d().optional(),headers:pe(d(),d()).optional(),requireApproval:ae([le(["always","never"]),T({never:T({toolNames:L(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."))),zx=ye(()=>me(T({}))),Fx=ye(()=>me(T({type:M("call"),serverLabel:d(),name:d(),arguments:d(),output:d().nullish(),error:ae([d(),zu]).optional()}))),Vx=sr({id:"openai.mcp",inputSchema:zx,outputSchema:Fx}),Zx=e=>Vx(e),Hx={applyPatch:sx,customTool:mx,codeInterpreter:dx,fileSearch:yx,imageGeneration:Tx,localShell:Cx,shell:xx,webSearchPreview:Dx,webSearch:Nx,mcp:Zx,toolSearch:Rx};function Zg(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 a=e.input_tokens,i=e.output_tokens,s=(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:a,noCache:a-s,cacheRead:s,cacheWrite:void 0},outputTokens:{total:i,text:i-l,reasoning:l},raw:e}}function Bx(e){return JSON.stringify(e===void 0?{}:e)}function Hg(e,t){return t?t.some(r=>e.startsWith(r)):!1}async function Jx({prompt:e,toolNameMapping:t,systemMessageMode:r,providerOptionsName:n,fileIdPrefixes:o,passThroughUnsupportedFiles:a=!1,store:i,hasConversation:s=!1,hasPreviousResponseId:l=!1,hasLocalShellTool:c=!1,hasShellTool:u=!1,hasApplyPatchTool:h=!1,customProviderToolNames:p}){var m,f,b,w,C,v,g,I,y,_,k,S,E,R,x,N,U,z,ee,Q,se,re,Se;let H=[];const D=[],B=new Set;for(const{role:F,content:$}of e)switch(F){case"system":{switch(r){case"system":{H.push({role:"system",content:$});break}case"developer":{H.push({role:"developer",content:$});break}case"remove":{D.push({type:"other",message:"system messages are removed for this model"});break}default:{const O=r;throw new Error(`Unsupported system message mode: ${O}`)}}break}case"user":{H.push({role:"user",content:$.map((O,j)=>{var G,Y,W;switch(O.type){case"text":return{type:"input_text",text:O.text};case"file":{const V=O.mediaType==="image/*"?"image/jpeg":O.mediaType;if(V.startsWith("image/"))return{type:"input_image",...O.data instanceof URL?{image_url:O.data.toString()}:typeof O.data=="string"&&Hg(O.data,o)?{file_id:O.data}:{image_url:`data:${V};base64,${vo(O.data)}`},detail:(Y=(G=O.providerOptions)==null?void 0:G[n])==null?void 0:Y.imageDetail};if(O.data instanceof URL)return{type:"input_file",file_url:O.data.toString()};if(V!=="application/pdf"&&!a)throw new Tr({functionality:`file part media type ${V}`});return{type:"input_file",...typeof O.data=="string"&&Hg(O.data,o)?{file_id:O.data}:{filename:(W=O.filename)!=null?W:V==="application/pdf"?`part-${j}.pdf`:`part-${j}`,file_data:`data:${V};base64,${vo(O.data)}`}}}}})});break}case"assistant":{const O={};for(const j of $)switch(j.type){case"text":{const G=(m=j.providerOptions)==null?void 0:m[n],Y=G?.itemId,W=G?.phase;if(s&&Y!=null)break;if(i&&Y!=null){H.push({type:"item_reference",id:Y});break}H.push({role:"assistant",content:[{type:"output_text",text:j.text}],id:Y,...W!=null&&{phase:W}});break}case"tool-call":{const G=(v=(b=(f=j.providerOptions)==null?void 0:f[n])==null?void 0:b.itemId)!=null?v:(C=(w=j.providerMetadata)==null?void 0:w[n])==null?void 0:C.itemId,Y=(k=(I=(g=j.providerOptions)==null?void 0:g[n])==null?void 0:I.namespace)!=null?k:(_=(y=j.providerMetadata)==null?void 0:y[n])==null?void 0:_.namespace;if(s&&G!=null)break;const W=t.toProviderToolName(j.toolName);if(W==="tool_search"){if(i&&G!=null){H.push({type:"item_reference",id:G});break}const A=typeof j.input=="string"?await gs({text:j.input,schema:Du}):await _t({value:j.input,schema:Du}),Z=A.call_id!=null?"client":"server";H.push({type:"tool_search_call",id:G??j.toolCallId,execution:Z,call_id:(S=A.call_id)!=null?S:null,status:"completed",arguments:A.arguments});break}if(j.providerExecuted){i&&G!=null&&H.push({type:"item_reference",id:G});break}if(l&&i&&G!=null)break;const V=c&&W==="local_shell"||u&&W==="shell"||h&&W==="apply_patch"||((E=p?.has(W))!=null?E:!1);if(i&&G!=null&&V){H.push({type:"item_reference",id:G});break}if(c&&W==="local_shell"){const A=await _t({value:j.input,schema:zg});H.push({type:"local_shell_call",call_id:j.toolCallId,id:G,action:{type:"exec",command:A.action.command,timeout_ms:A.action.timeoutMs,user:A.action.user,working_directory:A.action.workingDirectory,env:A.action.env}});break}if(u&&W==="shell"){const A=await _t({value:j.input,schema:Vg});H.push({type:"shell_call",call_id:j.toolCallId,id:G,status:"completed",action:{commands:A.action.commands,timeout_ms:A.action.timeoutMs,max_output_length:A.action.maxOutputLength}});break}if(h&&W==="apply_patch"){const A=await _t({value:j.input,schema:Lg});H.push({type:"apply_patch_call",call_id:A.callId,id:G,status:"completed",operation:A.operation});break}if(p?.has(W)){H.push({type:"custom_tool_call",call_id:j.toolCallId,name:W,input:typeof j.input=="string"?j.input:JSON.stringify(j.input),id:G});break}H.push({type:"function_call",call_id:j.toolCallId,name:W,arguments:Bx(j.input),...Y!=null&&{namespace:Y}});break}case"tool-result":{if(j.output.type==="execution-denied"||j.output.type==="json"&&typeof j.output.value=="object"&&j.output.value!=null&&"type"in j.output.value&&j.output.value.type==="execution-denied"||s)break;const G=t.toProviderToolName(j.toolName);if(G==="tool_search"){const Y=(N=(x=(R=j.providerOptions)==null?void 0:R[n])==null?void 0:x.itemId)!=null?N:j.toolCallId;if(i)H.push({type:"item_reference",id:Y});else if(j.output.type==="json"){const W=await _t({value:j.output.value,schema:Uu});H.push({type:"tool_search_output",id:Y,execution:"server",call_id:null,status:"completed",tools:W.tools})}break}if(u&&G==="shell"){if(j.output.type==="json"){const Y=await _t({value:j.output.value,schema:ju});H.push({type:"shell_call_output",call_id:j.toolCallId,output:Y.output.map(W=>({stdout:W.stdout,stderr:W.stderr,outcome:W.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:W.outcome.exitCode}}))})}break}if(i){const Y=(ee=(z=(U=j.providerOptions)==null?void 0:U[n])==null?void 0:z.itemId)!=null?ee:j.toolCallId;H.push({type:"item_reference",id:Y})}else D.push({type:"other",message:`Results for OpenAI tool ${j.toolName} are not sent to the API when store is false`});break}case"reasoning":{const G=await Ir({provider:n,providerOptions:j.providerOptions,schema:Gx}),Y=G?.itemId;if((s||l)&&Y!=null)break;if(Y!=null){const W=O[Y];if(i)W===void 0&&(H.push({type:"item_reference",id:Y}),O[Y]={type:"reasoning",id:Y,summary:[]});else{const V=[];j.text.length>0?V.push({type:"summary_text",text:j.text}):W!==void 0&&D.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(j)}.`}),W===void 0?(O[Y]={type:"reasoning",id:Y,encrypted_content:G?.reasoningEncryptedContent,summary:V},H.push(O[Y])):(W.summary.push(...V),G?.reasoningEncryptedContent!=null&&(W.encrypted_content=G.reasoningEncryptedContent))}}else{const W=G?.reasoningEncryptedContent;if(W!=null){const V=[];j.text.length>0&&V.push({type:"summary_text",text:j.text}),H.push({type:"reasoning",encrypted_content:W,summary:V})}else D.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(j)}.`})}break}}break}case"tool":{for(const O of $){if(O.type==="tool-approval-response"){const W=O;if(B.has(W.approvalId))continue;B.add(W.approvalId),i&&H.push({type:"item_reference",id:W.approvalId}),H.push({type:"mcp_approval_response",approval_request_id:W.approvalId,approve:W.approved});continue}const j=O.output;if(j.type==="execution-denied"&&((se=(Q=j.providerOptions)==null?void 0:Q.openai)==null?void 0:se.approvalId))continue;const G=t.toProviderToolName(O.toolName);if(G==="tool_search"&&j.type==="json"){const W=await _t({value:j.value,schema:Uu});H.push({type:"tool_search_output",execution:"client",call_id:O.toolCallId,status:"completed",tools:W.tools});continue}if(c&&G==="local_shell"&&j.type==="json"){const W=await _t({value:j.value,schema:Fg});H.push({type:"local_shell_call_output",call_id:O.toolCallId,output:W.output});continue}if(u&&G==="shell"&&j.type==="json"){const W=await _t({value:j.value,schema:ju});H.push({type:"shell_call_output",call_id:O.toolCallId,output:W.output.map(V=>({stdout:V.stdout,stderr:V.stderr,outcome:V.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:V.outcome.exitCode}}))});continue}if(h&&O.toolName==="apply_patch"&&j.type==="json"){const W=await _t({value:j.value,schema:jg});H.push({type:"apply_patch_call_output",call_id:O.toolCallId,status:W.status,output:W.output});continue}if(p?.has(G)){let W;switch(j.type){case"text":case"error-text":W=j.value;break;case"execution-denied":W=(re=j.reason)!=null?re:"Tool execution denied.";break;case"json":case"error-json":W=JSON.stringify(j.value);break;case"content":W=j.value.map(V=>{var A,Z,J,te,de;switch(V.type){case"text":return{type:"input_text",text:V.text};case"image-data":return{type:"input_image",image_url:`data:${V.mediaType};base64,${V.data}`,detail:(Z=(A=V.providerOptions)==null?void 0:A[n])==null?void 0:Z.imageDetail};case"image-url":return{type:"input_image",image_url:V.url,detail:(te=(J=V.providerOptions)==null?void 0:J[n])==null?void 0:te.imageDetail};case"file-data":return{type:"input_file",filename:(de=V.filename)!=null?de:"data",file_data:`data:${V.mediaType};base64,${V.data}`};case"file-url":return{type:"input_file",file_url:V.url};default:D.push({type:"other",message:`unsupported custom tool content part type: ${V.type}`});return}}).filter(hf);break;default:W=""}H.push({type:"custom_tool_call_output",call_id:O.toolCallId,output:W});continue}let Y;switch(j.type){case"text":case"error-text":Y=j.value;break;case"execution-denied":Y=(Se=j.reason)!=null?Se:"Tool execution denied.";break;case"json":case"error-json":Y=JSON.stringify(j.value);break;case"content":Y=j.value.map(W=>{var V,A,Z,J,te;switch(W.type){case"text":return{type:"input_text",text:W.text};case"image-data":return{type:"input_image",image_url:`data:${W.mediaType};base64,${W.data}`,detail:(A=(V=W.providerOptions)==null?void 0:V[n])==null?void 0:A.imageDetail};case"image-url":return{type:"input_image",image_url:W.url,detail:(J=(Z=W.providerOptions)==null?void 0:Z[n])==null?void 0:J.imageDetail};case"file-data":return{type:"input_file",filename:(te=W.filename)!=null?te:"data",file_data:`data:${W.mediaType};base64,${W.data}`};case"file-url":return{type:"input_file",file_url:W.url};default:{D.push({type:"other",message:`unsupported tool content part type: ${W.type}`});return}}}).filter(hf);break}H.push({type:"function_call_output",call_id:O.toolCallId,output:Y})}break}default:{const O=F;throw new Error(`Unsupported role: ${O}`)}}return!i&&H.some(F=>"type"in F&&F.type==="reasoning"&&F.encrypted_content==null)&&(D.push({type:"other",message:"Reasoning parts without encrypted content are not supported when store is false. Skipping reasoning parts."}),H=H.filter(F=>!("type"in F)||F.type!=="reasoning"||F.encrypted_content!=null)),{input:H,warnings:D}}var Gx=T({itemId:d().nullish(),reasoningEncryptedContent:d().nullish()});function Fu({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 Ra=ss(()=>ae([d(),q(),_e(),Qo(),L(Ra),pe(d(),Ra.optional())])),Wx=ye(()=>me(ae([T({type:M("response.output_text.delta"),item_id:d(),delta:d(),logprobs:L(T({token:d(),logprob:q(),top_logprobs:L(T({token:d(),logprob:q()}))})).nullish()}),T({type:le(["response.completed","response.incomplete"]),response:T({incomplete_details:T({reason:d()}).nullish(),usage:T({input_tokens:q(),input_tokens_details:T({cached_tokens:q().nullish(),orchestration_input_tokens:q().nullish(),orchestration_input_cached_tokens:q().nullish()}).nullish(),output_tokens:q(),output_tokens_details:T({reasoning_tokens:q().nullish(),orchestration_output_tokens:q().nullish()}).nullish()}),service_tier:d().nullish()})}),T({type:M("response.failed"),response:T({error:T({code:d().nullish(),message:d()}).nullish(),incomplete_details:T({reason:d()}).nullish(),usage:T({input_tokens:q(),input_tokens_details:T({cached_tokens:q().nullish(),orchestration_input_tokens:q().nullish(),orchestration_input_cached_tokens:q().nullish()}).nullish(),output_tokens:q(),output_tokens_details:T({reasoning_tokens:q().nullish(),orchestration_output_tokens:q().nullish()}).nullish()}).nullish(),service_tier:d().nullish()})}),T({type:M("response.created"),response:T({id:d(),created_at:q(),model:d(),service_tier:d().nullish()})}),T({type:M("response.output_item.added"),output_index:q(),item:Le("type",[T({type:M("message"),id:d(),phase:le(["commentary","final_answer"]).nullish()}),T({type:M("reasoning"),id:d(),encrypted_content:d().nullish()}),T({type:M("function_call"),id:d(),call_id:d(),name:d(),arguments:d(),namespace:d().nullish()}),T({type:M("web_search_call"),id:d(),status:d()}),T({type:M("computer_call"),id:d(),status:d()}),T({type:M("file_search_call"),id:d()}),T({type:M("image_generation_call"),id:d()}),T({type:M("code_interpreter_call"),id:d(),container_id:d(),code:d().nullable(),outputs:L(Le("type",[T({type:M("logs"),logs:d()}),T({type:M("image"),url:d()})])).nullable(),status:d()}),T({type:M("mcp_call"),id:d(),status:d(),approval_request_id:d().nullish()}),T({type:M("mcp_list_tools"),id:d()}),T({type:M("mcp_approval_request"),id:d()}),T({type:M("apply_patch_call"),id:d(),call_id:d(),status:le(["in_progress","completed"]),operation:Le("type",[T({type:M("create_file"),path:d(),diff:d()}),T({type:M("delete_file"),path:d()}),T({type:M("update_file"),path:d(),diff:d()})])}),T({type:M("custom_tool_call"),id:d(),call_id:d(),name:d(),input:d()}),T({type:M("shell_call"),id:d(),call_id:d(),status:le(["in_progress","completed","incomplete"]),action:T({commands:L(d())})}),T({type:M("shell_call_output"),id:d(),call_id:d(),status:le(["in_progress","completed","incomplete"]),output:L(T({stdout:d(),stderr:d(),outcome:Le("type",[T({type:M("timeout")}),T({type:M("exit"),exit_code:q()})])}))}),T({type:M("tool_search_call"),id:d(),execution:le(["server","client"]),call_id:d().nullable(),status:le(["in_progress","completed","incomplete"]),arguments:Te()}),T({type:M("tool_search_output"),id:d(),execution:le(["server","client"]),call_id:d().nullable(),status:le(["in_progress","completed","incomplete"]),tools:L(pe(d(),Ra.optional()))})])}),T({type:M("response.output_item.done"),output_index:q(),item:Le("type",[T({type:M("message"),id:d(),phase:le(["commentary","final_answer"]).nullish()}),T({type:M("reasoning"),id:d(),encrypted_content:d().nullish()}),T({type:M("function_call"),id:d(),call_id:d(),name:d(),arguments:d(),status:M("completed"),namespace:d().nullish()}),T({type:M("custom_tool_call"),id:d(),call_id:d(),name:d(),input:d(),status:M("completed")}),T({type:M("code_interpreter_call"),id:d(),code:d().nullable(),container_id:d(),outputs:L(Le("type",[T({type:M("logs"),logs:d()}),T({type:M("image"),url:d()})])).nullable()}),T({type:M("image_generation_call"),id:d(),result:d()}),T({type:M("web_search_call"),id:d(),status:d(),action:Le("type",[T({type:M("search"),query:d().nullish(),queries:L(d()).nullish(),sources:L(Le("type",[T({type:M("url"),url:d()}),T({type:M("api"),name:d()})])).nullish()}),T({type:M("open_page"),url:d().nullish()}),T({type:M("find_in_page"),url:d().nullish(),pattern:d().nullish()})]).nullish()}),T({type:M("file_search_call"),id:d(),queries:L(d()),results:L(T({attributes:pe(d(),ae([d(),q(),_e()])),file_id:d(),filename:d(),score:q(),text:d()})).nullish()}),T({type:M("local_shell_call"),id:d(),call_id:d(),action:T({type:M("exec"),command:L(d()),timeout_ms:q().optional(),user:d().optional(),working_directory:d().optional(),env:pe(d(),d()).optional()})}),T({type:M("computer_call"),id:d(),status:M("completed")}),T({type:M("mcp_call"),id:d(),status:d(),arguments:d(),name:d(),server_label:d(),output:d().nullish(),error:ae([d(),T({type:d().optional(),code:ae([q(),d()]).optional(),message:d().optional()}).loose()]).nullish(),approval_request_id:d().nullish()}),T({type:M("mcp_list_tools"),id:d(),server_label:d(),tools:L(T({name:d(),description:d().optional(),input_schema:ut(),annotations:pe(d(),Te()).optional()})),error:ae([d(),T({type:d().optional(),code:ae([q(),d()]).optional(),message:d().optional()}).loose()]).optional()}),T({type:M("mcp_approval_request"),id:d(),server_label:d(),name:d(),arguments:d(),approval_request_id:d().optional()}),T({type:M("apply_patch_call"),id:d(),call_id:d(),status:le(["in_progress","completed"]),operation:Le("type",[T({type:M("create_file"),path:d(),diff:d()}),T({type:M("delete_file"),path:d()}),T({type:M("update_file"),path:d(),diff:d()})])}),T({type:M("shell_call"),id:d(),call_id:d(),status:le(["in_progress","completed","incomplete"]),action:T({commands:L(d())})}),T({type:M("shell_call_output"),id:d(),call_id:d(),status:le(["in_progress","completed","incomplete"]),output:L(T({stdout:d(),stderr:d(),outcome:Le("type",[T({type:M("timeout")}),T({type:M("exit"),exit_code:q()})])}))}),T({type:M("tool_search_call"),id:d(),execution:le(["server","client"]),call_id:d().nullable(),status:le(["in_progress","completed","incomplete"]),arguments:Te()}),T({type:M("tool_search_output"),id:d(),execution:le(["server","client"]),call_id:d().nullable(),status:le(["in_progress","completed","incomplete"]),tools:L(pe(d(),Ra.optional()))})])}),T({type:M("response.function_call_arguments.delta"),item_id:d(),output_index:q(),delta:d()}),T({type:M("response.custom_tool_call_input.delta"),item_id:d(),output_index:q(),delta:d()}),T({type:M("response.image_generation_call.partial_image"),item_id:d(),output_index:q(),partial_image_b64:d()}),T({type:M("response.code_interpreter_call_code.delta"),item_id:d(),output_index:q(),delta:d()}),T({type:M("response.code_interpreter_call_code.done"),item_id:d(),output_index:q(),code:d()}),T({type:M("response.output_text.annotation.added"),annotation:Le("type",[T({type:M("url_citation"),start_index:q(),end_index:q(),url:d(),title:d()}),T({type:M("file_citation"),file_id:d(),filename:d(),index:q()}),T({type:M("container_file_citation"),container_id:d(),file_id:d(),filename:d(),start_index:q(),end_index:q()}),T({type:M("file_path"),file_id:d(),index:q()})])}),T({type:M("response.reasoning_summary_part.added"),item_id:d(),summary_index:q()}),T({type:M("response.reasoning_summary_text.delta"),item_id:d(),summary_index:q(),delta:d()}),T({type:M("response.reasoning_summary_part.done"),item_id:d(),summary_index:q()}),T({type:M("response.apply_patch_call_operation_diff.delta"),item_id:d(),output_index:q(),delta:d(),obfuscation:d().nullish()}),T({type:M("response.apply_patch_call_operation_diff.done"),item_id:d(),output_index:q(),diff:d()}),T({type:M("error"),sequence_number:q(),error:T({type:d(),code:d(),message:d(),param:d().nullish()})}),T({type:d()}).loose().transform(e=>({type:"unknown_chunk",message:e.type}))]))),Kx=ye(()=>me(T({id:d().optional(),created_at:q().optional(),error:T({message:d(),type:d(),param:d().nullish(),code:d()}).nullish(),model:d().optional(),output:L(Le("type",[T({type:M("message"),role:M("assistant"),id:d(),phase:le(["commentary","final_answer"]).nullish(),content:L(T({type:M("output_text"),text:d(),logprobs:L(T({token:d(),logprob:q(),top_logprobs:L(T({token:d(),logprob:q()}))})).nullish(),annotations:L(Le("type",[T({type:M("url_citation"),start_index:q(),end_index:q(),url:d(),title:d()}),T({type:M("file_citation"),file_id:d(),filename:d(),index:q()}),T({type:M("container_file_citation"),container_id:d(),file_id:d(),filename:d(),start_index:q(),end_index:q()}),T({type:M("file_path"),file_id:d(),index:q()})]))}))}),T({type:M("web_search_call"),id:d(),status:d(),action:Le("type",[T({type:M("search"),query:d().nullish(),queries:L(d()).nullish(),sources:L(Le("type",[T({type:M("url"),url:d()}),T({type:M("api"),name:d()})])).nullish()}),T({type:M("open_page"),url:d().nullish()}),T({type:M("find_in_page"),url:d().nullish(),pattern:d().nullish()})]).nullish()}),T({type:M("file_search_call"),id:d(),queries:L(d()),results:L(T({attributes:pe(d(),ae([d(),q(),_e()])),file_id:d(),filename:d(),score:q(),text:d()})).nullish()}),T({type:M("code_interpreter_call"),id:d(),code:d().nullable(),container_id:d(),outputs:L(Le("type",[T({type:M("logs"),logs:d()}),T({type:M("image"),url:d()})])).nullable()}),T({type:M("image_generation_call"),id:d(),result:d()}),T({type:M("local_shell_call"),id:d(),call_id:d(),action:T({type:M("exec"),command:L(d()),timeout_ms:q().optional(),user:d().optional(),working_directory:d().optional(),env:pe(d(),d()).optional()})}),T({type:M("function_call"),call_id:d(),name:d(),arguments:d(),id:d(),namespace:d().nullish()}),T({type:M("custom_tool_call"),call_id:d(),name:d(),input:d(),id:d()}),T({type:M("computer_call"),id:d(),status:d().optional()}),T({type:M("reasoning"),id:d(),encrypted_content:d().nullish(),summary:L(T({type:M("summary_text"),text:d()}))}),T({type:M("mcp_call"),id:d(),status:d(),arguments:d(),name:d(),server_label:d(),output:d().nullish(),error:ae([d(),T({type:d().optional(),code:ae([q(),d()]).optional(),message:d().optional()}).loose()]).nullish(),approval_request_id:d().nullish()}),T({type:M("mcp_list_tools"),id:d(),server_label:d(),tools:L(T({name:d(),description:d().optional(),input_schema:ut(),annotations:pe(d(),Te()).optional()})),error:ae([d(),T({type:d().optional(),code:ae([q(),d()]).optional(),message:d().optional()}).loose()]).optional()}),T({type:M("mcp_approval_request"),id:d(),server_label:d(),name:d(),arguments:d(),approval_request_id:d().optional()}),T({type:M("apply_patch_call"),id:d(),call_id:d(),status:le(["in_progress","completed"]),operation:Le("type",[T({type:M("create_file"),path:d(),diff:d()}),T({type:M("delete_file"),path:d()}),T({type:M("update_file"),path:d(),diff:d()})])}),T({type:M("shell_call"),id:d(),call_id:d(),status:le(["in_progress","completed","incomplete"]),action:T({commands:L(d())})}),T({type:M("shell_call_output"),id:d(),call_id:d(),status:le(["in_progress","completed","incomplete"]),output:L(T({stdout:d(),stderr:d(),outcome:Le("type",[T({type:M("timeout")}),T({type:M("exit"),exit_code:q()})])}))}),T({type:M("tool_search_call"),id:d(),execution:le(["server","client"]),call_id:d().nullable(),status:le(["in_progress","completed","incomplete"]),arguments:Te()}),T({type:M("tool_search_output"),id:d(),execution:le(["server","client"]),call_id:d().nullable(),status:le(["in_progress","completed","incomplete"]),tools:L(pe(d(),Ra.optional()))})])).optional(),service_tier:d().nullish(),incomplete_details:T({reason:d()}).nullish(),usage:T({input_tokens:q(),input_tokens_details:T({cached_tokens:q().nullish(),orchestration_input_tokens:q().nullish(),orchestration_input_cached_tokens:q().nullish()}).nullish(),output_tokens:q(),output_tokens_details:T({reasoning_tokens:q().nullish(),orchestration_output_tokens:q().nullish()}).nullish()}).optional()}))),Bg=20,Jg=ye(()=>me(T({conversation:d().nullish(),include:L(le(["reasoning.encrypted_content","file_search_call.results","web_search_call.results","message.output_text.logprobs"])).nullish(),instructions:d().nullish(),logprobs:ae([_e(),q().min(1).max(Bg)]).optional(),maxToolCalls:q().nullish(),metadata:ut().nullish(),parallelToolCalls:_e().nullish(),previousResponseId:d().nullish(),promptCacheKey:d().nullish(),promptCacheRetention:le(["in_memory","24h"]).nullish(),reasoningEffort:d().nullish(),reasoningSummary:d().nullish(),safetyIdentifier:d().nullish(),serviceTier:le(["auto","flex","priority","default"]).nullish(),store:_e().nullish(),passThroughUnsupportedFiles:_e().optional(),strictJsonSchema:_e().nullish(),textVerbosity:le(["low","medium","high"]).nullish(),truncation:le(["auto","disabled"]).nullish(),user:d().nullish(),systemMessageMode:le(["system","developer","remove"]).optional(),forceReasoning:_e().optional(),allowedTools:T({toolNames:L(d()).min(1),mode:le(["auto","required"]).optional()}).optional()})));async function Yx({tools:e,toolChoice:t,allowedTools:r,toolNameMapping:n,customProviderToolNames:o}){var a,i,s;e=e?.length?e:void 0;const l=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:l};const c=[],u=new Map,h=o??new Set;for(const m of e)switch(m.type){case"function":{const f=(a=m.providerOptions)==null?void 0:a.openai,b=Qx({tool:m,options:f}),w=f?.namespace;if(w==null)c.push(b);else{let C=u.get(w.name);if(C==null)C={type:"namespace",name:w.name,description:w.description,tools:[]},u.set(w.name,C),c.push(C);else if(C.description!==w.description)throw new Tr({functionality:`conflicting descriptions for OpenAI tool namespace "${w.name}"`});C.tools.push(b)}break}case"provider":{switch(m.id){case"openai.file_search":{const f=await _t({value:m.args,schema:gx});c.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":{c.push({type:"local_shell"});break}case"openai.shell":{const f=await _t({value:m.args,schema:Ix});c.push({type:"shell",...f.environment&&{environment:Xx(f.environment)}});break}case"openai.apply_patch":{c.push({type:"apply_patch"});break}case"openai.web_search_preview":{const f=await _t({value:m.args,schema:qx});c.push({type:"web_search_preview",search_context_size:f.searchContextSize,user_location:f.userLocation});break}case"openai.web_search":{const f=await _t({value:m.args,schema:Px});c.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 _t({value:m.args,schema:cx});c.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 _t({value:m.args,schema:vx});c.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 _t({value:m.args,schema:Ux}),b=v=>({tool_names:v.toolNames}),w=f.requireApproval,C=w==null?void 0:typeof w=="string"?w:w.never!=null?{never:b(w.never)}:void 0;c.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:C??"never",server_description:f.serverDescription,server_url:f.serverUrl});break}case"openai.custom":{const f=await _t({value:m.args,schema:px});c.push({type:"custom",name:f.name,description:f.description,format:f.format}),h.add(f.name);break}case"openai.tool_search":{const f=await _t({value:m.args,schema:Ex});c.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:l.push({type:"unsupported",feature:`function tool ${m}`});break}if(r!=null)return{tools:c,toolChoice:{type:"allowed_tools",mode:(i=r.mode)!=null?i:"auto",tools:r.toolNames.map(m=>{var f;return{type:"function",name:(f=n?.toProviderToolName(m))!=null?f:m}})},toolWarnings:l};if(t==null)return{tools:c,toolChoice:void 0,toolWarnings:l};const p=t.type;switch(p){case"auto":case"none":case"required":return{tools:c,toolChoice:p,toolWarnings:l};case"tool":{const m=(s=n?.toProviderToolName(t.toolName))!=null?s:t.toolName;return{tools:c,toolChoice:m==="code_interpreter"||m==="file_search"||m==="image_generation"||m==="web_search_preview"||m==="web_search"||m==="mcp"||m==="apply_patch"?{type:m}:h.has(m)?{type:"custom",name:m}:{type:"function",name:m},toolWarnings:l}}default:{const m=p;throw new Tr({functionality:`tool choice type: ${m}`})}}}function Qx({tool:e,options:t}){const r=t?.deferLoading;return{type:"function",name:e.name,description:e.description,parameters:e.inputSchema,...e.strict!=null?{strict:e.strict}:{},...r!=null?{defer_loading:r}:{}}}function Xx(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:e7(r.skills)}}return{type:"local",skills:e.skills}}function e7(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 Gg(e){var t,r;const n={};for(const o of e)if(o.role==="assistant")for(const a of o.content){if(a.type!=="tool-call")continue;const i=(r=(t=a.providerOptions)==null?void 0:t.openai)==null?void 0:r.approvalRequestId;i!=null&&(n[i]=a.toolCallId)}return n}var t7=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:a,frequencyPenalty:i,seed:s,prompt:l,providerOptions:c,tools:u,toolChoice:h,responseFormat:p}){var m,f,b,w,C,v,g,I,y,_,k;const S=[],E=xg(this.modelId);o!=null&&S.push({type:"unsupported",feature:"topK"}),s!=null&&S.push({type:"unsupported",feature:"seed"}),a!=null&&S.push({type:"unsupported",feature:"presencePenalty"}),i!=null&&S.push({type:"unsupported",feature:"frequencyPenalty"}),r!=null&&S.push({type:"unsupported",feature:"stopSequences"});const R=this.config.provider.includes("azure")?"azure":"openai";let x=await Ir({provider:R,providerOptions:c,schema:Jg});x==null&&R!=="openai"&&(x=await Ir({provider:"openai",providerOptions:c,schema:Jg}));const N=(m=x?.forceReasoning)!=null?m:E.isReasoningModel;x?.conversation&&x?.previousResponseId&&S.push({type:"unsupported",feature:"conversation",details:"conversation and previousResponseId cannot be used together"});const U=n4({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:V=>V.id==="openai.custom"?V.args.name:void 0}),z=new Set,{tools:ee,toolChoice:Q,toolWarnings:se}=await Yx({tools:u,toolChoice:h,allowedTools:(f=x?.allowedTools)!=null?f:void 0,toolNameMapping:U,customProviderToolNames:z}),{input:re,warnings:Se}=await Jx({prompt:l,toolNameMapping:U,systemMessageMode:(b=x?.systemMessageMode)!=null?b:N?"developer":E.systemMessageMode,providerOptionsName:R,fileIdPrefixes:this.config.fileIdPrefixes,passThroughUnsupportedFiles:(w=x?.passThroughUnsupportedFiles)!=null?w:!1,store:(C=x?.store)!=null?C:!0,hasConversation:x?.conversation!=null,hasPreviousResponseId:x?.previousResponseId!=null,hasLocalShellTool:F("openai.local_shell"),hasShellTool:F("openai.shell"),hasApplyPatchTool:F("openai.apply_patch"),customProviderToolNames:z.size>0?z:void 0});S.push(...Se);const H=(v=x?.strictJsonSchema)!=null?v:!0;let D=x?.include;function B(V){D==null?D=[V]:D.includes(V)||(D=[...D,V])}function F(V){return u?.find(A=>A.type==="provider"&&A.id===V)!=null}const $=typeof x?.logprobs=="number"?x?.logprobs:x?.logprobs===!0?Bg:void 0;$&&B("message.output_text.logprobs");const O=(g=u?.find(V=>V.type==="provider"&&(V.id==="openai.web_search"||V.id==="openai.web_search_preview")))==null?void 0:g.name;O&&B("web_search_call.action.sources"),F("openai.code_interpreter")&&B("code_interpreter_call.outputs");const j=x?.store;j===!1&&N&&B("reasoning.encrypted_content");const G={model:this.modelId,input:re,temperature:t,top_p:n,max_output_tokens:e,...(p?.type==="json"||x?.textVerbosity)&&{text:{...p?.type==="json"&&{format:p.schema!=null?{type:"json_schema",strict:H,name:(I=p.name)!=null?I:"response",description:p.description,schema:p.schema}:{type:"json_object"}},...x?.textVerbosity&&{verbosity:x.textVerbosity}}},conversation:x?.conversation,max_tool_calls:x?.maxToolCalls,metadata:x?.metadata,parallel_tool_calls:x?.parallelToolCalls,previous_response_id:x?.previousResponseId,store:j,user:x?.user,instructions:x?.instructions,service_tier:x?.serviceTier,include:D,prompt_cache_key:x?.promptCacheKey,prompt_cache_retention:x?.promptCacheRetention,safety_identifier:x?.safetyIdentifier,top_logprobs:$,truncation:x?.truncation,...N&&(x?.reasoningEffort!=null||x?.reasoningSummary!=null)&&{reasoning:{...x?.reasoningEffort!=null&&{effort:x.reasoningEffort},...x?.reasoningSummary!=null&&{summary:x.reasoningSummary}}}};N?x?.reasoningEffort==="none"&&E.supportsNonReasoningParameters||(G.temperature!=null&&(G.temperature=void 0,S.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),G.top_p!=null&&(G.top_p=void 0,S.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"}))):(x?.reasoningEffort!=null&&S.push({type:"unsupported",feature:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),x?.reasoningSummary!=null&&S.push({type:"unsupported",feature:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),x?.serviceTier==="flex"&&!E.supportsFlexProcessing&&(S.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete G.service_tier),x?.serviceTier==="priority"&&!E.supportsPriorityProcessing&&(S.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 G.service_tier);const Y=(k=(_=(y=u?.find(V=>V.type==="provider"&&V.id==="openai.shell"))==null?void 0:y.args)==null?void 0:_.environment)==null?void 0:k.type,W=Y==="containerAuto"||Y==="containerReference";return{webSearchToolName:O,args:{...G,tools:ee,tool_choice:Q},warnings:[...S,...se],store:j,toolNameMapping:U,providerOptionsName:R,isShellProviderExecuted:W}}async doGenerate(e){var t,r,n,o,a,i,s,l,c,u,h,p,m,f,b,w,C,v,g,I,y,_,k,S,E,R,x,N;const{args:U,warnings:z,webSearchToolName:ee,toolNameMapping:Q,providerOptionsName:se,isShellProviderExecuted:re}=await this.getArgs(e),Se=this.config.url({path:"/responses",modelId:this.modelId}),H=Gg(e.prompt),{responseHeaders:D,value:B,rawValue:F}=await Ot({url:Se,headers:It(this.config.headers(),e.headers),body:U,failedResponseHandler:Rr,successfulResponseHandler:At(Kx),abortSignal:e.abortSignal,fetch:this.config.fetch});if(B.error)throw new tt({message:B.error.message,url:Se,requestBodyValues:U,statusCode:400,responseHeaders:D,responseBody:F,isRetryable:!1});const $=[],O=[];let j=!1;const G=[];for(const V of B.output)switch(V.type){case"reasoning":{V.summary.length===0&&V.summary.push({type:"summary_text",text:""});for(const A of V.summary)$.push({type:"reasoning",text:A.text,providerMetadata:{[se]:{itemId:V.id,reasoningEncryptedContent:(t=V.encrypted_content)!=null?t:null}}});break}case"image_generation_call":{$.push({type:"tool-call",toolCallId:V.id,toolName:Q.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),$.push({type:"tool-result",toolCallId:V.id,toolName:Q.toCustomToolName("image_generation"),result:{result:V.result}});break}case"tool_search_call":{const A=(r=V.call_id)!=null?r:V.id,Z=V.execution==="server";Z&&G.push(A),$.push({type:"tool-call",toolCallId:A,toolName:Q.toCustomToolName("tool_search"),input:JSON.stringify({arguments:V.arguments,call_id:V.call_id}),...Z?{providerExecuted:!0}:{},providerMetadata:{[se]:{itemId:V.id}}});break}case"tool_search_output":{const A=(o=(n=V.call_id)!=null?n:G.shift())!=null?o:V.id;$.push({type:"tool-result",toolCallId:A,toolName:Q.toCustomToolName("tool_search"),result:{tools:V.tools},providerMetadata:{[se]:{itemId:V.id}}});break}case"local_shell_call":{$.push({type:"tool-call",toolCallId:V.call_id,toolName:Q.toCustomToolName("local_shell"),input:JSON.stringify({action:V.action}),providerMetadata:{[se]:{itemId:V.id}}});break}case"shell_call":{$.push({type:"tool-call",toolCallId:V.call_id,toolName:Q.toCustomToolName("shell"),input:JSON.stringify({action:{commands:V.action.commands}}),...re&&{providerExecuted:!0},providerMetadata:{[se]:{itemId:V.id}}});break}case"shell_call_output":{$.push({type:"tool-result",toolCallId:V.call_id,toolName:Q.toCustomToolName("shell"),result:{output:V.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 V.content){(i=(a=e.providerOptions)==null?void 0:a[se])!=null&&i.logprobs&&A.logprobs&&O.push(A.logprobs);const Z={itemId:V.id,...V.phase!=null&&{phase:V.phase},...A.annotations.length>0&&{annotations:A.annotations}};$.push({type:"text",text:A.text,providerMetadata:{[se]:Z}});for(const J of A.annotations)J.type==="url_citation"?$.push({type:"source",sourceType:"url",id:(c=(l=(s=this.config).generateId)==null?void 0:l.call(s))!=null?c:Kt(),url:J.url,title:J.title}):J.type==="file_citation"?$.push({type:"source",sourceType:"document",id:(p=(h=(u=this.config).generateId)==null?void 0:h.call(u))!=null?p:Kt(),mediaType:"text/plain",title:J.filename,filename:J.filename,providerMetadata:{[se]:{type:J.type,fileId:J.file_id,index:J.index}}}):J.type==="container_file_citation"?$.push({type:"source",sourceType:"document",id:(b=(f=(m=this.config).generateId)==null?void 0:f.call(m))!=null?b:Kt(),mediaType:"text/plain",title:J.filename,filename:J.filename,providerMetadata:{[se]:{type:J.type,fileId:J.file_id,containerId:J.container_id}}}):J.type==="file_path"&&$.push({type:"source",sourceType:"document",id:(v=(C=(w=this.config).generateId)==null?void 0:C.call(w))!=null?v:Kt(),mediaType:"application/octet-stream",title:J.file_id,filename:J.file_id,providerMetadata:{[se]:{type:J.type,fileId:J.file_id,index:J.index}}})}break}case"function_call":{j=!0,$.push({type:"tool-call",toolCallId:V.call_id,toolName:V.name,input:V.arguments,providerMetadata:{[se]:{itemId:V.id,...V.namespace!=null&&{namespace:V.namespace}}}});break}case"custom_tool_call":{j=!0;const A=Q.toCustomToolName(V.name);$.push({type:"tool-call",toolCallId:V.call_id,toolName:A,input:JSON.stringify(V.input),providerMetadata:{[se]:{itemId:V.id}}});break}case"web_search_call":{$.push({type:"tool-call",toolCallId:V.id,toolName:Q.toCustomToolName(ee??"web_search"),input:JSON.stringify({}),providerExecuted:!0}),$.push({type:"tool-result",toolCallId:V.id,toolName:Q.toCustomToolName(ee??"web_search"),result:Kg(V.action)});break}case"mcp_call":{const A=V.approval_request_id!=null&&(g=H[V.approval_request_id])!=null?g:V.id,Z=`mcp.${V.name}`;$.push({type:"tool-call",toolCallId:A,toolName:Z,input:V.arguments,providerExecuted:!0,dynamic:!0}),$.push({type:"tool-result",toolCallId:A,toolName:Z,result:{type:"call",serverLabel:V.server_label,name:V.name,arguments:V.arguments,...V.output!=null?{output:V.output}:{},...V.error!=null?{error:V.error}:{}},providerMetadata:{[se]:{itemId:V.id}}});break}case"mcp_list_tools":break;case"mcp_approval_request":{const A=(I=V.approval_request_id)!=null?I:V.id,Z=(k=(_=(y=this.config).generateId)==null?void 0:_.call(y))!=null?k:Kt(),J=`mcp.${V.name}`;$.push({type:"tool-call",toolCallId:Z,toolName:J,input:V.arguments,providerExecuted:!0,dynamic:!0}),$.push({type:"tool-approval-request",approvalId:A,toolCallId:Z});break}case"computer_call":{$.push({type:"tool-call",toolCallId:V.id,toolName:Q.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),$.push({type:"tool-result",toolCallId:V.id,toolName:Q.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:V.status||"completed"}});break}case"file_search_call":{$.push({type:"tool-call",toolCallId:V.id,toolName:Q.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),$.push({type:"tool-result",toolCallId:V.id,toolName:Q.toCustomToolName("file_search"),result:{queries:V.queries,results:(E=(S=V.results)==null?void 0:S.map(A=>({attributes:A.attributes,fileId:A.file_id,filename:A.filename,score:A.score,text:A.text})))!=null?E:null}});break}case"code_interpreter_call":{$.push({type:"tool-call",toolCallId:V.id,toolName:Q.toCustomToolName("code_interpreter"),input:JSON.stringify({code:V.code,containerId:V.container_id}),providerExecuted:!0}),$.push({type:"tool-result",toolCallId:V.id,toolName:Q.toCustomToolName("code_interpreter"),result:{outputs:V.outputs}});break}case"apply_patch_call":{$.push({type:"tool-call",toolCallId:V.call_id,toolName:Q.toCustomToolName("apply_patch"),input:JSON.stringify({callId:V.call_id,operation:V.operation}),providerMetadata:{[se]:{itemId:V.id}}});break}}const Y={[se]:{responseId:B.id,...O.length>0?{logprobs:O}:{},...typeof B.service_tier=="string"?{serviceTier:B.service_tier}:{}}},W=B.usage;return{content:$,finishReason:{unified:Fu({finishReason:(R=B.incomplete_details)==null?void 0:R.reason,hasFunctionCall:j}),raw:(N=(x=B.incomplete_details)==null?void 0:x.reason)!=null?N:void 0},usage:Zg(W),request:{body:U},response:{id:B.id,timestamp:new Date(B.created_at*1e3),modelId:B.model,headers:D,body:F},providerMetadata:Y,warnings:z}}async doStream(e){const{args:t,warnings:r,webSearchToolName:n,toolNameMapping:o,store:a,providerOptionsName:i,isShellProviderExecuted:s}=await this.getArgs(e),l=this.config.url({path:"/responses",modelId:this.modelId}),{responseHeaders:c,value:u}=await Ot({url:l,headers:It(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:Rr,successfulResponseHandler:_s(Wx),abortSignal:e.abortSignal,fetch:this.config.fetch}),h=this,p=Gg(e.prompt),m=new Map;let f={unified:"other",raw:void 0},b;const w=[];let C=null;const v={},g=[];let I,y=!1;const _={};let k;const S=[];return{stream:u.pipeThrough(new TransformStream({start(E){E.enqueue({type:"stream-start",warnings:r})},transform(E,R){var x,N,U,z,ee,Q,se,re,Se,H,D,B,F,$,O,j,G,Y,W,V,A,Z,J,te,de,fe,Ye,wt,st,et,Be,tr,it,qr,dr,rr,Lr,pr;if(e.includeRawChunks&&R.enqueue({type:"raw",rawValue:E.rawValue}),!E.success){const X=n7(E.rawValue)?o7({value:E.rawValue,cause:E.error,url:l,requestBodyValues:t,responseHeaders:c}):E.error;f={unified:"error",raw:void 0},R.enqueue({type:"error",error:X});return}const P=E.value;if(Wg(P)){if(P.item.type==="function_call")v[P.output_index]={toolName:P.item.name,toolCallId:P.item.call_id},R.enqueue({type:"tool-input-start",id:P.item.call_id,toolName:P.item.name});else if(P.item.type==="custom_tool_call"){const X=o.toCustomToolName(P.item.name);v[P.output_index]={toolName:X,toolCallId:P.item.call_id},R.enqueue({type:"tool-input-start",id:P.item.call_id,toolName:X})}else if(P.item.type==="web_search_call")v[P.output_index]={toolName:o.toCustomToolName(n??"web_search"),toolCallId:P.item.id},R.enqueue({type:"tool-input-start",id:P.item.id,toolName:o.toCustomToolName(n??"web_search"),providerExecuted:!0}),R.enqueue({type:"tool-input-end",id:P.item.id}),R.enqueue({type:"tool-call",toolCallId:P.item.id,toolName:o.toCustomToolName(n??"web_search"),input:JSON.stringify({}),providerExecuted:!0});else if(P.item.type==="computer_call")v[P.output_index]={toolName:o.toCustomToolName("computer_use"),toolCallId:P.item.id},R.enqueue({type:"tool-input-start",id:P.item.id,toolName:o.toCustomToolName("computer_use"),providerExecuted:!0});else if(P.item.type==="code_interpreter_call")v[P.output_index]={toolName:o.toCustomToolName("code_interpreter"),toolCallId:P.item.id,codeInterpreter:{containerId:P.item.container_id}},R.enqueue({type:"tool-input-start",id:P.item.id,toolName:o.toCustomToolName("code_interpreter"),providerExecuted:!0}),R.enqueue({type:"tool-input-delta",id:P.item.id,delta:`{"containerId":"${P.item.container_id}","code":"`});else if(P.item.type==="file_search_call")R.enqueue({type:"tool-call",toolCallId:P.item.id,toolName:o.toCustomToolName("file_search"),input:"{}",providerExecuted:!0});else if(P.item.type==="image_generation_call")R.enqueue({type:"tool-call",toolCallId:P.item.id,toolName:o.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0});else if(P.item.type==="tool_search_call"){const X=P.item.id,Ie=o.toCustomToolName("tool_search"),We=P.item.execution==="server";v[P.output_index]={toolName:Ie,toolCallId:X,toolSearchExecution:(x=P.item.execution)!=null?x:"server"},We&&R.enqueue({type:"tool-input-start",id:X,toolName:Ie,providerExecuted:!0})}else if(P.item.type!=="tool_search_output"){if(!(P.item.type==="mcp_call"||P.item.type==="mcp_list_tools"||P.item.type==="mcp_approval_request"))if(P.item.type==="apply_patch_call"){const{call_id:X,operation:Ie}=P.item;if(v[P.output_index]={toolName:o.toCustomToolName("apply_patch"),toolCallId:X,applyPatch:{hasDiff:Ie.type==="delete_file",endEmitted:Ie.type==="delete_file"}},R.enqueue({type:"tool-input-start",id:X,toolName:o.toCustomToolName("apply_patch")}),Ie.type==="delete_file"){const We=JSON.stringify({callId:X,operation:Ie});R.enqueue({type:"tool-input-delta",id:X,delta:We}),R.enqueue({type:"tool-input-end",id:X})}else R.enqueue({type:"tool-input-delta",id:X,delta:`{"callId":"${Xn(X)}","operation":{"type":"${Xn(Ie.type)}","path":"${Xn(Ie.path)}","diff":"`})}else P.item.type==="shell_call"?v[P.output_index]={toolName:o.toCustomToolName("shell"),toolCallId:P.item.call_id}:P.item.type==="shell_call_output"||(P.item.type==="message"?(g.splice(0,g.length),I=(N=P.item.phase)!=null?N:void 0,R.enqueue({type:"text-start",id:P.item.id,providerMetadata:{[i]:{itemId:P.item.id,...P.item.phase!=null&&{phase:P.item.phase}}}})):Wg(P)&&P.item.type==="reasoning"&&(_[P.item.id]={encryptedContent:P.item.encrypted_content,summaryParts:{0:"active"}},R.enqueue({type:"reasoning-start",id:`${P.item.id}:0`,providerMetadata:{[i]:{itemId:P.item.id,reasoningEncryptedContent:(U=P.item.encrypted_content)!=null?U:null}}})))}}else if(s7(P)){if(P.item.type==="message"){const X=(z=P.item.phase)!=null?z:I;I=void 0,R.enqueue({type:"text-end",id:P.item.id,providerMetadata:{[i]:{itemId:P.item.id,...X!=null&&{phase:X},...g.length>0&&{annotations:g}}}})}else if(P.item.type==="function_call")v[P.output_index]=void 0,y=!0,R.enqueue({type:"tool-input-end",id:P.item.call_id,...P.item.namespace!=null&&{providerMetadata:{[i]:{namespace:P.item.namespace}}}}),R.enqueue({type:"tool-call",toolCallId:P.item.call_id,toolName:P.item.name,input:P.item.arguments,providerMetadata:{[i]:{itemId:P.item.id,...P.item.namespace!=null&&{namespace:P.item.namespace}}}});else if(P.item.type==="custom_tool_call"){v[P.output_index]=void 0,y=!0;const X=o.toCustomToolName(P.item.name);R.enqueue({type:"tool-input-end",id:P.item.call_id}),R.enqueue({type:"tool-call",toolCallId:P.item.call_id,toolName:X,input:JSON.stringify(P.item.input),providerMetadata:{[i]:{itemId:P.item.id}}})}else if(P.item.type==="web_search_call")v[P.output_index]=void 0,R.enqueue({type:"tool-result",toolCallId:P.item.id,toolName:o.toCustomToolName(n??"web_search"),result:Kg(P.item.action)});else if(P.item.type==="computer_call")v[P.output_index]=void 0,R.enqueue({type:"tool-input-end",id:P.item.id}),R.enqueue({type:"tool-call",toolCallId:P.item.id,toolName:o.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),R.enqueue({type:"tool-result",toolCallId:P.item.id,toolName:o.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:P.item.status||"completed"}});else if(P.item.type==="file_search_call")v[P.output_index]=void 0,R.enqueue({type:"tool-result",toolCallId:P.item.id,toolName:o.toCustomToolName("file_search"),result:{queries:P.item.queries,results:(Q=(ee=P.item.results)==null?void 0:ee.map(X=>({attributes:X.attributes,fileId:X.file_id,filename:X.filename,score:X.score,text:X.text})))!=null?Q:null}});else if(P.item.type==="code_interpreter_call")v[P.output_index]=void 0,R.enqueue({type:"tool-result",toolCallId:P.item.id,toolName:o.toCustomToolName("code_interpreter"),result:{outputs:P.item.outputs}});else if(P.item.type==="image_generation_call")R.enqueue({type:"tool-result",toolCallId:P.item.id,toolName:o.toCustomToolName("image_generation"),result:{result:P.item.result}});else if(P.item.type==="tool_search_call"){const X=v[P.output_index],Ie=P.item.execution==="server";if(X!=null){const We=Ie?X.toolCallId:(se=P.item.call_id)!=null?se:P.item.id;Ie?S.push(We):R.enqueue({type:"tool-input-start",id:We,toolName:X.toolName}),R.enqueue({type:"tool-input-end",id:We}),R.enqueue({type:"tool-call",toolCallId:We,toolName:X.toolName,input:JSON.stringify({arguments:P.item.arguments,call_id:Ie?null:We}),...Ie?{providerExecuted:!0}:{},providerMetadata:{[i]:{itemId:P.item.id}}})}v[P.output_index]=void 0}else if(P.item.type==="tool_search_output"){const X=(Se=(re=P.item.call_id)!=null?re:S.shift())!=null?Se:P.item.id;R.enqueue({type:"tool-result",toolCallId:X,toolName:o.toCustomToolName("tool_search"),result:{tools:P.item.tools},providerMetadata:{[i]:{itemId:P.item.id}}})}else if(P.item.type==="mcp_call"){v[P.output_index]=void 0;const X=(H=P.item.approval_request_id)!=null?H:void 0,Ie=X!=null&&(B=(D=m.get(X))!=null?D:p[X])!=null?B:P.item.id,We=`mcp.${P.item.name}`;R.enqueue({type:"tool-call",toolCallId:Ie,toolName:We,input:P.item.arguments,providerExecuted:!0,dynamic:!0}),R.enqueue({type:"tool-result",toolCallId:Ie,toolName:We,result:{type:"call",serverLabel:P.item.server_label,name:P.item.name,arguments:P.item.arguments,...P.item.output!=null?{output:P.item.output}:{},...P.item.error!=null?{error:P.item.error}:{}},providerMetadata:{[i]:{itemId:P.item.id}}})}else if(P.item.type==="mcp_list_tools")v[P.output_index]=void 0;else if(P.item.type==="apply_patch_call"){const X=v[P.output_index];X?.applyPatch&&!X.applyPatch.endEmitted&&P.item.operation.type!=="delete_file"&&(X.applyPatch.hasDiff||R.enqueue({type:"tool-input-delta",id:X.toolCallId,delta:Xn(P.item.operation.diff)}),R.enqueue({type:"tool-input-delta",id:X.toolCallId,delta:'"}}'}),R.enqueue({type:"tool-input-end",id:X.toolCallId}),X.applyPatch.endEmitted=!0),X&&P.item.status==="completed"&&R.enqueue({type:"tool-call",toolCallId:X.toolCallId,toolName:o.toCustomToolName("apply_patch"),input:JSON.stringify({callId:P.item.call_id,operation:P.item.operation}),providerMetadata:{[i]:{itemId:P.item.id}}}),v[P.output_index]=void 0}else if(P.item.type==="mcp_approval_request"){v[P.output_index]=void 0;const X=(O=($=(F=h.config).generateId)==null?void 0:$.call(F))!=null?O:Kt(),Ie=(j=P.item.approval_request_id)!=null?j:P.item.id;m.set(Ie,X);const We=`mcp.${P.item.name}`;R.enqueue({type:"tool-call",toolCallId:X,toolName:We,input:P.item.arguments,providerExecuted:!0,dynamic:!0}),R.enqueue({type:"tool-approval-request",approvalId:Ie,toolCallId:X})}else if(P.item.type==="local_shell_call")v[P.output_index]=void 0,R.enqueue({type:"tool-call",toolCallId:P.item.call_id,toolName:o.toCustomToolName("local_shell"),input:JSON.stringify({action:{type:"exec",command:P.item.action.command,timeoutMs:P.item.action.timeout_ms,user:P.item.action.user,workingDirectory:P.item.action.working_directory,env:P.item.action.env}}),providerMetadata:{[i]:{itemId:P.item.id}}});else if(P.item.type==="shell_call")v[P.output_index]=void 0,R.enqueue({type:"tool-call",toolCallId:P.item.call_id,toolName:o.toCustomToolName("shell"),input:JSON.stringify({action:{commands:P.item.action.commands}}),...s&&{providerExecuted:!0},providerMetadata:{[i]:{itemId:P.item.id}}});else if(P.item.type==="shell_call_output")R.enqueue({type:"tool-result",toolCallId:P.item.call_id,toolName:o.toCustomToolName("shell"),result:{output:P.item.output.map(X=>({stdout:X.stdout,stderr:X.stderr,outcome:X.outcome.type==="exit"?{type:"exit",exitCode:X.outcome.exit_code}:{type:"timeout"}}))}});else if(P.item.type==="reasoning"){const X=_[P.item.id],Ie=Object.entries(X.summaryParts).filter(([We,ln])=>ln==="active"||ln==="can-conclude").map(([We])=>We);for(const We of Ie)R.enqueue({type:"reasoning-end",id:`${P.item.id}:${We}`,providerMetadata:{[i]:{itemId:P.item.id,reasoningEncryptedContent:(G=P.item.encrypted_content)!=null?G:null}}});delete _[P.item.id]}}else if(u7(P)){const X=v[P.output_index];X!=null&&R.enqueue({type:"tool-input-delta",id:X.toolCallId,delta:P.delta})}else if(d7(P)){const X=v[P.output_index];X!=null&&R.enqueue({type:"tool-input-delta",id:X.toolCallId,delta:P.delta})}else if(m7(P)){const X=v[P.output_index];X?.applyPatch&&(R.enqueue({type:"tool-input-delta",id:X.toolCallId,delta:Xn(P.delta)}),X.applyPatch.hasDiff=!0)}else if(g7(P)){const X=v[P.output_index];X?.applyPatch&&!X.applyPatch.endEmitted&&(X.applyPatch.hasDiff||(R.enqueue({type:"tool-input-delta",id:X.toolCallId,delta:Xn(P.diff)}),X.applyPatch.hasDiff=!0),R.enqueue({type:"tool-input-delta",id:X.toolCallId,delta:'"}}'}),R.enqueue({type:"tool-input-end",id:X.toolCallId}),X.applyPatch.endEmitted=!0)}else if(p7(P))R.enqueue({type:"tool-result",toolCallId:P.item_id,toolName:o.toCustomToolName("image_generation"),result:{result:P.partial_image_b64},preliminary:!0});else if(h7(P)){const X=v[P.output_index];X!=null&&R.enqueue({type:"tool-input-delta",id:X.toolCallId,delta:Xn(P.delta)})}else if(f7(P)){const X=v[P.output_index];X!=null&&(R.enqueue({type:"tool-input-delta",id:X.toolCallId,delta:'"}'}),R.enqueue({type:"tool-input-end",id:X.toolCallId}),R.enqueue({type:"tool-call",toolCallId:X.toolCallId,toolName:o.toCustomToolName("code_interpreter"),input:JSON.stringify({code:P.code,containerId:X.codeInterpreter.containerId}),providerExecuted:!0}))}else if(c7(P))C=P.response.id,R.enqueue({type:"response-metadata",id:P.response.id,timestamp:new Date(P.response.created_at*1e3),modelId:P.response.model});else if(r7(P))R.enqueue({type:"text-delta",id:P.item_id,delta:P.delta}),(W=(Y=e.providerOptions)==null?void 0:Y[i])!=null&&W.logprobs&&P.logprobs&&w.push(P.logprobs);else if(P.type==="response.reasoning_summary_part.added"){if(P.summary_index>0){const X=_[P.item_id];X.summaryParts[P.summary_index]="active";for(const Ie of Object.keys(X.summaryParts))X.summaryParts[Ie]==="can-conclude"&&(R.enqueue({type:"reasoning-end",id:`${P.item_id}:${Ie}`,providerMetadata:{[i]:{itemId:P.item_id}}}),X.summaryParts[Ie]="concluded");R.enqueue({type:"reasoning-start",id:`${P.item_id}:${P.summary_index}`,providerMetadata:{[i]:{itemId:P.item_id,reasoningEncryptedContent:(A=(V=_[P.item_id])==null?void 0:V.encryptedContent)!=null?A:null}}})}}else if(P.type==="response.reasoning_summary_text.delta")R.enqueue({type:"reasoning-delta",id:`${P.item_id}:${P.summary_index}`,delta:P.delta,providerMetadata:{[i]:{itemId:P.item_id}}});else if(P.type==="response.reasoning_summary_part.done")a?(R.enqueue({type:"reasoning-end",id:`${P.item_id}:${P.summary_index}`,providerMetadata:{[i]:{itemId:P.item_id}}}),_[P.item_id].summaryParts[P.summary_index]="concluded"):_[P.item_id].summaryParts[P.summary_index]="can-conclude";else if(i7(P))f={unified:Fu({finishReason:(Z=P.response.incomplete_details)==null?void 0:Z.reason,hasFunctionCall:y}),raw:(te=(J=P.response.incomplete_details)==null?void 0:J.reason)!=null?te:void 0},b=P.response.usage,typeof P.response.service_tier=="string"&&(k=P.response.service_tier);else if(l7(P)){const X=(de=P.response.incomplete_details)==null?void 0:de.reason;f={unified:X?Fu({finishReason:X,hasFunctionCall:y}):"error",raw:X??"error"},b=(fe=P.response.usage)!=null?fe:void 0}else _7(P)?(g.push(P.annotation),P.annotation.type==="url_citation"?R.enqueue({type:"source",sourceType:"url",id:(st=(wt=(Ye=h.config).generateId)==null?void 0:wt.call(Ye))!=null?st:Kt(),url:P.annotation.url,title:P.annotation.title}):P.annotation.type==="file_citation"?R.enqueue({type:"source",sourceType:"document",id:(tr=(Be=(et=h.config).generateId)==null?void 0:Be.call(et))!=null?tr:Kt(),mediaType:"text/plain",title:P.annotation.filename,filename:P.annotation.filename,providerMetadata:{[i]:{type:P.annotation.type,fileId:P.annotation.file_id,index:P.annotation.index}}}):P.annotation.type==="container_file_citation"?R.enqueue({type:"source",sourceType:"document",id:(dr=(qr=(it=h.config).generateId)==null?void 0:qr.call(it))!=null?dr:Kt(),mediaType:"text/plain",title:P.annotation.filename,filename:P.annotation.filename,providerMetadata:{[i]:{type:P.annotation.type,fileId:P.annotation.file_id,containerId:P.annotation.container_id}}}):P.annotation.type==="file_path"&&R.enqueue({type:"source",sourceType:"document",id:(pr=(Lr=(rr=h.config).generateId)==null?void 0:Lr.call(rr))!=null?pr:Kt(),mediaType:"application/octet-stream",title:P.annotation.file_id,filename:P.annotation.file_id,providerMetadata:{[i]:{type:P.annotation.type,fileId:P.annotation.file_id,index:P.annotation.index}}})):y7(P)&&R.enqueue({type:"error",error:P})},flush(E){const R={[i]:{responseId:C,...w.length>0?{logprobs:w}:{},...k!==void 0?{serviceTier:k}:{}}};E.enqueue({type:"finish",finishReason:f,usage:Zg(b),providerMetadata:R})}})),request:{body:t},response:{headers:c}}}};function r7(e){return e.type==="response.output_text.delta"}function n7(e){const t=a7(e);return t!=null&&Array.isArray(t.choices)&&typeof t.type!="string"}function o7({value:e,cause:t,url:r,requestBodyValues:n,responseHeaders:o}){return new tt({message:"Received a Chat Completions stream while using the OpenAI Responses API. The default OpenAI provider model uses the Responses API. If your custom baseURL targets a Chat Completions-compatible endpoint, use openai.chat('model-id') or createOpenAI(...).chat('model-id') instead. You can also use @ai-sdk/openai-compatible for OpenAI-compatible providers.",url:r,requestBodyValues:n,responseHeaders:o,responseBody:JSON.stringify(e),cause:t,data:e,isRetryable:!1})}function a7(e){return typeof e=="object"&&e!=null?e:void 0}function s7(e){return e.type==="response.output_item.done"}function i7(e){return e.type==="response.completed"||e.type==="response.incomplete"}function l7(e){return e.type==="response.failed"}function c7(e){return e.type==="response.created"}function u7(e){return e.type==="response.function_call_arguments.delta"}function d7(e){return e.type==="response.custom_tool_call_input.delta"}function p7(e){return e.type==="response.image_generation_call.partial_image"}function h7(e){return e.type==="response.code_interpreter_call_code.delta"}function f7(e){return e.type==="response.code_interpreter_call_code.done"}function m7(e){return e.type==="response.apply_patch_call_operation_diff.delta"}function g7(e){return e.type==="response.apply_patch_call_operation_diff.done"}function Wg(e){return e.type==="response.output_item.added"}function _7(e){return e.type==="response.output_text.annotation.added"}function y7(e){return e.type==="error"}function Kg(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.queries!=null&&{queries:e.queries}},...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 Xn(e){return JSON.stringify(e).slice(1,-1)}var v7=ye(()=>me(T({instructions:d().nullish(),speed:q().min(.25).max(4).default(1).nullish()}))),w7=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:a,providerOptions:i}){const s=[],l=await Ir({provider:"openai",providerOptions:i,schema:v7}),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:s.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${r}. Using mp3 instead.`})),l){const u={};for(const h in u){const p=u[h];p!==void 0&&(c[h]=p)}}return a&&s.push({type:"unsupported",feature:"language",details:`OpenAI speech models do not support language selection. Language parameter "${a}" was ignored.`}),{requestBody:c,warnings:s}}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:a,warnings:i}=await this.getArgs(e),{value:s,responseHeaders:l,rawValue:c}=await Ot({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:It(this.config.headers(),e.headers),body:a,failedResponseHandler:Rr,successfulResponseHandler:v6(),abortSignal:e.abortSignal,fetch:this.config.fetch});return{audio:s,warnings:i,request:{body:JSON.stringify(a)},response:{timestamp:o,modelId:this.modelId,headers:l,body:c}}}},b7=ye(()=>me(T({text:d(),language:d().nullish(),duration:q().nullish(),words:L(T({word:d(),start:q(),end:q()})).nullish(),segments:L(T({id:q(),seek:q(),start:q(),end:q(),text:d(),tokens:L(q()),temperature:q(),avg_logprob:q(),compression_ratio:q(),no_speech_prob:q()})).nullish()}))),k7=ye(()=>me(T({include:L(d()).optional(),language:d().optional(),prompt:d().optional(),temperature:q().min(0).max(1).default(0).optional(),timestampGranularities:L(le(["word","segment"])).default(["segment"]).optional()}))),Yg={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"},T7=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 Ir({provider:"openai",providerOptions:r,schema:k7}),a=new FormData,i=e instanceof Uint8Array?new Blob([e]):new Blob([Un(e)]);a.append("model",this.modelId);const s=b4(t);if(a.append("file",new File([i],"audio",{type:t}),`audio.${s}`),o){const l={include:o.include,language:o.language,prompt:o.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:o.temperature,timestamp_granularities:o.timestampGranularities};for(const[c,u]of Object.entries(l))if(u!=null)if(Array.isArray(u))for(const h of u)a.append(`${c}[]`,String(h));else a.append(c,String(u))}return{formData:a,warnings:n}}async doGenerate(e){var t,r,n,o,a,i,s,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:h}=await this.getArgs(e),{value:p,responseHeaders:m,rawValue:f}=await Tf({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:It(this.config.headers(),e.headers),formData:u,failedResponseHandler:Rr,successfulResponseHandler:At(b7),abortSignal:e.abortSignal,fetch:this.config.fetch}),b=p.language!=null&&p.language in Yg?Yg[p.language]:void 0;return{text:p.text,segments:(s=(i=(o=p.segments)==null?void 0:o.map(w=>({text:w.text,startSecond:w.start,endSecond:w.end})))!=null?i:(a=p.words)==null?void 0:a.map(w=>({text:w.word,startSecond:w.start,endSecond:w.end})))!=null?s:[],language:b,durationInSeconds:(l=p.duration)!=null?l:void 0,warnings:h,response:{timestamp:c,modelId:this.modelId,headers:m,body:f}}}},C7="3.0.78";function Qg(e={}){var t,r;const n=(t=If(wo({settingValue:e.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?t:"https://api.openai.com/v1",o=(r=e.name)!=null?r:"openai",a=()=>_n({Authorization:`Bearer ${w4({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${C7}`),i=b=>new Z8(b,{provider:`${o}.chat`,url:({path:w})=>`${n}${w}`,headers:a,fetch:e.fetch}),s=b=>new G8(b,{provider:`${o}.completion`,url:({path:w})=>`${n}${w}`,headers:a,fetch:e.fetch}),l=b=>new Y8(b,{provider:`${o}.embedding`,url:({path:w})=>`${n}${w}`,headers:a,fetch:e.fetch}),c=b=>new nx(b,{provider:`${o}.image`,url:({path:w})=>`${n}${w}`,headers:a,fetch:e.fetch}),u=b=>new T7(b,{provider:`${o}.transcription`,url:({path:w})=>`${n}${w}`,headers:a,fetch:e.fetch}),h=b=>new w7(b,{provider:`${o}.speech`,url:({path:w})=>`${n}${w}`,headers:a,fetch:e.fetch}),p=b=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return m(b)},m=b=>new t7(b,{provider:`${o}.responses`,url:({path:w})=>`${n}${w}`,headers:a,fetch:e.fetch,fileIdPrefixes:["file-"]}),f=function(b){return p(b)};return f.specificationVersion="v3",f.languageModel=p,f.chat=i,f.completion=s,f.responses=m,f.embedding=l,f.embeddingModel=l,f.textEmbedding=l,f.textEmbeddingModel=l,f.image=c,f.imageModel=c,f.transcription=u,f.transcriptionModel=u,f.speech=h,f.speechModel=h,f.tools=Hx,f}Qg();var Xg="vercel.ai.error",S7=Symbol.for(Xg),e_,I7=class w1 extends Error{constructor({name:t,message:r,cause:n}){super(r),this[e_]=!0,this.name=t,this.cause=n}static isInstance(t){return w1.hasMarker(t,Xg)}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}};e_=S7;var Pt=I7,t_="AI_APICallError",r_=`vercel.ai.error.${t_}`,x7=Symbol.for(r_),n_,tn=class extends Pt{constructor({message:e,url:t,requestBodyValues:r,statusCode:n,responseHeaders:o,responseBody:a,cause:i,isRetryable:s=n!=null&&(n===408||n===409||n===429||n>=500),data:l}){super({name:t_,message:e,cause:i}),this[n_]=!0,this.url=t,this.requestBodyValues=r,this.statusCode=n,this.responseHeaders=o,this.responseBody=a,this.isRetryable=s,this.data=l}static isInstance(e){return Pt.hasMarker(e,r_)}};n_=x7;var o_="AI_EmptyResponseBodyError",a_=`vercel.ai.error.${o_}`,E7=Symbol.for(a_),s_,$7=class extends Pt{constructor({message:e="Empty response body"}={}){super({name:o_,message:e}),this[s_]=!0}static isInstance(e){return Pt.hasMarker(e,a_)}};s_=E7;function i_(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var l_="AI_InvalidArgumentError",c_=`vercel.ai.error.${l_}`,R7=Symbol.for(c_),u_,d_=class extends Pt{constructor({message:e,cause:t,argument:r}){super({name:l_,message:e,cause:t}),this[u_]=!0,this.argument=r}static isInstance(e){return Pt.hasMarker(e,c_)}};u_=R7;var p_="AI_InvalidResponseDataError",h_=`vercel.ai.error.${p_}`,P7=Symbol.for(h_),f_,m_=class extends Pt{constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:p_,message:t}),this[f_]=!0,this.data=e}static isInstance(e){return Pt.hasMarker(e,h_)}};f_=P7;var g_="AI_JSONParseError",__=`vercel.ai.error.${g_}`,M7=Symbol.for(__),y_,Xs=class extends Pt{constructor({text:e,cause:t}){super({name:g_,message:`JSON parsing failed: Text: ${e}.
|
|
87
|
+
Error message: ${i_(t)}`,cause:t}),this[y_]=!0,this.text=e}static isInstance(e){return Pt.hasMarker(e,__)}};y_=M7;var v_="AI_LoadAPIKeyError",w_=`vercel.ai.error.${v_}`,O7=Symbol.for(w_),b_,ei=class extends Pt{constructor({message:e}){super({name:v_,message:e}),this[b_]=!0}static isInstance(e){return Pt.hasMarker(e,w_)}};b_=O7;var k_="AI_NoSuchModelError",T_=`vercel.ai.error.${k_}`,A7=Symbol.for(T_),C_,S_=class extends Pt{constructor({errorName:e=k_,modelId:t,modelType:r,message:n=`No such ${r}: ${t}`}){super({name:e,message:n}),this[C_]=!0,this.modelId=t,this.modelType=r}static isInstance(e){return Pt.hasMarker(e,T_)}};C_=A7;var I_="AI_TypeValidationError",x_=`vercel.ai.error.${I_}`,N7=Symbol.for(x_),E_,q7=class zd extends Pt{constructor({value:t,cause:r}){super({name:I_,message:`Type validation failed: Value: ${JSON.stringify(t)}.
|
|
88
|
+
Error message: ${i_(r)}`,cause:r}),this[E_]=!0,this.value=t}static isInstance(t){return Pt.hasMarker(t,x_)}static wrap({value:t,cause:r}){return zd.isInstance(r)&&r.value===t?r:new zd({value:t,cause:r})}};E_=N7;var Pa=q7,$_="AI_UnsupportedFunctionalityError",R_=`vercel.ai.error.${$_}`,L7=Symbol.for(R_),P_,M_=class extends Pt{constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:$_,message:t}),this[P_]=!0,this.functionality=e}static isInstance(e){return Pt.hasMarker(e,R_)}};P_=L7;function O_(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}function ti(e){return Object.fromEntries([...e.headers])}var j7=({prefix:e,size:t=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{const o=()=>{const a=r.length,i=new Array(t);for(let s=0;s<t;s++)i[s]=r[Math.random()*a|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()}`},ri=j7();function Vu(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var D7=["fetch failed","failed to fetch"];function U7({error:e,url:t,requestBodyValues:r}){if(Vu(e))return e;if(e instanceof TypeError&&D7.includes(e.message.toLowerCase())){const n=e.cause;if(n!=null)return new tn({message:`Cannot connect to API: ${n.message}`,cause:n,url:t,requestBodyValues:r,isRetryable:!0})}return e}function z7(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 F7(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 A_(e,...t){const r=new Headers(F7(e)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var V7="3.0.18";function Z7({apiKey:e,environmentVariableName:t,apiKeyParameterName:r="apiKey",description:n}){if(typeof e=="string")return e;if(e!=null)throw new ei({message:`${n} API key must be a string.`});if(typeof process>"u")throw new ei({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 ei({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new ei({message:`${n} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}var H7=/"__proto__"\s*:/,B7=/"constructor"\s*:/;function N_(e){const t=JSON.parse(e);return t===null||typeof t!="object"||H7.test(e)===!1&&B7.test(e)===!1?t:J7(t)}function J7(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 a=n[o];a&&typeof a=="object"&&t.push(a)}}}return e}function Zu(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return N_(e)}try{return N_(e)}finally{Error.stackTraceLimit=t}}var Hu=Symbol.for("vercel.ai.validator");function G7(e){return{[Hu]:!0,validate:e}}function W7(e){return typeof e=="object"&&e!==null&&Hu in e&&e[Hu]===!0&&"validate"in e}function K7(e){return W7(e)?e:typeof e=="function"?e():Y7(e)}function Y7(e){return G7(async t=>{const r=await e["~standard"].validate(t);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new Pa({value:t,cause:r.issues})}})}async function Q7({value:e,schema:t}){const r=await Ma({value:e,schema:t});if(!r.success)throw Pa.wrap({value:e,cause:r.error});return r.value}async function Ma({value:e,schema:t}){const r=K7(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:Pa.wrap({value:e,cause:n.error}),rawValue:e}}catch(n){return{success:!1,error:Pa.wrap({value:e,cause:n}),rawValue:e}}}async function X7({text:e,schema:t}){try{const r=Zu(e);return t==null?r:Q7({value:r,schema:t})}catch(r){throw Xs.isInstance(r)||Pa.isInstance(r)?r:new Xs({text:e,cause:r})}}async function q_({text:e,schema:t}){try{const r=Zu(e);return t==null?{success:!0,value:r,rawValue:r}:await Ma({value:r,schema:t})}catch(r){return{success:!1,error:Xs.isInstance(r)?r:new Xs({text:e,cause:r}),rawValue:void 0}}}function L_(e){try{return Zu(e),!0}catch{return!1}}function eE({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new _o).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await q_({text:r,schema:t}))}}))}async function j_({provider:e,providerOptions:t,schema:r}){if(t?.[e]==null)return;const n=await Ma({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 tE=()=>globalThis.fetch,D_=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:a,fetch:i})=>rE({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:a,fetch:i}),rE=async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:a,fetch:i=tE()})=>{try{const s=await i(e,{method:"POST",headers:A_(t,`ai-sdk/provider-utils/${V7}`,z7()),body:r.content,signal:a}),l=ti(s);if(!s.ok){let c;try{c=await o({response:s,url:e,requestBodyValues:r.values})}catch(u){throw Vu(u)||tn.isInstance(u)?u:new tn({message:"Failed to process error response",cause:u,statusCode:s.status,url:e,responseHeaders:l,requestBodyValues:r.values})}throw c.value}try{return await n({response:s,url:e,requestBodyValues:r.values})}catch(c){throw c instanceof Error&&(Vu(c)||tn.isInstance(c))?c:new tn({message:"Failed to process successful response",cause:c,statusCode:s.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(s){throw U7({error:s,url:e,requestBodyValues:r.values})}},nE=({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:n,url:o,requestBodyValues:a})=>{const i=await n.text(),s=ti(n);if(i.trim()==="")return{responseHeaders:s,value:new tn({message:n.statusText,url:o,requestBodyValues:a,statusCode:n.status,responseHeaders:s,responseBody:i,isRetryable:r?.(n)})};try{const l=await X7({text:i,schema:e});return{responseHeaders:s,value:new tn({message:t(l),url:o,requestBodyValues:a,statusCode:n.status,responseHeaders:s,responseBody:i,data:l,isRetryable:r?.(n,l)})}}catch{return{responseHeaders:s,value:new tn({message:n.statusText,url:o,requestBodyValues:a,statusCode:n.status,responseHeaders:s,responseBody:i,isRetryable:r?.(n)})}}},oE=e=>async({response:t})=>{const r=ti(t);if(t.body==null)throw new $7({});return{responseHeaders:r,value:eE({stream:t.body,schema:e})}},aE=e=>async({response:t,url:r,requestBodyValues:n})=>{const o=await t.text(),a=await q_({text:o,schema:e}),i=ti(t);if(!a.success)throw new tn({message:"Invalid JSON response",cause:a.error,statusCode:t.status,responseHeaders:i,responseBody:o,url:r,requestBodyValues:n});return{responseHeaders:i,value:a.value,rawValue:a.rawValue}};new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");var{btoa:sE}=globalThis;function iE(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return sE(t)}function lE(e){return e instanceof Uint8Array?iE(e):e}function cE(e){return e?.replace(/\/$/,"")}function Oa(e){var t,r;return(r=(t=e?.providerOptions)==null?void 0:t.openaiCompatible)!=null?r:{}}function uE(e){const t=[];for(const{role:r,content:n,...o}of e){const a=Oa({...o});switch(r){case"system":{t.push({role:"system",content:n,...a});break}case"user":{if(n.length===1&&n[0].type==="text"){t.push({role:"user",content:n[0].text,...Oa(n[0])});break}t.push({role:"user",content:n.map(i=>{const s=Oa(i);switch(i.type){case"text":return{type:"text",text:i.text,...s};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,${lE(i.data)}`},...s}}else throw new M_({functionality:`file part media type ${i.mediaType}`})}}),...a});break}case"assistant":{let i="";const s=[];for(const l of n){const c=Oa(l);switch(l.type){case"text":{i+=l.text;break}case"tool-call":{s.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:s.length>0?s:void 0,...a});break}case"tool":{for(const i of n){const s=i.output;let l;switch(s.type){case"text":case"error-text":l=s.value;break;case"content":case"json":case"error-json":l=JSON.stringify(s.value);break}const c=Oa(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 U_({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 z_(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 Bu=T({user:d().optional(),reasoningEffort:d().optional(),textVerbosity:d().optional()}),dE=T({error:T({message:d(),type:d().nullish(),param:ut().nullish(),code:ae([d(),q()]).nullish()})}),pE={errorSchema:dE,errorToMessage:e=>e.error.message};function hE({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 a of e)a.type==="provider-defined"?r.push({type:"unsupported-tool",tool:a}):n.push({type:"function",function:{name:a.name,description:a.description,parameters:a.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 a=o;throw new M_({functionality:`tool choice type: ${a}`})}}}var fE=class{constructor(e,t){this.specificationVersion="v2";var r,n;this.modelId=e,this.config=t;const o=(r=t.errorStructure)!=null?r:pE;this.chunkSchema=gE(o.errorSchema),this.failedResponseHandler=nE(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:a,presencePenalty:i,providerOptions:s,stopSequences:l,responseFormat:c,seed:u,toolChoice:h,tools:p}){var m,f,b,w;const C=[],v=Object.assign((m=await j_({provider:"openai-compatible",providerOptions:s,schema:Bu}))!=null?m:{},(f=await j_({provider:this.providerOptionsName,providerOptions:s,schema:Bu}))!=null?f:{});o!=null&&C.push({type:"unsupported-setting",setting:"topK"}),c?.type==="json"&&c.schema!=null&&!this.supportsStructuredOutputs&&C.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:g,toolChoice:I,toolWarnings:y}=hE({tools:p,toolChoice:h});return{args:{model:this.modelId,user:v.user,max_tokens:t,temperature:r,top_p:n,frequency_penalty:a,presence_penalty:i,response_format:c?.type==="json"?this.supportsStructuredOutputs===!0&&c.schema!=null?{type:"json_schema",json_schema:{schema:c.schema,name:(b=c.name)!=null?b:"response",description:c.description}}:{type:"json_object"}:void 0,stop:l,seed:u,...Object.fromEntries(Object.entries((w=s?.[this.providerOptionsName])!=null?w:{}).filter(([_])=>!Object.keys(Bu.shape).includes(_))),reasoning_effort:v.reasoningEffort,verbosity:v.textVerbosity,messages:uE(e),tools:g,tool_choice:I},warnings:[...C,...y]}}async doGenerate(e){var t,r,n,o,a,i,s,l,c,u,h,p,m,f,b,w,C;const{args:v,warnings:g}=await this.getArgs({...e}),I=JSON.stringify(v),{responseHeaders:y,value:_,rawValue:k}=await D_({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:O_(this.config.headers(),e.headers),body:v,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:aE(mE),abortSignal:e.abortSignal,fetch:this.config.fetch}),S=_.choices[0],E=[],R=S.message.content;R!=null&&R.length>0&&E.push({type:"text",text:R});const x=(t=S.message.reasoning_content)!=null?t:S.message.reasoning;if(x!=null&&x.length>0&&E.push({type:"reasoning",text:x}),S.message.tool_calls!=null)for(const z of S.message.tool_calls)E.push({type:"tool-call",toolCallId:(r=z.id)!=null?r:ri(),toolName:z.function.name,input:z.function.arguments});const N={[this.providerOptionsName]:{},...await((o=(n=this.config.metadataExtractor)==null?void 0:n.extractMetadata)==null?void 0:o.call(n,{parsedBody:k}))},U=(a=_.usage)==null?void 0:a.completion_tokens_details;return U?.accepted_prediction_tokens!=null&&(N[this.providerOptionsName].acceptedPredictionTokens=U?.accepted_prediction_tokens),U?.rejected_prediction_tokens!=null&&(N[this.providerOptionsName].rejectedPredictionTokens=U?.rejected_prediction_tokens),{content:E,finishReason:z_(S.finish_reason),usage:{inputTokens:(s=(i=_.usage)==null?void 0:i.prompt_tokens)!=null?s:void 0,outputTokens:(c=(l=_.usage)==null?void 0:l.completion_tokens)!=null?c:void 0,totalTokens:(h=(u=_.usage)==null?void 0:u.total_tokens)!=null?h:void 0,reasoningTokens:(f=(m=(p=_.usage)==null?void 0:p.completion_tokens_details)==null?void 0:m.reasoning_tokens)!=null?f:void 0,cachedInputTokens:(C=(w=(b=_.usage)==null?void 0:b.prompt_tokens_details)==null?void 0:w.cached_tokens)!=null?C:void 0},providerMetadata:N,request:{body:I},response:{...U_(_),headers:y,body:k},warnings:g}}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},a=(t=this.config.metadataExtractor)==null?void 0:t.createStreamExtractor(),{responseHeaders:i,value:s}=await D_({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:O_(this.config.headers(),e.headers),body:o,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:oE(this.chunkSchema),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=[];let c="unknown";const u={completionTokens:void 0,completionTokensDetails:{reasoningTokens:void 0,acceptedPredictionTokens:void 0,rejectedPredictionTokens:void 0},promptTokens:void 0,promptTokensDetails:{cachedTokens:void 0},totalTokens:void 0};let h=!0;const p=this.providerOptionsName;let m=!1,f=!1;return{stream:s.pipeThrough(new TransformStream({start(b){b.enqueue({type:"stream-start",warnings:n})},transform(b,w){var C,v,g,I,y,_,k,S,E,R,x,N,U;if(e.includeRawChunks&&w.enqueue({type:"raw",rawValue:b.rawValue}),!b.success){c="error",w.enqueue({type:"error",error:b.error});return}const z=b.value;if(a?.processChunk(b.rawValue),"error"in z){c="error",w.enqueue({type:"error",error:z.error.message});return}if(h&&(h=!1,w.enqueue({type:"response-metadata",...U_(z)})),z.usage!=null){const{prompt_tokens:re,completion_tokens:Se,total_tokens:H,prompt_tokens_details:D,completion_tokens_details:B}=z.usage;u.promptTokens=re??void 0,u.completionTokens=Se??void 0,u.totalTokens=H??void 0,B?.reasoning_tokens!=null&&(u.completionTokensDetails.reasoningTokens=B?.reasoning_tokens),B?.accepted_prediction_tokens!=null&&(u.completionTokensDetails.acceptedPredictionTokens=B?.accepted_prediction_tokens),B?.rejected_prediction_tokens!=null&&(u.completionTokensDetails.rejectedPredictionTokens=B?.rejected_prediction_tokens),D?.cached_tokens!=null&&(u.promptTokensDetails.cachedTokens=D?.cached_tokens)}const ee=z.choices[0];if(ee?.finish_reason!=null&&(c=z_(ee.finish_reason)),ee?.delta==null)return;const Q=ee.delta,se=(C=Q.reasoning_content)!=null?C:Q.reasoning;if(se&&(m||(w.enqueue({type:"reasoning-start",id:"reasoning-0"}),m=!0),w.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:se})),Q.content&&(f||(w.enqueue({type:"text-start",id:"txt-0"}),f=!0),w.enqueue({type:"text-delta",id:"txt-0",delta:Q.content})),Q.tool_calls!=null)for(const re of Q.tool_calls){const Se=re.index;if(l[Se]==null){if(re.id==null)throw new m_({data:re,message:"Expected 'id' to be a string."});if(((v=re.function)==null?void 0:v.name)==null)throw new m_({data:re,message:"Expected 'function.name' to be a string."});w.enqueue({type:"tool-input-start",id:re.id,toolName:re.function.name}),l[Se]={id:re.id,type:"function",function:{name:re.function.name,arguments:(g=re.function.arguments)!=null?g:""},hasFinished:!1};const D=l[Se];((I=D.function)==null?void 0:I.name)!=null&&((y=D.function)==null?void 0:y.arguments)!=null&&(D.function.arguments.length>0&&w.enqueue({type:"tool-input-delta",id:D.id,delta:D.function.arguments}),L_(D.function.arguments)&&(w.enqueue({type:"tool-input-end",id:D.id}),w.enqueue({type:"tool-call",toolCallId:(_=D.id)!=null?_:ri(),toolName:D.function.name,input:D.function.arguments}),D.hasFinished=!0));continue}const H=l[Se];H.hasFinished||(((k=re.function)==null?void 0:k.arguments)!=null&&(H.function.arguments+=(E=(S=re.function)==null?void 0:S.arguments)!=null?E:""),w.enqueue({type:"tool-input-delta",id:H.id,delta:(R=re.function.arguments)!=null?R:""}),((x=H.function)==null?void 0:x.name)!=null&&((N=H.function)==null?void 0:N.arguments)!=null&&L_(H.function.arguments)&&(w.enqueue({type:"tool-input-end",id:H.id}),w.enqueue({type:"tool-call",toolCallId:(U=H.id)!=null?U:ri(),toolName:H.function.name,input:H.function.arguments}),H.hasFinished=!0))}},flush(b){var w,C,v,g,I,y;m&&b.enqueue({type:"reasoning-end",id:"reasoning-0"}),f&&b.enqueue({type:"text-end",id:"txt-0"});for(const k of l.filter(S=>!S.hasFinished))b.enqueue({type:"tool-input-end",id:k.id}),b.enqueue({type:"tool-call",toolCallId:(w=k.id)!=null?w:ri(),toolName:k.function.name,input:k.function.arguments});const _={[p]:{},...a?.buildMetadata()};u.completionTokensDetails.acceptedPredictionTokens!=null&&(_[p].acceptedPredictionTokens=u.completionTokensDetails.acceptedPredictionTokens),u.completionTokensDetails.rejectedPredictionTokens!=null&&(_[p].rejectedPredictionTokens=u.completionTokensDetails.rejectedPredictionTokens),b.enqueue({type:"finish",finishReason:c,usage:{inputTokens:(C=u.promptTokens)!=null?C:void 0,outputTokens:(v=u.completionTokens)!=null?v:void 0,totalTokens:(g=u.totalTokens)!=null?g:void 0,reasoningTokens:(I=u.completionTokensDetails.reasoningTokens)!=null?I:void 0,cachedInputTokens:(y=u.promptTokensDetails.cachedTokens)!=null?y:void 0},providerMetadata:_})}})),request:{body:o},response:{headers:i}}}},F_=T({prompt_tokens:q().nullish(),completion_tokens:q().nullish(),total_tokens:q().nullish(),prompt_tokens_details:T({cached_tokens:q().nullish()}).nullish(),completion_tokens_details:T({reasoning_tokens:q().nullish(),accepted_prediction_tokens:q().nullish(),rejected_prediction_tokens:q().nullish()}).nullish()}).nullish(),mE=T({id:d().nullish(),created:q().nullish(),model:d().nullish(),choices:L(T({message:T({role:M("assistant").nullish(),content:d().nullish(),reasoning_content:d().nullish(),reasoning:d().nullish(),tool_calls:L(T({id:d().nullish(),function:T({name:d(),arguments:d()})})).nullish()}),finish_reason:d().nullish()})),usage:F_}),gE=e=>ae([T({id:d().nullish(),created:q().nullish(),model:d().nullish(),choices:L(T({delta:T({role:le(["assistant"]).nullish(),content:d().nullish(),reasoning_content:d().nullish(),reasoning:d().nullish(),tool_calls:L(T({index:q(),id:d().nullish(),function:T({name:d().nullish(),arguments:d().nullish()})})).nullish()}).nullish(),finish_reason:d().nullish()})),usage:F_}),e]);T({echo:_e().optional(),logitBias:pe(d(),q()).optional(),suffix:d().optional(),user:d().optional()});var _E=T({prompt_tokens:q(),completion_tokens:q(),total_tokens:q()});T({id:d().nullish(),created:q().nullish(),model:d().nullish(),choices:L(T({text:d(),finish_reason:d()})),usage:_E.nullish()}),T({dimensions:q().optional(),user:d().optional()}),T({data:L(T({embedding:L(q())})),usage:T({prompt_tokens:q()}).nullish(),providerMetadata:pe(d(),pe(d(),ut())).optional()}),T({data:L(T({b64_json:d()}))});var V_=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}}},yE={extractMetadata:async({parsedBody:e})=>{const t=await Ma({value:e,schema:vE});return!t.success||t.value.usage==null?void 0:V_(t.value.usage)},createStreamExtractor:()=>{let e;return{processChunk:async t=>{var r,n;const o=await Ma({value:t,schema:wE});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:()=>V_(e)}}},Z_=T({prompt_cache_hit_tokens:q().nullish(),prompt_cache_miss_tokens:q().nullish()}),vE=T({usage:Z_.nullish()}),wE=T({choices:L(T({finish_reason:d().nullish()})).nullish(),usage:Z_.nullish()}),bE="1.0.30";function H_(e={}){var t;const r=cE((t=e.baseURL)!=null?t:"https://api.deepseek.com/v1"),n=()=>A_({Authorization:`Bearer ${Z7({apiKey:e.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...e.headers},`ai-sdk/deepseek/${bE}`);class o extends fE{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 a=s=>new o(s,{provider:"deepseek.chat",url:({path:l})=>`${r}${l}`,headers:n,fetch:e.fetch,metadataExtractor:yE}),i=s=>a(s);return i.languageModel=a,i.chat=a,i.textEmbeddingModel=s=>{throw new S_({modelId:s,modelType:"textEmbeddingModel"})},i.imageModel=s=>{throw new S_({modelId:s,modelType:"imageModel"})},i}H_();const kE=(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})},TE=(e,t,r,n)=>{const o=(a,i,s)=>{if(a.type===e&&a.direction===r){const{data:l}=a;t(l,i,s),s(i)}};return chrome.runtime.onMessage.addListener(o),()=>chrome.runtime.onMessage.removeListener(o)};class CE{constructor(t){this._isStarted=!1,this._isClosed=!1,this.targetSessionId=t,this._messageListener=TE("mcp-server-to-client",r=>{try{if(r.sessionId!==this.targetSessionId)return;const n=Wn.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}`),kE("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 ni(e){return!!e._zod}function bn(e,t){return ni(e)?Dp(e,t):e.safeParse(t)}function B_(e){if(!e)return;let t;if(ni(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function SE(e){if(ni(e)){const a=e._zod?.def;if(a){if(a.value!==void 0)return a.value;if(Array.isArray(a.values)&&a.values.length>0)return a.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 eo(e){return e==="completed"||e==="failed"||e==="cancelled"}new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function J_(e){const r=B_(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const n=SE(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function G_(e,t){const r=bn(e,t);if(!r.success)throw r.error;return r.data}const IE=6e4;class xE{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(Fc,r=>{this._oncancel(r)}),this.setNotificationHandler(Zc,r=>{this._onprogress(r)}),this.setRequestHandler(Vc,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Hc,async(r,n)=>{const o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new Ce($e.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Jc,async(r,n)=>{const o=async()=>{const a=r.params.taskId;if(this._taskMessageQueue){let s;for(;s=await this._taskMessageQueue.dequeue(a,n.sessionId);){if(s.type==="response"||s.type==="error"){const l=s.message,c=l.id,u=this._requestResolvers.get(c);if(u)if(this._requestResolvers.delete(c),s.type==="response")u(l);else{const h=l,p=new Ce(h.error.code,h.error.message,h.error.data);u(p)}else{const h=s.type==="response"?"Response":"Error";this._onerror(new Error(`${h} handler missing for request ${c}`))}continue}await this._transport?.send(s.message,{relatedRequestId:n.requestId})}}const i=await this._taskStore.getTask(a,n.sessionId);if(!i)throw new Ce($e.InvalidParams,`Task not found: ${a}`);if(!eo(i.status))return await this._waitForTaskUpdate(a,n.signal),await o();if(eo(i.status)){const s=await this._taskStore.getTaskResult(a,n.sessionId);return this._clearTaskQueue(a),{...s,_meta:{...s._meta,[Gn]:{taskId:a}}}}return await o()};return await o()}),this.setRequestHandler(Gc,async(r,n)=>{try{const{tasks:o,nextCursor:a}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:a,_meta:{}}}catch(o){throw new Ce($e.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Kc,async(r,n)=>{try{const o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new Ce($e.InvalidParams,`Task not found: ${r.params.taskId}`);if(eo(o.status))throw new Ce($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 a=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!a)throw new Ce($e.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...a}}catch(o){throw o instanceof Ce?o:new Ce($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,a=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:a,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),Ce.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=a=>{n?.(a),this._onerror(a)};const o=this._transport?.onmessage;this._transport.onmessage=(a,i)=>{o?.(a,i),ya(a)||NS(a)?this._onresponse(a):Dc(a)?this._onrequest(a,i):AS(a)?this._onnotification(a):this._onerror(new Error(`Unknown message type: ${JSON.stringify(a)}`))},await this._transport.start()}_onclose(){const t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();const r=Ce.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,a=t.params?._meta?.[Gn]?.taskId;if(n===void 0){const u={jsonrpc:"2.0",id:t.id,error:{code:$e.MethodNotFound,message:"Method not found"}};a&&this._taskMessageQueue?this._enqueueTaskMessage(a,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch(h=>this._onerror(new Error(`Failed to enqueue error response: ${h}`))):o?.send(u).catch(h=>this._onerror(new Error(`Failed to send an error response: ${h}`)));return}const i=new AbortController;this._requestHandlerAbortControllers.set(t.id,i);const s=OS(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 h={relatedRequestId:t.id};a&&(h.relatedTask={taskId:a}),await this.notification(u,h)},sendRequest:async(u,h,p)=>{const m={...p,relatedRequestId:t.id};a&&!m.relatedTask&&(m.relatedTask={taskId:a});const f=m.relatedTask?.taskId??a;return f&&l&&await l.updateTaskStatus(f,"input_required"),await this.request(u,h,m)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:a,taskStore:l,taskRequestedTtl:s?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{s&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,c)).then(async u=>{if(i.signal.aborted)return;const h={result:u,jsonrpc:"2.0",id:t.id};a&&this._taskMessageQueue?await this._enqueueTaskMessage(a,{type:"response",message:h,timestamp:Date.now()},o?.sessionId):await o?.send(h)},async u=>{if(i.signal.aborted)return;const h={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}}};a&&this._taskMessageQueue?await this._enqueueTaskMessage(a,{type:"error",message:h,timestamp:Date.now()},o?.sessionId):await o?.send(h)}).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),a=this._progressHandlers.get(o);if(!a){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}const i=this._responseHandlers.get(o),s=this._timeoutInfo.get(o);if(s&&i&&s.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(l){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(l);return}a(n)}_onresponse(t){const r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),ya(t))n(t);else{const i=new Ce(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 a=!1;if(ya(t)&&t.result&&typeof t.result=="object"){const i=t.result;if(i.task&&typeof i.task=="object"){const s=i.task;typeof s.taskId=="string"&&(a=!0,this._taskProgressTokens.set(s.taskId,r))}}if(a||this._progressHandlers.delete(r),ya(t))o(t);else{const i=Ce.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 Ce?i:new Ce($e.InternalError,String(i))}}return}let a;try{const i=await this.request(t,Ta,n);if(i.task)a=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new Ce($e.InternalError,"Task creation did not return a task");for(;;){const s=await this.getTask({taskId:a},n);if(yield{type:"taskStatus",task:s},eo(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:a},r,n)}:s.status==="failed"?yield{type:"error",error:new Ce($e.InternalError,`Task ${a} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new Ce($e.InternalError,`Task ${a} was cancelled`)});return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:a},r,n)};return}const l=s.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(c=>setTimeout(c,l)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof Ce?i:new Ce($e.InternalError,String(i))}}}request(t,r,n){const{relatedRequestId:o,resumptionToken:a,onresumptiontoken:i,task:s,relatedTask:l}=n??{};return new Promise((c,u)=>{const h=v=>{u(v)};if(!this._transport){h(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),s&&this.assertTaskCapability(t.method)}catch(v){h(v);return}n?.signal?.throwIfAborted();const p=this._requestMessageId++,m={...t,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.onprogress),m.params={...t.params,_meta:{...t.params?._meta||{},progressToken:p}}),s&&(m.params={...m.params,task:s}),l&&(m.params={...m.params,_meta:{...m.params?._meta||{},[Gn]:l}});const f=v=>{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(v)}},{relatedRequestId:o,resumptionToken:a,onresumptiontoken:i}).catch(I=>this._onerror(new Error(`Failed to send cancellation: ${I}`)));const g=v instanceof Ce?v:new Ce($e.RequestTimeout,String(v));u(g)};this._responseHandlers.set(p,v=>{if(!n?.signal?.aborted){if(v instanceof Error)return u(v);try{const g=bn(r,v.result);g.success?c(g.data):u(g.error)}catch(g){u(g)}}}),n?.signal?.addEventListener("abort",()=>{f(n?.signal?.reason)});const b=n?.timeout??IE,w=()=>f(Ce.fromError($e.RequestTimeout,"Request timed out",{timeout:b}));this._setupTimeout(p,b,n?.maxTotalTimeout,w,n?.resetTimeoutOnProgress??!1);const C=l?.taskId;if(C){const v=g=>{const I=this._responseHandlers.get(p);I?I(g):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,v),this._enqueueTaskMessage(C,{type:"request",message:m,timestamp:Date.now()}).catch(g=>{this._cleanupTimeout(p),u(g)})}else this._transport.send(m,{relatedRequestId:o,resumptionToken:a,onresumptiontoken:i}).catch(v=>{this._cleanupTimeout(p),u(v)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},Bc,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},Wc,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},QS,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 s={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[Gn]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:s,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 s={...t,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[Gn]:r.relatedTask}}}),this._transport?.send(s,r).catch(l=>this._onerror(l))});return}let i={...t,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Gn]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(t,r){const n=J_(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,a)=>{const i=G_(t,o);return Promise.resolve(r(i,a))})}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=J_(t);this._notificationHandlers.set(n,o=>{const a=G_(t,o);return Promise.resolve(r(a))})}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"&&Dc(o.message)){const a=o.message.id,i=this._requestResolvers.get(a);i?(i(new Ce($e.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(a)):this._onerror(new Error(`Resolver missing for request ${a} 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,a)=>{if(r.aborted){a(new Ce($e.InvalidRequest,"Request cancelled"));return}const i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),a(new Ce($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 a=await n.getTask(o,r);if(!a)throw new Ce($e.InvalidParams,"Failed to retrieve task: Task not found");return a},storeTaskResult:async(o,a,i)=>{await n.storeTaskResult(o,a,i,r);const s=await n.getTask(o,r);if(s){const l=Us.parse({method:"notifications/tasks/status",params:s});await this.notification(l),eo(s.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,a,i)=>{const s=await n.getTask(o,r);if(!s)throw new Ce($e.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(eo(s.status))throw new Ce($e.InvalidParams,`Cannot update task "${o}" from terminal status "${s.status}" to "${a}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,a,i,r);const l=await n.getTask(o,r);if(l){const c=Us.parse({method:"notifications/tasks/status",params:l});await this.notification(c),eo(l.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}function W_(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function EE(e,t){const r={...e};for(const n in t){const o=n,a=t[o];if(a===void 0)continue;const i=r[o];W_(i)&&W_(a)?r[o]={...i,...a}:r[o]=a}return r}var oi={exports:{}},Ju={},rn={},to={},Gu={},Wu={},Ku={},K_;function ai(){return K_||(K_=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(v){if(super(),!e.IDENTIFIER.test(v))throw new Error("CodeGen: name must be a valid identifier");this.str=v}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=r;class n extends t{constructor(v){super(),this._items=typeof v=="string"?[v]:v}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const v=this._items[0];return v===""||v==='""'}get str(){var v;return(v=this._str)!==null&&v!==void 0?v:this._str=this._items.reduce((g,I)=>`${g}${I}`,"")}get names(){var v;return(v=this._names)!==null&&v!==void 0?v:this._names=this._items.reduce((g,I)=>(I instanceof r&&(g[I.str]=(g[I.str]||0)+1),g),{})}}e._Code=n,e.nil=new n("");function o(C,...v){const g=[C[0]];let I=0;for(;I<v.length;)s(g,v[I]),g.push(C[++I]);return new n(g)}e._=o;const a=new n("+");function i(C,...v){const g=[m(C[0])];let I=0;for(;I<v.length;)g.push(a),s(g,v[I]),g.push(a,m(C[++I]));return l(g),new n(g)}e.str=i;function s(C,v){v instanceof n?C.push(...v._items):v instanceof r?C.push(v):C.push(h(v))}e.addCodeArg=s;function l(C){let v=1;for(;v<C.length-1;){if(C[v]===a){const g=c(C[v-1],C[v+1]);if(g!==void 0){C.splice(v-1,3,g);continue}C[v++]="+"}v++}}function c(C,v){if(v==='""')return C;if(C==='""')return v;if(typeof C=="string")return v instanceof r||C[C.length-1]!=='"'?void 0:typeof v!="string"?`${C.slice(0,-1)}${v}"`:v[0]==='"'?C.slice(0,-1)+v.slice(1):void 0;if(typeof v=="string"&&v[0]==='"'&&!(C instanceof r))return`"${C}${v.slice(1)}`}function u(C,v){return v.emptyStr()?C:C.emptyStr()?v:i`${C}${v}`}e.strConcat=u;function h(C){return typeof C=="number"||typeof C=="boolean"||C===null?C:m(Array.isArray(C)?C.join(","):C)}function p(C){return new n(m(C))}e.stringify=p;function m(C){return JSON.stringify(C).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.safeStringify=m;function f(C){return typeof C=="string"&&e.IDENTIFIER.test(C)?new n(`.${C}`):o`[${C}]`}e.getProperty=f;function b(C){if(typeof C=="string"&&e.IDENTIFIER.test(C))return new n(`${C}`);throw new Error(`CodeGen: invalid export name: ${C}, use explicit $id name mapping`)}e.getEsmExportName=b;function w(C){return new n(C.toString())}e.regexpCode=w})(Ku)),Ku}var Yu={},Y_;function Q_(){return Y_||(Y_=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=ai();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,h;if(!((h=(u=this._parent)===null||u===void 0?void 0:u._prefixes)===null||h===void 0)&&h.has(c)||this._prefixes&&!this._prefixes.has(c))throw new Error(`CodeGen: prefix "${c}" is not allowed in this scope`);return this._names[c]={prefix:c,index:0}}}e.Scope=o;class a extends t.Name{constructor(c,u){super(u),this.prefix=c}setValue(c,{property:u,itemIndex:h}){this.value=c,this.scopePath=(0,t._)`.${new t.Name(u)}[${h}]`}}e.ValueScopeName=a;const i=(0,t._)`\n`;class s 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 a(c,this._newName(c))}value(c,u){var h;if(u.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const p=this.toName(c),{prefix:m}=p,f=(h=u.key)!==null&&h!==void 0?h:u.ref;let b=this._values[m];if(b){const v=b.get(f);if(v)return v}else b=this._values[m]=new Map;b.set(f,p);const w=this._scope[m]||(this._scope[m]=[]),C=w.length;return w[C]=u.ref,p.setValue(u,{property:m,itemIndex:C}),p}getValue(c,u){const h=this._values[c];if(h)return h.get(u)}scopeRefs(c,u=this._values){return this._reduceValues(u,h=>{if(h.scopePath===void 0)throw new Error(`CodeGen: name "${h}" has no value`);return(0,t._)`${c}${h.scopePath}`})}scopeCode(c=this._values,u,h){return this._reduceValues(c,p=>{if(p.value===void 0)throw new Error(`CodeGen: name "${p}" has no value`);return p.value.code},u,h)}_reduceValues(c,u,h={},p){let m=t.nil;for(const f in c){const b=c[f];if(!b)continue;const w=h[f]=h[f]||new Map;b.forEach(C=>{if(w.has(C))return;w.set(C,n.Started);let v=u(C);if(v){const g=this.opts.es5?e.varKinds.var:e.varKinds.const;m=(0,t._)`${m}${g} ${C} = ${v};${this.opts._n}`}else if(v=p?.(C))m=(0,t._)`${m}${v}${this.opts._n}`;else throw new r(C);w.set(C,n.Completed)})}return m}}e.ValueScope=s})(Yu)),Yu}var X_;function Oe(){return X_||(X_=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=ai(),r=Q_();var n=ai();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=Q_();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 a{optimizeNodes(){return this}optimizeNames($,O){return this}}class i extends a{constructor($,O,j){super(),this.varKind=$,this.name=O,this.rhs=j}render({es5:$,_n:O}){const j=$?r.varKinds.var:this.varKind,G=this.rhs===void 0?"":` = ${this.rhs}`;return`${j} ${this.name}${G};`+O}optimizeNames($,O){if($[this.name.str])return this.rhs&&(this.rhs=z(this.rhs,$,O)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class s extends a{constructor($,O,j){super(),this.lhs=$,this.rhs=O,this.sideEffects=j}render({_n:$}){return`${this.lhs} = ${this.rhs};`+$}optimizeNames($,O){if(!(this.lhs instanceof t.Name&&!$[this.lhs.str]&&!this.sideEffects))return this.rhs=z(this.rhs,$,O),this}get names(){const $=this.lhs instanceof t.Name?{}:{...this.lhs.names};return U($,this.rhs)}}class l extends s{constructor($,O,j,G){super($,j,G),this.op=O}render({_n:$}){return`${this.lhs} ${this.op}= ${this.rhs};`+$}}class c extends a{constructor($){super(),this.label=$,this.names={}}render({_n:$}){return`${this.label}:`+$}}class u extends a{constructor($){super(),this.label=$,this.names={}}render({_n:$}){return`break${this.label?` ${this.label}`:""};`+$}}class h extends a{constructor($){super(),this.error=$}render({_n:$}){return`throw ${this.error};`+$}get names(){return this.error.names}}class p extends a{constructor($){super(),this.code=$}render({_n:$}){return`${this.code};`+$}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames($,O){return this.code=z(this.code,$,O),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class m extends a{constructor($=[]){super(),this.nodes=$}render($){return this.nodes.reduce((O,j)=>O+j.render($),"")}optimizeNodes(){const{nodes:$}=this;let O=$.length;for(;O--;){const j=$[O].optimizeNodes();Array.isArray(j)?$.splice(O,1,...j):j?$[O]=j:$.splice(O,1)}return $.length>0?this:void 0}optimizeNames($,O){const{nodes:j}=this;let G=j.length;for(;G--;){const Y=j[G];Y.optimizeNames($,O)||(ee($,Y.names),j.splice(G,1))}return j.length>0?this:void 0}get names(){return this.nodes.reduce(($,O)=>N($,O.names),{})}}class f extends m{render($){return"{"+$._n+super.render($)+"}"+$._n}}class b extends m{}class w extends f{}w.kind="else";class C extends f{constructor($,O){super(O),this.condition=$}render($){let O=`if(${this.condition})`+super.render($);return this.else&&(O+="else "+this.else.render($)),O}optimizeNodes(){super.optimizeNodes();const $=this.condition;if($===!0)return this.nodes;let O=this.else;if(O){const j=O.optimizeNodes();O=this.else=Array.isArray(j)?new w(j):j}if(O)return $===!1?O instanceof C?O:O.nodes:this.nodes.length?this:new C(Q($),O instanceof C?[O]:O.nodes);if(!($===!1||!this.nodes.length))return this}optimizeNames($,O){var j;if(this.else=(j=this.else)===null||j===void 0?void 0:j.optimizeNames($,O),!!(super.optimizeNames($,O)||this.else))return this.condition=z(this.condition,$,O),this}get names(){const $=super.names;return U($,this.condition),this.else&&N($,this.else.names),$}}C.kind="if";class v extends f{}v.kind="for";class g extends v{constructor($){super(),this.iteration=$}render($){return`for(${this.iteration})`+super.render($)}optimizeNames($,O){if(super.optimizeNames($,O))return this.iteration=z(this.iteration,$,O),this}get names(){return N(super.names,this.iteration.names)}}class I extends v{constructor($,O,j,G){super(),this.varKind=$,this.name=O,this.from=j,this.to=G}render($){const O=$.es5?r.varKinds.var:this.varKind,{name:j,from:G,to:Y}=this;return`for(${O} ${j}=${G}; ${j}<${Y}; ${j}++)`+super.render($)}get names(){const $=U(super.names,this.from);return U($,this.to)}}class y extends v{constructor($,O,j,G){super(),this.loop=$,this.varKind=O,this.name=j,this.iterable=G}render($){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render($)}optimizeNames($,O){if(super.optimizeNames($,O))return this.iterable=z(this.iterable,$,O),this}get names(){return N(super.names,this.iterable.names)}}class _ extends f{constructor($,O,j){super(),this.name=$,this.args=O,this.async=j}render($){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render($)}}_.kind="func";class k extends m{render($){return"return "+super.render($)}}k.kind="return";class S extends f{render($){let O="try"+super.render($);return this.catch&&(O+=this.catch.render($)),this.finally&&(O+=this.finally.render($)),O}optimizeNodes(){var $,O;return super.optimizeNodes(),($=this.catch)===null||$===void 0||$.optimizeNodes(),(O=this.finally)===null||O===void 0||O.optimizeNodes(),this}optimizeNames($,O){var j,G;return super.optimizeNames($,O),(j=this.catch)===null||j===void 0||j.optimizeNames($,O),(G=this.finally)===null||G===void 0||G.optimizeNames($,O),this}get names(){const $=super.names;return this.catch&&N($,this.catch.names),this.finally&&N($,this.finally.names),$}}class E extends f{constructor($){super(),this.error=$}render($){return`catch(${this.error})`+super.render($)}}E.kind="catch";class R extends f{render($){return"finally"+super.render($)}}R.kind="finally";class x{constructor($,O={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...O,_n:O.lines?`
|
|
89
|
+
`:""},this._extScope=$,this._scope=new r.Scope({parent:$}),this._nodes=[new b]}toString(){return this._root.render(this.opts)}name($){return this._scope.name($)}scopeName($){return this._extScope.name($)}scopeValue($,O){const j=this._extScope.value($,O);return(this._values[j.prefix]||(this._values[j.prefix]=new Set)).add(j),j}getScopeValue($,O){return this._extScope.getValue($,O)}scopeRefs($){return this._extScope.scopeRefs($,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def($,O,j,G){const Y=this._scope.toName(O);return j!==void 0&&G&&(this._constants[Y.str]=j),this._leafNode(new i($,Y,j)),Y}const($,O,j){return this._def(r.varKinds.const,$,O,j)}let($,O,j){return this._def(r.varKinds.let,$,O,j)}var($,O,j){return this._def(r.varKinds.var,$,O,j)}assign($,O,j){return this._leafNode(new s($,O,j))}add($,O){return this._leafNode(new l($,e.operators.ADD,O))}code($){return typeof $=="function"?$():$!==t.nil&&this._leafNode(new p($)),this}object(...$){const O=["{"];for(const[j,G]of $)O.length>1&&O.push(","),O.push(j),(j!==G||this.opts.es5)&&(O.push(":"),(0,t.addCodeArg)(O,G));return O.push("}"),new t._Code(O)}if($,O,j){if(this._blockNode(new C($)),O&&j)this.code(O).else().code(j).endIf();else if(O)this.code(O).endIf();else if(j)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf($){return this._elseNode(new C($))}else(){return this._elseNode(new w)}endIf(){return this._endBlockNode(C,w)}_for($,O){return this._blockNode($),O&&this.code(O).endFor(),this}for($,O){return this._for(new g($),O)}forRange($,O,j,G,Y=this.opts.es5?r.varKinds.var:r.varKinds.let){const W=this._scope.toName($);return this._for(new I(Y,W,O,j),()=>G(W))}forOf($,O,j,G=r.varKinds.const){const Y=this._scope.toName($);if(this.opts.es5){const W=O instanceof t.Name?O:this.var("_arr",O);return this.forRange("_i",0,(0,t._)`${W}.length`,V=>{this.var(Y,(0,t._)`${W}[${V}]`),j(Y)})}return this._for(new y("of",G,Y,O),()=>j(Y))}forIn($,O,j,G=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf($,(0,t._)`Object.keys(${O})`,j);const Y=this._scope.toName($);return this._for(new y("in",G,Y,O),()=>j(Y))}endFor(){return this._endBlockNode(v)}label($){return this._leafNode(new c($))}break($){return this._leafNode(new u($))}return($){const O=new k;if(this._blockNode(O),this.code($),O.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(k)}try($,O,j){if(!O&&!j)throw new Error('CodeGen: "try" without "catch" and "finally"');const G=new S;if(this._blockNode(G),this.code($),O){const Y=this.name("e");this._currNode=G.catch=new E(Y),O(Y)}return j&&(this._currNode=G.finally=new R,this.code(j)),this._endBlockNode(E,R)}throw($){return this._leafNode(new h($))}block($,O){return this._blockStarts.push(this._nodes.length),$&&this.code($).endBlock(O),this}endBlock($){const O=this._blockStarts.pop();if(O===void 0)throw new Error("CodeGen: not in self-balancing block");const j=this._nodes.length-O;if(j<0||$!==void 0&&j!==$)throw new Error(`CodeGen: wrong number of nodes: ${j} vs ${$} expected`);return this._nodes.length=O,this}func($,O=t.nil,j,G){return this._blockNode(new _($,O,j)),G&&this.code(G).endFunc(),this}endFunc(){return this._endBlockNode(_)}optimize($=1){for(;$-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode($){return this._currNode.nodes.push($),this}_blockNode($){this._currNode.nodes.push($),this._nodes.push($)}_endBlockNode($,O){const j=this._currNode;if(j instanceof $||O&&j instanceof O)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${O?`${$.kind}/${O.kind}`:$.kind}"`)}_elseNode($){const O=this._currNode;if(!(O instanceof C))throw new Error('CodeGen: "else" without "if"');return this._currNode=O.else=$,this}get _root(){return this._nodes[0]}get _currNode(){const $=this._nodes;return $[$.length-1]}set _currNode($){const O=this._nodes;O[O.length-1]=$}}e.CodeGen=x;function N(F,$){for(const O in $)F[O]=(F[O]||0)+($[O]||0);return F}function U(F,$){return $ instanceof t._CodeOrName?N(F,$.names):F}function z(F,$,O){if(F instanceof t.Name)return j(F);if(!G(F))return F;return new t._Code(F._items.reduce((Y,W)=>(W instanceof t.Name&&(W=j(W)),W instanceof t._Code?Y.push(...W._items):Y.push(W),Y),[]));function j(Y){const W=O[Y.str];return W===void 0||$[Y.str]!==1?Y:(delete $[Y.str],W)}function G(Y){return Y instanceof t._Code&&Y._items.some(W=>W instanceof t.Name&&$[W.str]===1&&O[W.str]!==void 0)}}function ee(F,$){for(const O in $)F[O]=(F[O]||0)-($[O]||0)}function Q(F){return typeof F=="boolean"||typeof F=="number"||F===null?!F:(0,t._)`!${B(F)}`}e.not=Q;const se=D(e.operators.AND);function re(...F){return F.reduce(se)}e.and=re;const Se=D(e.operators.OR);function H(...F){return F.reduce(Se)}e.or=H;function D(F){return($,O)=>$===t.nil?O:O===t.nil?$:(0,t._)`${B($)} ${F} ${B(O)}`}function B(F){return F instanceof t.Name?F:(0,t._)`(${F})`}})(Wu)),Wu}var Ae={},ey;function Fe(){if(ey)return Ae;ey=1,Object.defineProperty(Ae,"__esModule",{value:!0}),Ae.checkStrictMode=Ae.getErrorPath=Ae.Type=Ae.useFunc=Ae.setEvaluated=Ae.evaluatedPropsToName=Ae.mergeEvaluated=Ae.eachItem=Ae.unescapeJsonPointer=Ae.escapeJsonPointer=Ae.escapeFragment=Ae.unescapeFragment=Ae.schemaRefOrVal=Ae.schemaHasRulesButRef=Ae.schemaHasRules=Ae.checkUnknownRules=Ae.alwaysValidSchema=Ae.toHash=void 0;const e=Oe(),t=ai();function r(y){const _={};for(const k of y)_[k]=!0;return _}Ae.toHash=r;function n(y,_){return typeof _=="boolean"?_:Object.keys(_).length===0?!0:(o(y,_),!a(_,y.self.RULES.all))}Ae.alwaysValidSchema=n;function o(y,_=y.schema){const{opts:k,self:S}=y;if(!k.strictSchema||typeof _=="boolean")return;const E=S.RULES.keywords;for(const R in _)E[R]||I(y,`unknown keyword: "${R}"`)}Ae.checkUnknownRules=o;function a(y,_){if(typeof y=="boolean")return!y;for(const k in y)if(_[k])return!0;return!1}Ae.schemaHasRules=a;function i(y,_){if(typeof y=="boolean")return!y;for(const k in y)if(k!=="$ref"&&_.all[k])return!0;return!1}Ae.schemaHasRulesButRef=i;function s({topSchemaRef:y,schemaPath:_},k,S,E){if(!E){if(typeof k=="number"||typeof k=="boolean")return k;if(typeof k=="string")return(0,e._)`${k}`}return(0,e._)`${y}${_}${(0,e.getProperty)(S)}`}Ae.schemaRefOrVal=s;function l(y){return h(decodeURIComponent(y))}Ae.unescapeFragment=l;function c(y){return encodeURIComponent(u(y))}Ae.escapeFragment=c;function u(y){return typeof y=="number"?`${y}`:y.replace(/~/g,"~0").replace(/\//g,"~1")}Ae.escapeJsonPointer=u;function h(y){return y.replace(/~1/g,"/").replace(/~0/g,"~")}Ae.unescapeJsonPointer=h;function p(y,_){if(Array.isArray(y))for(const k of y)_(k);else _(y)}Ae.eachItem=p;function m({mergeNames:y,mergeToName:_,mergeValues:k,resultToName:S}){return(E,R,x,N)=>{const U=x===void 0?R:x instanceof e.Name?(R instanceof e.Name?y(E,R,x):_(E,R,x),x):R instanceof e.Name?(_(E,x,R),R):k(R,x);return N===e.Name&&!(U instanceof e.Name)?S(E,U):U}}Ae.mergeEvaluated={props:m({mergeNames:(y,_,k)=>y.if((0,e._)`${k} !== true && ${_} !== undefined`,()=>{y.if((0,e._)`${_} === true`,()=>y.assign(k,!0),()=>y.assign(k,(0,e._)`${k} || {}`).code((0,e._)`Object.assign(${k}, ${_})`))}),mergeToName:(y,_,k)=>y.if((0,e._)`${k} !== true`,()=>{_===!0?y.assign(k,!0):(y.assign(k,(0,e._)`${k} || {}`),b(y,k,_))}),mergeValues:(y,_)=>y===!0?!0:{...y,..._},resultToName:f}),items:m({mergeNames:(y,_,k)=>y.if((0,e._)`${k} !== true && ${_} !== undefined`,()=>y.assign(k,(0,e._)`${_} === true ? true : ${k} > ${_} ? ${k} : ${_}`)),mergeToName:(y,_,k)=>y.if((0,e._)`${k} !== true`,()=>y.assign(k,_===!0?!0:(0,e._)`${k} > ${_} ? ${k} : ${_}`)),mergeValues:(y,_)=>y===!0?!0:Math.max(y,_),resultToName:(y,_)=>y.var("items",_)})};function f(y,_){if(_===!0)return y.var("props",!0);const k=y.var("props",(0,e._)`{}`);return _!==void 0&&b(y,k,_),k}Ae.evaluatedPropsToName=f;function b(y,_,k){Object.keys(k).forEach(S=>y.assign((0,e._)`${_}${(0,e.getProperty)(S)}`,!0))}Ae.setEvaluated=b;const w={};function C(y,_){return y.scopeValue("func",{ref:_,code:w[_.code]||(w[_.code]=new t._Code(_.code))})}Ae.useFunc=C;var v;(function(y){y[y.Num=0]="Num",y[y.Str=1]="Str"})(v||(Ae.Type=v={}));function g(y,_,k){if(y instanceof e.Name){const S=_===v.Num;return k?S?(0,e._)`"[" + ${y} + "]"`:(0,e._)`"['" + ${y} + "']"`:S?(0,e._)`"/" + ${y}`:(0,e._)`"/" + ${y}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return k?(0,e.getProperty)(y).toString():"/"+u(y)}Ae.getErrorPath=g;function I(y,_,k=y.opts.strictSchema){if(k){if(_=`strict mode: ${_}`,k===!0)throw new Error(_);y.self.logger.warn(_)}}return Ae.checkStrictMode=I,Ae}var si={},ty;function kn(){if(ty)return si;ty=1,Object.defineProperty(si,"__esModule",{value:!0});const e=Oe(),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 si.default=t,si}var ry;function ii(){return ry||(ry=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=Oe(),r=Fe(),n=kn();e.keywordError={message:({keyword:w})=>(0,t.str)`must pass "${w}" keyword validation`},e.keyword$DataError={message:({keyword:w,schemaType:C})=>C?(0,t.str)`"${w}" keyword must be ${C} ($data)`:(0,t.str)`"${w}" keyword is invalid ($data)`};function o(w,C=e.keywordError,v,g){const{it:I}=w,{gen:y,compositeRule:_,allErrors:k}=I,S=h(w,C,v);g??(_||k)?l(y,S):c(I,(0,t._)`[${S}]`)}e.reportError=o;function a(w,C=e.keywordError,v){const{it:g}=w,{gen:I,compositeRule:y,allErrors:_}=g,k=h(w,C,v);l(I,k),y||_||c(g,n.default.vErrors)}e.reportExtraError=a;function i(w,C){w.assign(n.default.errors,C),w.if((0,t._)`${n.default.vErrors} !== null`,()=>w.if(C,()=>w.assign((0,t._)`${n.default.vErrors}.length`,C),()=>w.assign(n.default.vErrors,null)))}e.resetErrorsCount=i;function s({gen:w,keyword:C,schemaValue:v,data:g,errsCount:I,it:y}){if(I===void 0)throw new Error("ajv implementation error");const _=w.name("err");w.forRange("i",I,n.default.errors,k=>{w.const(_,(0,t._)`${n.default.vErrors}[${k}]`),w.if((0,t._)`${_}.instancePath === undefined`,()=>w.assign((0,t._)`${_}.instancePath`,(0,t.strConcat)(n.default.instancePath,y.errorPath))),w.assign((0,t._)`${_}.schemaPath`,(0,t.str)`${y.errSchemaPath}/${C}`),y.opts.verbose&&(w.assign((0,t._)`${_}.schema`,v),w.assign((0,t._)`${_}.data`,g))})}e.extendErrors=s;function l(w,C){const v=w.const("err",C);w.if((0,t._)`${n.default.vErrors} === null`,()=>w.assign(n.default.vErrors,(0,t._)`[${v}]`),(0,t._)`${n.default.vErrors}.push(${v})`),w.code((0,t._)`${n.default.errors}++`)}function c(w,C){const{gen:v,validateName:g,schemaEnv:I}=w;I.$async?v.throw((0,t._)`new ${w.ValidationError}(${C})`):(v.assign((0,t._)`${g}.errors`,C),v.return(!1))}const u={keyword:new t.Name("keyword"),schemaPath:new t.Name("schemaPath"),params:new t.Name("params"),propertyName:new t.Name("propertyName"),message:new t.Name("message"),schema:new t.Name("schema"),parentSchema:new t.Name("parentSchema")};function h(w,C,v){const{createErrors:g}=w.it;return g===!1?(0,t._)`{}`:p(w,C,v)}function p(w,C,v={}){const{gen:g,it:I}=w,y=[m(I,v),f(w,v)];return b(w,C,y),g.object(...y)}function m({errorPath:w},{instancePath:C}){const v=C?(0,t.str)`${w}${(0,r.getErrorPath)(C,r.Type.Str)}`:w;return[n.default.instancePath,(0,t.strConcat)(n.default.instancePath,v)]}function f({keyword:w,it:{errSchemaPath:C}},{schemaPath:v,parentSchema:g}){let I=g?C:(0,t.str)`${C}/${w}`;return v&&(I=(0,t.str)`${I}${(0,r.getErrorPath)(v,r.Type.Str)}`),[u.schemaPath,I]}function b(w,{params:C,message:v},g){const{keyword:I,data:y,schemaValue:_,it:k}=w,{opts:S,propertyName:E,topSchemaRef:R,schemaPath:x}=k;g.push([u.keyword,I],[u.params,typeof C=="function"?C(w):C||(0,t._)`{}`]),S.messages&&g.push([u.message,typeof v=="function"?v(w):v]),S.verbose&&g.push([u.schema,_],[u.parentSchema,(0,t._)`${R}${x}`],[n.default.data,y]),E&&g.push([u.propertyName,E])}})(Gu)),Gu}var ny;function $E(){if(ny)return to;ny=1,Object.defineProperty(to,"__esModule",{value:!0}),to.boolOrEmptySchema=to.topBoolOrEmptySchema=void 0;const e=ii(),t=Oe(),r=kn(),n={message:"boolean schema is false"};function o(s){const{gen:l,schema:c,validateName:u}=s;c===!1?i(s,!1):typeof c=="object"&&c.$async===!0?l.return(r.default.data):(l.assign((0,t._)`${u}.errors`,null),l.return(!0))}to.topBoolOrEmptySchema=o;function a(s,l){const{gen:c,schema:u}=s;u===!1?(c.var(l,!1),i(s)):c.var(l,!0)}to.boolOrEmptySchema=a;function i(s,l){const{gen:c,data:u}=s,h={gen:c,keyword:"false schema",data:u,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:s};(0,e.reportError)(h,n,void 0,l)}return to}var Dt={},ro={},oy;function ay(){if(oy)return ro;oy=1,Object.defineProperty(ro,"__esModule",{value:!0}),ro.getRules=ro.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)}ro.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 ro.getRules=n,ro}var nn={},sy;function iy(){if(sy)return nn;sy=1,Object.defineProperty(nn,"__esModule",{value:!0}),nn.shouldUseRule=nn.shouldUseGroup=nn.schemaHasRulesForType=void 0;function e({schema:n,self:o},a){const i=o.RULES.types[a];return i&&i!==!0&&t(n,i)}nn.schemaHasRulesForType=e;function t(n,o){return o.rules.some(a=>r(n,a))}nn.shouldUseGroup=t;function r(n,o){var a;return n[o.keyword]!==void 0||((a=o.definition.implements)===null||a===void 0?void 0:a.some(i=>n[i]!==void 0))}return nn.shouldUseRule=r,nn}var ly;function li(){if(ly)return Dt;ly=1,Object.defineProperty(Dt,"__esModule",{value:!0}),Dt.reportTypeError=Dt.checkDataTypes=Dt.checkDataType=Dt.coerceAndCheckDataType=Dt.getJSONTypes=Dt.getSchemaTypes=Dt.DataType=void 0;const e=ay(),t=iy(),r=ii(),n=Oe(),o=Fe();var a;(function(v){v[v.Correct=0]="Correct",v[v.Wrong=1]="Wrong"})(a||(Dt.DataType=a={}));function i(v){const g=s(v.type);if(g.includes("null")){if(v.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!g.length&&v.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');v.nullable===!0&&g.push("null")}return g}Dt.getSchemaTypes=i;function s(v){const g=Array.isArray(v)?v:v?[v]:[];if(g.every(e.isJSONType))return g;throw new Error("type must be JSONType or JSONType[]: "+g.join(","))}Dt.getJSONTypes=s;function l(v,g){const{gen:I,data:y,opts:_}=v,k=u(g,_.coerceTypes),S=g.length>0&&!(k.length===0&&g.length===1&&(0,t.schemaHasRulesForType)(v,g[0]));if(S){const E=f(g,y,_.strictNumbers,a.Wrong);I.if(E,()=>{k.length?h(v,g,k):w(v)})}return S}Dt.coerceAndCheckDataType=l;const c=new Set(["string","number","integer","boolean","null"]);function u(v,g){return g?v.filter(I=>c.has(I)||g==="array"&&I==="array"):[]}function h(v,g,I){const{gen:y,data:_,opts:k}=v,S=y.let("dataType",(0,n._)`typeof ${_}`),E=y.let("coerced",(0,n._)`undefined`);k.coerceTypes==="array"&&y.if((0,n._)`${S} == 'object' && Array.isArray(${_}) && ${_}.length == 1`,()=>y.assign(_,(0,n._)`${_}[0]`).assign(S,(0,n._)`typeof ${_}`).if(f(g,_,k.strictNumbers),()=>y.assign(E,_))),y.if((0,n._)`${E} !== undefined`);for(const x of I)(c.has(x)||x==="array"&&k.coerceTypes==="array")&&R(x);y.else(),w(v),y.endIf(),y.if((0,n._)`${E} !== undefined`,()=>{y.assign(_,E),p(v,E)});function R(x){switch(x){case"string":y.elseIf((0,n._)`${S} == "number" || ${S} == "boolean"`).assign(E,(0,n._)`"" + ${_}`).elseIf((0,n._)`${_} === null`).assign(E,(0,n._)`""`);return;case"number":y.elseIf((0,n._)`${S} == "boolean" || ${_} === null
|
|
90
|
+
|| (${S} == "string" && ${_} && ${_} == +${_})`).assign(E,(0,n._)`+${_}`);return;case"integer":y.elseIf((0,n._)`${S} === "boolean" || ${_} === null
|
|
91
|
+
|| (${S} === "string" && ${_} && ${_} == +${_} && !(${_} % 1))`).assign(E,(0,n._)`+${_}`);return;case"boolean":y.elseIf((0,n._)`${_} === "false" || ${_} === 0 || ${_} === null`).assign(E,!1).elseIf((0,n._)`${_} === "true" || ${_} === 1`).assign(E,!0);return;case"null":y.elseIf((0,n._)`${_} === "" || ${_} === 0 || ${_} === false`),y.assign(E,null);return;case"array":y.elseIf((0,n._)`${S} === "string" || ${S} === "number"
|
|
92
|
+
|| ${S} === "boolean" || ${_} === null`).assign(E,(0,n._)`[${_}]`)}}}function p({gen:v,parentData:g,parentDataProperty:I},y){v.if((0,n._)`${g} !== undefined`,()=>v.assign((0,n._)`${g}[${I}]`,y))}function m(v,g,I,y=a.Correct){const _=y===a.Correct?n.operators.EQ:n.operators.NEQ;let k;switch(v){case"null":return(0,n._)`${g} ${_} null`;case"array":k=(0,n._)`Array.isArray(${g})`;break;case"object":k=(0,n._)`${g} && typeof ${g} == "object" && !Array.isArray(${g})`;break;case"integer":k=S((0,n._)`!(${g} % 1) && !isNaN(${g})`);break;case"number":k=S();break;default:return(0,n._)`typeof ${g} ${_} ${v}`}return y===a.Correct?k:(0,n.not)(k);function S(E=n.nil){return(0,n.and)((0,n._)`typeof ${g} == "number"`,E,I?(0,n._)`isFinite(${g})`:n.nil)}}Dt.checkDataType=m;function f(v,g,I,y){if(v.length===1)return m(v[0],g,I,y);let _;const k=(0,o.toHash)(v);if(k.array&&k.object){const S=(0,n._)`typeof ${g} != "object"`;_=k.null?S:(0,n._)`!${g} || ${S}`,delete k.null,delete k.array,delete k.object}else _=n.nil;k.number&&delete k.integer;for(const S in k)_=(0,n.and)(_,m(S,g,I,y));return _}Dt.checkDataTypes=f;const b={message:({schema:v})=>`must be ${v}`,params:({schema:v,schemaValue:g})=>typeof v=="string"?(0,n._)`{type: ${v}}`:(0,n._)`{type: ${g}}`};function w(v){const g=C(v);(0,r.reportError)(g,b)}Dt.reportTypeError=w;function C(v){const{gen:g,data:I,schema:y}=v,_=(0,o.schemaRefOrVal)(v,y,"type");return{gen:g,keyword:"type",data:I,schema:y.type,schemaCode:_,schemaValue:_,parentSchema:y,params:{},it:v}}return Dt}var Aa={},cy;function RE(){if(cy)return Aa;cy=1,Object.defineProperty(Aa,"__esModule",{value:!0}),Aa.assignDefaults=void 0;const e=Oe(),t=Fe();function r(o,a){const{properties:i,items:s}=o.schema;if(a==="object"&&i)for(const l in i)n(o,l,i[l].default);else a==="array"&&Array.isArray(s)&&s.forEach((l,c)=>n(o,c,l.default))}Aa.assignDefaults=r;function n(o,a,i){const{gen:s,compositeRule:l,data:c,opts:u}=o;if(i===void 0)return;const h=(0,e._)`${c}${(0,e.getProperty)(a)}`;if(l){(0,t.checkStrictMode)(o,`default is ignored for: ${h}`);return}let p=(0,e._)`${h} === undefined`;u.useDefaults==="empty"&&(p=(0,e._)`${p} || ${h} === null || ${h} === ""`),s.if(p,(0,e._)`${h} = ${(0,e.stringify)(i)}`)}return Aa}var Pr={},Ge={},uy;function Mr(){if(uy)return Ge;uy=1,Object.defineProperty(Ge,"__esModule",{value:!0}),Ge.validateUnion=Ge.validateArray=Ge.usePattern=Ge.callValidateCode=Ge.schemaProperties=Ge.allSchemaProperties=Ge.noPropertyInData=Ge.propertyInData=Ge.isOwnProperty=Ge.hasPropFunc=Ge.reportMissingProp=Ge.checkMissingProp=Ge.checkReportMissingProp=void 0;const e=Oe(),t=Fe(),r=kn(),n=Fe();function o(v,g){const{gen:I,data:y,it:_}=v;I.if(u(I,y,g,_.opts.ownProperties),()=>{v.setParams({missingProperty:(0,e._)`${g}`},!0),v.error()})}Ge.checkReportMissingProp=o;function a({gen:v,data:g,it:{opts:I}},y,_){return(0,e.or)(...y.map(k=>(0,e.and)(u(v,g,k,I.ownProperties),(0,e._)`${_} = ${k}`)))}Ge.checkMissingProp=a;function i(v,g){v.setParams({missingProperty:g},!0),v.error()}Ge.reportMissingProp=i;function s(v){return v.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,e._)`Object.prototype.hasOwnProperty`})}Ge.hasPropFunc=s;function l(v,g,I){return(0,e._)`${s(v)}.call(${g}, ${I})`}Ge.isOwnProperty=l;function c(v,g,I,y){const _=(0,e._)`${g}${(0,e.getProperty)(I)} !== undefined`;return y?(0,e._)`${_} && ${l(v,g,I)}`:_}Ge.propertyInData=c;function u(v,g,I,y){const _=(0,e._)`${g}${(0,e.getProperty)(I)} === undefined`;return y?(0,e.or)(_,(0,e.not)(l(v,g,I))):_}Ge.noPropertyInData=u;function h(v){return v?Object.keys(v).filter(g=>g!=="__proto__"):[]}Ge.allSchemaProperties=h;function p(v,g){return h(g).filter(I=>!(0,t.alwaysValidSchema)(v,g[I]))}Ge.schemaProperties=p;function m({schemaCode:v,data:g,it:{gen:I,topSchemaRef:y,schemaPath:_,errorPath:k},it:S},E,R,x){const N=x?(0,e._)`${v}, ${g}, ${y}${_}`:g,U=[[r.default.instancePath,(0,e.strConcat)(r.default.instancePath,k)],[r.default.parentData,S.parentData],[r.default.parentDataProperty,S.parentDataProperty],[r.default.rootData,r.default.rootData]];S.opts.dynamicRef&&U.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);const z=(0,e._)`${N}, ${I.object(...U)}`;return R!==e.nil?(0,e._)`${E}.call(${R}, ${z})`:(0,e._)`${E}(${z})`}Ge.callValidateCode=m;const f=(0,e._)`new RegExp`;function b({gen:v,it:{opts:g}},I){const y=g.unicodeRegExp?"u":"",{regExp:_}=g.code,k=_(I,y);return v.scopeValue("pattern",{key:k.toString(),ref:k,code:(0,e._)`${_.code==="new RegExp"?f:(0,n.useFunc)(v,_)}(${I}, ${y})`})}Ge.usePattern=b;function w(v){const{gen:g,data:I,keyword:y,it:_}=v,k=g.name("valid");if(_.allErrors){const E=g.let("valid",!0);return S(()=>g.assign(E,!1)),E}return g.var(k,!0),S(()=>g.break()),k;function S(E){const R=g.const("len",(0,e._)`${I}.length`);g.forRange("i",0,R,x=>{v.subschema({keyword:y,dataProp:x,dataPropType:t.Type.Num},k),g.if((0,e.not)(k),E)})}}Ge.validateArray=w;function C(v){const{gen:g,schema:I,keyword:y,it:_}=v;if(!Array.isArray(I))throw new Error("ajv implementation error");if(I.some(R=>(0,t.alwaysValidSchema)(_,R))&&!_.opts.unevaluated)return;const S=g.let("valid",!1),E=g.name("_valid");g.block(()=>I.forEach((R,x)=>{const N=v.subschema({keyword:y,schemaProp:x,compositeRule:!0},E);g.assign(S,(0,e._)`${S} || ${E}`),v.mergeValidEvaluated(N,E)||g.if((0,e.not)(S))})),v.result(S,()=>v.reset(),()=>v.error(!0))}return Ge.validateUnion=C,Ge}var dy;function PE(){if(dy)return Pr;dy=1,Object.defineProperty(Pr,"__esModule",{value:!0}),Pr.validateKeywordUsage=Pr.validSchemaType=Pr.funcKeywordCode=Pr.macroKeywordCode=void 0;const e=Oe(),t=kn(),r=Mr(),n=ii();function o(p,m){const{gen:f,keyword:b,schema:w,parentSchema:C,it:v}=p,g=m.macro.call(v.self,w,C,v),I=c(f,b,g);v.opts.validateSchema!==!1&&v.self.validateSchema(g,!0);const y=f.name("valid");p.subschema({schema:g,schemaPath:e.nil,errSchemaPath:`${v.errSchemaPath}/${b}`,topSchemaRef:I,compositeRule:!0},y),p.pass(y,()=>p.error(!0))}Pr.macroKeywordCode=o;function a(p,m){var f;const{gen:b,keyword:w,schema:C,parentSchema:v,$data:g,it:I}=p;l(I,m);const y=!g&&m.compile?m.compile.call(I.self,C,v,I):m.validate,_=c(b,w,y),k=b.let("valid");p.block$data(k,S),p.ok((f=m.valid)!==null&&f!==void 0?f:k);function S(){if(m.errors===!1)x(),m.modifying&&i(p),N(()=>p.error());else{const U=m.async?E():R();m.modifying&&i(p),N(()=>s(p,U))}}function E(){const U=b.let("ruleErrs",null);return b.try(()=>x((0,e._)`await `),z=>b.assign(k,!1).if((0,e._)`${z} instanceof ${I.ValidationError}`,()=>b.assign(U,(0,e._)`${z}.errors`),()=>b.throw(z))),U}function R(){const U=(0,e._)`${_}.errors`;return b.assign(U,null),x(e.nil),U}function x(U=m.async?(0,e._)`await `:e.nil){const z=I.opts.passContext?t.default.this:t.default.self,ee=!("compile"in m&&!g||m.schema===!1);b.assign(k,(0,e._)`${U}${(0,r.callValidateCode)(p,_,z,ee)}`,m.modifying)}function N(U){var z;b.if((0,e.not)((z=m.valid)!==null&&z!==void 0?z:k),U)}}Pr.funcKeywordCode=a;function i(p){const{gen:m,data:f,it:b}=p;m.if(b.parentData,()=>m.assign(f,(0,e._)`${b.parentData}[${b.parentDataProperty}]`))}function s(p,m){const{gen:f}=p;f.if((0,e._)`Array.isArray(${m})`,()=>{f.assign(t.default.vErrors,(0,e._)`${t.default.vErrors} === null ? ${m} : ${t.default.vErrors}.concat(${m})`).assign(t.default.errors,(0,e._)`${t.default.vErrors}.length`),(0,n.extendErrors)(p)},()=>p.error())}function l({schemaEnv:p},m){if(m.async&&!p.$async)throw new Error("async keyword in sync schema")}function c(p,m,f){if(f===void 0)throw new Error(`keyword "${m}" failed to compile`);return p.scopeValue("keyword",typeof f=="function"?{ref:f}:{ref:f,code:(0,e.stringify)(f)})}function u(p,m,f=!1){return!m.length||m.some(b=>b==="array"?Array.isArray(p):b==="object"?p&&typeof p=="object"&&!Array.isArray(p):typeof p==b||f&&typeof p>"u")}Pr.validSchemaType=u;function h({schema:p,opts:m,self:f,errSchemaPath:b},w,C){if(Array.isArray(w.keyword)?!w.keyword.includes(C):w.keyword!==C)throw new Error("ajv implementation error");const v=w.dependencies;if(v?.some(g=>!Object.prototype.hasOwnProperty.call(p,g)))throw new Error(`parent schema must have dependencies of ${C}: ${v.join(",")}`);if(w.validateSchema&&!w.validateSchema(p[C])){const I=`keyword "${C}" value is invalid at path "${b}": `+f.errorsText(w.validateSchema.errors);if(m.validateSchema==="log")f.logger.error(I);else throw new Error(I)}}return Pr.validateKeywordUsage=h,Pr}var on={},py;function ME(){if(py)return on;py=1,Object.defineProperty(on,"__esModule",{value:!0}),on.extendSubschemaMode=on.extendSubschemaData=on.getSubschema=void 0;const e=Oe(),t=Fe();function r(a,{keyword:i,schemaProp:s,schema:l,schemaPath:c,errSchemaPath:u,topSchemaRef:h}){if(i!==void 0&&l!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(i!==void 0){const p=a.schema[i];return s===void 0?{schema:p,schemaPath:(0,e._)`${a.schemaPath}${(0,e.getProperty)(i)}`,errSchemaPath:`${a.errSchemaPath}/${i}`}:{schema:p[s],schemaPath:(0,e._)`${a.schemaPath}${(0,e.getProperty)(i)}${(0,e.getProperty)(s)}`,errSchemaPath:`${a.errSchemaPath}/${i}/${(0,t.escapeFragment)(s)}`}}if(l!==void 0){if(c===void 0||u===void 0||h===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:l,schemaPath:c,topSchemaRef:h,errSchemaPath:u}}throw new Error('either "keyword" or "schema" must be passed')}on.getSubschema=r;function n(a,i,{dataProp:s,dataPropType:l,data:c,dataTypes:u,propertyName:h}){if(c!==void 0&&s!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:p}=i;if(s!==void 0){const{errorPath:f,dataPathArr:b,opts:w}=i,C=p.let("data",(0,e._)`${i.data}${(0,e.getProperty)(s)}`,!0);m(C),a.errorPath=(0,e.str)`${f}${(0,t.getErrorPath)(s,l,w.jsPropertySyntax)}`,a.parentDataProperty=(0,e._)`${s}`,a.dataPathArr=[...b,a.parentDataProperty]}if(c!==void 0){const f=c instanceof e.Name?c:p.let("data",c,!0);m(f),h!==void 0&&(a.propertyName=h)}u&&(a.dataTypes=u);function m(f){a.data=f,a.dataLevel=i.dataLevel+1,a.dataTypes=[],i.definedProperties=new Set,a.parentData=i.data,a.dataNames=[...i.dataNames,f]}}on.extendSubschemaData=n;function o(a,{jtdDiscriminator:i,jtdMetadata:s,compositeRule:l,createErrors:c,allErrors:u}){l!==void 0&&(a.compositeRule=l),c!==void 0&&(a.createErrors=c),u!==void 0&&(a.allErrors=u),a.jtdDiscriminator=i,a.jtdMetadata=s}return on.extendSubschemaMode=o,on}var Qt={},Qu,hy;function fy(){return hy||(hy=1,Qu=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,a;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(a=Object.keys(t),n=a.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,a[o]))return!1;for(o=n;o--!==0;){var i=a[o];if(!e(t[i],r[i]))return!1}return!0}return t!==t&&r!==r}),Qu}var Xu={exports:{}},my;function OE(){if(my)return Xu.exports;my=1;var e=Xu.exports=function(n,o,a){typeof o=="function"&&(a=o,o={}),a=o.cb||a;var i=typeof a=="function"?a:a.pre||function(){},s=a.post||function(){};t(o,i,s,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,a,i,s,l,c,u,h,p){if(i&&typeof i=="object"&&!Array.isArray(i)){o(i,s,l,c,u,h,p);for(var m in i){var f=i[m];if(Array.isArray(f)){if(m in e.arrayKeywords)for(var b=0;b<f.length;b++)t(n,o,a,f[b],s+"/"+m+"/"+b,l,s,m,i,b)}else if(m in e.propsKeywords){if(f&&typeof f=="object")for(var w in f)t(n,o,a,f[w],s+"/"+m+"/"+r(w),l,s,m,i,w)}else(m in e.keywords||n.allKeys&&!(m in e.skipKeywords))&&t(n,o,a,f,s+"/"+m,l,s,m,i)}a(i,s,l,c,u,h,p)}}function r(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}return Xu.exports}var gy;function ci(){if(gy)return Qt;gy=1,Object.defineProperty(Qt,"__esModule",{value:!0}),Qt.getSchemaRefs=Qt.resolveUrl=Qt.normalizeId=Qt._getFullPath=Qt.getFullPath=Qt.inlineRef=void 0;const e=Fe(),t=fy(),r=OE(),n=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function o(b,w=!0){return typeof b=="boolean"?!0:w===!0?!i(b):w?s(b)<=w:!1}Qt.inlineRef=o;const a=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function i(b){for(const w in b){if(a.has(w))return!0;const C=b[w];if(Array.isArray(C)&&C.some(i)||typeof C=="object"&&i(C))return!0}return!1}function s(b){let w=0;for(const C in b){if(C==="$ref")return 1/0;if(w++,!n.has(C)&&(typeof b[C]=="object"&&(0,e.eachItem)(b[C],v=>w+=s(v)),w===1/0))return 1/0}return w}function l(b,w="",C){C!==!1&&(w=h(w));const v=b.parse(w);return c(b,v)}Qt.getFullPath=l;function c(b,w){return b.serialize(w).split("#")[0]+"#"}Qt._getFullPath=c;const u=/#\/?$/;function h(b){return b?b.replace(u,""):""}Qt.normalizeId=h;function p(b,w,C){return C=h(C),b.resolve(w,C)}Qt.resolveUrl=p;const m=/^[a-z_][-a-z0-9._]*$/i;function f(b,w){if(typeof b=="boolean")return{};const{schemaId:C,uriResolver:v}=this.opts,g=h(b[C]||w),I={"":g},y=l(v,g,!1),_={},k=new Set;return r(b,{allKeys:!0},(R,x,N,U)=>{if(U===void 0)return;const z=y+x;let ee=I[U];typeof R[C]=="string"&&(ee=Q.call(this,R[C])),se.call(this,R.$anchor),se.call(this,R.$dynamicAnchor),I[x]=ee;function Q(re){const Se=this.opts.uriResolver.resolve;if(re=h(ee?Se(ee,re):re),k.has(re))throw E(re);k.add(re);let H=this.refs[re];return typeof H=="string"&&(H=this.refs[H]),typeof H=="object"?S(R,H.schema,re):re!==h(z)&&(re[0]==="#"?(S(R,_[re],re),_[re]=R):this.refs[re]=z),re}function se(re){if(typeof re=="string"){if(!m.test(re))throw new Error(`invalid anchor "${re}"`);Q.call(this,`#${re}`)}}}),_;function S(R,x,N){if(x!==void 0&&!t(R,x))throw E(N)}function E(R){return new Error(`reference "${R}" resolves to more than one schema`)}}return Qt.getSchemaRefs=f,Qt}var _y;function ui(){if(_y)return rn;_y=1,Object.defineProperty(rn,"__esModule",{value:!0}),rn.getData=rn.KeywordCxt=rn.validateFunctionCode=void 0;const e=$E(),t=li(),r=iy(),n=li(),o=RE(),a=PE(),i=ME(),s=Oe(),l=kn(),c=ci(),u=Fe(),h=ii();function p(A){if(y(A)&&(k(A),I(A))){w(A);return}m(A,()=>(0,e.topBoolOrEmptySchema)(A))}rn.validateFunctionCode=p;function m({gen:A,validateName:Z,schema:J,schemaEnv:te,opts:de},fe){de.code.es5?A.func(Z,(0,s._)`${l.default.data}, ${l.default.valCxt}`,te.$async,()=>{A.code((0,s._)`"use strict"; ${v(J,de)}`),b(A,de),A.code(fe)}):A.func(Z,(0,s._)`${l.default.data}, ${f(de)}`,te.$async,()=>A.code(v(J,de)).code(fe))}function f(A){return(0,s._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${A.dynamicRef?(0,s._)`, ${l.default.dynamicAnchors}={}`:s.nil}}={}`}function b(A,Z){A.if(l.default.valCxt,()=>{A.var(l.default.instancePath,(0,s._)`${l.default.valCxt}.${l.default.instancePath}`),A.var(l.default.parentData,(0,s._)`${l.default.valCxt}.${l.default.parentData}`),A.var(l.default.parentDataProperty,(0,s._)`${l.default.valCxt}.${l.default.parentDataProperty}`),A.var(l.default.rootData,(0,s._)`${l.default.valCxt}.${l.default.rootData}`),Z.dynamicRef&&A.var(l.default.dynamicAnchors,(0,s._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{A.var(l.default.instancePath,(0,s._)`""`),A.var(l.default.parentData,(0,s._)`undefined`),A.var(l.default.parentDataProperty,(0,s._)`undefined`),A.var(l.default.rootData,l.default.data),Z.dynamicRef&&A.var(l.default.dynamicAnchors,(0,s._)`{}`)})}function w(A){const{schema:Z,opts:J,gen:te}=A;m(A,()=>{J.$comment&&Z.$comment&&U(A),R(A),te.let(l.default.vErrors,null),te.let(l.default.errors,0),J.unevaluated&&C(A),S(A),z(A)})}function C(A){const{gen:Z,validateName:J}=A;A.evaluated=Z.const("evaluated",(0,s._)`${J}.evaluated`),Z.if((0,s._)`${A.evaluated}.dynamicProps`,()=>Z.assign((0,s._)`${A.evaluated}.props`,(0,s._)`undefined`)),Z.if((0,s._)`${A.evaluated}.dynamicItems`,()=>Z.assign((0,s._)`${A.evaluated}.items`,(0,s._)`undefined`))}function v(A,Z){const J=typeof A=="object"&&A[Z.schemaId];return J&&(Z.code.source||Z.code.process)?(0,s._)`/*# sourceURL=${J} */`:s.nil}function g(A,Z){if(y(A)&&(k(A),I(A))){_(A,Z);return}(0,e.boolOrEmptySchema)(A,Z)}function I({schema:A,self:Z}){if(typeof A=="boolean")return!A;for(const J in A)if(Z.RULES.all[J])return!0;return!1}function y(A){return typeof A.schema!="boolean"}function _(A,Z){const{schema:J,gen:te,opts:de}=A;de.$comment&&J.$comment&&U(A),x(A),N(A);const fe=te.const("_errs",l.default.errors);S(A,fe),te.var(Z,(0,s._)`${fe} === ${l.default.errors}`)}function k(A){(0,u.checkUnknownRules)(A),E(A)}function S(A,Z){if(A.opts.jtd)return Q(A,[],!1,Z);const J=(0,t.getSchemaTypes)(A.schema),te=(0,t.coerceAndCheckDataType)(A,J);Q(A,J,!te,Z)}function E(A){const{schema:Z,errSchemaPath:J,opts:te,self:de}=A;Z.$ref&&te.ignoreKeywordsWithRef&&(0,u.schemaHasRulesButRef)(Z,de.RULES)&&de.logger.warn(`$ref: keywords ignored in schema at path "${J}"`)}function R(A){const{schema:Z,opts:J}=A;Z.default!==void 0&&J.useDefaults&&J.strictSchema&&(0,u.checkStrictMode)(A,"default is ignored in the schema root")}function x(A){const Z=A.schema[A.opts.schemaId];Z&&(A.baseId=(0,c.resolveUrl)(A.opts.uriResolver,A.baseId,Z))}function N(A){if(A.schema.$async&&!A.schemaEnv.$async)throw new Error("async schema in sync schema")}function U({gen:A,schemaEnv:Z,schema:J,errSchemaPath:te,opts:de}){const fe=J.$comment;if(de.$comment===!0)A.code((0,s._)`${l.default.self}.logger.log(${fe})`);else if(typeof de.$comment=="function"){const Ye=(0,s.str)`${te}/$comment`,wt=A.scopeValue("root",{ref:Z.root});A.code((0,s._)`${l.default.self}.opts.$comment(${fe}, ${Ye}, ${wt}.schema)`)}}function z(A){const{gen:Z,schemaEnv:J,validateName:te,ValidationError:de,opts:fe}=A;J.$async?Z.if((0,s._)`${l.default.errors} === 0`,()=>Z.return(l.default.data),()=>Z.throw((0,s._)`new ${de}(${l.default.vErrors})`)):(Z.assign((0,s._)`${te}.errors`,l.default.vErrors),fe.unevaluated&&ee(A),Z.return((0,s._)`${l.default.errors} === 0`))}function ee({gen:A,evaluated:Z,props:J,items:te}){J instanceof s.Name&&A.assign((0,s._)`${Z}.props`,J),te instanceof s.Name&&A.assign((0,s._)`${Z}.items`,te)}function Q(A,Z,J,te){const{gen:de,schema:fe,data:Ye,allErrors:wt,opts:st,self:et}=A,{RULES:Be}=et;if(fe.$ref&&(st.ignoreKeywordsWithRef||!(0,u.schemaHasRulesButRef)(fe,Be))){de.block(()=>G(A,"$ref",Be.all.$ref.definition));return}st.jtd||re(A,Z),de.block(()=>{for(const it of Be.rules)tr(it);tr(Be.post)});function tr(it){(0,r.shouldUseGroup)(fe,it)&&(it.type?(de.if((0,n.checkDataType)(it.type,Ye,st.strictNumbers)),se(A,it),Z.length===1&&Z[0]===it.type&&J&&(de.else(),(0,n.reportTypeError)(A)),de.endIf()):se(A,it),wt||de.if((0,s._)`${l.default.errors} === ${te||0}`))}}function se(A,Z){const{gen:J,schema:te,opts:{useDefaults:de}}=A;de&&(0,o.assignDefaults)(A,Z.type),J.block(()=>{for(const fe of Z.rules)(0,r.shouldUseRule)(te,fe)&&G(A,fe.keyword,fe.definition,Z.type)})}function re(A,Z){A.schemaEnv.meta||!A.opts.strictTypes||(Se(A,Z),A.opts.allowUnionTypes||H(A,Z),D(A,A.dataTypes))}function Se(A,Z){if(Z.length){if(!A.dataTypes.length){A.dataTypes=Z;return}Z.forEach(J=>{F(A.dataTypes,J)||O(A,`type "${J}" not allowed by context "${A.dataTypes.join(",")}"`)}),$(A,Z)}}function H(A,Z){Z.length>1&&!(Z.length===2&&Z.includes("null"))&&O(A,"use allowUnionTypes to allow union type keyword")}function D(A,Z){const J=A.self.RULES.all;for(const te in J){const de=J[te];if(typeof de=="object"&&(0,r.shouldUseRule)(A.schema,de)){const{type:fe}=de.definition;fe.length&&!fe.some(Ye=>B(Z,Ye))&&O(A,`missing type "${fe.join(",")}" for keyword "${te}"`)}}}function B(A,Z){return A.includes(Z)||Z==="number"&&A.includes("integer")}function F(A,Z){return A.includes(Z)||Z==="integer"&&A.includes("number")}function $(A,Z){const J=[];for(const te of A.dataTypes)F(Z,te)?J.push(te):Z.includes("integer")&&te==="number"&&J.push("integer");A.dataTypes=J}function O(A,Z){const J=A.schemaEnv.baseId+A.errSchemaPath;Z+=` at "${J}" (strictTypes)`,(0,u.checkStrictMode)(A,Z,A.opts.strictTypes)}class j{constructor(Z,J,te){if((0,a.validateKeywordUsage)(Z,J,te),this.gen=Z.gen,this.allErrors=Z.allErrors,this.keyword=te,this.data=Z.data,this.schema=Z.schema[te],this.$data=J.$data&&Z.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,u.schemaRefOrVal)(Z,this.schema,te,this.$data),this.schemaType=J.schemaType,this.parentSchema=Z.schema,this.params={},this.it=Z,this.def=J,this.$data)this.schemaCode=Z.gen.const("vSchema",V(this.$data,Z));else if(this.schemaCode=this.schemaValue,!(0,a.validSchemaType)(this.schema,J.schemaType,J.allowUndefined))throw new Error(`${te} value must be ${JSON.stringify(J.schemaType)}`);("code"in J?J.trackErrors:J.errors!==!1)&&(this.errsCount=Z.gen.const("_errs",l.default.errors))}result(Z,J,te){this.failResult((0,s.not)(Z),J,te)}failResult(Z,J,te){this.gen.if(Z),te?te():this.error(),J?(this.gen.else(),J(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(Z,J){this.failResult((0,s.not)(Z),void 0,J)}fail(Z){if(Z===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(Z),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(Z){if(!this.$data)return this.fail(Z);const{schemaCode:J}=this;this.fail((0,s._)`${J} !== undefined && (${(0,s.or)(this.invalid$data(),Z)})`)}error(Z,J,te){if(J){this.setParams(J),this._error(Z,te),this.setParams({});return}this._error(Z,te)}_error(Z,J){(Z?h.reportExtraError:h.reportError)(this,this.def.error,J)}$dataError(){(0,h.reportError)(this,this.def.$dataError||h.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,h.resetErrorsCount)(this.gen,this.errsCount)}ok(Z){this.allErrors||this.gen.if(Z)}setParams(Z,J){J?Object.assign(this.params,Z):this.params=Z}block$data(Z,J,te=s.nil){this.gen.block(()=>{this.check$data(Z,te),J()})}check$data(Z=s.nil,J=s.nil){if(!this.$data)return;const{gen:te,schemaCode:de,schemaType:fe,def:Ye}=this;te.if((0,s.or)((0,s._)`${de} === undefined`,J)),Z!==s.nil&&te.assign(Z,!0),(fe.length||Ye.validateSchema)&&(te.elseIf(this.invalid$data()),this.$dataError(),Z!==s.nil&&te.assign(Z,!1)),te.else()}invalid$data(){const{gen:Z,schemaCode:J,schemaType:te,def:de,it:fe}=this;return(0,s.or)(Ye(),wt());function Ye(){if(te.length){if(!(J instanceof s.Name))throw new Error("ajv implementation error");const st=Array.isArray(te)?te:[te];return(0,s._)`${(0,n.checkDataTypes)(st,J,fe.opts.strictNumbers,n.DataType.Wrong)}`}return s.nil}function wt(){if(de.validateSchema){const st=Z.scopeValue("validate$data",{ref:de.validateSchema});return(0,s._)`!${st}(${J})`}return s.nil}}subschema(Z,J){const te=(0,i.getSubschema)(this.it,Z);(0,i.extendSubschemaData)(te,this.it,Z),(0,i.extendSubschemaMode)(te,Z);const de={...this.it,...te,items:void 0,props:void 0};return g(de,J),de}mergeEvaluated(Z,J){const{it:te,gen:de}=this;te.opts.unevaluated&&(te.props!==!0&&Z.props!==void 0&&(te.props=u.mergeEvaluated.props(de,Z.props,te.props,J)),te.items!==!0&&Z.items!==void 0&&(te.items=u.mergeEvaluated.items(de,Z.items,te.items,J)))}mergeValidEvaluated(Z,J){const{it:te,gen:de}=this;if(te.opts.unevaluated&&(te.props!==!0||te.items!==!0))return de.if(J,()=>this.mergeEvaluated(Z,s.Name)),!0}}rn.KeywordCxt=j;function G(A,Z,J,te){const de=new j(A,J,Z);"code"in J?J.code(de,te):de.$data&&J.validate?(0,a.funcKeywordCode)(de,J):"macro"in J?(0,a.macroKeywordCode)(de,J):(J.compile||J.validate)&&(0,a.funcKeywordCode)(de,J)}const Y=/^\/(?:[^~]|~0|~1)*$/,W=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function V(A,{dataLevel:Z,dataNames:J,dataPathArr:te}){let de,fe;if(A==="")return l.default.rootData;if(A[0]==="/"){if(!Y.test(A))throw new Error(`Invalid JSON-pointer: ${A}`);de=A,fe=l.default.rootData}else{const et=W.exec(A);if(!et)throw new Error(`Invalid JSON-pointer: ${A}`);const Be=+et[1];if(de=et[2],de==="#"){if(Be>=Z)throw new Error(st("property/index",Be));return te[Z-Be]}if(Be>Z)throw new Error(st("data",Be));if(fe=J[Z-Be],!de)return fe}let Ye=fe;const wt=de.split("/");for(const et of wt)et&&(fe=(0,s._)`${fe}${(0,s.getProperty)((0,u.unescapeJsonPointer)(et))}`,Ye=(0,s._)`${Ye} && ${fe}`);return Ye;function st(et,Be){return`Cannot access ${et} ${Be} levels up, current level is ${Z}`}}return rn.getData=V,rn}var di={},yy;function ed(){if(yy)return di;yy=1,Object.defineProperty(di,"__esModule",{value:!0});class e extends Error{constructor(r){super("validation failed"),this.errors=r,this.ajv=this.validation=!0}}return di.default=e,di}var pi={},vy;function hi(){if(vy)return pi;vy=1,Object.defineProperty(pi,"__esModule",{value:!0});const e=ci();class t extends Error{constructor(n,o,a,i){super(i||`can't resolve reference ${a} from id ${o}`),this.missingRef=(0,e.resolveUrl)(n,o,a),this.missingSchema=(0,e.normalizeId)((0,e.getFullPath)(n,this.missingRef))}}return pi.default=t,pi}var ur={},wy;function td(){if(wy)return ur;wy=1,Object.defineProperty(ur,"__esModule",{value:!0}),ur.resolveSchema=ur.getCompilingSchema=ur.resolveRef=ur.compileSchema=ur.SchemaEnv=void 0;const e=Oe(),t=ed(),r=kn(),n=ci(),o=Fe(),a=ui();class i{constructor(C){var v;this.refs={},this.dynamicAnchors={};let g;typeof C.schema=="object"&&(g=C.schema),this.schema=C.schema,this.schemaId=C.schemaId,this.root=C.root||this,this.baseId=(v=C.baseId)!==null&&v!==void 0?v:(0,n.normalizeId)(g?.[C.schemaId||"$id"]),this.schemaPath=C.schemaPath,this.localRefs=C.localRefs,this.meta=C.meta,this.$async=g?.$async,this.refs={}}}ur.SchemaEnv=i;function s(w){const C=u.call(this,w);if(C)return C;const v=(0,n.getFullPath)(this.opts.uriResolver,w.root.baseId),{es5:g,lines:I}=this.opts.code,{ownProperties:y}=this.opts,_=new e.CodeGen(this.scope,{es5:g,lines:I,ownProperties:y});let k;w.$async&&(k=_.scopeValue("Error",{ref:t.default,code:(0,e._)`require("ajv/dist/runtime/validation_error").default`}));const S=_.scopeName("validate");w.validateName=S;const E={gen:_,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:_.scopeValue("schema",this.opts.code.source===!0?{ref:w.schema,code:(0,e.stringify)(w.schema)}:{ref:w.schema}),validateName:S,ValidationError:k,schema:w.schema,schemaEnv:w,rootId:v,baseId:w.baseId||v,schemaPath:e.nil,errSchemaPath:w.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,e._)`""`,opts:this.opts,self:this};let R;try{this._compilations.add(w),(0,a.validateFunctionCode)(E),_.optimize(this.opts.code.optimize);const x=_.toString();R=`${_.scopeRefs(r.default.scope)}return ${x}`,this.opts.code.process&&(R=this.opts.code.process(R,w));const U=new Function(`${r.default.self}`,`${r.default.scope}`,R)(this,this.scope.get());if(this.scope.value(S,{ref:U}),U.errors=null,U.schema=w.schema,U.schemaEnv=w,w.$async&&(U.$async=!0),this.opts.code.source===!0&&(U.source={validateName:S,validateCode:x,scopeValues:_._values}),this.opts.unevaluated){const{props:z,items:ee}=E;U.evaluated={props:z instanceof e.Name?void 0:z,items:ee instanceof e.Name?void 0:ee,dynamicProps:z instanceof e.Name,dynamicItems:ee instanceof e.Name},U.source&&(U.source.evaluated=(0,e.stringify)(U.evaluated))}return w.validate=U,w}catch(x){throw delete w.validate,delete w.validateName,R&&this.logger.error("Error compiling schema, function code:",R),x}finally{this._compilations.delete(w)}}ur.compileSchema=s;function l(w,C,v){var g;v=(0,n.resolveUrl)(this.opts.uriResolver,C,v);const I=w.refs[v];if(I)return I;let y=p.call(this,w,v);if(y===void 0){const _=(g=w.localRefs)===null||g===void 0?void 0:g[v],{schemaId:k}=this.opts;_&&(y=new i({schema:_,schemaId:k,root:w,baseId:C}))}if(y!==void 0)return w.refs[v]=c.call(this,y)}ur.resolveRef=l;function c(w){return(0,n.inlineRef)(w.schema,this.opts.inlineRefs)?w.schema:w.validate?w:s.call(this,w)}function u(w){for(const C of this._compilations)if(h(C,w))return C}ur.getCompilingSchema=u;function h(w,C){return w.schema===C.schema&&w.root===C.root&&w.baseId===C.baseId}function p(w,C){let v;for(;typeof(v=this.refs[C])=="string";)C=v;return v||this.schemas[C]||m.call(this,w,C)}function m(w,C){const v=this.opts.uriResolver.parse(C),g=(0,n._getFullPath)(this.opts.uriResolver,v);let I=(0,n.getFullPath)(this.opts.uriResolver,w.baseId,void 0);if(Object.keys(w.schema).length>0&&g===I)return b.call(this,v,w);const y=(0,n.normalizeId)(g),_=this.refs[y]||this.schemas[y];if(typeof _=="string"){const k=m.call(this,w,_);return typeof k?.schema!="object"?void 0:b.call(this,v,k)}if(typeof _?.schema=="object"){if(_.validate||s.call(this,_),y===(0,n.normalizeId)(C)){const{schema:k}=_,{schemaId:S}=this.opts,E=k[S];return E&&(I=(0,n.resolveUrl)(this.opts.uriResolver,I,E)),new i({schema:k,schemaId:S,root:w,baseId:I})}return b.call(this,v,_)}}ur.resolveSchema=m;const f=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function b(w,{baseId:C,schema:v,root:g}){var I;if(((I=w.fragment)===null||I===void 0?void 0:I[0])!=="/")return;for(const k of w.fragment.slice(1).split("/")){if(typeof v=="boolean")return;const S=v[(0,o.unescapeFragment)(k)];if(S===void 0)return;v=S;const E=typeof v=="object"&&v[this.opts.schemaId];!f.has(k)&&E&&(C=(0,n.resolveUrl)(this.opts.uriResolver,C,E))}let y;if(typeof v!="boolean"&&v.$ref&&!(0,o.schemaHasRulesButRef)(v,this.RULES)){const k=(0,n.resolveUrl)(this.opts.uriResolver,C,v.$ref);y=m.call(this,g,k)}const{schemaId:_}=this.opts;if(y=y||new i({schema:v,schemaId:_,root:g,baseId:C}),y.schema!==y.root.schema)return y}return ur}const AE={$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 fi={},Na={exports:{}},rd,by;function ky(){if(by)return rd;by=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),r=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),n=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),o=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function a(y){let _="",k=0,S=0;for(S=0;S<y.length;S++)if(k=y[S].charCodeAt(0),k!==48){if(!(k>=48&&k<=57||k>=65&&k<=70||k>=97&&k<=102))return"";_+=y[S];break}for(S+=1;S<y.length;S++){if(k=y[S].charCodeAt(0),!(k>=48&&k<=57||k>=65&&k<=70||k>=97&&k<=102))return"";_+=y[S]}return _}const i=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function s(y){return y.length=0,!0}function l(y,_,k){if(y.length){const S=a(y);if(S!=="")_.push(S);else return k.error=!0,!1;y.length=0}return!0}function c(y){let _=0;const k={error:!1,address:"",zone:""},S=[],E=[];let R=!1,x=!1,N=l;for(let U=0;U<y.length;U++){const z=y[U];if(!(z==="["||z==="]"))if(z===":"){if(R===!0&&(x=!0),!N(E,S,k))break;if(++_>7){k.error=!0;break}U>0&&y[U-1]===":"&&(R=!0),S.push(":");continue}else if(z==="%"){if(!N(E,S,k))break;N=s}else{E.push(z);continue}}return E.length&&(N===s?k.zone=E.join(""):x?S.push(E.join("")):S.push(a(E))),k.address=S.join(""),k}function u(y){if(h(y,":")<2)return{host:y,isIPV6:!1};const _=c(y);if(_.error)return{host:y,isIPV6:!1};{let k=_.address,S=_.address;return _.zone&&(k+="%"+_.zone,S+="%25"+_.zone),{host:k,isIPV6:!0,escapedHost:S}}}function h(y,_){let k=0;for(let S=0;S<y.length;S++)y[S]===_&&k++;return k}function p(y){let _=y;const k=[];let S=-1,E=0;for(;E=_.length;){if(E===1){if(_===".")break;if(_==="/"){k.push("/");break}else{k.push(_);break}}else if(E===2){if(_[0]==="."){if(_[1]===".")break;if(_[1]==="/"){_=_.slice(2);continue}}else if(_[0]==="/"&&(_[1]==="."||_[1]==="/")){k.push("/");break}}else if(E===3&&_==="/.."){k.length!==0&&k.pop(),k.push("/");break}if(_[0]==="."){if(_[1]==="."){if(_[2]==="/"){_=_.slice(3);continue}}else if(_[1]==="/"){_=_.slice(2);continue}}else if(_[0]==="/"&&_[1]==="."){if(_[2]==="/"){_=_.slice(2);continue}else if(_[2]==="."&&_[3]==="/"){_=_.slice(3),k.length!==0&&k.pop();continue}}if((S=_.indexOf("/",1))===-1){k.push(_);break}else k.push(_.slice(0,S)),_=_.slice(S)}return k.join("")}const m={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},f=/[@/?#:]/g,b=/[@/?#]/g;function w(y,_){const k=_?b:f;return k.lastIndex=0,y.replace(k,S=>m[S])}function C(y,_=!1){if(y.indexOf("%")===-1)return y;let k="";for(let S=0;S<y.length;S++){if(y[S]==="%"&&S+2<y.length){const E=y.slice(S+1,S+3);if(r(E)){const R=E.toUpperCase(),x=String.fromCharCode(parseInt(R,16));_&&n(x)?k+=x:k+="%"+R,S+=2;continue}}k+=y[S]}return k}function v(y){let _="";for(let k=0;k<y.length;k++){if(y[k]==="%"&&k+2<y.length){const S=y.slice(k+1,k+3);if(r(S)){const E=S.toUpperCase(),R=String.fromCharCode(parseInt(E,16));R!=="."&&n(R)?_+=R:_+="%"+E,k+=2;continue}}o(y[k])?_+=y[k]:_+=escape(y[k])}return _}function g(y){let _="";for(let k=0;k<y.length;k++){if(y[k]==="%"&&k+2<y.length){const S=y.slice(k+1,k+3);if(r(S)){_+="%"+S.toUpperCase(),k+=2;continue}}_+=escape(y[k])}return _}function I(y){const _=[];if(y.userinfo!==void 0&&(_.push(y.userinfo),_.push("@")),y.host!==void 0){let k=unescape(y.host);if(!t(k)){const S=u(k);S.isIPV6===!0?k=`[${S.escapedHost}]`:k=w(k,!1)}_.push(k)}return(typeof y.port=="number"||typeof y.port=="string")&&(_.push(":"),_.push(String(y.port))),_.length?_.join(""):void 0}return rd={nonSimpleDomain:i,recomposeAuthority:I,reescapeHostDelimiters:w,normalizePercentEncoding:C,normalizePathEncoding:v,escapePreservingEscapes:g,removeDotSegments:p,isIPv4:t,isUUID:e,normalizeIPv6:u,stringArrayToHexStripped:a},rd}var nd,Ty;function NE(){if(Ty)return nd;Ty=1;const{isUUID:e}=ky(),t=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,r=["http","https","ws","wss","urn","urn:uuid"];function n(y){return r.indexOf(y)!==-1}function o(y){return y.secure===!0?!0:y.secure===!1?!1:y.scheme?y.scheme.length===3&&(y.scheme[0]==="w"||y.scheme[0]==="W")&&(y.scheme[1]==="s"||y.scheme[1]==="S")&&(y.scheme[2]==="s"||y.scheme[2]==="S"):!1}function a(y){return y.host||(y.error=y.error||"HTTP URIs must have a host."),y}function i(y){const _=String(y.scheme).toLowerCase()==="https";return(y.port===(_?443:80)||y.port==="")&&(y.port=void 0),y.path||(y.path="/"),y}function s(y){return y.secure=o(y),y.resourceName=(y.path||"/")+(y.query?"?"+y.query:""),y.path=void 0,y.query=void 0,y}function l(y){if((y.port===(o(y)?443:80)||y.port==="")&&(y.port=void 0),typeof y.secure=="boolean"&&(y.scheme=y.secure?"wss":"ws",y.secure=void 0),y.resourceName){const[_,k]=y.resourceName.split("?");y.path=_&&_!=="/"?_:void 0,y.query=k,y.resourceName=void 0}return y.fragment=void 0,y}function c(y,_){if(!y.path)return y.error="URN can not be parsed",y;const k=y.path.match(t);if(k){const S=_.scheme||y.scheme||"urn";y.nid=k[1].toLowerCase(),y.nss=k[2];const E=`${S}:${_.nid||y.nid}`,R=I(E);y.path=void 0,R&&(y=R.parse(y,_))}else y.error=y.error||"URN can not be parsed.";return y}function u(y,_){if(y.nid===void 0)throw new Error("URN without nid cannot be serialized");const k=_.scheme||y.scheme||"urn",S=y.nid.toLowerCase(),E=`${k}:${_.nid||S}`,R=I(E);R&&(y=R.serialize(y,_));const x=y,N=y.nss;return x.path=`${S||_.nid}:${N}`,_.skipEscape=!0,x}function h(y,_){const k=y;return k.uuid=k.nss,k.nss=void 0,!_.tolerant&&(!k.uuid||!e(k.uuid))&&(k.error=k.error||"UUID is not valid."),k}function p(y){const _=y;return _.nss=(y.uuid||"").toLowerCase(),_}const m={scheme:"http",domainHost:!0,parse:a,serialize:i},f={scheme:"https",domainHost:m.domainHost,parse:a,serialize:i},b={scheme:"ws",domainHost:!0,parse:s,serialize:l},w={scheme:"wss",domainHost:b.domainHost,parse:b.parse,serialize:b.serialize},g={http:m,https:f,ws:b,wss:w,urn:{scheme:"urn",parse:c,serialize:u,skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:h,serialize:p,skipNormalize:!0}};Object.setPrototypeOf(g,null);function I(y){return y&&(g[y]||g[y.toLowerCase()])||void 0}return nd={wsIsSecure:o,SCHEMES:g,isValidSchemeName:n,getSchemeHandler:I},nd}var Cy;function qE(){if(Cy)return Na.exports;Cy=1;const{normalizeIPv6:e,removeDotSegments:t,recomposeAuthority:r,normalizePercentEncoding:n,normalizePathEncoding:o,escapePreservingEscapes:a,reescapeHostDelimiters:i,isIPv4:s,nonSimpleDomain:l}=ky(),{SCHEMES:c,getSchemeHandler:u}=NE();function h(S,E){return typeof S=="string"?S=I(S,E):typeof S=="object"&&(S=g(b(S,E),E)),S}function p(S,E,R){const x=R?Object.assign({scheme:"null"},R):{scheme:"null"},N=m(g(S,x),g(E,x),x,!0);return x.skipEscape=!0,b(N,x)}function m(S,E,R,x){const N={};return x||(S=g(b(S,R),R),E=g(b(E,R),R)),R=R||{},!R.tolerant&&E.scheme?(N.scheme=E.scheme,N.userinfo=E.userinfo,N.host=E.host,N.port=E.port,N.path=t(E.path||""),N.query=E.query):(E.userinfo!==void 0||E.host!==void 0||E.port!==void 0?(N.userinfo=E.userinfo,N.host=E.host,N.port=E.port,N.path=t(E.path||""),N.query=E.query):(E.path?(E.path[0]==="/"?N.path=t(E.path):((S.userinfo!==void 0||S.host!==void 0||S.port!==void 0)&&!S.path?N.path="/"+E.path:S.path?N.path=S.path.slice(0,S.path.lastIndexOf("/")+1)+E.path:N.path=E.path,N.path=t(N.path)),N.query=E.query):(N.path=S.path,E.query!==void 0?N.query=E.query:N.query=S.query),N.userinfo=S.userinfo,N.host=S.host,N.port=S.port),N.scheme=S.scheme),N.fragment=E.fragment,N}function f(S,E,R){const x=_(S,R),N=_(E,R);return x!==void 0&&N!==void 0&&x.toLowerCase()===N.toLowerCase()}function b(S,E){const R={host:S.host,scheme:S.scheme,userinfo:S.userinfo,port:S.port,path:S.path,query:S.query,nid:S.nid,nss:S.nss,uuid:S.uuid,fragment:S.fragment,reference:S.reference,resourceName:S.resourceName,secure:S.secure,error:""},x=Object.assign({},E),N=[],U=u(x.scheme||R.scheme);U&&U.serialize&&U.serialize(R,x),R.path!==void 0&&(x.skipEscape?R.path=n(R.path):(R.path=a(R.path),R.scheme!==void 0&&(R.path=R.path.split("%3A").join(":")))),x.reference!=="suffix"&&R.scheme&&N.push(R.scheme,":");const z=r(R);if(z!==void 0&&(x.reference!=="suffix"&&N.push("//"),N.push(z),R.path&&R.path[0]!=="/"&&N.push("/")),R.path!==void 0){let ee=R.path;!x.absolutePath&&(!U||!U.absolutePath)&&(ee=t(ee)),z===void 0&&ee[0]==="/"&&ee[1]==="/"&&(ee="/%2F"+ee.slice(2)),N.push(ee)}return R.query!==void 0&&N.push("?",R.query),R.fragment!==void 0&&N.push("#",R.fragment),N.join("")}const w=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function C(S,E){if(E[2]!==void 0&&S.path&&S.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof S.port=="number"&&(S.port<0||S.port>65535))return"URI port is malformed."}function v(S,E){const R=Object.assign({},E),x={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let N=!1,U=!1;R.reference==="suffix"&&(R.scheme?S=R.scheme+":"+S:S="//"+S);const z=S.match(w);if(z){x.scheme=z[1],x.userinfo=z[3],x.host=z[4],x.port=parseInt(z[5],10),x.path=z[6]||"",x.query=z[7],x.fragment=z[8],isNaN(x.port)&&(x.port=z[5]);const ee=C(x,z);if(ee!==void 0&&(x.error=x.error||ee,N=!0),x.host)if(s(x.host)===!1){const re=e(x.host);x.host=re.host.toLowerCase(),U=re.isIPV6}else U=!0;x.scheme===void 0&&x.userinfo===void 0&&x.host===void 0&&x.port===void 0&&x.query===void 0&&!x.path?x.reference="same-document":x.scheme===void 0?x.reference="relative":x.fragment===void 0?x.reference="absolute":x.reference="uri",R.reference&&R.reference!=="suffix"&&R.reference!==x.reference&&(x.error=x.error||"URI is not a "+R.reference+" reference.");const Q=u(R.scheme||x.scheme);if(!R.unicodeSupport&&(!Q||!Q.unicodeSupport)&&x.host&&(R.domainHost||Q&&Q.domainHost)&&U===!1&&l(x.host))try{x.host=new URL("http://"+x.host).hostname}catch(se){x.error=x.error||"Host's domain name can not be converted to ASCII: "+se}if((!Q||Q&&!Q.skipNormalize)&&(S.indexOf("%")!==-1&&(x.scheme!==void 0&&(x.scheme=unescape(x.scheme)),x.host!==void 0&&(x.host=i(unescape(x.host),U))),x.path&&(x.path=o(x.path)),x.fragment))try{x.fragment=encodeURI(decodeURIComponent(x.fragment))}catch{x.error=x.error||"URI malformed"}Q&&Q.parse&&Q.parse(x,R)}else x.error=x.error||"URI can not be parsed.";return{parsed:x,malformedAuthorityOrPort:N}}function g(S,E){return v(S,E).parsed}function I(S,E){return y(S,E).normalized}function y(S,E){const{parsed:R,malformedAuthorityOrPort:x}=v(S,E);return{normalized:x?S:b(R,E),malformedAuthorityOrPort:x}}function _(S,E){if(typeof S=="string"){const{normalized:R,malformedAuthorityOrPort:x}=y(S,E);return x?void 0:R}if(typeof S=="object")return b(S,E)}const k={SCHEMES:c,normalize:h,resolve:p,resolveComponent:m,equal:f,serialize:b,parse:g};return Na.exports=k,Na.exports.default=k,Na.exports.fastUri=k,Na.exports}var Sy;function LE(){if(Sy)return fi;Sy=1,Object.defineProperty(fi,"__esModule",{value:!0});const e=qE();return e.code='require("ajv/dist/runtime/uri").default',fi.default=e,fi}var Iy;function jE(){return Iy||(Iy=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=ui();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var r=Oe();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=ed(),o=hi(),a=ay(),i=td(),s=Oe(),l=ci(),c=li(),u=Fe(),h=AE,p=LE(),m=(H,D)=>new RegExp(H,D);m.code="new RegExp";const f=["removeAdditional","useDefaults","coerceTypes"],b=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),w={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."},C={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},v=200;function g(H){var D,B,F,$,O,j,G,Y,W,V,A,Z,J,te,de,fe,Ye,wt,st,et,Be,tr,it,qr,dr;const rr=H.strict,Lr=(D=H.code)===null||D===void 0?void 0:D.optimize,pr=Lr===!0||Lr===void 0?1:Lr||0,P=(F=(B=H.code)===null||B===void 0?void 0:B.regExp)!==null&&F!==void 0?F:m,X=($=H.uriResolver)!==null&&$!==void 0?$:p.default;return{strictSchema:(j=(O=H.strictSchema)!==null&&O!==void 0?O:rr)!==null&&j!==void 0?j:!0,strictNumbers:(Y=(G=H.strictNumbers)!==null&&G!==void 0?G:rr)!==null&&Y!==void 0?Y:!0,strictTypes:(V=(W=H.strictTypes)!==null&&W!==void 0?W:rr)!==null&&V!==void 0?V:"log",strictTuples:(Z=(A=H.strictTuples)!==null&&A!==void 0?A:rr)!==null&&Z!==void 0?Z:"log",strictRequired:(te=(J=H.strictRequired)!==null&&J!==void 0?J:rr)!==null&&te!==void 0?te:!1,code:H.code?{...H.code,optimize:pr,regExp:P}:{optimize:pr,regExp:P},loopRequired:(de=H.loopRequired)!==null&&de!==void 0?de:v,loopEnum:(fe=H.loopEnum)!==null&&fe!==void 0?fe:v,meta:(Ye=H.meta)!==null&&Ye!==void 0?Ye:!0,messages:(wt=H.messages)!==null&&wt!==void 0?wt:!0,inlineRefs:(st=H.inlineRefs)!==null&&st!==void 0?st:!0,schemaId:(et=H.schemaId)!==null&&et!==void 0?et:"$id",addUsedSchema:(Be=H.addUsedSchema)!==null&&Be!==void 0?Be:!0,validateSchema:(tr=H.validateSchema)!==null&&tr!==void 0?tr:!0,validateFormats:(it=H.validateFormats)!==null&&it!==void 0?it:!0,unicodeRegExp:(qr=H.unicodeRegExp)!==null&&qr!==void 0?qr:!0,int32range:(dr=H.int32range)!==null&&dr!==void 0?dr:!0,uriResolver:X}}class I{constructor(D={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,D=this.opts={...D,...g(D)};const{es5:B,lines:F}=this.opts.code;this.scope=new s.ValueScope({scope:{},prefixes:b,es5:B,lines:F}),this.logger=N(D.logger);const $=D.validateFormats;D.validateFormats=!1,this.RULES=(0,a.getRules)(),y.call(this,w,D,"NOT SUPPORTED"),y.call(this,C,D,"DEPRECATED","warn"),this._metaOpts=R.call(this),D.formats&&S.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),D.keywords&&E.call(this,D.keywords),typeof D.meta=="object"&&this.addMetaSchema(D.meta),k.call(this),D.validateFormats=$}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:D,meta:B,schemaId:F}=this.opts;let $=h;F==="id"&&($={...h},$.id=$.$id,delete $.$id),B&&D&&this.addMetaSchema($,$[F],!1)}defaultMeta(){const{meta:D,schemaId:B}=this.opts;return this.opts.defaultMeta=typeof D=="object"?D[B]||D:void 0}validate(D,B){let F;if(typeof D=="string"){if(F=this.getSchema(D),!F)throw new Error(`no schema with key or ref "${D}"`)}else F=this.compile(D);const $=F(B);return"$async"in F||(this.errors=F.errors),$}compile(D,B){const F=this._addSchema(D,B);return F.validate||this._compileSchemaEnv(F)}compileAsync(D,B){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:F}=this.opts;return $.call(this,D,B);async function $(V,A){await O.call(this,V.$schema);const Z=this._addSchema(V,A);return Z.validate||j.call(this,Z)}async function O(V){V&&!this.getSchema(V)&&await $.call(this,{$ref:V},!0)}async function j(V){try{return this._compileSchemaEnv(V)}catch(A){if(!(A instanceof o.default))throw A;return G.call(this,A),await Y.call(this,A.missingSchema),j.call(this,V)}}function G({missingSchema:V,missingRef:A}){if(this.refs[V])throw new Error(`AnySchema ${V} is loaded but ${A} cannot be resolved`)}async function Y(V){const A=await W.call(this,V);this.refs[V]||await O.call(this,A.$schema),this.refs[V]||this.addSchema(A,V,B)}async function W(V){const A=this._loading[V];if(A)return A;try{return await(this._loading[V]=F(V))}finally{delete this._loading[V]}}}addSchema(D,B,F,$=this.opts.validateSchema){if(Array.isArray(D)){for(const j of D)this.addSchema(j,void 0,F,$);return this}let O;if(typeof D=="object"){const{schemaId:j}=this.opts;if(O=D[j],O!==void 0&&typeof O!="string")throw new Error(`schema ${j} must be string`)}return B=(0,l.normalizeId)(B||O),this._checkUnique(B),this.schemas[B]=this._addSchema(D,F,B,$,!0),this}addMetaSchema(D,B,F=this.opts.validateSchema){return this.addSchema(D,B,!0,F),this}validateSchema(D,B){if(typeof D=="boolean")return!0;let F;if(F=D.$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 $=this.validate(F,D);if(!$&&B){const O="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(O);else throw new Error(O)}return $}getSchema(D){let B;for(;typeof(B=_.call(this,D))=="string";)D=B;if(B===void 0){const{schemaId:F}=this.opts,$=new i.SchemaEnv({schema:{},schemaId:F});if(B=i.resolveSchema.call(this,$,D),!B)return;this.refs[D]=B}return B.validate||this._compileSchemaEnv(B)}removeSchema(D){if(D instanceof RegExp)return this._removeAllSchemas(this.schemas,D),this._removeAllSchemas(this.refs,D),this;switch(typeof D){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const B=_.call(this,D);return typeof B=="object"&&this._cache.delete(B.schema),delete this.schemas[D],delete this.refs[D],this}case"object":{const B=D;this._cache.delete(B);let F=D[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(D){for(const B of D)this.addKeyword(B);return this}addKeyword(D,B){let F;if(typeof D=="string")F=D,typeof B=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),B.keyword=F);else if(typeof D=="object"&&B===void 0){if(B=D,F=B.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(z.call(this,F,B),!B)return(0,u.eachItem)(F,O=>ee.call(this,O)),this;se.call(this,B);const $={...B,type:(0,c.getJSONTypes)(B.type),schemaType:(0,c.getJSONTypes)(B.schemaType)};return(0,u.eachItem)(F,$.type.length===0?O=>ee.call(this,O,$):O=>$.type.forEach(j=>ee.call(this,O,$,j))),this}getKeyword(D){const B=this.RULES.all[D];return typeof B=="object"?B.definition:!!B}removeKeyword(D){const{RULES:B}=this;delete B.keywords[D],delete B.all[D];for(const F of B.rules){const $=F.rules.findIndex(O=>O.keyword===D);$>=0&&F.rules.splice($,1)}return this}addFormat(D,B){return typeof B=="string"&&(B=new RegExp(B)),this.formats[D]=B,this}errorsText(D=this.errors,{separator:B=", ",dataVar:F="data"}={}){return!D||D.length===0?"No errors":D.map($=>`${F}${$.instancePath} ${$.message}`).reduce(($,O)=>$+B+O)}$dataMetaSchema(D,B){const F=this.RULES.all;D=JSON.parse(JSON.stringify(D));for(const $ of B){const O=$.split("/").slice(1);let j=D;for(const G of O)j=j[G];for(const G in F){const Y=F[G];if(typeof Y!="object")continue;const{$data:W}=Y.definition,V=j[G];W&&V&&(j[G]=Se(V))}}return D}_removeAllSchemas(D,B){for(const F in D){const $=D[F];(!B||B.test(F))&&(typeof $=="string"?delete D[F]:$&&!$.meta&&(this._cache.delete($.schema),delete D[F]))}}_addSchema(D,B,F,$=this.opts.validateSchema,O=this.opts.addUsedSchema){let j;const{schemaId:G}=this.opts;if(typeof D=="object")j=D[G];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof D!="boolean")throw new Error("schema must be object or boolean")}let Y=this._cache.get(D);if(Y!==void 0)return Y;F=(0,l.normalizeId)(j||F);const W=l.getSchemaRefs.call(this,D,F);return Y=new i.SchemaEnv({schema:D,schemaId:G,meta:B,baseId:F,localRefs:W}),this._cache.set(Y.schema,Y),O&&!F.startsWith("#")&&(F&&this._checkUnique(F),this.refs[F]=Y),$&&this.validateSchema(D,!0),Y}_checkUnique(D){if(this.schemas[D]||this.refs[D])throw new Error(`schema with key or id "${D}" already exists`)}_compileSchemaEnv(D){if(D.meta?this._compileMetaSchema(D):i.compileSchema.call(this,D),!D.validate)throw new Error("ajv implementation error");return D.validate}_compileMetaSchema(D){const B=this.opts;this.opts=this._metaOpts;try{i.compileSchema.call(this,D)}finally{this.opts=B}}}I.ValidationError=n.default,I.MissingRefError=o.default,e.default=I;function y(H,D,B,F="error"){for(const $ in H){const O=$;O in D&&this.logger[F](`${B}: option ${$}. ${H[O]}`)}}function _(H){return H=(0,l.normalizeId)(H),this.schemas[H]||this.refs[H]}function k(){const H=this.opts.schemas;if(H)if(Array.isArray(H))this.addSchema(H);else for(const D in H)this.addSchema(H[D],D)}function S(){for(const H in this.opts.formats){const D=this.opts.formats[H];D&&this.addFormat(H,D)}}function E(H){if(Array.isArray(H)){this.addVocabulary(H);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const D in H){const B=H[D];B.keyword||(B.keyword=D),this.addKeyword(B)}}function R(){const H={...this.opts};for(const D of f)delete H[D];return H}const x={log(){},warn(){},error(){}};function N(H){if(H===!1)return x;if(H===void 0)return console;if(H.log&&H.warn&&H.error)return H;throw new Error("logger must implement log, warn and error methods")}const U=/^[a-z_$][a-z0-9_$:-]*$/i;function z(H,D){const{RULES:B}=this;if((0,u.eachItem)(H,F=>{if(B.keywords[F])throw new Error(`Keyword ${F} is already defined`);if(!U.test(F))throw new Error(`Keyword ${F} has invalid name`)}),!!D&&D.$data&&!("code"in D||"validate"in D))throw new Error('$data keyword must have "code" or "validate" function')}function ee(H,D,B){var F;const $=D?.post;if(B&&$)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:O}=this;let j=$?O.post:O.rules.find(({type:Y})=>Y===B);if(j||(j={type:B,rules:[]},O.rules.push(j)),O.keywords[H]=!0,!D)return;const G={keyword:H,definition:{...D,type:(0,c.getJSONTypes)(D.type),schemaType:(0,c.getJSONTypes)(D.schemaType)}};D.before?Q.call(this,j,G,D.before):j.rules.push(G),O.all[H]=G,(F=D.implements)===null||F===void 0||F.forEach(Y=>this.addKeyword(Y))}function Q(H,D,B){const F=H.rules.findIndex($=>$.keyword===B);F>=0?H.rules.splice(F,0,D):(H.rules.push(D),this.logger.warn(`rule ${B} is not defined`))}function se(H){let{metaSchema:D}=H;D!==void 0&&(H.$data&&this.opts.$data&&(D=Se(D)),H.validateSchema=this.compile(D,!0))}const re={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Se(H){return{anyOf:[H,re]}}})(Ju)),Ju}var mi={},gi={},_i={},xy;function DE(){if(xy)return _i;xy=1,Object.defineProperty(_i,"__esModule",{value:!0});const e={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};return _i.default=e,_i}var Tn={},Ey;function UE(){if(Ey)return Tn;Ey=1,Object.defineProperty(Tn,"__esModule",{value:!0}),Tn.callRef=Tn.getValidate=void 0;const e=hi(),t=Mr(),r=Oe(),n=kn(),o=td(),a=Fe(),i={keyword:"$ref",schemaType:"string",code(c){const{gen:u,schema:h,it:p}=c,{baseId:m,schemaEnv:f,validateName:b,opts:w,self:C}=p,{root:v}=f;if((h==="#"||h==="#/")&&m===v.baseId)return I();const g=o.resolveRef.call(C,v,m,h);if(g===void 0)throw new e.default(p.opts.uriResolver,m,h);if(g instanceof o.SchemaEnv)return y(g);return _(g);function I(){if(f===v)return l(c,b,f,f.$async);const k=u.scopeValue("root",{ref:v});return l(c,(0,r._)`${k}.validate`,v,v.$async)}function y(k){const S=s(c,k);l(c,S,k,k.$async)}function _(k){const S=u.scopeValue("schema",w.code.source===!0?{ref:k,code:(0,r.stringify)(k)}:{ref:k}),E=u.name("valid"),R=c.subschema({schema:k,dataTypes:[],schemaPath:r.nil,topSchemaRef:S,errSchemaPath:h},E);c.mergeEvaluated(R),c.ok(E)}}};function s(c,u){const{gen:h}=c;return u.validate?h.scopeValue("validate",{ref:u.validate}):(0,r._)`${h.scopeValue("wrapper",{ref:u})}.validate`}Tn.getValidate=s;function l(c,u,h,p){const{gen:m,it:f}=c,{allErrors:b,schemaEnv:w,opts:C}=f,v=C.passContext?n.default.this:r.nil;p?g():I();function g(){if(!w.$async)throw new Error("async schema referenced by sync schema");const k=m.let("valid");m.try(()=>{m.code((0,r._)`await ${(0,t.callValidateCode)(c,u,v)}`),_(u),b||m.assign(k,!0)},S=>{m.if((0,r._)`!(${S} instanceof ${f.ValidationError})`,()=>m.throw(S)),y(S),b||m.assign(k,!1)}),c.ok(k)}function I(){c.result((0,t.callValidateCode)(c,u,v),()=>_(u),()=>y(u))}function y(k){const S=(0,r._)`${k}.errors`;m.assign(n.default.vErrors,(0,r._)`${n.default.vErrors} === null ? ${S} : ${n.default.vErrors}.concat(${S})`),m.assign(n.default.errors,(0,r._)`${n.default.vErrors}.length`)}function _(k){var S;if(!f.opts.unevaluated)return;const E=(S=h?.validate)===null||S===void 0?void 0:S.evaluated;if(f.props!==!0)if(E&&!E.dynamicProps)E.props!==void 0&&(f.props=a.mergeEvaluated.props(m,E.props,f.props));else{const R=m.var("props",(0,r._)`${k}.evaluated.props`);f.props=a.mergeEvaluated.props(m,R,f.props,r.Name)}if(f.items!==!0)if(E&&!E.dynamicItems)E.items!==void 0&&(f.items=a.mergeEvaluated.items(m,E.items,f.items));else{const R=m.var("items",(0,r._)`${k}.evaluated.items`);f.items=a.mergeEvaluated.items(m,R,f.items,r.Name)}}}return Tn.callRef=l,Tn.default=i,Tn}var $y;function zE(){if($y)return gi;$y=1,Object.defineProperty(gi,"__esModule",{value:!0});const e=DE(),t=UE(),r=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",e.default,t.default];return gi.default=r,gi}var yi={},vi={},Ry;function FE(){if(Ry)return vi;Ry=1,Object.defineProperty(vi,"__esModule",{value:!0});const e=Oe(),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:a,schemaCode:i})=>(0,e.str)`must be ${r[a].okStr} ${i}`,params:({keyword:a,schemaCode:i})=>(0,e._)`{comparison: ${r[a].okStr}, limit: ${i}}`},o={keyword:Object.keys(r),type:"number",schemaType:"number",$data:!0,error:n,code(a){const{keyword:i,data:s,schemaCode:l}=a;a.fail$data((0,e._)`${s} ${r[i].fail} ${l} || isNaN(${s})`)}};return vi.default=o,vi}var wi={},Py;function VE(){if(Py)return wi;Py=1,Object.defineProperty(wi,"__esModule",{value:!0});const e=Oe(),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:a,schemaCode:i,it:s}=n,l=s.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} = ${a}/${i}, ${u}))`)}};return wi.default=r,wi}var bi={},ki={},My;function ZE(){if(My)return ki;My=1,Object.defineProperty(ki,"__esModule",{value:!0});function e(t){const r=t.length;let n=0,o=0,a;for(;o<r;)n++,a=t.charCodeAt(o++),a>=55296&&a<=56319&&o<r&&(a=t.charCodeAt(o),(a&64512)===56320&&o++);return n}return ki.default=e,e.code='require("ajv/dist/runtime/ucs2length").default',ki}var Oy;function HE(){if(Oy)return bi;Oy=1,Object.defineProperty(bi,"__esModule",{value:!0});const e=Oe(),t=Fe(),r=ZE(),o={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message({keyword:a,schemaCode:i}){const s=a==="maxLength"?"more":"fewer";return(0,e.str)`must NOT have ${s} than ${i} characters`},params:({schemaCode:a})=>(0,e._)`{limit: ${a}}`},code(a){const{keyword:i,data:s,schemaCode:l,it:c}=a,u=i==="maxLength"?e.operators.GT:e.operators.LT,h=c.opts.unicode===!1?(0,e._)`${s}.length`:(0,e._)`${(0,t.useFunc)(a.gen,r.default)}(${s})`;a.fail$data((0,e._)`${h} ${u} ${l}`)}};return bi.default=o,bi}var Ti={},Ay;function BE(){if(Ay)return Ti;Ay=1,Object.defineProperty(Ti,"__esModule",{value:!0});const e=Mr(),t=Fe(),r=Oe(),o={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:a})=>(0,r.str)`must match pattern "${a}"`,params:({schemaCode:a})=>(0,r._)`{pattern: ${a}}`},code(a){const{gen:i,data:s,$data:l,schema:c,schemaCode:u,it:h}=a,p=h.opts.unicodeRegExp?"u":"";if(l){const{regExp:m}=h.opts.code,f=m.code==="new RegExp"?(0,r._)`new RegExp`:(0,t.useFunc)(i,m),b=i.let("valid");i.try(()=>i.assign(b,(0,r._)`${f}(${u}, ${p}).test(${s})`),()=>i.assign(b,!1)),a.fail$data((0,r._)`!${b}`)}else{const m=(0,e.usePattern)(a,c);a.fail$data((0,r._)`!${m}.test(${s})`)}}};return Ti.default=o,Ti}var Ci={},Ny;function JE(){if(Ny)return Ci;Ny=1,Object.defineProperty(Ci,"__esModule",{value:!0});const e=Oe(),r={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:{message({keyword:n,schemaCode:o}){const a=n==="maxProperties"?"more":"fewer";return(0,e.str)`must NOT have ${a} than ${o} properties`},params:({schemaCode:n})=>(0,e._)`{limit: ${n}}`},code(n){const{keyword:o,data:a,schemaCode:i}=n,s=o==="maxProperties"?e.operators.GT:e.operators.LT;n.fail$data((0,e._)`Object.keys(${a}).length ${s} ${i}`)}};return Ci.default=r,Ci}var Si={},qy;function GE(){if(qy)return Si;qy=1,Object.defineProperty(Si,"__esModule",{value:!0});const e=Mr(),t=Oe(),r=Fe(),o={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:a}})=>(0,t.str)`must have required property '${a}'`,params:({params:{missingProperty:a}})=>(0,t._)`{missingProperty: ${a}}`},code(a){const{gen:i,schema:s,schemaCode:l,data:c,$data:u,it:h}=a,{opts:p}=h;if(!u&&s.length===0)return;const m=s.length>=p.loopRequired;if(h.allErrors?f():b(),p.strictRequired){const v=a.parentSchema.properties,{definedProperties:g}=a.it;for(const I of s)if(v?.[I]===void 0&&!g.has(I)){const y=h.schemaEnv.baseId+h.errSchemaPath,_=`required property "${I}" is not defined at "${y}" (strictRequired)`;(0,r.checkStrictMode)(h,_,h.opts.strictRequired)}}function f(){if(m||u)a.block$data(t.nil,w);else for(const v of s)(0,e.checkReportMissingProp)(a,v)}function b(){const v=i.let("missing");if(m||u){const g=i.let("valid",!0);a.block$data(g,()=>C(v,g)),a.ok(g)}else i.if((0,e.checkMissingProp)(a,s,v)),(0,e.reportMissingProp)(a,v),i.else()}function w(){i.forOf("prop",l,v=>{a.setParams({missingProperty:v}),i.if((0,e.noPropertyInData)(i,c,v,p.ownProperties),()=>a.error())})}function C(v,g){a.setParams({missingProperty:v}),i.forOf(v,l,()=>{i.assign(g,(0,e.propertyInData)(i,c,v,p.ownProperties)),i.if((0,t.not)(g),()=>{a.error(),i.break()})},t.nil)}}};return Si.default=o,Si}var Ii={},Ly;function WE(){if(Ly)return Ii;Ly=1,Object.defineProperty(Ii,"__esModule",{value:!0});const e=Oe(),r={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message({keyword:n,schemaCode:o}){const a=n==="maxItems"?"more":"fewer";return(0,e.str)`must NOT have ${a} than ${o} items`},params:({schemaCode:n})=>(0,e._)`{limit: ${n}}`},code(n){const{keyword:o,data:a,schemaCode:i}=n,s=o==="maxItems"?e.operators.GT:e.operators.LT;n.fail$data((0,e._)`${a}.length ${s} ${i}`)}};return Ii.default=r,Ii}var xi={},Ei={},jy;function od(){if(jy)return Ei;jy=1,Object.defineProperty(Ei,"__esModule",{value:!0});const e=fy();return e.code='require("ajv/dist/runtime/equal").default',Ei.default=e,Ei}var Dy;function KE(){if(Dy)return xi;Dy=1,Object.defineProperty(xi,"__esModule",{value:!0});const e=li(),t=Oe(),r=Fe(),n=od(),a={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i,j:s}})=>(0,t.str)`must NOT have duplicate items (items ## ${s} and ${i} are identical)`,params:({params:{i,j:s}})=>(0,t._)`{i: ${i}, j: ${s}}`},code(i){const{gen:s,data:l,$data:c,schema:u,parentSchema:h,schemaCode:p,it:m}=i;if(!c&&!u)return;const f=s.let("valid"),b=h.items?(0,e.getSchemaTypes)(h.items):[];i.block$data(f,w,(0,t._)`${p} === false`),i.ok(f);function w(){const I=s.let("i",(0,t._)`${l}.length`),y=s.let("j");i.setParams({i:I,j:y}),s.assign(f,!0),s.if((0,t._)`${I} > 1`,()=>(C()?v:g)(I,y))}function C(){return b.length>0&&!b.some(I=>I==="object"||I==="array")}function v(I,y){const _=s.name("item"),k=(0,e.checkDataTypes)(b,_,m.opts.strictNumbers,e.DataType.Wrong),S=s.const("indices",(0,t._)`{}`);s.for((0,t._)`;${I}--;`,()=>{s.let(_,(0,t._)`${l}[${I}]`),s.if(k,(0,t._)`continue`),b.length>1&&s.if((0,t._)`typeof ${_} == "string"`,(0,t._)`${_} += "_"`),s.if((0,t._)`typeof ${S}[${_}] == "number"`,()=>{s.assign(y,(0,t._)`${S}[${_}]`),i.error(),s.assign(f,!1).break()}).code((0,t._)`${S}[${_}] = ${I}`)})}function g(I,y){const _=(0,r.useFunc)(s,n.default),k=s.name("outer");s.label(k).for((0,t._)`;${I}--;`,()=>s.for((0,t._)`${y} = ${I}; ${y}--;`,()=>s.if((0,t._)`${_}(${l}[${I}], ${l}[${y}])`,()=>{i.error(),s.assign(f,!1).break(k)})))}}};return xi.default=a,xi}var $i={},Uy;function YE(){if(Uy)return $i;Uy=1,Object.defineProperty($i,"__esModule",{value:!0});const e=Oe(),t=Fe(),r=od(),o={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:a})=>(0,e._)`{allowedValue: ${a}}`},code(a){const{gen:i,data:s,$data:l,schemaCode:c,schema:u}=a;l||u&&typeof u=="object"?a.fail$data((0,e._)`!${(0,t.useFunc)(i,r.default)}(${s}, ${c})`):a.fail((0,e._)`${u} !== ${s}`)}};return $i.default=o,$i}var Ri={},zy;function QE(){if(zy)return Ri;zy=1,Object.defineProperty(Ri,"__esModule",{value:!0});const e=Oe(),t=Fe(),r=od(),o={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:a})=>(0,e._)`{allowedValues: ${a}}`},code(a){const{gen:i,data:s,$data:l,schema:c,schemaCode:u,it:h}=a;if(!l&&c.length===0)throw new Error("enum must have non-empty array");const p=c.length>=h.opts.loopEnum;let m;const f=()=>m??(m=(0,t.useFunc)(i,r.default));let b;if(p||l)b=i.let("valid"),a.block$data(b,w);else{if(!Array.isArray(c))throw new Error("ajv implementation error");const v=i.const("vSchema",u);b=(0,e.or)(...c.map((g,I)=>C(v,I)))}a.pass(b);function w(){i.assign(b,!1),i.forOf("v",u,v=>i.if((0,e._)`${f()}(${s}, ${v})`,()=>i.assign(b,!0).break()))}function C(v,g){const I=c[g];return typeof I=="object"&&I!==null?(0,e._)`${f()}(${s}, ${v}[${g}])`:(0,e._)`${s} === ${I}`}}};return Ri.default=o,Ri}var Fy;function XE(){if(Fy)return yi;Fy=1,Object.defineProperty(yi,"__esModule",{value:!0});const e=FE(),t=VE(),r=HE(),n=BE(),o=JE(),a=GE(),i=WE(),s=KE(),l=YE(),c=QE(),u=[e.default,t.default,r.default,n.default,o.default,a.default,i.default,s.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},l.default,c.default];return yi.default=u,yi}var Pi={},qo={},Vy;function Zy(){if(Vy)return qo;Vy=1,Object.defineProperty(qo,"__esModule",{value:!0}),qo.validateAdditionalItems=void 0;const e=Oe(),t=Fe(),n={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:a}})=>(0,e.str)`must NOT have more than ${a} items`,params:({params:{len:a}})=>(0,e._)`{limit: ${a}}`},code(a){const{parentSchema:i,it:s}=a,{items:l}=i;if(!Array.isArray(l)){(0,t.checkStrictMode)(s,'"additionalItems" is ignored when "items" is not an array of schemas');return}o(a,l)}};function o(a,i){const{gen:s,schema:l,data:c,keyword:u,it:h}=a;h.items=!0;const p=s.const("len",(0,e._)`${c}.length`);if(l===!1)a.setParams({len:i.length}),a.pass((0,e._)`${p} <= ${i.length}`);else if(typeof l=="object"&&!(0,t.alwaysValidSchema)(h,l)){const f=s.var("valid",(0,e._)`${p} <= ${i.length}`);s.if((0,e.not)(f),()=>m(f)),a.ok(f)}function m(f){s.forRange("i",i.length,p,b=>{a.subschema({keyword:u,dataProp:b,dataPropType:t.Type.Num},f),h.allErrors||s.if((0,e.not)(f),()=>s.break())})}}return qo.validateAdditionalItems=o,qo.default=n,qo}var Mi={},Lo={},Hy;function By(){if(Hy)return Lo;Hy=1,Object.defineProperty(Lo,"__esModule",{value:!0}),Lo.validateTuple=void 0;const e=Oe(),t=Fe(),r=Mr(),n={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(a){const{schema:i,it:s}=a;if(Array.isArray(i))return o(a,"additionalItems",i);s.items=!0,!(0,t.alwaysValidSchema)(s,i)&&a.ok((0,r.validateArray)(a))}};function o(a,i,s=a.schema){const{gen:l,parentSchema:c,data:u,keyword:h,it:p}=a;b(c),p.opts.unevaluated&&s.length&&p.items!==!0&&(p.items=t.mergeEvaluated.items(l,s.length,p.items));const m=l.name("valid"),f=l.const("len",(0,e._)`${u}.length`);s.forEach((w,C)=>{(0,t.alwaysValidSchema)(p,w)||(l.if((0,e._)`${f} > ${C}`,()=>a.subschema({keyword:h,schemaProp:C,dataProp:C},m)),a.ok(m))});function b(w){const{opts:C,errSchemaPath:v}=p,g=s.length,I=g===w.minItems&&(g===w.maxItems||w[i]===!1);if(C.strictTuples&&!I){const y=`"${h}" is ${g}-tuple, but minItems or maxItems/${i} are not specified or different at path "${v}"`;(0,t.checkStrictMode)(p,y,C.strictTuples)}}}return Lo.validateTuple=o,Lo.default=n,Lo}var Jy;function e$(){if(Jy)return Mi;Jy=1,Object.defineProperty(Mi,"__esModule",{value:!0});const e=By(),t={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,e.validateTuple)(r,"items")};return Mi.default=t,Mi}var Oi={},Gy;function t$(){if(Gy)return Oi;Gy=1,Object.defineProperty(Oi,"__esModule",{value:!0});const e=Oe(),t=Fe(),r=Mr(),n=Zy(),a={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:s,parentSchema:l,it:c}=i,{prefixItems:u}=l;c.items=!0,!(0,t.alwaysValidSchema)(c,s)&&(u?(0,n.validateAdditionalItems)(i,u):i.ok((0,r.validateArray)(i)))}};return Oi.default=a,Oi}var Ai={},Wy;function r$(){if(Wy)return Ai;Wy=1,Object.defineProperty(Ai,"__esModule",{value:!0});const e=Oe(),t=Fe(),n={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:o,max:a}})=>a===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 ${a} valid item(s)`,params:({params:{min:o,max:a}})=>a===void 0?(0,e._)`{minContains: ${o}}`:(0,e._)`{minContains: ${o}, maxContains: ${a}}`},code(o){const{gen:a,schema:i,parentSchema:s,data:l,it:c}=o;let u,h;const{minContains:p,maxContains:m}=s;c.opts.next?(u=p===void 0?1:p,h=m):u=1;const f=a.const("len",(0,e._)`${l}.length`);if(o.setParams({min:u,max:h}),h===void 0&&u===0){(0,t.checkStrictMode)(c,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(h!==void 0&&u>h){(0,t.checkStrictMode)(c,'"minContains" > "maxContains" is always invalid'),o.fail();return}if((0,t.alwaysValidSchema)(c,i)){let g=(0,e._)`${f} >= ${u}`;h!==void 0&&(g=(0,e._)`${g} && ${f} <= ${h}`),o.pass(g);return}c.items=!0;const b=a.name("valid");h===void 0&&u===1?C(b,()=>a.if(b,()=>a.break())):u===0?(a.let(b,!0),h!==void 0&&a.if((0,e._)`${l}.length > 0`,w)):(a.let(b,!1),w()),o.result(b,()=>o.reset());function w(){const g=a.name("_valid"),I=a.let("count",0);C(g,()=>a.if(g,()=>v(I)))}function C(g,I){a.forRange("i",0,f,y=>{o.subschema({keyword:"contains",dataProp:y,dataPropType:t.Type.Num,compositeRule:!0},g),I()})}function v(g){a.code((0,e._)`${g}++`),h===void 0?a.if((0,e._)`${g} >= ${u}`,()=>a.assign(b,!0).break()):(a.if((0,e._)`${g} > ${h}`,()=>a.assign(b,!1).break()),u===1?a.assign(b,!0):a.if((0,e._)`${g} >= ${u}`,()=>a.assign(b,!0)))}}};return Ai.default=n,Ai}var ad={},Ky;function n$(){return Ky||(Ky=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=Oe(),r=Fe(),n=Mr();e.error={message:({params:{property:l,depsCount:c,deps:u}})=>{const h=c===1?"property":"properties";return(0,t.str)`must have ${h} ${u} when property ${l} is present`},params:({params:{property:l,depsCount:c,deps:u,missingProperty:h}})=>(0,t._)`{property: ${l},
|
|
93
|
+
missingProperty: ${h},
|
|
86
94
|
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})(Mu)),Mu}var Ti={},Y_;function S7(){if(Y_)return Ti;Y_=1,Object.defineProperty(Ti,"__esModule",{value:!0});const e=Re(),t=Ue(),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=Ir(),t=Re(),r=pn(),n=Ue(),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 I7(){if(ey)return Si;ey=1,Object.defineProperty(Si,"__esModule",{value:!0});const e=Qa(),t=Ir(),r=Ue(),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 x7(){if(ty)return Ii;ty=1,Object.defineProperty(Ii,"__esModule",{value:!0});const e=Ir(),t=Re(),r=Ue(),n=Ue(),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 E7(){if(ry)return xi;ry=1,Object.defineProperty(xi,"__esModule",{value:!0});const e=Ue(),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 $7(){if(ny)return Ei;ny=1,Object.defineProperty(Ei,"__esModule",{value:!0});const t={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Ir().validateUnion,error:{message:"must match a schema in anyOf"}};return Ei.default=t,Ei}var $i={},oy;function R7(){if(oy)return $i;oy=1,Object.defineProperty($i,"__esModule",{value:!0});const e=Re(),t=Ue(),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 P7(){if(sy)return Ri;sy=1,Object.defineProperty(Ri,"__esModule",{value:!0});const e=Ue(),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 M7(){if(ay)return Pi;ay=1,Object.defineProperty(Pi,"__esModule",{value:!0});const e=Re(),t=Ue(),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 N7(){if(iy)return Mi;iy=1,Object.defineProperty(Mi,"__esModule",{value:!0});const e=Ue(),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 O7(){if(ly)return vi;ly=1,Object.defineProperty(vi,"__esModule",{value:!0});const e=Z_(),t=b7(),r=H_(),n=k7(),o=T7(),s=C7(),i=S7(),a=X_(),l=I7(),c=x7(),u=E7(),f=$7(),p=R7(),h=P7(),g=M7(),v=N7();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 A7(){if(cy)return Oi;cy=1,Object.defineProperty(Oi,"__esModule",{value:!0});const e=Re(),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 q7(){if(uy)return Ni;uy=1,Object.defineProperty(Ni,"__esModule",{value:!0});const t=[A7().default];return Ni.default=t,Ni}var Hn={},dy;function L7(){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 j7(){if(py)return ni;py=1,Object.defineProperty(ni,"__esModule",{value:!0});const e=l7(),t=w7(),r=O7(),n=q7(),o=L7(),s=[e.default,t.default,(0,r.default)(),n.default,o.metadataVocabulary,o.contentVocabulary];return ni.default=s,ni}var Ai={},Ss={},fy;function D7(){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 U7(){if(hy)return Ai;hy=1,Object.defineProperty(Ai,"__esModule",{value:!0});const e=Re(),t=D7(),r=Eu(),n=ti(),o=Ue(),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 N=0;N<h.length;N++){let L=h[N];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,N)}if(!I)throw new Error(`discriminator: "${g}" must be required`);return b;function R({required:N}){return Array.isArray(N)&&N.includes(g)}function S(N,L){if(N.const)j(N.const,L);else if(N.enum)for(const z of N.enum)j(z,L);else throw new Error(`discriminator: "properties/${g}" must have "const" or "enum"`)}function j(N,L){if(typeof N!="string"||N in b)throw new Error(`discriminator: "${g}" values must be unique strings`);b[N]=L}}}};return Ai.default=i,Ai}const z7={$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=s7(),n=j7(),o=U7(),s=z7,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=Re();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=xu();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 F7=gy();const V7=Rl(F7);var qi={exports:{}},Nu={},_y;function Z7(){return _y||(_y=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(N,L){return{validate:N,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(N){return N%4===0&&(N%100!==0||N%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(N){const L=n.exec(N);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(N,L){if(N&&L)return N>L?1:N<L?-1:0}const a=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function l(N){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||N&&!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(N,L){if(!(N&&L))return;const z=new Date("2020-01-01T"+N).valueOf(),B=new Date("2020-01-01T"+L).valueOf();if(z&&B)return z-B}function u(N,L){if(!(N&&L))return;const z=a.exec(N),B=a.exec(L);if(z&&B)return N=z[1]+z[2]+z[3],L=B[1]+B[2]+B[3],N>L?1:N<L?-1:0}const f=/t|\s/i;function p(N){const L=l(N);return function(B){const X=B.split(f);return X.length===2&&s(X[0])&&L(X[1])}}function h(N,L){if(!(N&&L))return;const z=new Date(N).valueOf(),B=new Date(L).valueOf();if(z&&B)return z-B}function g(N,L){if(!(N&&L))return;const[z,B]=N.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(N){return v.test(N)&&_.test(N)}const y=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function m(N){return y.lastIndex=0,y.test(N)}const C=-2147483648,b=2**31-1;function T(N){return Number.isInteger(N)&&N<=b&&N>=C}function I(N){return Number.isInteger(N)}function R(){return!0}const S=/[^\\]\\Z/;function j(N){if(S.test(N))return!1;try{return new RegExp(N),!0}catch{return!1}}})(Nu)),Nu}var Ou={},yy;function B7(){return yy||(yy=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;const t=gy(),r=Re(),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})(Ou)),Ou}var vy;function H7(){return vy||(vy=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r=Z7(),n=B7(),o=Re(),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 J7=H7();const W7=Rl(J7);function G7(){const e=new V7({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return W7(e),e}class K7{constructor(t){this._ajv=t??G7()}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 Y7{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 ke(xe.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 ke(xe.InvalidParams,`Structured content does not match the tool's output schema: ${u.errorMessage}`)};return}}catch(u){if(u instanceof ke){yield{type:"error",error:u};return}yield{type:"error",error:new ke(xe.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 Q7(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 X7(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 eE(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 Wx{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 K7,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Mc,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Pc,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Ic,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new Y7(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Gx(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=dn(Ac,l);if(!u.success){const y=u.error instanceof Error?u.error.message:String(u.error);throw new ke(xe.InvalidParams,`Invalid elicitation request: ${y}`)}const{params:f}=u.data;f.mode=f.mode??"form";const{supportsFormMode:p,supportsUrlMode:h}=eE(this._capabilities.elicitation);if(f.mode==="form"&&!p)throw new ke(xe.InvalidParams,"Client does not support form-mode elicitation requests");if(f.mode==="url"&&!h)throw new ke(xe.InvalidParams,"Client does not support URL-mode elicitation requests");const g=await Promise.resolve(r(l,c));if(f.task){const y=dn(ps,g);if(!y.success){const m=y.error instanceof Error?y.error.message:String(y.error);throw new ke(xe.InvalidParams,`Invalid task creation result: ${m}`)}return y.data}const v=dn(qc,g);if(!v.success){const y=v.error instanceof Error?v.error.message:String(v.error);throw new ke(xe.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=dn(Nc,l);if(!u.success){const _=u.error instanceof Error?u.error.message:String(u.error);throw new ke(xe.InvalidParams,`Invalid sampling request: ${_}`)}const{params:f}=u.data,p=await Promise.resolve(r(l,c));if(f.task){const _=dn(ps,p);if(!_.success){const w=_.error instanceof Error?_.error.message:String(_.error);throw new ke(xe.InvalidParams,`Invalid task creation result: ${w}`)}return _.data}const g=f.tools||f.toolChoice?m2:Oc,v=dn(g,p);if(!v.success){const _=v.error instanceof Error?v.error.message:String(v.error);throw new ke(xe.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(!s5.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){Q7(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&X7(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 ke(xe.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 ke(xe.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`);if(o.structuredContent)try{const i=s(o.structuredContent);if(!i.valid)throw new ke(xe.InvalidParams,`Structured content does not match the tool's output schema: ${i.errorMessage}`)}catch(i){throw i instanceof ke?i:new ke(xe.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=Q5.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 tE="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,tE),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 Io=xr;(function(e,t){const r=xr,n=xr,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 rE=()=>{const e=xr,t=xr,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}},nE=(e,t,r)=>{const n=xr,o=xr,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[Io(401)](){const t=Io,r=Io;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=xr,l=xr;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=Io,o=Io;(t=this._port)==null||t[n(393)](),this[n(422)]=void 0,(r=this[o(408)])==null||r.call(this)}}class oE extends by{constructor(t,r=rE()){const n=Io,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)](nE,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 xr(e,t){const r=Di();return xr=function(n,o){return n=n-(17227+1*-16844),r[n]},xr(e,t)}(function(e,t){const r=Ke,n=Ke,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 sE=async(e,t,r)=>{var n;const o=Ke,s=Ke,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))},aE=async(e,t,r)=>{var n;const o=Ke,s=Ke,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,Oc);break;case a[o(487)]:const v={};v.method=c,v[s(446)]=u,f=await t.request(v,qc);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 Ke(e,t){const r=Ui();return Ke=function(n,o){return n=n-(-8023+4*-2344+-17809*-1),r[n]},Ke(e,t)}const iE=(e,t)=>{const r=Ke,n=Ke,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)](sE,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)}}}},lE=(e,t)=>{const r=Ke,n=Ke,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)}}},cE=(e,t)=>async r=>{var n,o,s,i,a;const l=Ke,c=Ke,u={TJhyV:function(f,p,h,g){return f(p,h,g)},MMNTY:l(465)};try{return await u.TJhyV(aE,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)}}},uE=(e,t)=>async r=>{var n,o,s;const i=Ke,a=Ke,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 dE=(e,t)=>async r=>{var n,o,s,i,a,l;const c=Ke,u=Ke,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)}}},Au=()=>{const e=Ke,t={rgPZO:function(l,c){return l!==c},VWsxO:function(l,c){return l(c)},FjTAY:"function"},r=[],n=(l,c)=>{const u=Ke;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=Ke,u=Ke;typeof l===t[c(456)]&&!r.includes(l)&&r[u(471)](l)},s=l=>{const c=Ke,u=r[c(415)](l);u!==-1&&r.splice(u,-17591+6*2932)},i=()=>{const l=Ke;r[l(430)]=-505*7+1322+2213},a={};return a.handleListener=n,a[e(447)]=o,a.removeListener=s,a.clearListener=i,a},pE=e=>{const t=Ke,r=Ke,n={UlqiY:function(o){return o()},jsmFN:function(o){return o()}};{const{handleListener:o,addListener:s,removeListener:i,clearListener:a}=n[t(423)](Au);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)](Au);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(Au);e.fallbackNotificationHandler=o,e[t(444)]=s,e.removeNotificationListener=i,e[r(426)]=a}},fE=(e,{beforeInit:t,afterInit:r}={})=>{const n=Ke,o=Ke,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(pE,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)})},hE=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 mE=()=>{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)})},gE=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)]("")},hn={};hn[hE(211)]=mE,hn.randomBytes=gE;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 Er=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 _E=(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)](iE,e,t),lE(e,t);const s=o[n(283)](cE,t,e),i=o[n(294)](dE,t,e),a=o[r(277)](uE,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)}},qu=(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(_E,e,t)},s={};s.afterInit=o,n.Qalmc(fE,t,s)},ky=(e,t=hn[Er(299)]())=>{const r=Er,n=Er,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=hn[Er(299)]())=>{const r=Is,n=Er,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},Lu=async(e,t,r)=>{const n=Er,o=Er,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,gr)){const l=await t();return await i[n(257)](l),await Lu(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 yE=async e=>{const t=Is,r=Er,n={GKDjq:function(S,j,N){return S(j,N)},JzpWy:t(281),mcbiU:"1.0.0",CfBXU:function(S){return S()},kdowC:function(S,j,N,L){return S(j,N,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||hn[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)](Lu,b,S,T)}else await b.connect(I);qu(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},vE=async e=>{const t=Is,r=Er,n={wfHUn:function(S,j,N){return S(j,N)},tUMle:"mcp-stream-proxy-client",omKPe:t(248),rSiEq:function(S){return S()},PdsSn:function(S,j,N,L){return S(j,N,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||hn.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)](Lu,b,S,T)}else await b[t(260)](I);n.PdsSn(qu,b,o,I);const R={};return R.transport=I,R[r(286)]=I[r(286)],R},wE=async e=>{const t=Er,r=Er,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||hn[r(299)](),v=new wy(new URL(s+"?sessionId="+g+r(265)+i));await h.connect(v),n[t(259)](qu,h,o,v);const _={};return _.transport=v,_[r(286)]=g,_},mn=$r,xs=$r;(function(e,t){const r=$r,n=$r,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 $r(e,t){const r=Vi();return $r=function(n,o){return n=n-(-4158*1+-2*581+-1*-5510),r[n]},$r(e,t)}const bE=()=>hn.randomBytes(-8746+-382*-23);class k${constructor(t){const r=$r,n=$r,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(bE),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=$r,c=$r,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[mn(191)](t,r){const n=mn,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=$r;t.resolve=r,t[o(196)]=n})}get redirectUrl(){return this[mn(206)]}get[xs(190)](){return this._clientMetadata}[mn(213)](){return this[mn(197)]}[xs(218)](){return this[xs(200)]}[mn(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}[mn(212)](){const t=mn,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 kE=e=>{e.onmessage=async t=>{if(!t||typeof t!="object")return;const r=t.id;try{if(t.method==="initialize")await e.send({jsonrpc:"2.0",id:r,result:{protocolVersion:"2024-11-05",capabilities:{tools:{}},serverInfo:{name:"browser-builtin-webmcp-proxy",version:"1.0.0"}}});else if(t.method!=="notifications/initialized")if(t.method==="ping"||t.method==="custom_ping")await e.send({jsonrpc:"2.0",id:r,result:{}});else if(t.method==="tools/list"){const n=typeof navigator<"u"?navigator.modelContextTesting||navigator.modelContext:null;if(n&&n.listTools){const s=(await n.listTools()).map(i=>{let a={};if(typeof i.inputSchema=="string")try{a=JSON.parse(i.inputSchema)}catch(l){console.error("Failed to parse inputSchema:",l)}else typeof i.inputSchema=="object"&&i.inputSchema!==null&&(a=i.inputSchema);return{name:i.name,description:i.description||"",inputSchema:{type:"object",properties:a.properties||{},required:a.required||[]}}});await e.send({jsonrpc:"2.0",id:r,result:{tools:s}})}else await e.send({jsonrpc:"2.0",id:r,result:{tools:[]}})}else if(t.method==="tools/call"){const n=typeof navigator<"u"?navigator.modelContextTesting||navigator.modelContext:null;if(n&&n.executeTool){const{name:o,arguments:s}=t.params,i=await n.executeTool(o,JSON.stringify(s||{})),a=i&&typeof i=="object"&&"content"in i?i:{content:[{type:"text",text:typeof i=="string"?i:JSON.stringify(i)}]};await e.send({jsonrpc:"2.0",id:r,result:a})}else await e.send({jsonrpc:"2.0",id:r,error:{code:-32601,message:"Browser built-in WebMCP not available"}})}else r!==void 0&&await e.send({jsonrpc:"2.0",id:r,error:{code:-32601,message:`Method not found: ${t.method}`}})}catch(n){r!==void 0&&await e.send({jsonrpc:"2.0",id:r,error:{code:-32e3,message:n.message||String(n)}})}}};class TE{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===!0){const f={client:this.client,url:r,token:n,sessionId:o};let p;return await(async()=>{const{transport:g,sessionId:v}=s==="sse"?await yE(f):s==="socket"?await wE(f):await vE(f);g.onerror=async _=>{l?.(_)},a===!0&&kE(g),p={transport:g,sessionId:v}})(),p}const c=new URL(r);let u;if(s==="channel"&&(u=new oE(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)),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(Ac,t)}onCreateMessage(t){this.client.setRequestHandler(Nc,t)}onListRoots(t){this.client.setRequestHandler(_2,t)}onToolListChanged(t){this.client.setNotificationHandler(Mc,t)}onPromptListChanged(t){this.client.setNotificationHandler(Pc,t)}onResourceListChanged(t){this.client.setNotificationHandler(Ic,t)}onResourceUpdated(t){this.client.setNotificationHandler(l2,t)}onLoggingMessage(t){this.client.setNotificationHandler(h2,t)}async onPagehide(t){t.persisted||(CE(this.transport)?await this.transport.terminateSession():this.transport&&typeof this.transport.close=="function"&&await this.transport.close())}}const CE=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]=$l({description:o,inputSchema:Pn({...s,properties:s.properties??{},additionalProperties:!1}),execute:i})}return t}catch(r){throw r}},SE=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]=$l({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 IE(e){const t=Object.entries(e);if(t.length===0)return"";let r=`
|
|
95
|
+
deps: ${u}}`};const o={keyword:"dependencies",type:"object",schemaType:"object",error:e.error,code(l){const[c,u]=a(l);i(l,c),s(l,u)}};function a({schema:l}){const c={},u={};for(const h in l){if(h==="__proto__")continue;const p=Array.isArray(l[h])?c:u;p[h]=l[h]}return[c,u]}function i(l,c=l.schema){const{gen:u,data:h,it:p}=l;if(Object.keys(c).length===0)return;const m=u.let("missing");for(const f in c){const b=c[f];if(b.length===0)continue;const w=(0,n.propertyInData)(u,h,f,p.opts.ownProperties);l.setParams({property:f,depsCount:b.length,deps:b.join(", ")}),p.allErrors?u.if(w,()=>{for(const C of b)(0,n.checkReportMissingProp)(l,C)}):(u.if((0,t._)`${w} && (${(0,n.checkMissingProp)(l,b,m)})`),(0,n.reportMissingProp)(l,m),u.else())}}e.validatePropertyDeps=i;function s(l,c=l.schema){const{gen:u,data:h,keyword:p,it:m}=l,f=u.name("valid");for(const b in c)(0,r.alwaysValidSchema)(m,c[b])||(u.if((0,n.propertyInData)(u,h,b,m.opts.ownProperties),()=>{const w=l.subschema({keyword:p,schemaProp:b},f);l.mergeValidEvaluated(w,f)},()=>u.var(f,!0)),l.ok(f))}e.validateSchemaDeps=s,e.default=o})(ad)),ad}var Ni={},Yy;function o$(){if(Yy)return Ni;Yy=1,Object.defineProperty(Ni,"__esModule",{value:!0});const e=Oe(),t=Fe(),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:a,schema:i,data:s,it:l}=o;if((0,t.alwaysValidSchema)(l,i))return;const c=a.name("valid");a.forIn("key",s,u=>{o.setParams({propertyName:u}),o.subschema({keyword:"propertyNames",data:u,dataTypes:["string"],propertyName:u,compositeRule:!0},c),a.if((0,e.not)(c),()=>{o.error(!0),l.allErrors||a.break()})}),o.ok(c)}};return Ni.default=n,Ni}var qi={},Qy;function Xy(){if(Qy)return qi;Qy=1,Object.defineProperty(qi,"__esModule",{value:!0});const e=Mr(),t=Oe(),r=kn(),n=Fe(),a={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:s,schema:l,parentSchema:c,data:u,errsCount:h,it:p}=i;if(!h)throw new Error("ajv implementation error");const{allErrors:m,opts:f}=p;if(p.props=!0,f.removeAdditional!=="all"&&(0,n.alwaysValidSchema)(p,l))return;const b=(0,e.allSchemaProperties)(c.properties),w=(0,e.allSchemaProperties)(c.patternProperties);C(),i.ok((0,t._)`${h} === ${r.default.errors}`);function C(){s.forIn("key",u,_=>{!b.length&&!w.length?I(_):s.if(v(_),()=>I(_))})}function v(_){let k;if(b.length>8){const S=(0,n.schemaRefOrVal)(p,c.properties,"properties");k=(0,e.isOwnProperty)(s,S,_)}else b.length?k=(0,t.or)(...b.map(S=>(0,t._)`${_} === ${S}`)):k=t.nil;return w.length&&(k=(0,t.or)(k,...w.map(S=>(0,t._)`${(0,e.usePattern)(i,S)}.test(${_})`))),(0,t.not)(k)}function g(_){s.code((0,t._)`delete ${u}[${_}]`)}function I(_){if(f.removeAdditional==="all"||f.removeAdditional&&l===!1){g(_);return}if(l===!1){i.setParams({additionalProperty:_}),i.error(),m||s.break();return}if(typeof l=="object"&&!(0,n.alwaysValidSchema)(p,l)){const k=s.name("valid");f.removeAdditional==="failing"?(y(_,k,!1),s.if((0,t.not)(k),()=>{i.reset(),g(_)})):(y(_,k),m||s.if((0,t.not)(k),()=>s.break()))}}function y(_,k,S){const E={keyword:"additionalProperties",dataProp:_,dataPropType:n.Type.Str};S===!1&&Object.assign(E,{compositeRule:!0,createErrors:!1,allErrors:!1}),i.subschema(E,k)}}};return qi.default=a,qi}var Li={},ev;function a$(){if(ev)return Li;ev=1,Object.defineProperty(Li,"__esModule",{value:!0});const e=ui(),t=Mr(),r=Fe(),n=Xy(),o={keyword:"properties",type:"object",schemaType:"object",code(a){const{gen:i,schema:s,parentSchema:l,data:c,it:u}=a;u.opts.removeAdditional==="all"&&l.additionalProperties===void 0&&n.default.code(new e.KeywordCxt(u,n.default,"additionalProperties"));const h=(0,t.allSchemaProperties)(s);for(const w of h)u.definedProperties.add(w);u.opts.unevaluated&&h.length&&u.props!==!0&&(u.props=r.mergeEvaluated.props(i,(0,r.toHash)(h),u.props));const p=h.filter(w=>!(0,r.alwaysValidSchema)(u,s[w]));if(p.length===0)return;const m=i.name("valid");for(const w of p)f(w)?b(w):(i.if((0,t.propertyInData)(i,c,w,u.opts.ownProperties)),b(w),u.allErrors||i.else().var(m,!0),i.endIf()),a.it.definedProperties.add(w),a.ok(m);function f(w){return u.opts.useDefaults&&!u.compositeRule&&s[w].default!==void 0}function b(w){a.subschema({keyword:"properties",schemaProp:w,dataProp:w},m)}}};return Li.default=o,Li}var ji={},tv;function s$(){if(tv)return ji;tv=1,Object.defineProperty(ji,"__esModule",{value:!0});const e=Mr(),t=Oe(),r=Fe(),n=Fe(),o={keyword:"patternProperties",type:"object",schemaType:"object",code(a){const{gen:i,schema:s,data:l,parentSchema:c,it:u}=a,{opts:h}=u,p=(0,e.allSchemaProperties)(s),m=p.filter(I=>(0,r.alwaysValidSchema)(u,s[I]));if(p.length===0||m.length===p.length&&(!u.opts.unevaluated||u.props===!0))return;const f=h.strictSchema&&!h.allowMatchingProperties&&c.properties,b=i.name("valid");u.props!==!0&&!(u.props instanceof t.Name)&&(u.props=(0,n.evaluatedPropsToName)(i,u.props));const{props:w}=u;C();function C(){for(const I of p)f&&v(I),u.allErrors?g(I):(i.var(b,!0),g(I),i.if(b))}function v(I){for(const y in f)new RegExp(I).test(y)&&(0,r.checkStrictMode)(u,`property ${y} matches pattern ${I} (use allowMatchingProperties)`)}function g(I){i.forIn("key",l,y=>{i.if((0,t._)`${(0,e.usePattern)(a,I)}.test(${y})`,()=>{const _=m.includes(I);_||a.subschema({keyword:"patternProperties",schemaProp:I,dataProp:y,dataPropType:n.Type.Str},b),u.opts.unevaluated&&w!==!0?i.assign((0,t._)`${w}[${y}]`,!0):!_&&!u.allErrors&&i.if((0,t.not)(b),()=>i.break())})})}}};return ji.default=o,ji}var Di={},rv;function i$(){if(rv)return Di;rv=1,Object.defineProperty(Di,"__esModule",{value:!0});const e=Fe(),t={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(r){const{gen:n,schema:o,it:a}=r;if((0,e.alwaysValidSchema)(a,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 Di.default=t,Di}var Ui={},nv;function l$(){if(nv)return Ui;nv=1,Object.defineProperty(Ui,"__esModule",{value:!0});const t={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Mr().validateUnion,error:{message:"must match a schema in anyOf"}};return Ui.default=t,Ui}var zi={},ov;function c$(){if(ov)return zi;ov=1,Object.defineProperty(zi,"__esModule",{value:!0});const e=Oe(),t=Fe(),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:a,schema:i,parentSchema:s,it:l}=o;if(!Array.isArray(i))throw new Error("ajv implementation error");if(l.opts.discriminator&&s.discriminator)return;const c=i,u=a.let("valid",!1),h=a.let("passing",null),p=a.name("_valid");o.setParams({passing:h}),a.block(m),o.result(u,()=>o.reset(),()=>o.error(!0));function m(){c.forEach((f,b)=>{let w;(0,t.alwaysValidSchema)(l,f)?a.var(p,!0):w=o.subschema({keyword:"oneOf",schemaProp:b,compositeRule:!0},p),b>0&&a.if((0,e._)`${p} && ${u}`).assign(u,!1).assign(h,(0,e._)`[${h}, ${b}]`).else(),a.if(p,()=>{a.assign(u,!0),a.assign(h,b),w&&o.mergeEvaluated(w,e.Name)})})}}};return zi.default=n,zi}var Fi={},av;function u$(){if(av)return Fi;av=1,Object.defineProperty(Fi,"__esModule",{value:!0});const e=Fe(),t={keyword:"allOf",schemaType:"array",code(r){const{gen:n,schema:o,it:a}=r;if(!Array.isArray(o))throw new Error("ajv implementation error");const i=n.name("valid");o.forEach((s,l)=>{if((0,e.alwaysValidSchema)(a,s))return;const c=r.subschema({keyword:"allOf",schemaProp:l},i);r.ok(i),r.mergeEvaluated(c)})}};return Fi.default=t,Fi}var Vi={},sv;function d$(){if(sv)return Vi;sv=1,Object.defineProperty(Vi,"__esModule",{value:!0});const e=Oe(),t=Fe(),n={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:a})=>(0,e.str)`must match "${a.ifClause}" schema`,params:({params:a})=>(0,e._)`{failingKeyword: ${a.ifClause}}`},code(a){const{gen:i,parentSchema:s,it:l}=a;s.then===void 0&&s.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 h=i.let("valid",!0),p=i.name("_valid");if(m(),a.reset(),c&&u){const b=i.let("ifClause");a.setParams({ifClause:b}),i.if(p,f("then",b),f("else",b))}else c?i.if(p,f("then")):i.if((0,e.not)(p),f("else"));a.pass(h,()=>a.error(!0));function m(){const b=a.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},p);a.mergeEvaluated(b)}function f(b,w){return()=>{const C=a.subschema({keyword:b},p);i.assign(h,p),a.mergeValidEvaluated(C,h),w?i.assign(w,(0,e._)`${b}`):a.setParams({ifClause:b})}}}};function o(a,i){const s=a.schema[i];return s!==void 0&&!(0,t.alwaysValidSchema)(a,s)}return Vi.default=n,Vi}var Zi={},iv;function p$(){if(iv)return Zi;iv=1,Object.defineProperty(Zi,"__esModule",{value:!0});const e=Fe(),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 Zi.default=t,Zi}var lv;function h$(){if(lv)return Pi;lv=1,Object.defineProperty(Pi,"__esModule",{value:!0});const e=Zy(),t=e$(),r=By(),n=t$(),o=r$(),a=n$(),i=o$(),s=Xy(),l=a$(),c=s$(),u=i$(),h=l$(),p=c$(),m=u$(),f=d$(),b=p$();function w(C=!1){const v=[u.default,h.default,p.default,m.default,f.default,b.default,i.default,s.default,a.default,l.default,c.default];return C?v.push(t.default,n.default):v.push(e.default,r.default),v.push(o.default),v}return Pi.default=w,Pi}var Hi={},Bi={},cv;function f$(){if(cv)return Bi;cv=1,Object.defineProperty(Bi,"__esModule",{value:!0});const e=Oe(),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:a,data:i,$data:s,schema:l,schemaCode:c,it:u}=n,{opts:h,errSchemaPath:p,schemaEnv:m,self:f}=u;if(!h.validateFormats)return;s?b():w();function b(){const C=a.scopeValue("formats",{ref:f.formats,code:h.code.formats}),v=a.const("fDef",(0,e._)`${C}[${c}]`),g=a.let("fType"),I=a.let("format");a.if((0,e._)`typeof ${v} == "object" && !(${v} instanceof RegExp)`,()=>a.assign(g,(0,e._)`${v}.type || "string"`).assign(I,(0,e._)`${v}.validate`),()=>a.assign(g,(0,e._)`"string"`).assign(I,v)),n.fail$data((0,e.or)(y(),_()));function y(){return h.strictSchema===!1?e.nil:(0,e._)`${c} && !${I}`}function _(){const k=m.$async?(0,e._)`(${v}.async ? await ${I}(${i}) : ${I}(${i}))`:(0,e._)`${I}(${i})`,S=(0,e._)`(typeof ${I} == "function" ? ${k} : ${I}.test(${i}))`;return(0,e._)`${I} && ${I} !== true && ${g} === ${o} && !${S}`}}function w(){const C=f.formats[l];if(!C){y();return}if(C===!0)return;const[v,g,I]=_(C);v===o&&n.pass(k());function y(){if(h.strictSchema===!1){f.logger.warn(S());return}throw new Error(S());function S(){return`unknown format "${l}" ignored in schema at path "${p}"`}}function _(S){const E=S instanceof RegExp?(0,e.regexpCode)(S):h.code.formats?(0,e._)`${h.code.formats}${(0,e.getProperty)(l)}`:void 0,R=a.scopeValue("formats",{key:l,ref:S,code:E});return typeof S=="object"&&!(S instanceof RegExp)?[S.type||"string",S.validate,(0,e._)`${R}.validate`]:["string",S,R]}function k(){if(typeof C=="object"&&!(C instanceof RegExp)&&C.async){if(!m.$async)throw new Error("async format in sync schema");return(0,e._)`await ${I}(${i})`}return typeof g=="function"?(0,e._)`${I}(${i})`:(0,e._)`${I}.test(${i})`}}}};return Bi.default=r,Bi}var uv;function m$(){if(uv)return Hi;uv=1,Object.defineProperty(Hi,"__esModule",{value:!0});const t=[f$().default];return Hi.default=t,Hi}var no={},dv;function g$(){return dv||(dv=1,Object.defineProperty(no,"__esModule",{value:!0}),no.contentVocabulary=no.metadataVocabulary=void 0,no.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],no.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]),no}var pv;function _$(){if(pv)return mi;pv=1,Object.defineProperty(mi,"__esModule",{value:!0});const e=zE(),t=XE(),r=h$(),n=m$(),o=g$(),a=[e.default,t.default,(0,r.default)(),n.default,o.metadataVocabulary,o.contentVocabulary];return mi.default=a,mi}var Ji={},qa={},hv;function y$(){if(hv)return qa;hv=1,Object.defineProperty(qa,"__esModule",{value:!0}),qa.DiscrError=void 0;var e;return(function(t){t.Tag="tag",t.Mapping="mapping"})(e||(qa.DiscrError=e={})),qa}var fv;function v$(){if(fv)return Ji;fv=1,Object.defineProperty(Ji,"__esModule",{value:!0});const e=Oe(),t=y$(),r=td(),n=hi(),o=Fe(),i={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:s,tagName:l}})=>s===t.DiscrError.Tag?`tag "${l}" must be string`:`value of tag "${l}" must be in oneOf`,params:({params:{discrError:s,tag:l,tagName:c}})=>(0,e._)`{error: ${s}, tag: ${c}, tagValue: ${l}}`},code(s){const{gen:l,data:c,schema:u,parentSchema:h,it:p}=s,{oneOf:m}=h;if(!p.opts.discriminator)throw new Error("discriminator: requires discriminator option");const f=u.propertyName;if(typeof f!="string")throw new Error("discriminator: requires propertyName");if(u.mapping)throw new Error("discriminator: mapping is not supported");if(!m)throw new Error("discriminator: requires oneOf keyword");const b=l.let("valid",!1),w=l.const("tag",(0,e._)`${c}${(0,e.getProperty)(f)}`);l.if((0,e._)`typeof ${w} == "string"`,()=>C(),()=>s.error(!1,{discrError:t.DiscrError.Tag,tag:w,tagName:f})),s.ok(b);function C(){const I=g();l.if(!1);for(const y in I)l.elseIf((0,e._)`${w} === ${y}`),l.assign(b,v(I[y]));l.else(),s.error(!1,{discrError:t.DiscrError.Mapping,tag:w,tagName:f}),l.endIf()}function v(I){const y=l.name("valid"),_=s.subschema({keyword:"oneOf",schemaProp:I},y);return s.mergeEvaluated(_,e.Name),y}function g(){var I;const y={},_=S(h);let k=!0;for(let x=0;x<m.length;x++){let N=m[x];if(N?.$ref&&!(0,o.schemaHasRulesButRef)(N,p.self.RULES)){const z=N.$ref;if(N=r.resolveRef.call(p.self,p.schemaEnv.root,p.baseId,z),N instanceof r.SchemaEnv&&(N=N.schema),N===void 0)throw new n.default(p.opts.uriResolver,p.baseId,z)}const U=(I=N?.properties)===null||I===void 0?void 0:I[f];if(typeof U!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${f}"`);k=k&&(_||S(N)),E(U,x)}if(!k)throw new Error(`discriminator: "${f}" must be required`);return y;function S({required:x}){return Array.isArray(x)&&x.includes(f)}function E(x,N){if(x.const)R(x.const,N);else if(x.enum)for(const U of x.enum)R(U,N);else throw new Error(`discriminator: "properties/${f}" must have "const" or "enum"`)}function R(x,N){if(typeof x!="string"||x in y)throw new Error(`discriminator: "${f}" values must be unique strings`);y[x]=N}}}};return Ji.default=i,Ji}const w$={$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 mv;function gv(){return mv||(mv=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=jE(),n=_$(),o=v$(),a=w$,i=["/properties"],s="http://json-schema.org/draft-07/schema";class l extends r.default{_addVocabularies(){super._addVocabularies(),n.default.forEach(f=>this.addVocabulary(f)),this.opts.discriminator&&this.addKeyword(o.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const f=this.opts.$data?this.$dataMetaSchema(a,i):a;this.addMetaSchema(f,s,!1),this.refs["http://json-schema.org/schema"]=s}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(s)?s:void 0)}}t.Ajv=l,e.exports=t=l,e.exports.Ajv=l,Object.defineProperty(t,"__esModule",{value:!0}),t.default=l;var c=ui();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return c.KeywordCxt}});var u=Oe();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var h=ed();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return h.default}});var p=hi();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return p.default}})})(oi,oi.exports)),oi.exports}var b$=gv();const k$=Hl(b$);var Gi={exports:{}},sd={},_v;function T$(){return _v||(_v=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(x,N){return{validate:x,compare:N}}e.fullFormats={date:t(a,i),time:t(l(!0),c),"date-time":t(p(!0),m),"iso-time":t(l(),u),"iso-date-time":t(p(),f),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:C,"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:R,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:g,int32:{type:"number",validate:_},int64:{type:"number",validate:k},float:{type:"number",validate:S},double:{type:"number",validate:S},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,m),"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,f),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(x){return x%4===0&&(x%100!==0||x%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 a(x){const N=n.exec(x);if(!N)return!1;const U=+N[1],z=+N[2],ee=+N[3];return z>=1&&z<=12&&ee>=1&&ee<=(z===2&&r(U)?29:o[z])}function i(x,N){if(x&&N)return x>N?1:x<N?-1:0}const s=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function l(x){return function(U){const z=s.exec(U);if(!z)return!1;const ee=+z[1],Q=+z[2],se=+z[3],re=z[4],Se=z[5]==="-"?-1:1,H=+(z[6]||0),D=+(z[7]||0);if(H>23||D>59||x&&!re)return!1;if(ee<=23&&Q<=59&&se<60)return!0;const B=Q-D*Se,F=ee-H*Se-(B<0?1:0);return(F===23||F===-1)&&(B===59||B===-1)&&se<61}}function c(x,N){if(!(x&&N))return;const U=new Date("2020-01-01T"+x).valueOf(),z=new Date("2020-01-01T"+N).valueOf();if(U&&z)return U-z}function u(x,N){if(!(x&&N))return;const U=s.exec(x),z=s.exec(N);if(U&&z)return x=U[1]+U[2]+U[3],N=z[1]+z[2]+z[3],x>N?1:x<N?-1:0}const h=/t|\s/i;function p(x){const N=l(x);return function(z){const ee=z.split(h);return ee.length===2&&a(ee[0])&&N(ee[1])}}function m(x,N){if(!(x&&N))return;const U=new Date(x).valueOf(),z=new Date(N).valueOf();if(U&&z)return U-z}function f(x,N){if(!(x&&N))return;const[U,z]=x.split(h),[ee,Q]=N.split(h),se=i(U,ee);if(se!==void 0)return se||c(z,Q)}const b=/\/|:/,w=/^(?:[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 C(x){return b.test(x)&&w.test(x)}const v=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function g(x){return v.lastIndex=0,v.test(x)}const I=-2147483648,y=2**31-1;function _(x){return Number.isInteger(x)&&x<=y&&x>=I}function k(x){return Number.isInteger(x)}function S(){return!0}const E=/[^\\]\\Z/;function R(x){if(E.test(x))return!1;try{return new RegExp(x),!0}catch{return!1}}})(sd)),sd}var id={},yv;function C$(){return yv||(yv=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;const t=gv(),r=Oe(),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}},a={message:({keyword:s,schemaCode:l})=>(0,r.str)`should be ${o[s].okStr} ${l}`,params:({keyword:s,schemaCode:l})=>(0,r._)`{comparison: ${o[s].okStr}, limit: ${l}}`};e.formatLimitDefinition={keyword:Object.keys(o),type:"string",schemaType:"string",$data:!0,error:a,code(s){const{gen:l,data:c,schemaCode:u,keyword:h,it:p}=s,{opts:m,self:f}=p;if(!m.validateFormats)return;const b=new t.KeywordCxt(p,f.RULES.all.format.definition,"format");b.$data?w():C();function w(){const g=l.scopeValue("formats",{ref:f.formats,code:m.code.formats}),I=l.const("fmt",(0,r._)`${g}[${b.schemaCode}]`);s.fail$data((0,r.or)((0,r._)`typeof ${I} != "object"`,(0,r._)`${I} instanceof RegExp`,(0,r._)`typeof ${I}.compare != "function"`,v(I)))}function C(){const g=b.schema,I=f.formats[g];if(!I||I===!0)return;if(typeof I!="object"||I instanceof RegExp||typeof I.compare!="function")throw new Error(`"${h}": format "${g}" does not define "compare" function`);const y=l.scopeValue("formats",{key:g,ref:I,code:m.code.formats?(0,r._)`${m.code.formats}${(0,r.getProperty)(g)}`:void 0});s.fail$data(v(y))}function v(g){return(0,r._)`${g}.compare(${c}, ${u}) ${o[h].fail} 0`}},dependencies:["format"]};const i=s=>(s.addKeyword(e.formatLimitDefinition),s);e.default=i})(id)),id}var vv;function S$(){return vv||(vv=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r=T$(),n=C$(),o=Oe(),a=new o.Name("fullFormats"),i=new o.Name("fastFormats"),s=(c,u={keywords:!0})=>{if(Array.isArray(u))return l(c,u,r.fullFormats,a),c;const[h,p]=u.mode==="fast"?[r.fastFormats,i]:[r.fullFormats,a],m=u.formats||r.formatNames;return l(c,m,h,p),u.keywords&&(0,n.default)(c),c};s.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,h,p){var m,f;(m=(f=c.opts.code).formats)!==null&&m!==void 0||(f.formats=(0,o._)`require("ajv-formats/dist/formats").${p}`);for(const b of u)c.addFormat(b,h[b])}e.exports=t=s,Object.defineProperty(t,"__esModule",{value:!0}),t.default=s})(Gi,Gi.exports)),Gi.exports}var I$=S$();const x$=Hl(I$);function E$(){const e=new k$({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return x$(e),e}class $${constructor(t){this._ajv=t??E$()}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 R${constructor(t){this._client=t}async*callToolStream(t,r=Sa,n){const o=this._client,a={...n,task:n?.task??(o.isToolTask(t.name)?{}:void 0)},i=o.requestStream({method:"tools/call",params:t},r,a),s=o.getToolOutputValidator(t.name);for await(const l of i){if(l.type==="result"&&s){const c=l.result;if(!c.structuredContent&&!c.isError){yield{type:"error",error:new Ce($e.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`)};return}if(c.structuredContent)try{const u=s(c.structuredContent);if(!u.valid){yield{type:"error",error:new Ce($e.InvalidParams,`Structured content does not match the tool's output schema: ${u.errorMessage}`)};return}}catch(u){if(u instanceof Ce){yield{type:"error",error:u};return}yield{type:"error",error:new Ce($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 P$(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 M$(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 Wi(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 a=n[o];r[o]===void 0&&Object.prototype.hasOwnProperty.call(a,"default")&&(r[o]=a.default),r[o]!==void 0&&Wi(a,r[o])}}if(Array.isArray(e.anyOf))for(const r of e.anyOf)typeof r!="boolean"&&Wi(r,t);if(Array.isArray(e.oneOf))for(const r of e.oneOf)typeof r!="boolean"&&Wi(r,t)}}function O$(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 Ki extends xE{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 $$,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",au,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",ou,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 R$(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=EE(this._capabilities,t)}setRequestHandler(t,r){const o=B_(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let a;if(ni(o)){const s=o;a=s._zod?.def?.value??s.value}else{const s=o;a=s._def?.value??s.value}if(typeof a!="string")throw new Error("Schema method literal must be a string");const i=a;if(i==="elicitation/create"){const s=async(l,c)=>{const u=bn(lu,l);if(!u.success){const v=u.error instanceof Error?u.error.message:String(u.error);throw new Ce($e.InvalidParams,`Invalid elicitation request: ${v}`)}const{params:h}=u.data;h.mode=h.mode??"form";const{supportsFormMode:p,supportsUrlMode:m}=O$(this._capabilities.elicitation);if(h.mode==="form"&&!p)throw new Ce($e.InvalidParams,"Client does not support form-mode elicitation requests");if(h.mode==="url"&&!m)throw new Ce($e.InvalidParams,"Client does not support URL-mode elicitation requests");const f=await Promise.resolve(r(l,c));if(h.task){const v=bn(Ta,f);if(!v.success){const g=v.error instanceof Error?v.error.message:String(v.error);throw new Ce($e.InvalidParams,`Invalid task creation result: ${g}`)}return v.data}const b=bn(cu,f);if(!b.success){const v=b.error instanceof Error?b.error.message:String(b.error);throw new Ce($e.InvalidParams,`Invalid elicitation result: ${v}`)}const w=b.data,C=h.mode==="form"?h.requestedSchema:void 0;if(h.mode==="form"&&w.action==="accept"&&w.content&&C&&this._capabilities.elicitation?.form?.applyDefaults)try{Wi(C,w.content)}catch{}return w};return super.setRequestHandler(t,s)}if(i==="sampling/createMessage"){const s=async(l,c)=>{const u=bn(su,l);if(!u.success){const w=u.error instanceof Error?u.error.message:String(u.error);throw new Ce($e.InvalidParams,`Invalid sampling request: ${w}`)}const{params:h}=u.data,p=await Promise.resolve(r(l,c));if(h.task){const w=bn(Ta,p);if(!w.success){const C=w.error instanceof Error?w.error.message:String(w.error);throw new Ce($e.InvalidParams,`Invalid task creation result: ${C}`)}return w.data}const f=h.tools||h.toolChoice?fg:iu,b=bn(f,p);if(!b.success){const w=b.error instanceof Error?b.error.message:String(b.error);throw new Ce($e.InvalidParams,`Invalid sampling result: ${w}`)}return b.data};return super.setRequestHandler(t,s)}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:Ls,capabilities:this._capabilities,clientInfo:this._clientInfo}},Q2,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!RS.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){P$(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&M$(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},Kn,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},mg,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},Kn,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},cg,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},lg,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},og,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},ag,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},sg,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},Kn,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},Kn,r)}async callTool(t,r=Sa,n){if(this.isToolTaskRequired(t.name))throw new Ce($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),a=this.getToolOutputValidator(t.name);if(a){if(!o.structuredContent&&!o.isError)throw new Ce($e.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`);if(o.structuredContent)try{const i=a(o.structuredContent);if(!i.valid)throw new Ce($e.InvalidParams,`Structured content does not match the tool's output schema: ${i.errorMessage}`)}catch(i){throw i instanceof Ce?i:new Ce($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},dg,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,o){const a=TI.safeParse(n);if(!a.success)throw new Error(`Invalid ${t} listChanged options: ${a.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${t} listChanged options: onChanged must be a function`);const{autoRefresh:i,debounceMs:s}=a.data,{onChanged:l}=n,c=async()=>{if(!i){l(null,null);return}try{const h=await o();l(null,h)}catch(h){const p=h instanceof Error?h:new Error(String(h));l(p,null)}},u=()=>{if(s){const h=this._listChangedDebounceTimers.get(t);h&&clearTimeout(h);const p=setTimeout(c,s);this._listChangedDebounceTimers.set(t,p)}else c()};this.setNotificationHandler(r,u)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}const A$="mcp";class wv{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,A$),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=Wn.parse(JSON.parse(n.data))}catch(a){this.onerror?.(a);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 jo=Or;(function(e,t){const r=Or,n=Or,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())}})(Yi,-118057+3521*-35+-2099*-233);const N$=()=>{const e=Or,t=Or,r={};r[e(420)]="3|0|2|1|4",r.vQYJZ=function(i,s){return i!==s},r[t(394)]=t(414),r.ktWqD=function(i,s){return i!==s},r[e(424)]=e(391);const n=r,o=n[t(420)].split("|");let a=859*2+-3*-1039+-4835*1;for(;;){switch(o[a++]){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}},q$=(e,t,r)=>{const n=Or,o=Or,a={};a.eOzBp=function(s,l){return s!==l},a.ooaJk="undefined",a[n(402)]=function(s,l){return s===l},a[n(421)]="function";const i=a;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 bv{constructor(t){this._port=t}async[jo(401)](){const t=jo,r=jo;this[t(422)]&&(this[r(422)].onmessage=n=>{var o,a;const i=t;try{const s=Wn.parse(n.data.message);(o=this.onmessage)==null||o.call(this,s,n[i(412)][i(428)])}catch(s){const l=new Error("MessageChannel failed to parse message: "+s);(a=this[i(383)])==null||a.call(this,l)}},this._port.onmessageerror=n=>{var o;const a=r,i=new Error("MessageChannel transport error: "+JSON[a(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,a){return o instanceof a},cDUwk:function(o,a){return o(a)}};return new Promise((o,a)=>{var i;const s=Or,l=Or;try{const c={};c[s(404)]=r?.[s(404)];const u={};u[s(392)]=t,u.extra=c,this._port&&this._port[l(423)](u),n[s(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),a(u)}})}async close(){var t,r;const n=jo,o=jo;(t=this._port)==null||t[n(393)](),this[n(422)]=void 0,(r=this[o(408)])==null||r.call(this)}}class L$ extends bv{constructor(t,r=N$()){const n=jo,o={lSpBh:function(i,s,l,c){return i(s,l,c)}};super(),this._endpoint=t,this._globalObject=r;const a=new MessageChannel;this._port=a[n(410)],o[n(418)](q$,this._globalObject,{endpoint:this[n(397)]},[a[n(429)]])}}function Yi(){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 Yi=function(){return e},Yi()}function Or(e,t){const r=Yi();return Or=function(n,o){return n=n-(17227+1*-16844),r[n]},Or(e,t)}(function(e,t){const r=Ke,n=Ke,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())}})(Qi,-411935*1+228107+208149*2);const j$=async(e,t,r)=>{var n;const o=Ke,a=Ke,i={};i.VRyiJ="tools/list",i.VkPYu="tools/call",i[o(475)]=o(411),i.SoCaE="resources/templates/list",i[a(484)]="resources/read",i[o(461)]="prompts/get",i.srIIC=a(477),i[a(436)]=a(478),i[a(442)]=o(437),i.dEmVs=o(465);const s=i,{id:l,method:c,params:u}=r;let h={};switch(c){case s.VRyiJ:h=await t.listTools(u);break;case s.VkPYu:h=await t.callTool(u);break;case s.fgMSD:h=await t.listResources(u);break;case s[a(466)]:h=await t.listResourceTemplates(u);break;case s.sthgI:h=await t[o(455)](u);break;case a(486):h=await t.subscribeResource(u);break;case o(410):h=await t.unsubscribeResource(u);break;case s[a(461)]:h=await t[a(414)](u);break;case s[o(412)]:h=await t[o(491)](u);break;case s[o(436)]:h=await t[o(478)]();break;case s.kkNqg:h=await t.complete(u);break;case o(464):h=await t.setLoggingLevel(u?.[a(443)]);break}const p={};p.result=h,p.jsonrpc=s[a(472)],p.id=l,await((n=e?.[a(488)])==null?void 0:n[o(460)](p))},D$=async(e,t,r)=>{var n;const o=Ke,a=Ke,i={};i[o(487)]=a(462),i.ypHTC="ping",i.fPExS=o(465);const s=i,{id:l,method:c,params:u}=r;let h={};switch(c){case"roots/list":const m={};m.method=c,m[a(446)]=u,h=await t[o(469)](m,_g);break;case"sampling/createMessage":const f={};f[o(481)]=c,f[o(446)]=u,h=await t.request(f,iu);break;case s[o(487)]:const b={};b.method=c,b[a(446)]=u,h=await t.request(b,cu);break;case s.ypHTC:const w={};w.method=c,h=await t.request(w,Kn);break}const p={};return p.result=h,p.jsonrpc=s.fPExS,p.id=l,await((n=e?.transport)==null?void 0:n.send(p)),h};function Ke(e,t){const r=Qi();return Ke=function(n,o){return n=n-(-8023+4*-2344+-17809*-1),r[n]},Ke(e,t)}const U$=(e,t)=>{const r=Ke,n=Ke,o={vYlhn:function(i,s){return i===s},DhPFX:r(470),NYVNC:function(i,s,l,c){return i(s,l,c)},yfZbw:"2.0"},a=e._onrequest;e[n(463)]=async(i,s)=>{var l,c,u,h,p;const m=n,f=r,{id:b,method:w}=i;try{o[m(451)](w,o.DhPFX)?await a.call(e,i,s):await o[f(474)](j$,e,t,i)}catch(C){const{code:v,message:g,data:I}=C;try{if(v){const y={};y[f(485)]=v,y[m(422)]=g,y.data=I;const _={};_[f(448)]=y,_.jsonrpc=o[m(417)],_.id=b,await((l=e?.transport)==null?void 0:l[f(460)](_))}else(u=(c=e?.transport)==null?void 0:c.onerror)==null||u.call(c,C)}catch(y){(p=(h=e?.transport)==null?void 0:h.onerror)==null||p.call(h,y)}}}},z$=(e,t)=>{const r=Ke,n=Ke,o={};o[r(476)]=r(439),o[r(431)]=function(i,s){return i!==s},o.UPdQt="notifications/cancelled";const a=o;e[r(421)]=async i=>{var s,l;const c=r,u=n,{method:h,params:p}=i;if(h!==a[c(476)]&&(a.QWYMz(h,a.UPdQt)||p?.[u(490)]))try{await t[c(445)](i)}catch(m){(l=(s=e?.[c(488)])==null?void 0:s[c(480)])==null||l.call(s,m)}}},F$=(e,t)=>async r=>{var n,o,a,i,s;const l=Ke,c=Ke,u={TJhyV:function(h,p,m,f){return h(p,m,f)},MMNTY:l(465)};try{return await u.TJhyV(D$,e,t,r)}catch(h){const{code:p,message:m,data:f}=h;try{if(p){const b={};b.code=p,b[l(422)]=m,b[c(419)]=f;const w={};w[l(448)]=b,w[l(424)]=u.MMNTY,w.id=r.id,await((n=e?.transport)==null?void 0:n[c(460)](w))}else(a=(o=e?.transport)==null?void 0:o[l(480)])==null||a.call(o,h)}catch(b){(s=(i=e?.[l(488)])==null?void 0:i.onerror)==null||s.call(i,b)}}},V$=(e,t)=>async r=>{var n,o,a;const i=Ke,s=Ke,l={};l.xmcLM=function(p,m){return p!==m},l.xSWLt="notifications/initialized",l[i(420)]=s(453);const c=l,{method:u,params:h}=r;if(c.xmcLM(u,c.xSWLt)&&(c.xmcLM(u,c[s(420)])||h?.[s(490)]))try{const p={...r};p.jsonrpc=i(465),await((n=t?.[i(488)])==null?void 0:n.send(p))}catch(p){(a=(o=e?.transport)==null?void 0:o.onerror)==null||a.call(o,p)}};function Qi(){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 Qi=function(){return e},Qi()}const Z$=(e,t)=>async r=>{var n,o,a,i,s,l;const c=Ke,u=Ke,h={};h.kSvAZ=c(465);const p=h;try{await((n=t?.[u(488)])==null?void 0:n[u(460)](r))}catch(m){const{code:f,message:b,data:w}=m;try{if(f){const C={};C.code=f,C.message=b,C.data=w;const v={};v.error=C,v[u(424)]=p.kSvAZ,v.id=r.id,await((o=e?.transport)==null?void 0:o.send(v))}else(i=(a=e?.transport)==null?void 0:a[c(480)])==null||i.call(a,m)}catch(C){(l=(s=e?.[c(488)])==null?void 0:s[u(480)])==null||l.call(s,C)}}},ld=()=>{const e=Ke,t={rgPZO:function(l,c){return l!==c},VWsxO:function(l,c){return l(c)},FjTAY:"function"},r=[],n=(l,c)=>{const u=Ke;if(c){const h=[];for(const p of r)try{h.push(p(l,c))}catch{}for(const p of h)if(t.rgPZO(p,null))return p}else for(const h of r)try{t[u(427)](h,l)}catch{}},o=l=>{const c=Ke,u=Ke;typeof l===t[c(456)]&&!r.includes(l)&&r[u(471)](l)},a=l=>{const c=Ke,u=r[c(415)](l);u!==-1&&r.splice(u,-17591+6*2932)},i=()=>{const l=Ke;r[l(430)]=-505*7+1322+2213},s={};return s.handleListener=n,s[e(447)]=o,s.removeListener=a,s.clearListener=i,s},H$=e=>{const t=Ke,r=Ke,n={UlqiY:function(o){return o()},jsmFN:function(o){return o()}};{const{handleListener:o,addListener:a,removeListener:i,clearListener:s}=n[t(423)](ld);e._onresponse=o,e[r(438)]=a,e.removeResponseListener=i,e.clearResponseListener=s}{const{handleListener:o,addListener:a,removeListener:i,clearListener:s}=n[t(489)](ld);e[t(432)]=o,e[r(473)]=a,e.removeRequestListener=i,e.clearRequestListener=s}{const{handleListener:o,addListener:a,removeListener:i,clearListener:s}=n.jsmFN(ld);e.fallbackNotificationHandler=o,e[t(444)]=a,e.removeNotificationListener=i,e[r(426)]=s}},B$=(e,{beforeInit:t,afterInit:r}={})=>{const n=Ke,o=Ke,a={HucXo:function(s,l){return s===l},HicFO:n(468),JMaxV:function(s){return s()},DclXr:function(s,l){return s(l)},UynHf:function(s,l){return s===l},yCyFn:function(s){return s()}},i=new Map(e._notificationHandlers);e[n(454)].clear(),e._notificationHandlers.clear(),a.HucXo(typeof t,a.HicFO)&&a[n(435)](t),a[n(467)](e[n(449)][o(428)],n(449))&&(e[o(413)]=e[o(449)]),a.DclXr(H$,e),e[o(438)](s=>{const l=n;e.originalOnResponse[l(440)](e,s)}),a[n(429)](typeof r,a.HicFO)&&a[o(425)](r),e[o(444)](s=>{const l=o,{method:c}=s,u=i[l(483)](c);a[l(467)](typeof u,"function")&&u(s)})},J$=an;(function(e,t){const r=an,n=an,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())}})(Xi,995159+-6*-266138+-1619768);const G$=()=>{const e=an,t=an,r={};r.svuxn=function(o,a){return o&a},r.ZUPdr=function(o,a){return o===a},r[e(227)]=function(o,a){return o===a},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 a=e,i=n.svuxn(crypto.getRandomValues(new Uint8Array(-3798+8571*-1+12370))[0],-8324+8339*1);return(n[a(225)](o,"x")?i:n[a(209)](i,-12998+-1*-13001)|813*10+-3707+883*-5).toString(-1*-1851+6493+-8328)})},W$=e=>{const t=an,r=an,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)]("")},Cn={};Cn[J$(211)]=G$,Cn.randomBytes=W$;function an(e,t){const r=Xi();return an=function(n,o){return n=n-(-7373+7187*1+395),r[n]},an(e,t)}function Xi(){const e=["join","2500590yHdCUG","3CzpgOE","219762yRRBUK","592022JqIdxi","from","6033730pSHJFF","28gKZiuO","getRandomValues","147169GUBreL","5fFOMNB","1140KVOWlq","ZUPdr","toString","DBGzc","45351XtLuDF","svuxn","9892WpQPGF","randomUUID","2504EaskHQ"];return Xi=function(){return e},Xi()}function sn(e,t){const r=el();return sn=function(n,o){return n=n-(-1483*3+-5564+20*513),r[n]},sn(e,t)}const Ar=sn,La=sn;(function(e,t){const r=sn,n=sn,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())}})(el,-4*308317+753182*2+658196);const K$=(e,t)=>{const r=sn,n=sn,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)](U$,e,t),z$(e,t);const a=o[n(283)](F$,t,e),i=o[n(294)](Z$,t,e),s=o[r(277)](V$,t,e);t.addRequestListener(a),t.addResponseListener(i),t[n(287)](s),e.onclose=()=>{const l=r,c=n;t[l(247)](a),t.removeResponseListener(i),t[c(252)](s)}},cd=(e,t,r)=>{const n={QhPqi:function(i,s){return i instanceof s},AIICR:"close",Qalmc:function(i,s,l){return i(s,l)}},o=()=>{var i;n.QhPqi(r,Ys)&&((i=r._eventSource)==null||i.addEventListener(n.AIICR,()=>{var s;(s=r[sn(295)])==null||s.close()})),n.Qalmc(K$,e,t)},a={};a.afterInit=o,n.Qalmc(B$,t,a)},kv=(e,t=Cn[Ar(299)]())=>{const r=Ar,n=Ar,o={RVabx:function(u,h,p){return u(h,p)},crCTs:"include"},a={};a["sse-session-id"]=t;const i=a,s={};s["sse-session-id"]=t;const l={};l.headers=s,l.credentials=o[r(304)];const c={requestInit:l,eventSourceInit:{async fetch(u,h){const p=r,m=r,f=new Headers(h?.[p(268)]||{});Object.entries(i).forEach(([w,C])=>{f.set(w,C)});const b={...h};return b.headers=f,o[m(279)](fetch,u,b)},withCredentials:!0}};return e&&(c[r(280)].headers.Authorization="Bearer "+e,i.Authorization=n(256)+e),c},Tv=(e,t=Cn[Ar(299)]())=>{const r=La,n=Ar,o={};o[r(271)]="include";const a=o,i={};i["stream-session-id"]=t;const s={};s[n(268)]=i,s.credentials=a[r(271)];const l={};l.requestInit=s;const c=l;return e&&(c[n(280)][r(268)][n(301)]=r(256)+e),c},ud=async(e,t,r)=>{const n=Ar,o=Ar,a={rRtFD:function(s){return s()},ToRAF:function(s,l){return s instanceof l}},i=a[n(276)](r);try{return await e[o(260)](i),i}catch(s){if(a[n(275)](s,kr)){const l=await t();return await i[n(257)](l),await ud(e,t,r)}else throw s}},Cv=(e,t)=>{const r=La,n=La,o={};o[r(267)]=function(i,s){return i in s},o.timcZ="waitForOAuthCode",o[r(253)]=function(i,s){return i===s},o.ufiEQ=r(285),o[n(250)]=r(293);const a=o;if(a.oGmBG(a[r(258)],e))return e[n(278)];if(a[n(253)](typeof t,a.ufiEQ))return t;throw new Error(a.daYBw)};function el(){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 el=function(){return e},el()}const Y$=async e=>{const t=La,r=Ar,n={GKDjq:function(E,R,x){return E(R,x)},JzpWy:t(281),mcbiU:"1.0.0",CfBXU:function(E){return E()},kdowC:function(E,R,x,N){return E(R,x,N)},KkViY:"sessionId"},{client:o,url:a,token:i,sessionId:s,authProvider:l,requestInit:c,eventSourceInit:u,waitForOAuthCode:h}=e,p={};p[r(305)]=l,p.requestInit=c,p.eventSourceInit=u;const m=p,f=s||Cn[r(299)](),b=n[t(289)](kv,i,f);if(c){const E={...b.requestInit,...c};E[r(268)]={...b[r(280)][t(268)],...c.headers},m.requestInit=E}else m.requestInit=b[t(280)];if(u){const E={...b[t(270)],...u};m.eventSourceInit=E}else m.eventSourceInit=b[t(270)];const w={};w[t(254)]=!0;const C={};C.roots=w,C[t(298)]={},C[r(303)]={};const v=C,g={};g.name=n[r(261)],g[t(288)]=n.mcbiU;const I={};I[t(251)]=v;const y=new Ki(g,I),_=()=>new Ys(new URL(a),m);let k=n[t(282)](_);if(l){const E=Cv(l,h);k=await n[t(263)](ud,y,E,_)}else await y.connect(k);cd(y,o,k),k.sessionId=k[r(274)].searchParams[t(297)](n.KkViY);const S={};return S.transport=k,S.sessionId=k[r(286)],S},Q$=async e=>{const t=La,r=Ar,n={wfHUn:function(E,R,x){return E(R,x)},tUMle:"mcp-stream-proxy-client",omKPe:t(248),rSiEq:function(E){return E()},PdsSn:function(E,R,x,N){return E(R,x,N)}},{client:o,url:a,token:i,sessionId:s,authProvider:l,requestInit:c,reconnectionOptions:u,waitForOAuthCode:h}=e,p={};p.authProvider=l,p.requestInit=c,p.reconnectionOptions=u;const m=p,f=s||Cn.randomUUID(),b=n[r(272)](Tv,i,f);if(c){const E={...b[t(280)],...c};E.headers={...b.requestInit[t(268)],...c.headers},m.requestInit=E}else m[r(280)]=b[r(280)];const w={};w[r(254)]=!0;const C={};C.roots=w,C[t(298)]={},C[t(303)]={};const v=C,g={};g.name=n[t(262)],g.version=n.omKPe;const I={};I.capabilities=v;const y=new Ki(g,I),_=()=>new Js(new URL(a),m);let k=n.rSiEq(_);if(l){const E=n[t(272)](Cv,l,h);k=await n[t(296)](ud,y,E,_)}else await y[t(260)](k);n.PdsSn(cd,y,o,k);const S={};return S.transport=k,S[r(286)]=k[r(286)],S},X$=async e=>{const t=Ar,r=Ar,n={eZwNI:function(C,v,g,I){return C(v,g,I)}},{client:o,url:a,token:i,sessionId:s}=e,l={};l[t(254)]=!0;const c={};c[r(290)]=l,c.sampling={},c.elicitation={};const u=c,h={};h.name="mcp-socket-proxy-client",h.version=r(248);const p={};p[r(251)]=u;const m=new Ki(h,p),f=s||Cn[r(299)](),b=new wv(new URL(a+"?sessionId="+f+r(265)+i));await m.connect(b),n[t(259)](cd,m,o,b);const w={};return w.transport=b,w[r(286)]=f,w},Sn=Nr,ja=Nr;(function(e,t){const r=Nr,n=Nr,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())}})(tl,1297719+-42747*-22+-1289197);function Nr(e,t){const r=tl();return Nr=function(n,o){return n=n-(-4158*1+-2*581+-1*-5510),r[n]},Nr(e,t)}const eR=()=>Cn.randomBytes(-8746+-382*-23);class rP{constructor(t){const r=Nr,n=Nr,o={HbwOh:function(u){return u()}};this._callBackPromise={};const{clientMetadata:a,state:i,redirectCallback:s,getAuthCodeByState:l,waitForOAuthCode:c}=t;this._clientMetadata=a,this[r(206)]=a.redirect_uris[-10*629+1*7646+-1356],this[n(197)]=i||o.HbwOh(eR),this._redirectCallback=s||this[n(202)],this[n(195)]=l||this[r(191)],this.waitForOAuthCode=c||this.waitForOAuthCodeFunction()}async redirectCallbackFunction(t){var r,n,o,a,i,s;const l=Nr,c=Nr,u={};u[l(198)]="GET";const h=await fetch(t,u);!h.ok&&((n=(r=this[c(207)])[c(196)])==null||n.call(r,l(208)+h[c(205)]));const p=await this[c(195)](this._redirectUrl,this[l(197)]);if(!p.ok){(a=(o=this[l(207)]).reject)==null||a.call(o,"Failed to fetch auth code: "+p[c(205)]);return}const m=await p.json();(s=(i=this._callBackPromise).resolve)==null||s.call(i,m.code)}async[Sn(191)](t,r){const n=Sn,o={};o.xAOmI="POST";const a=o,i={};i["Content-Type"]=n(217);const s={};return s.state=r,fetch(t,{method:a.xAOmI,headers:i,body:new URLSearchParams(s)})}waitForOAuthCodeFunction(){const t=this._callBackPromise;return()=>new Promise((r,n)=>{const o=Nr;t.resolve=r,t[o(196)]=n})}get redirectUrl(){return this[Sn(206)]}get[ja(190)](){return this._clientMetadata}[Sn(213)](){return this[Sn(197)]}[ja(218)](){return this[ja(200)]}[Sn(194)](t){this._clientInformation=t}tokens(){return this[ja(210)]}saveTokens(t){const r=ja;this[r(210)]=t}redirectToAuthorization(t){this._redirectCallback(t)}saveCodeVerifier(t){this._codeVerifier=t}[Sn(212)](){const t=Sn,r={};r[t(215)]=t(214);const n=r;if(!this[t(209)])throw new Error(n.mMdVl);return this[t(209)]}}function tl(){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 tl=function(){return e},tl()}(function(e,t){for(var r=nl,n=nl,o=e();;)try{var a=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(a===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(rl,262*-2438+1346066*-1+2*1373311);function rl(){var e=["279100FsqxFu","7326315yxcNFg","50823VTWXXj","6441948uoPUwt","92BSiBRu","1361711dyawqa","5202960gnlAWp","7tNVFlv","11056792usEcvw","90CRWXmt"];return rl=function(){return e},rl()}function nl(e,t){var r=rl();return nl=function(n,o){n=n-287;var a=r[n];return a},nl(e,t)}const tR=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 a=t();if(a&&a.listTools){const s=(await a.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:s}})}else await e.send({jsonrpc:"2.0",id:n,result:{tools:[]}})}else if(o==="tools/call"){const a=t();if(a&&a.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:s}=r.params,l=await a.executeTool(i,JSON.stringify(s||{})),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(a){n!==void 0&&await e.send({jsonrpc:"2.0",id:n,error:{code:a.code||-32e3,message:a.message||String(a)}})}}};class rR{constructor(t,r){const n={name:"web-mcp-client",version:"1.0.0"},o={roots:{listChanged:!0},sampling:{},elicitation:{}};this.client=new Ki(t||n,r||{capabilities:o}),this.client.onclose=()=>{this.onclose?.()},this.client.onerror=a=>{this.onerror?.(a)}}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:a,agent:i,builtin:s,onError:l}=t;if(i){const h={client:this.client,url:r,token:n,sessionId:o},p=a==="sse"?await Y$(h):a==="socket"?await X$(h):await Q$(h);return p.transport.onerror=async m=>{l?.(m)},s&&tR(p.transport),p}const c=new URL(r);let u;if(a==="channel"&&(u=new L$(r),await this.client.connect(u)),a==="sse"){const h=kv(n,o);u=new Ys(c,h),await this.client.connect(u)}if(a==="socket"&&(u=new wv(new URL(`${r}?sessionId=${o}&token=${n}`)),u.sessionId=o,await this.client.connect(u)),a==="stream"||typeof u>"u"){const h=Tv(n,o);u=new Js(c,h),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,Sa,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(lu,t)}onCreateMessage(t){this.client.setRequestHandler(su,t)}onListRoots(t){this.client.setRequestHandler(gg,t)}onToolListChanged(t){this.client.setNotificationHandler(au,t)}onPromptListChanged(t){this.client.setNotificationHandler(ou,t)}onResourceListChanged(t){this.client.setNotificationHandler(Xc,t)}onResourceUpdated(t){this.client.setNotificationHandler(ig,t)}onLoggingMessage(t){this.client.setNotificationHandler(hg,t)}async onPagehide(t){t.persisted||(nR(this.transport)?await this.transport.terminateSession():this.transport&&typeof this.transport.close=="function"&&await this.transport.close())}}const nR=e=>e instanceof Js,Sv=async e=>{const t={};try{const r=await e.listTools();for(const{name:n,description:o,inputSchema:a}of r.tools){const i=async(s,l)=>e.callTool({name:n,arguments:s},{signal:l?.abortSignal});t[n]=Zl({description:o,inputSchema:Vn({...a,properties:a.properties??{},additionalProperties:!1}),execute:i})}return t}catch(r){throw r}},oR=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),a=Array.isArray(o)?o:[];for(const i of a){const{name:s,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 h={type:"object",properties:u.properties??{},...u.required?{required:u.required}:{},additionalProperties:!1,...u};t[s]=Zl({description:l??"",inputSchema:Vn(h),async execute(p){if(!r.executeTool)throw new Error("navigator.modelContextTesting.executeTool is not available");return r.executeTool(s,JSON.stringify(p??{}))}})}return t};function aR(e){const t=Object.entries(e);if(t.length===0)return"";let r=`
|
|
88
96
|
# 工具调用
|
|
89
97
|
|
|
90
98
|
你可以根据需要调用以下工具:
|
|
91
99
|
|
|
92
100
|
<tools>
|
|
93
|
-
`;return t.forEach(([n,o])=>{const
|
|
101
|
+
`;return t.forEach(([n,o])=>{const a=o,i=a.description||"无描述",s=a.parameters||a.inputSchema||{};r+=`${JSON.stringify({name:n,description:i,parameters:s},null,2)}
|
|
94
102
|
`}),r+=`
|
|
95
103
|
</tools>
|
|
96
104
|
|
|
@@ -120,23 +128,23 @@ Thought: 用户想要获取今天的日期,我需要调用日期相关的工
|
|
|
120
128
|
- 必须严格按照 XML 格式调用工具
|
|
121
129
|
- arguments 必须是有效的 JSON 格式
|
|
122
130
|
- 如果不需要调用工具,直接给出最终答案即可
|
|
123
|
-
`,r}function
|
|
124
|
-
${o}`}async _executeReActToolCall(t,r,n){const o=n[t];if(!o)return{success:!1,error:`工具 ${t} 不存在`};try{const
|
|
125
|
-
${
|
|
126
|
-
</tool_response>`};l.push(
|
|
127
|
-
${
|
|
128
|
-
</tool_response>`;
|
|
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:tc(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(oc,t)}}var xo={},ju,xy;function $E(){return xy||(xy=1,ju=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),ju}var Du={},gn={},Ey;function Jn(){if(Ey)return gn;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 gn.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},gn.getSymbolTotalCodewords=function(n){return t[n]},gn.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},gn.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');e=n},gn.isKanjiModeEnabled=function(){return typeof e<"u"},gn.toSJIS=function(n){return e(n)},gn}var Uu={},$y;function zu(){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}}})(Uu)),Uu}var Fu,Ry;function RE(){if(Ry)return Fu;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++}},Fu=e,Fu}var Vu,Py;function PE(){if(Py)return Vu;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]},Vu=e,Vu}var Zu={},My;function ME(){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}})(Zu)),Zu}var Bu={},Ny;function NE(){if(Ny)return Bu;Ny=1;const e=Jn().getSymbolSize,t=7;return Bu.getPositions=function(n){const o=e(n);return[[0,0],[o-t,0],[0,o-t]]},Bu}var Hu={},Oy;function OE(){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}})(Hu)),Hu}var Hi={},Ay;function qy(){if(Ay)return Hi;Ay=1;const e=zu(),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 Ju={},Es={},Ly;function AE(){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 qE(){return jy||(jy=1,(function(e){const t=AE();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}})(Ju)),Ju}var Wu,Dy;function LE(){if(Dy)return Wu;Dy=1;const e=qE();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 Gu={},Ku={},Yu={},Uy;function zy(){return Uy||(Uy=1,Yu.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),Yu}var jr={},Fy;function Vy(){if(Fy)return jr;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
|
-
]))+`;
|
|
131
|
-
Make sure your charset is UTF-8`);
|
|
132
|
-
Suggested mode is: `+t.toString(
|
|
131
|
+
`,r}function Iv(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),a=o.name||o.action||o.tool,i=o.arguments||o.args||o.input||{};if(a&&t[a])return{toolName:a,arguments:i}}catch{}return null}const sR={openai:Qg,deepseek:H_};class iR{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=sR[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:()=>oR(o),close:async()=>{}}}if("type"in t&&t.type.toLocaleLowerCase()==="streamablehttp"){const o=t,a=o.headers?{headers:o.headers}:void 0;r=new Js(new URL(o.url),{requestInit:a})}else if("type"in t&&t.type==="sse"){const o=t,a=o.headers?{headers:o.headers}:void 0;r=new Ys(new URL(o.url),{requestInit:a})}else"type"in t&&t.type==="extension"?r=new CE(t.sessionId):"transport"in t?r=t.transport:r=t;if(t.useAISdkClient??!1){const o=await ES({transport:r});return o.__transport__=r,o}else{const o=new rR({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 Qs||r&&r instanceof bv)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 a=await this._createOneClient(o);return{serverName:n,client:a}}));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 Sv(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 a=await this._getClientTools(o,n);return{serverName:n,tools:a}}));this.mcpTools={},r.forEach(({serverName:n,tools:o})=>{const a=o&&typeof o=="object"?o:{};this.mcpTools[n]=a})}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(a=>a!==o)}),this.onUpdatedTools?.()}_tempMergeTools(t={},r=!0){const n=Object.values(this.mcpTools).reduce((o,a)=>({...o,...a}),{});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=aR(t);return n?`${n}${o}`:`你是一个智能助手,可以通过调用工具来完成任务。
|
|
132
|
+
${o}`}async _executeReActToolCall(t,r,n){const o=n[t];if(!o)return{success:!1,error:`工具 ${t} 不存在`};try{const a=o,i=a.execute||a.call;return typeof i!="function"?{success:!1,error:`工具 ${t} 没有可执行的函数`}:{success:!0,result:await i(r,{})}}catch(a){return{success:!1,error:a?.message||String(a)||"工具执行失败"}}}async _chatReAct(t,{model:r,maxSteps:n=5,...o}){if(!this.llm)throw new Error("LLM is not initialized");await this.initClientsAndTools();const a=this._tempMergeTools(o.tools);if(Object.keys(a).length===0)return this._chat(t,{model:r,maxSteps:n,...o});let s=[];o.message&&!o.messages?s.push({role:"user",content:o.message}):o.messages?s=[...o.messages]:s=[...this.responseMessages];const l=typeof r=="string"?r:r?.modelId||"default-model",u={role:"system",content:this._generateReActSystemPrompt(a,l,o.system)},h=s[0]?.role==="system"?s:[u,...s];return t===Ec?this._chatReActStream(h,a,l,n,o):this._chatReActNonStream(h,a,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 a=0;const i=[];for(let s=r.length-1;s>=0;s--){const l=r[s];if(this._messageHasImage(l.content))if(a<n)i.unshift(l),a++;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,a){let i=[...t];const s=t[0]?.role==="system"?t[0]:null,l=s?t.slice(1):t;let c=0;const u=a.maxImages??3;for(;c<o;){c++;const p=this._buildMessagesForModel(s,l,u),{tools:m,...f}=a,w=(await s2({model:this.llm(n),messages:p,...f})).text,C={role:"assistant",content:w};l.push(C),i.push(C);const v=Iv(w,r);if(!v)return this.responseMessages=i,{text:w,response:{messages:i}};const g=await this._executeReActToolCall(v.toolName,v.arguments,r),_={role:"user",content:`<tool_response>
|
|
133
|
+
${g.success?JSON.stringify(g.result):`工具执行失败 - ${g.error}`}
|
|
134
|
+
</tool_response>`};l.push(_),i.push(_)}return this.responseMessages=i,{text:i[i.length-2]?.content||"",response:{messages:i}}}_chatReActStream(t,r,n,o,a){const i=this,s=this.llm(n);let l,c;const u=new Promise((p,m)=>{l=p,c=m});return{fullStream:new ReadableStream({async start(p){let m=[...t];const f=t[0]?.role==="system"?t[0]:null,b=f?t.slice(1):[...t];let w=0,C="";const v=a.maxImages??3;p.enqueue({type:"start"}),p.enqueue({type:"start-step"});try{for(;w<o;){w++;const g=i._buildMessagesForModel(f,b,v),{tools:I,...y}=a;delete y.system,delete y.onFinish;const _=await Ec({...y,model:s,messages:g});let k="";for await(const Q of _.fullStream)Q.type==="text-delta"?(k+=Q.text||"",p.enqueue({type:"text-delta",text:Q.text})):Q.type==="text-start"?p.enqueue({type:"text-start"}):Q.type==="text-end"||Q.type==="finish-step"||Q.type==="finish"||Q.type==="start"||Q.type==="start-step"||p.enqueue(Q);C+=k;const S={role:"assistant",content:C};b.push(S),m.push(S);const E=Iv(C,r);if(!E){p.enqueue({type:"text-end"}),p.enqueue({type:"finish-step"}),p.enqueue({type:"finish"}),p.close(),i.responseMessages=m,l({messages:m});return}if(E.toolName==="computer"&&E.arguments?.action==="terminate"){p.enqueue({type:"text-end"}),p.enqueue({type:"finish-step"}),p.enqueue({type:"finish"}),p.close(),i.responseMessages=m,l({messages:m});return}const R=`react-${Date.now()}`;p.enqueue({type:"tool-input-start",id:R,toolName:E.toolName});const x=JSON.stringify(E.arguments,null,2);p.enqueue({type:"tool-input-delta",id:R,delta:x}),p.enqueue({type:"tool-input-end",id:R}),p.enqueue({type:"tool-call",toolCallId:R,toolName:E.toolName,input:E.arguments});const N=await i._executeReActToolCall(E.toolName,E.arguments,r);let U,z=N.result;if(N.success&&N.result&&typeof N.result=="object"&&N.result.screenshot){U=N.result.screenshot;const{screenshot:Q,...se}=N.result;z=se}let ee="";if(N.success){z&&Array.isArray(z.content)&&z.content.length>0&&z.content[0].text?ee=z.content[0].text:ee=JSON.stringify(z);let Q=`<tool_response>
|
|
135
|
+
${ee}
|
|
136
|
+
</tool_response>`;U&&(Q+=`
|
|
137
|
+
请检查截图以确认操作是否成功。如果成功,请继续下一步;如果失败,请重试。`),p.enqueue({type:"tool-result",toolCallId:R,result:Q});const se=U?{role:"user",content:[{type:"text",text:Q},{type:"image",image:U}]}:{role:"user",content:Q};b.push(se),m.push(se),C=""}else ee=`工具执行失败 - ${N.error}`,p.enqueue({type:"tool-error",toolCallId:R,input:E.arguments,error:{message:ee}})}p.enqueue({type:"text-end"}),p.enqueue({type:"finish-step"}),p.enqueue({type:"finish"}),p.close(),i.responseMessages=m,l({messages:m})}catch(g){p.error(g),c(g)}}}),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 a=o.tools||{},i=this._tempMergeTools(a,!1),s=()=>{const m=this._tempMergeTools(a,!1);Object.entries(m).forEach(([f,b])=>{i[f]=b}),Object.keys(i).forEach(f=>{f in m||delete i[f]})},l=o.prepareStep,c=async m=>{s();const f=this._getActiveToolNames(i),b=typeof l=="function"?await l(m):void 0,w=b&&typeof b=="object"?b:{};return{...w,activeTools:Array.isArray(w.activeTools)?w.activeTools.filter(C=>f.includes(C)):f}},u={model:this.llm(r),stopWhen:Sc(n),...o,tools:i,prepareStep:c,activeTools:this._getActiveToolNames(i)};let h=null;if(o.message&&!o.messages)h={role:"user",content:o.message},this.responseMessages.push(h),u.messages=[...this.responseMessages];else if(o.messages&&o.messages.length>0){const m=o.messages[o.messages.length-1];m.role==="user"&&(h=m)}const p=t(u);return p?.response?.then(m=>{const f=m.messages?.[0];h&&f?.role!=="user"&&this.responseMessages.push(h),this.responseMessages.push(...m.messages)}),p}async chat(t){return this._chat(s2,t)}async chatStream(t){return this._chat(Ec,t)}}var Do={},dd,xv;function lR(){return xv||(xv=1,dd=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),dd}var pd={},In={},Ev;function oo(){if(Ev)return In;Ev=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 In.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},In.getSymbolTotalCodewords=function(n){return t[n]},In.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},In.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');e=n},In.isKanjiModeEnabled=function(){return typeof e<"u"},In.toSJIS=function(n){return e(n)},In}var hd={},$v;function fd(){return $v||($v=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}}})(hd)),hd}var md,Rv;function cR(){if(Rv)return md;Rv=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++}},md=e,md}var gd,Pv;function uR(){if(Pv)return gd;Pv=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 a=t*this.size+r;this.data[a]=n,o&&(this.reservedBit[a]=!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]},gd=e,gd}var _d={},Mv;function dR(){return Mv||(Mv=1,(function(e){const t=oo().getSymbolSize;e.getRowColCoords=function(n){if(n===1)return[];const o=Math.floor(n/7)+2,a=t(n),i=a===145?26:Math.ceil((a-13)/(2*o-2))*2,s=[a-7];for(let l=1;l<o-1;l++)s[l]=s[l-1]-i;return s.push(6),s.reverse()},e.getPositions=function(n){const o=[],a=e.getRowColCoords(n),i=a.length;for(let s=0;s<i;s++)for(let l=0;l<i;l++)s===0&&l===0||s===0&&l===i-1||s===i-1&&l===0||o.push([a[s],a[l]]);return o}})(_d)),_d}var yd={},Ov;function pR(){if(Ov)return yd;Ov=1;const e=oo().getSymbolSize,t=7;return yd.getPositions=function(n){const o=e(n);return[[0,0],[o-t,0],[0,o-t]]},yd}var vd={},Av;function hR(){return Av||(Av=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 a=o.size;let i=0,s=0,l=0,c=null,u=null;for(let h=0;h<a;h++){s=l=0,c=u=null;for(let p=0;p<a;p++){let m=o.get(h,p);m===c?s++:(s>=5&&(i+=t.N1+(s-5)),c=m,s=1),m=o.get(p,h),m===u?l++:(l>=5&&(i+=t.N1+(l-5)),u=m,l=1)}s>=5&&(i+=t.N1+(s-5)),l>=5&&(i+=t.N1+(l-5))}return i},e.getPenaltyN2=function(o){const a=o.size;let i=0;for(let s=0;s<a-1;s++)for(let l=0;l<a-1;l++){const c=o.get(s,l)+o.get(s,l+1)+o.get(s+1,l)+o.get(s+1,l+1);(c===4||c===0)&&i++}return i*t.N2},e.getPenaltyN3=function(o){const a=o.size;let i=0,s=0,l=0;for(let c=0;c<a;c++){s=l=0;for(let u=0;u<a;u++)s=s<<1&2047|o.get(c,u),u>=10&&(s===1488||s===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 a=0;const i=o.data.length;for(let l=0;l<i;l++)a+=o.data[l];return Math.abs(Math.ceil(a*100/i/5)-10)*t.N4};function r(n,o,a){switch(n){case e.Patterns.PATTERN000:return(o+a)%2===0;case e.Patterns.PATTERN001:return o%2===0;case e.Patterns.PATTERN010:return a%3===0;case e.Patterns.PATTERN011:return(o+a)%3===0;case e.Patterns.PATTERN100:return(Math.floor(o/2)+Math.floor(a/3))%2===0;case e.Patterns.PATTERN101:return o*a%2+o*a%3===0;case e.Patterns.PATTERN110:return(o*a%2+o*a%3)%2===0;case e.Patterns.PATTERN111:return(o*a%3+(o+a)%2)%2===0;default:throw new Error("bad maskPattern:"+n)}}e.applyMask=function(o,a){const i=a.size;for(let s=0;s<i;s++)for(let l=0;l<i;l++)a.isReserved(l,s)||a.xor(l,s,r(o,l,s))},e.getBestMask=function(o,a){const i=Object.keys(e.Patterns).length;let s=0,l=1/0;for(let c=0;c<i;c++){a(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,s=c)}return s}})(vd)),vd}var ol={},Nv;function qv(){if(Nv)return ol;Nv=1;const e=fd(),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 ol.getBlocksCount=function(o,a){switch(a){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}},ol.getTotalCodewordsCount=function(o,a){switch(a){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}},ol}var wd={},Da={},Lv;function fR(){if(Lv)return Da;Lv=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]})(),Da.log=function(n){if(n<1)throw new Error("log("+n+")");return t[n]},Da.exp=function(n){return e[n]},Da.mul=function(n,o){return n===0||o===0?0:e[t[n]+t[o]]},Da}var jv;function mR(){return jv||(jv=1,(function(e){const t=fR();e.mul=function(n,o){const a=new Uint8Array(n.length+o.length-1);for(let i=0;i<n.length;i++)for(let s=0;s<o.length;s++)a[i+s]^=t.mul(n[i],o[s]);return a},e.mod=function(n,o){let a=new Uint8Array(n);for(;a.length-o.length>=0;){const i=a[0];for(let l=0;l<o.length;l++)a[l]^=t.mul(o[l],i);let s=0;for(;s<a.length&&a[s]===0;)s++;a=a.slice(s)}return a},e.generateECPolynomial=function(n){let o=new Uint8Array([1]);for(let a=0;a<n;a++)o=e.mul(o,new Uint8Array([1,t.exp(a)]));return o}})(wd)),wd}var bd,Dv;function gR(){if(Dv)return bd;Dv=1;const e=mR();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 a=e.mod(o,this.genPoly),i=this.degree-a.length;if(i>0){const s=new Uint8Array(this.degree);return s.set(a,i),s}return a},bd=t,bd}var kd={},Td={},Cd={},Uv;function zv(){return Uv||(Uv=1,Cd.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),Cd}var Jr={},Fv;function Vv(){if(Fv)return Jr;Fv=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
|
|
138
|
+
]))+`;Jr.KANJI=new RegExp(r,"g"),Jr.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),Jr.BYTE=new RegExp(n,"g"),Jr.NUMERIC=new RegExp(e,"g"),Jr.ALPHANUMERIC=new RegExp(t,"g");const o=new RegExp("^"+r+"$"),a=new RegExp("^"+e+"$"),i=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return Jr.testKanji=function(l){return o.test(l)},Jr.testNumeric=function(l){return a.test(l)},Jr.testAlphanumeric=function(l){return i.test(l)},Jr}var Zv;function ao(){return Zv||(Zv=1,(function(e){const t=zv(),r=Vv();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(a,i){if(!a.ccBits)throw new Error("Invalid mode: "+a);if(!t.isValid(i))throw new Error("Invalid version: "+i);return i>=1&&i<10?a.ccBits[0]:i<27?a.ccBits[1]:a.ccBits[2]},e.getBestModeForData=function(a){return r.testNumeric(a)?e.NUMERIC:r.testAlphanumeric(a)?e.ALPHANUMERIC:r.testKanji(a)?e.KANJI:e.BYTE},e.toString=function(a){if(a&&a.id)return a.id;throw new Error("Invalid mode")},e.isValid=function(a){return a&&a.bit&&a.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(a,i){if(e.isValid(a))return a;try{return n(a)}catch{return i}}})(Td)),Td}var Hv;function _R(){return Hv||(Hv=1,(function(e){const t=oo(),r=qv(),n=fd(),o=ao(),a=zv(),i=7973,s=t.getBCHDigit(i);function l(p,m,f){for(let b=1;b<=40;b++)if(m<=e.getCapacity(b,f,p))return b}function c(p,m){return o.getCharCountIndicator(p,m)+4}function u(p,m){let f=0;return p.forEach(function(b){const w=c(b.mode,m);f+=w+b.getBitsLength()}),f}function h(p,m){for(let f=1;f<=40;f++)if(u(p,f)<=e.getCapacity(f,m,o.MIXED))return f}e.from=function(m,f){return a.isValid(m)?parseInt(m,10):f},e.getCapacity=function(m,f,b){if(!a.isValid(m))throw new Error("Invalid QR Code version");typeof b>"u"&&(b=o.BYTE);const w=t.getSymbolTotalCodewords(m),C=r.getTotalCodewordsCount(m,f),v=(w-C)*8;if(b===o.MIXED)return v;const g=v-c(b,m);switch(b){case o.NUMERIC:return Math.floor(g/10*3);case o.ALPHANUMERIC:return Math.floor(g/11*2);case o.KANJI:return Math.floor(g/13);case o.BYTE:default:return Math.floor(g/8)}},e.getBestVersionForData=function(m,f){let b;const w=n.from(f,n.M);if(Array.isArray(m)){if(m.length>1)return h(m,w);if(m.length===0)return 1;b=m[0]}else b=m;return l(b.mode,b.getLength(),w)},e.getEncodedBits=function(m){if(!a.isValid(m)||m<7)throw new Error("Invalid QR Code version");let f=m<<12;for(;t.getBCHDigit(f)-s>=0;)f^=i<<t.getBCHDigit(f)-s;return m<<12|f}})(kd)),kd}var Sd={},Bv;function yR(){if(Bv)return Sd;Bv=1;const e=oo(),t=1335,r=21522,n=e.getBCHDigit(t);return Sd.getEncodedBits=function(a,i){const s=a.bit<<3|i;let l=s<<10;for(;e.getBCHDigit(l)-n>=0;)l^=t<<e.getBCHDigit(l)-n;return(s<<10|l)^r},Sd}var Id={},xd,Jv;function vR(){if(Jv)return xd;Jv=1;const e=ao();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,a,i;for(o=0;o+3<=this.data.length;o+=3)a=this.data.substr(o,3),i=parseInt(a,10),n.put(i,10);const s=this.data.length-o;s>0&&(a=this.data.substr(o),i=parseInt(a,10),n.put(i,s*3+1))},xd=t,xd}var Ed,Gv;function wR(){if(Gv)return Ed;Gv=1;const e=ao(),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 a;for(a=0;a+2<=this.data.length;a+=2){let i=t.indexOf(this.data[a])*45;i+=t.indexOf(this.data[a+1]),o.put(i,11)}this.data.length%2&&o.put(t.indexOf(this.data[a]),6)},Ed=r,Ed}var $d,Wv;function bR(){if(Wv)return $d;Wv=1;const e=ao();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)},$d=t,$d}var Rd,Kv;function kR(){if(Kv)return Rd;Kv=1;const e=ao(),t=oo();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 a=t.toSJIS(this.data[o]);if(a>=33088&&a<=40956)a-=33088;else if(a>=57408&&a<=60351)a-=49472;else throw new Error("Invalid SJIS character: "+this.data[o]+`
|
|
139
|
+
Make sure your charset is UTF-8`);a=(a>>>8&255)*192+(a&255),n.put(a,13)}},Rd=r,Rd}var Pd={exports:{}},Yv;function TR(){return Yv||(Yv=1,(function(e){var t={single_source_shortest_paths:function(r,n,o){var a={},i={};i[n]=0;var s=t.PriorityQueue.make();s.push(n,0);for(var l,c,u,h,p,m,f,b,w;!s.empty();){l=s.pop(),c=l.value,h=l.cost,p=r[c]||{};for(u in p)p.hasOwnProperty(u)&&(m=p[u],f=h+m,b=i[u],w=typeof i[u]>"u",(w||b>f)&&(i[u]=f,s.push(u,f),a[u]=c))}if(typeof o<"u"&&typeof i[o]>"u"){var C=["Could not find a path from ",n," to ",o,"."].join("");throw new Error(C)}return a},extract_shortest_path_from_predecessor_list:function(r,n){for(var o=[],a=n;a;)o.push(a),r[a],a=r[a];return o.reverse(),o},find_path:function(r,n,o){var a=t.single_source_shortest_paths(r,n,o);return t.extract_shortest_path_from_predecessor_list(a,o)},PriorityQueue:{make:function(r){var n=t.PriorityQueue,o={},a;r=r||{};for(a in n)n.hasOwnProperty(a)&&(o[a]=n[a]);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})(Pd)),Pd.exports}var Qv;function CR(){return Qv||(Qv=1,(function(e){const t=ao(),r=vR(),n=wR(),o=bR(),a=kR(),i=Vv(),s=oo(),l=TR();function c(C){return unescape(encodeURIComponent(C)).length}function u(C,v,g){const I=[];let y;for(;(y=C.exec(g))!==null;)I.push({data:y[0],index:y.index,mode:v,length:y[0].length});return I}function h(C){const v=u(i.NUMERIC,t.NUMERIC,C),g=u(i.ALPHANUMERIC,t.ALPHANUMERIC,C);let I,y;return s.isKanjiModeEnabled()?(I=u(i.BYTE,t.BYTE,C),y=u(i.KANJI,t.KANJI,C)):(I=u(i.BYTE_KANJI,t.BYTE,C),y=[]),v.concat(g,I,y).sort(function(k,S){return k.index-S.index}).map(function(k){return{data:k.data,mode:k.mode,length:k.length}})}function p(C,v){switch(v){case t.NUMERIC:return r.getBitsLength(C);case t.ALPHANUMERIC:return n.getBitsLength(C);case t.KANJI:return a.getBitsLength(C);case t.BYTE:return o.getBitsLength(C)}}function m(C){return C.reduce(function(v,g){const I=v.length-1>=0?v[v.length-1]:null;return I&&I.mode===g.mode?(v[v.length-1].data+=g.data,v):(v.push(g),v)},[])}function f(C){const v=[];for(let g=0;g<C.length;g++){const I=C[g];switch(I.mode){case t.NUMERIC:v.push([I,{data:I.data,mode:t.ALPHANUMERIC,length:I.length},{data:I.data,mode:t.BYTE,length:I.length}]);break;case t.ALPHANUMERIC:v.push([I,{data:I.data,mode:t.BYTE,length:I.length}]);break;case t.KANJI:v.push([I,{data:I.data,mode:t.BYTE,length:c(I.data)}]);break;case t.BYTE:v.push([{data:I.data,mode:t.BYTE,length:c(I.data)}])}}return v}function b(C,v){const g={},I={start:{}};let y=["start"];for(let _=0;_<C.length;_++){const k=C[_],S=[];for(let E=0;E<k.length;E++){const R=k[E],x=""+_+E;S.push(x),g[x]={node:R,lastCount:0},I[x]={};for(let N=0;N<y.length;N++){const U=y[N];g[U]&&g[U].node.mode===R.mode?(I[U][x]=p(g[U].lastCount+R.length,R.mode)-p(g[U].lastCount,R.mode),g[U].lastCount+=R.length):(g[U]&&(g[U].lastCount=R.length),I[U][x]=p(R.length,R.mode)+4+t.getCharCountIndicator(R.mode,v))}}y=S}for(let _=0;_<y.length;_++)I[y[_]].end=0;return{map:I,table:g}}function w(C,v){let g;const I=t.getBestModeForData(C);if(g=t.from(v,I),g!==t.BYTE&&g.bit<I.bit)throw new Error('"'+C+'" cannot be encoded with mode '+t.toString(g)+`.
|
|
140
|
+
Suggested mode is: `+t.toString(I));switch(g===t.KANJI&&!s.isKanjiModeEnabled()&&(g=t.BYTE),g){case t.NUMERIC:return new r(C);case t.ALPHANUMERIC:return new n(C);case t.KANJI:return new a(C);case t.BYTE:return new o(C)}}e.fromArray=function(v){return v.reduce(function(g,I){return typeof I=="string"?g.push(w(I,null)):I.data&&g.push(w(I.data,I.mode)),g},[])},e.fromString=function(v,g){const I=h(v,s.isKanjiModeEnabled()),y=f(I),_=b(y,g),k=l.find_path(_.map,"start","end"),S=[];for(let E=1;E<k.length-1;E++)S.push(_.table[k[E]].node);return e.fromArray(m(S))},e.rawSplit=function(v){return e.fromArray(h(v,s.isKanjiModeEnabled()))}})(Id)),Id}var Xv;function SR(){if(Xv)return pd;Xv=1;const e=oo(),t=fd(),r=cR(),n=uR(),o=dR(),a=pR(),i=hR(),s=qv(),l=gR(),c=_R(),u=yR(),h=ao(),p=CR();function m(_,k){const S=_.size,E=a.getPositions(k);for(let R=0;R<E.length;R++){const x=E[R][0],N=E[R][1];for(let U=-1;U<=7;U++)if(!(x+U<=-1||S<=x+U))for(let z=-1;z<=7;z++)N+z<=-1||S<=N+z||(U>=0&&U<=6&&(z===0||z===6)||z>=0&&z<=6&&(U===0||U===6)||U>=2&&U<=4&&z>=2&&z<=4?_.set(x+U,N+z,!0,!0):_.set(x+U,N+z,!1,!0))}}function f(_){const k=_.size;for(let S=8;S<k-8;S++){const E=S%2===0;_.set(S,6,E,!0),_.set(6,S,E,!0)}}function b(_,k){const S=o.getPositions(k);for(let E=0;E<S.length;E++){const R=S[E][0],x=S[E][1];for(let N=-2;N<=2;N++)for(let U=-2;U<=2;U++)N===-2||N===2||U===-2||U===2||N===0&&U===0?_.set(R+N,x+U,!0,!0):_.set(R+N,x+U,!1,!0)}}function w(_,k){const S=_.size,E=c.getEncodedBits(k);let R,x,N;for(let U=0;U<18;U++)R=Math.floor(U/3),x=U%3+S-8-3,N=(E>>U&1)===1,_.set(R,x,N,!0),_.set(x,R,N,!0)}function C(_,k,S){const E=_.size,R=u.getEncodedBits(k,S);let x,N;for(x=0;x<15;x++)N=(R>>x&1)===1,x<6?_.set(x,8,N,!0):x<8?_.set(x+1,8,N,!0):_.set(E-15+x,8,N,!0),x<8?_.set(8,E-x-1,N,!0):x<9?_.set(8,15-x-1+1,N,!0):_.set(8,15-x-1,N,!0);_.set(E-8,8,1,!0)}function v(_,k){const S=_.size;let E=-1,R=S-1,x=7,N=0;for(let U=S-1;U>0;U-=2)for(U===6&&U--;;){for(let z=0;z<2;z++)if(!_.isReserved(R,U-z)){let ee=!1;N<k.length&&(ee=(k[N]>>>x&1)===1),_.set(R,U-z,ee),x--,x===-1&&(N++,x=7)}if(R+=E,R<0||S<=R){R-=E,E=-E;break}}}function g(_,k,S){const E=new r;S.forEach(function(z){E.put(z.mode.bit,4),E.put(z.getLength(),h.getCharCountIndicator(z.mode,_)),z.write(E)});const R=e.getSymbolTotalCodewords(_),x=s.getTotalCodewordsCount(_,k),N=(R-x)*8;for(E.getLengthInBits()+4<=N&&E.put(0,4);E.getLengthInBits()%8!==0;)E.putBit(0);const U=(N-E.getLengthInBits())/8;for(let z=0;z<U;z++)E.put(z%2?17:236,8);return I(E,_,k)}function I(_,k,S){const E=e.getSymbolTotalCodewords(k),R=s.getTotalCodewordsCount(k,S),x=E-R,N=s.getBlocksCount(k,S),U=E%N,z=N-U,ee=Math.floor(E/N),Q=Math.floor(x/N),se=Q+1,re=ee-Q,Se=new l(re);let H=0;const D=new Array(N),B=new Array(N);let F=0;const $=new Uint8Array(_.buffer);for(let W=0;W<N;W++){const V=W<z?Q:se;D[W]=$.slice(H,H+V),B[W]=Se.encode(D[W]),H+=V,F=Math.max(F,V)}const O=new Uint8Array(E);let j=0,G,Y;for(G=0;G<F;G++)for(Y=0;Y<N;Y++)G<D[Y].length&&(O[j++]=D[Y][G]);for(G=0;G<re;G++)for(Y=0;Y<N;Y++)O[j++]=B[Y][G];return O}function y(_,k,S,E){let R;if(Array.isArray(_))R=p.fromArray(_);else if(typeof _=="string"){let ee=k;if(!ee){const Q=p.rawSplit(_);ee=c.getBestVersionForData(Q,S)}R=p.fromString(_,ee||40)}else throw new Error("Invalid data");const x=c.getBestVersionForData(R,S);if(!x)throw new Error("The amount of data is too big to be stored in a QR Code");if(!k)k=x;else if(k<x)throw new Error(`
|
|
133
141
|
The chosen QR Code version cannot contain this amount of data.
|
|
134
|
-
Minimum version required to store current data is: `+
|
|
135
|
-
`);const
|
|
136
|
-
`;return typeof
|
|
142
|
+
Minimum version required to store current data is: `+x+`.
|
|
143
|
+
`);const N=g(k,S,R),U=e.getSymbolSize(k),z=new n(U);return m(z,k),f(z),b(z,k),C(z,S,0),k>=7&&w(z,k),v(z,N),isNaN(E)&&(E=i.getBestMask(z,C.bind(null,z,S))),i.applyMask(E,z),C(z,S,E),{modules:z,version:k,errorCorrectionLevel:S,maskPattern:E,segments:R}}return pd.create=function(k,S){if(typeof k>"u"||k==="")throw new Error("No input text");let E=t.M,R,x;return typeof S<"u"&&(E=t.from(S.errorCorrectionLevel,t.M),R=c.from(S.version),x=i.from(S.maskPattern),S.toSJISFunc&&e.setToSJISFunction(S.toSJISFunc)),y(k,R,E,x)},pd}var Md={},Od={},e1;function t1(){return e1||(e1=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(a){return[a,a]}))),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,a=n.width&&n.width>=21?n.width:void 0,i=n.scale||4;return{width:a,scale:a?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 a=e.getScale(n,o);return Math.floor((n+o.margin*2)*a)},e.qrToImageData=function(n,o,a){const i=o.modules.size,s=o.modules.data,l=e.getScale(i,a),c=Math.floor((i+a.margin*2)*l),u=a.margin*l,h=[a.color.light,a.color.dark];for(let p=0;p<c;p++)for(let m=0;m<c;m++){let f=(p*c+m)*4,b=a.color.light;if(p>=u&&m>=u&&p<c-u&&m<c-u){const w=Math.floor((p-u)/l),C=Math.floor((m-u)/l);b=h[s[w*i+C]?1:0]}n[f++]=b.r,n[f++]=b.g,n[f++]=b.b,n[f]=b.a}}})(Od)),Od}var r1;function IR(){return r1||(r1=1,(function(e){const t=t1();function r(o,a,i){o.clearRect(0,0,a.width,a.height),a.style||(a.style={}),a.height=i,a.width=i,a.style.height=i+"px",a.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(a,i,s){let l=s,c=i;typeof l>"u"&&(!i||!i.getContext)&&(l=i,i=void 0),i||(c=n()),l=t.getOptions(l);const u=t.getImageWidth(a.modules.size,l),h=c.getContext("2d"),p=h.createImageData(u,u);return t.qrToImageData(p.data,a,l),r(h,c,u),h.putImageData(p,0,0),c},e.renderToDataURL=function(a,i,s){let l=s;typeof l>"u"&&(!i||!i.getContext)&&(l=i,i=void 0),l||(l={});const c=e.render(a,i,l),u=l.type||"image/png",h=l.rendererOpts||{};return c.toDataURL(u,h.quality)}})(Md)),Md}var Ad={},n1;function xR(){if(n1)return Ad;n1=1;const e=t1();function t(o,a){const i=o.a/255,s=a+'="'+o.hex+'"';return i<1?s+" "+a+'-opacity="'+i.toFixed(2).slice(1)+'"':s}function r(o,a,i){let s=o+a;return typeof i<"u"&&(s+=" "+i),s}function n(o,a,i){let s="",l=0,c=!1,u=0;for(let h=0;h<o.length;h++){const p=Math.floor(h%a),m=Math.floor(h/a);!p&&!c&&(c=!0),o[h]?(u++,h>0&&p>0&&o[h-1]||(s+=c?r("M",p+i,.5+m+i):r("m",l,0),l=0,c=!1),p+1<a&&o[h+1]||(s+=r("h",u),u=0)):l++}return s}return Ad.render=function(a,i,s){const l=e.getOptions(i),c=a.modules.size,u=a.modules.data,h=c+l.margin*2,p=l.color.light.a?"<path "+t(l.color.light,"fill")+' d="M0 0h'+h+"v"+h+'H0z"/>':"",m="<path "+t(l.color.dark,"stroke")+' d="'+n(u,c,l.margin)+'"/>',f='viewBox="0 0 '+h+" "+h+'"',w='<svg xmlns="http://www.w3.org/2000/svg" '+(l.width?'width="'+l.width+'" height="'+l.width+'" ':"")+f+' shape-rendering="crispEdges">'+p+m+`</svg>
|
|
144
|
+
`;return typeof s=="function"&&s(null,w),w},Ad}var o1;function ER(){if(o1)return Do;o1=1;const e=lR(),t=SR(),r=IR(),n=xR();function o(a,i,s,l,c){const u=[].slice.call(arguments,1),h=u.length,p=typeof u[h-1]=="function";if(!p&&!e())throw new Error("Callback required as last argument");if(p){if(h<2)throw new Error("Too few arguments provided");h===2?(c=s,s=i,i=l=void 0):h===3&&(i.getContext&&typeof c>"u"?(c=l,l=void 0):(c=l,l=s,s=i,i=void 0))}else{if(h<1)throw new Error("Too few arguments provided");return h===1?(s=i,i=l=void 0):h===2&&!i.getContext&&(l=s,s=i,i=void 0),new Promise(function(m,f){try{const b=t.create(s,l);m(a(b,i,l))}catch(b){f(b)}})}try{const m=t.create(s,l);c(null,a(m,i,l))}catch(m){c(m)}}return Do.create=t.create,Do.toCanvas=o.bind(null,r.render),Do.toDataURL=o.bind(null,r.renderToDataURL),Do.toString=o.bind(null,function(a,i,s){return n.render(a,s)}),Do}var $R=ER();const a1=Hl($R);class s1{constructor(t,{size:r=200,margin:n=4,color:o="#000",bgColor:a="#fff"}){this.value=t,this.size=r,this.margin=n,this.color=o,this.bgColor=a}get qrCodeOption(){return{width:this.size,margin:this.margin,color:{dark:this.color,light:this.bgColor}}}async toDataURL(){return a1.toDataURL(this.value,this.qrCodeOption)}async toCanvas(t){return a1.toCanvas(t,this.value,this.qrCodeOption)}async toImage(t){t.src=await this.toDataURL()}}const RR={content:"",placement:"top",trigger:"hover",delay:150,hideDelay:150,container:document.body,className:"tiny-remoter-native-tooltip"};class PR{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={...RR,...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
145
|
<div class="${this.opts.className}__arrow"></div>
|
|
138
146
|
<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,
|
|
147
|
+
`}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,a=window.pageXOffset||document.documentElement.scrollLeft,i=6,[s,l="center"]=t.split("-");let c=0,u=0;return s==="top"?c=r.top+o-n.height-i:s==="bottom"?c=r.bottom+o+i:s==="left"?u=r.left+a-n.width-i:s==="right"&&(u=r.right+a+i),(s==="top"||s==="bottom")&&(l==="start"?u=r.left+a:l==="end"?u=r.right+a-n.width:u=(r.left+r.right)/2+a-n.width/2),(s==="left"||s==="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,a=window.innerHeight,i=this.tip.getBoundingClientRect();return r>=5&&t>=5&&r+i.width<=o-5&&t+i.height<=a-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 i1="tiny-remoter-native-tooltip-style";(()=>{if(document.getElementById(i1))return;const e=document.createElement("style");e.id=i1,e.textContent=`
|
|
140
148
|
.tiny-remoter-native-tooltip {
|
|
141
149
|
position: absolute;
|
|
142
150
|
z-index: 9999;
|
|
@@ -183,7 +191,7 @@ Minimum version required to store current data is: `+N+`.
|
|
|
183
191
|
transform: translateY(-50%);
|
|
184
192
|
border-right-color: rgba(0,0,0,.75);
|
|
185
193
|
}
|
|
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",XE="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",e$="https://chat.opentiny.design",t$="https://ai.opentiny.design/next-remoter",r$="https://ai.opentiny.design/next-remoter/svgs/logo-next-no-bg-left.svg",n$=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 o${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 QE(n,{content:"复制",placement:"top",trigger:"hover"})},this.options={...t,qrCodeUrl:t.qrCodeUrl||t$,remoteUrl:t.remoteUrl||e$,logoUrl:t.logoUrl||r$},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?n$(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=`
|
|
194
|
+
`,document.head.appendChild(e)})();const l1="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",c1="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",u1="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",d1="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",MR="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",OR="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",AR="https://chat.opentiny.design",NR="https://ai.opentiny.design/next-remoter",qR=OR,LR=e=>{const t=!!e.sessionId;return[{action:"qr-code",show:t,text:"扫码登录",desc:"使用手机遥控页面",icon:d1},{action:"ai-chat",show:!0,text:"打开对话框",desc:"支持在网页端操作AI",icon:l1},{action:"remote-url",show:t,text:"遥控器链接",desc:`${e.remoteUrl}`,active:!0,tip:e.remoteUrl,showCopyIcon:!0,icon:u1},{action:"remote-control",show:t,text:"识别码",desc:t?`${e.sessionId.slice(-6)}`:"",know:!0,showCopyIcon:!0,icon:c1}]};class jR{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 PR(n,{content:"复制",placement:"top",trigger:"hover"})},this.options={...t,qrCodeUrl:t.qrCodeUrl||NR,remoteUrl:t.remoteUrl||AR,logoUrl:t.logoUrl||qR},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":d1,"ai-chat":l1,"remote-url":u1,"remote-control":c1};return t?t.map(n=>({...n,icon:n.icon??r[n.action]})):this.options.sessionId?LR(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
195
|
<div class="tiny-remoter-floating-block__icon">
|
|
188
196
|
<img style="display: block; width: 56px;" src="${this.options.logoUrl}" alt="icon" />
|
|
189
197
|
</div>
|
|
@@ -198,14 +206,14 @@ Minimum version required to store current data is: `+N+`.
|
|
|
198
206
|
<div>
|
|
199
207
|
${r.showCopyIcon?`
|
|
200
208
|
<div class="tiny-remoter-copy-icon" id="${r.action}" data-action="${r.action}">
|
|
201
|
-
<img src="${
|
|
209
|
+
<img src="${MR}"/>
|
|
202
210
|
</div>
|
|
203
211
|
`:""}
|
|
204
212
|
</div>
|
|
205
213
|
</div>
|
|
206
214
|
</div>
|
|
207
215
|
</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
|
|
216
|
+
`).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 a=r.closest(".tiny-remoter-dropdown-item")?.dataset.action;a&&this.handleAction(a)}),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(a=>a.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 s1((this.options.qrCodeUrl||"")+this.sessionPrefix+this.options.sessionId,{}).toDataURL(),n=this.createModal("扫码前往智能遥控器",`
|
|
209
217
|
<div style="text-align: center; padding: 32px;">
|
|
210
218
|
<!-- 二维码容器 - 添加渐变背景和阴影效果 -->
|
|
211
219
|
<div style="
|
|
@@ -297,7 +305,7 @@ Minimum version required to store current data is: `+N+`.
|
|
|
297
305
|
${r}
|
|
298
306
|
</div>
|
|
299
307
|
</div>
|
|
300
|
-
`;const o=n.querySelector(".tiny-remoter-modal-close"),
|
|
308
|
+
`;const o=n.querySelector(".tiny-remoter-modal-close"),a=n.querySelector(".tiny-remoter-modal-overlay");return o.addEventListener("click",()=>this.hideModal(n)),a.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
309
|
/* 浮动块样式 */
|
|
302
310
|
.tiny-remoter-floating-block {
|
|
303
311
|
position: fixed;
|
|
@@ -631,4 +639,4 @@ Minimum version required to store current data is: `+N+`.
|
|
|
631
639
|
color: white;
|
|
632
640
|
}
|
|
633
641
|
}
|
|
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
|
|
642
|
+
`,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 DR=(e={})=>new jR(e);Kr.AgentModelProvider=iR,Kr.QrCode=s1,Kr.createRemoter=DR,Kr.getAISDKTools=Sv,Object.defineProperty(Kr,Symbol.toStringTag,{value:"Module"})}));
|