@opentiny/next-sdk 0.3.0-alpha.0 → 0.3.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/dist/webagent.js CHANGED
@@ -1,8 +1,8 @@
1
- (function(Ur,Yn){typeof exports=="object"&&typeof module<"u"?Yn(exports):typeof define=="function"&&define.amd?define(["exports"],Yn):(Ur=typeof globalThis<"u"?globalThis:Ur||self,Yn(Ur.WebAgent={}))})(this,(function(Ur){"use strict";var Yn="vercel.ai.error",vv=Symbol.for(Yn),fd,hd,we=class hv extends(hd=Error,fd=vv,hd){constructor({name:t,message:r,cause:n}){super(r),this[fd]=!0,this.name=t,this.cause=n}static isInstance(t){return hv.hasMarker(t,Yn)}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}},md="AI_APICallError",gd=`vercel.ai.error.${md}`,wv=Symbol.for(gd),_d,yd,lt=class extends(yd=we,_d=wv,yd){constructor({message:t,url:r,requestBodyValues:n,statusCode:o,responseHeaders:s,responseBody:i,cause:a,isRetryable:l=o!=null&&(o===408||o===409||o===429||o>=500),data:c}){super({name:md,message:t,cause:a}),this[_d]=!0,this.url=r,this.requestBodyValues=n,this.statusCode=o,this.responseHeaders=s,this.responseBody=i,this.isRetryable=l,this.data=c}static isInstance(t){return we.hasMarker(t,gd)}},vd="AI_EmptyResponseBodyError",wd=`vercel.ai.error.${vd}`,bv=Symbol.for(wd),bd,kd,kv=class extends(kd=we,bd=bv,kd){constructor({message:t="Empty response body"}={}){super({name:vd,message:t}),this[bd]=!0}static isInstance(t){return we.hasMarker(t,wd)}};function Tn(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var Td="AI_InvalidArgumentError",Cd=`vercel.ai.error.${Td}`,Tv=Symbol.for(Cd),Sd,Id,xd=class extends(Id=we,Sd=Tv,Id){constructor({message:t,cause:r,argument:n}){super({name:Td,message:t,cause:r}),this[Sd]=!0,this.argument=n}static isInstance(t){return we.hasMarker(t,Cd)}},Ed="AI_InvalidPromptError",$d=`vercel.ai.error.${Ed}`,Cv=Symbol.for($d),Rd,Pd,Cn=class extends(Pd=we,Rd=Cv,Pd){constructor({prompt:e,message:t,cause:r}){super({name:Ed,message:`Invalid prompt: ${t}`,cause:r}),this[Rd]=!0,this.prompt=e}static isInstance(e){return we.hasMarker(e,$d)}},Md="AI_InvalidResponseDataError",Nd=`vercel.ai.error.${Md}`,Sv=Symbol.for(Nd),Od,Ad,Yi=class extends(Ad=we,Od=Sv,Ad){constructor({data:t,message:r=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:Md,message:r}),this[Od]=!0,this.data=t}static isInstance(t){return we.hasMarker(t,Nd)}},qd="AI_JSONParseError",Ld=`vercel.ai.error.${qd}`,Iv=Symbol.for(Ld),jd,Dd,Ds=class extends(Dd=we,jd=Iv,Dd){constructor({text:t,cause:r}){super({name:qd,message:`JSON parsing failed: Text: ${t}.
2
- Error message: ${Tn(r)}`,cause:r}),this[jd]=!0,this.text=t}static isInstance(t){return we.hasMarker(t,Ld)}},Ud="AI_LoadAPIKeyError",zd=`vercel.ai.error.${Ud}`,xv=Symbol.for(zd),Fd,Vd,Us=class extends(Vd=we,Fd=xv,Vd){constructor({message:t}){super({name:Ud,message:t}),this[Fd]=!0}static isInstance(t){return we.hasMarker(t,zd)}},Zd="AI_TooManyEmbeddingValuesForCallError",Bd=`vercel.ai.error.${Zd}`,Ev=Symbol.for(Bd),Hd,Jd,$v=class extends(Jd=we,Hd=Ev,Jd){constructor(e){super({name:Zd,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[Hd]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return we.hasMarker(e,Bd)}},Gd="AI_TypeValidationError",Wd=`vercel.ai.error.${Gd}`,Rv=Symbol.for(Wd),Kd,Yd,Sn=class dd extends(Yd=we,Kd=Rv,Yd){constructor({value:t,cause:r,context:n}){let o="Type validation failed";if(n?.field&&(o+=` for ${n.field}`),n?.entityName||n?.entityId){o+=" (";const s=[];n.entityName&&s.push(n.entityName),n.entityId&&s.push(`id: "${n.entityId}"`),o+=s.join(", "),o+=")"}super({name:Gd,message:`${o}: Value: ${JSON.stringify(t)}.
3
- Error message: ${Tn(r)}`,cause:r}),this[Kd]=!0,this.value=t,this.context=n}static isInstance(t){return we.hasMarker(t,Wd)}static wrap({value:t,cause:r,context:n}){var o,s,i;return dd.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 dd({value:t,cause:r,context:n})}},Qd="AI_UnsupportedFunctionalityError",Xd=`vercel.ai.error.${Qd}`,Pv=Symbol.for(Xd),ep,tp,Mr=class extends(tp=we,ep=Pv,tp){constructor({functionality:t,message:r=`'${t}' functionality not supported.`}){super({name:Qd,message:r}),this[ep]=!0,this.functionality=t}static isInstance(t){return we.hasMarker(t,Xd)}};const rp=Object.freeze({status:"aborted"});function W(e,t,r){function n(a,l){var c;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(c=a._zod).traits??(c.traits=new Set),a._zod.traits.add(e),t(a,l);for(const u in i.prototype)u in a||Object.defineProperty(a,u,{value:i.prototype[u].bind(a)});a._zod.constr=i,a._zod.def=l}const o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:e});function i(a){var l;const c=r?.Parent?new s:this;n(c,a),(l=c._zod).deferred??(l.deferred=[]);for(const u of c._zod.deferred)u();return c}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}class Mo extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const np={};function Xr(e){return np}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 Mv(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 Nv(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 sp=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function Fs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Ov=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 Av=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 qv(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const Lv={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 jv(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 Dv(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 Uv(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 zv(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 Fv(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 Vv(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 ap=(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,Mv,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},ip=W("$ZodError",ap),lp=W("$ZodError",ap,{Parent:Error});function Zv(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 Bv(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 Hv=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 sp(a,o?.callee),a}return i.value},Jv=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 sp(a,o?.callee),a}return i.value},cp=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??ip)(s.issues.map(i=>en(i,o,Xr())))}:{success:!0,data:s.value}},up=cp(lp),dp=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=dp(lp),Wv=/^[cC][^\s-]{8,}$/,Kv=/^[0-9a-z]+$/,Yv=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Qv=/^[0-9a-vA-V]{20}$/,Xv=/^[A-Za-z0-9]{27}$/,e1=/^[a-zA-Z0-9_-]{21}$/,t1=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,r1=/^([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})$/,pp=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)$/,n1=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,o1="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function s1(){return new RegExp(o1,"u")}const a1=/^(?:(?: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])$/,i1=/^(([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})$/,l1=/^((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])$/,c1=/^(([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])$/,u1=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,fp=/^[A-Za-z0-9_-]*$/,d1=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,p1=/^\+(?:[0-9]){6,14}[0-9]$/,hp="(?:(?:\\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])))",f1=new RegExp(`^${hp}$`);function mp(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 h1(e){return new RegExp(`^${mp(e)}$`)}function m1(e){const t=mp({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(`^${hp}T(?:${n})$`)}const g1=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},_1=/^\d+$/,y1=/^-?\d+(?:\.\d+)?/i,v1=/true|false/i,w1=/null/i,b1=/^[^A-Z]*$/,k1=/^[^a-z]*$/,Bt=W("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),gp={number:"number",bigint:"bigint",object:"date"},_p=W("$ZodCheckLessThan",(e,t)=>{Bt.init(e,t);const r=gp[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})}}),yp=W("$ZodCheckGreaterThan",(e,t)=>{Bt.init(e,t);const r=gp[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})}}),T1=W("$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):Nv(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})}}),C1=W("$ZodCheckNumberFormat",(e,t)=>{Bt.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),n=r?"int":"number",[o,s]=Lv[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=_1)}),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})}}),S1=W("$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})}}),I1=W("$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})}}),x1=W("$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=W("$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=()=>{})}),E1=W("$ZodCheckRegex",(e,t)=>{Bs.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),$1=W("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=b1),Bs.init(e,t)}),R1=W("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=k1),Bs.init(e,t)}),P1=W("$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})}}),M1=W("$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})}}),N1=W("$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})}}),O1=W("$ZodCheckOverwrite",(e,t)=>{Bt.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});class A1{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(`
1
+ (function(Ur,Qn){typeof exports=="object"&&typeof module<"u"?Qn(exports):typeof define=="function"&&define.amd?define(["exports"],Qn):(Ur=typeof globalThis<"u"?globalThis:Ur||self,Qn(Ur.WebAgent={}))})(this,(function(Ur){"use strict";var Qn="vercel.ai.error",wv=Symbol.for(Qn),md,gd,we=class mv extends(gd=Error,md=wv,gd){constructor({name:t,message:r,cause:n}){super(r),this[md]=!0,this.name=t,this.cause=n}static isInstance(t){return mv.hasMarker(t,Qn)}static hasMarker(t,r){const n=Symbol.for(r);return t!=null&&typeof t=="object"&&n in t&&typeof t[n]=="boolean"&&t[n]===!0}},_d="AI_APICallError",yd=`vercel.ai.error.${_d}`,bv=Symbol.for(yd),vd,wd,lt=class extends(wd=we,vd=bv,wd){constructor({message:t,url:r,requestBodyValues:n,statusCode:o,responseHeaders:s,responseBody:i,cause:a,isRetryable:l=o!=null&&(o===408||o===409||o===429||o>=500),data:c}){super({name:_d,message:t,cause:a}),this[vd]=!0,this.url=r,this.requestBodyValues=n,this.statusCode=o,this.responseHeaders=s,this.responseBody=i,this.isRetryable=l,this.data=c}static isInstance(t){return we.hasMarker(t,yd)}},bd="AI_EmptyResponseBodyError",kd=`vercel.ai.error.${bd}`,kv=Symbol.for(kd),Td,Cd,Tv=class extends(Cd=we,Td=kv,Cd){constructor({message:t="Empty response body"}={}){super({name:bd,message:t}),this[Td]=!0}static isInstance(t){return we.hasMarker(t,kd)}};function Tn(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var Sd="AI_InvalidArgumentError",Id=`vercel.ai.error.${Sd}`,Cv=Symbol.for(Id),xd,Ed,$d=class extends(Ed=we,xd=Cv,Ed){constructor({message:t,cause:r,argument:n}){super({name:Sd,message:t,cause:r}),this[xd]=!0,this.argument=n}static isInstance(t){return we.hasMarker(t,Id)}},Rd="AI_InvalidPromptError",Pd=`vercel.ai.error.${Rd}`,Sv=Symbol.for(Pd),Md,Nd,Cn=class extends(Nd=we,Md=Sv,Nd){constructor({prompt:e,message:t,cause:r}){super({name:Rd,message:`Invalid prompt: ${t}`,cause:r}),this[Md]=!0,this.prompt=e}static isInstance(e){return we.hasMarker(e,Pd)}},Od="AI_InvalidResponseDataError",Ad=`vercel.ai.error.${Od}`,Iv=Symbol.for(Ad),qd,Ld,Yi=class extends(Ld=we,qd=Iv,Ld){constructor({data:t,message:r=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:Od,message:r}),this[qd]=!0,this.data=t}static isInstance(t){return we.hasMarker(t,Ad)}},jd="AI_JSONParseError",Dd=`vercel.ai.error.${jd}`,xv=Symbol.for(Dd),Ud,zd,Ds=class extends(zd=we,Ud=xv,zd){constructor({text:t,cause:r}){super({name:jd,message:`JSON parsing failed: Text: ${t}.
2
+ Error message: ${Tn(r)}`,cause:r}),this[Ud]=!0,this.text=t}static isInstance(t){return we.hasMarker(t,Dd)}},Fd="AI_LoadAPIKeyError",Vd=`vercel.ai.error.${Fd}`,Ev=Symbol.for(Vd),Zd,Bd,Us=class extends(Bd=we,Zd=Ev,Bd){constructor({message:t}){super({name:Fd,message:t}),this[Zd]=!0}static isInstance(t){return we.hasMarker(t,Vd)}},Hd="AI_TooManyEmbeddingValuesForCallError",Jd=`vercel.ai.error.${Hd}`,$v=Symbol.for(Jd),Wd,Gd,Rv=class extends(Gd=we,Wd=$v,Gd){constructor(e){super({name:Hd,message:`Too many values for a single embedding call. The ${e.provider} model "${e.modelId}" can only embed up to ${e.maxEmbeddingsPerCall} values per call, but ${e.values.length} values were provided.`}),this[Wd]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return we.hasMarker(e,Jd)}},Kd="AI_TypeValidationError",Yd=`vercel.ai.error.${Kd}`,Pv=Symbol.for(Yd),Qd,Xd,Sn=class fd extends(Xd=we,Qd=Pv,Xd){constructor({value:t,cause:r,context:n}){let o="Type validation failed";if(n?.field&&(o+=` for ${n.field}`),n?.entityName||n?.entityId){o+=" (";const s=[];n.entityName&&s.push(n.entityName),n.entityId&&s.push(`id: "${n.entityId}"`),o+=s.join(", "),o+=")"}super({name:Kd,message:`${o}: Value: ${JSON.stringify(t)}.
3
+ Error message: ${Tn(r)}`,cause:r}),this[Qd]=!0,this.value=t,this.context=n}static isInstance(t){return 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
4
  `).filter(i=>i),o=Math.min(...n.map(i=>i.length-i.trimStart().length)),s=n.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(const i of s)this.content.push(i)}compile(){const t=Function,r=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new t(...r,o.join(`
5
- `))}}const q1={major:4,minor:0,patch:0},Xe=W("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=q1;const n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(const o of n)for(const s of o._zod.onattach)s(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const o=(s,i,a)=>{let l=Ao(s),c;for(const u of i){if(u._zod.def.when){if(!u._zod.def.when(s))continue}else if(l)continue;const f=s.issues.length,p=u._zod.check(s);if(p instanceof Promise&&a?.async===!1)throw new Mo;if(c||p instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await p,s.issues.length!==f&&(l||(l=Ao(s,f)))});else{if(s.issues.length===f)continue;l||(l=Ao(s,f))}}return c?c.then(()=>s):s};e._zod.run=(s,i)=>{const a=e._zod.parse(s,i);if(a instanceof Promise){if(i.async===!1)throw new Mo;return a.then(l=>o(l,n,i))}return o(a,n,i)}}e["~standard"]={validate:o=>{try{const s=up(e,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Gv(e,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),rl=W("$ZodString",(e,t)=>{Xe.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??g1(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}}),st=W("$ZodStringFormat",(e,t)=>{Bs.init(e,t),rl.init(e,t)}),L1=W("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=r1),st.init(e,t)}),j1=W("$ZodUUID",(e,t)=>{if(t.version){const n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=pp(n))}else t.pattern??(t.pattern=pp());st.init(e,t)}),D1=W("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=n1),st.init(e,t)}),U1=W("$ZodURL",(e,t)=>{st.init(e,t),e._zod.check=r=>{try{const n=r.value,o=new URL(n),s=o.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:d1.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),!n.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),z1=W("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=s1()),st.init(e,t)}),F1=W("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=e1),st.init(e,t)}),V1=W("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Wv),st.init(e,t)}),Z1=W("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Kv),st.init(e,t)}),B1=W("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Yv),st.init(e,t)}),H1=W("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Qv),st.init(e,t)}),J1=W("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Xv),st.init(e,t)}),G1=W("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=m1(t)),st.init(e,t)}),W1=W("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=f1),st.init(e,t)}),K1=W("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=h1(t)),st.init(e,t)}),Y1=W("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=t1),st.init(e,t)}),Q1=W("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=a1),st.init(e,t),e._zod.onattach.push(r=>{const n=r._zod.bag;n.format="ipv4"})}),X1=W("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=i1),st.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})}}}),ew=W("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=l1),st.init(e,t)}),tw=W("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=c1),st.init(e,t),e._zod.check=r=>{const[n,o]=r.value.split("/");try{if(!o)throw new Error;const s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function vp(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const rw=W("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=u1),st.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{vp(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function nw(e){if(!fp.test(e))return!1;const t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return vp(r)}const ow=W("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=fp),st.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{nw(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),sw=W("$ZodE164",(e,t)=>{t.pattern??(t.pattern=p1),st.init(e,t)});function aw(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 iw=W("$ZodJWT",(e,t)=>{st.init(e,t),e._zod.check=r=>{aw(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),wp=W("$ZodNumber",(e,t)=>{Xe.init(e,t),e._zod.pattern=e._zod.bag.pattern??y1,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}const o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;const s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...s?{received:s}:{}}),r}}),lw=W("$ZodNumber",(e,t)=>{C1.init(e,t),wp.init(e,t)}),cw=W("$ZodBoolean",(e,t)=>{Xe.init(e,t),e._zod.pattern=v1,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}}),uw=W("$ZodNull",(e,t)=>{Xe.init(e,t),e._zod.pattern=w1,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}}),dw=W("$ZodAny",(e,t)=>{Xe.init(e,t),e._zod.parse=r=>r}),pw=W("$ZodUnknown",(e,t)=>{Xe.init(e,t),e._zod.parse=r=>r}),fw=W("$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 bp(e,t,r){e.issues.length&&t.issues.push(...xn(r,e.issues)),t.value[r]=e.value}const hw=W("$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 s=[];for(let i=0;i<o.length;i++){const a=o[i],l=t.element._zod.run({value:a,issues:[]},n);l instanceof Promise?s.push(l.then(c=>bp(c,r,i))):bp(l,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function Hs(e,t,r){e.issues.length&&t.issues.push(...xn(r,e.issues)),t.value[r]=e.value}function kp(e,t,r,n){e.issues.length?n[r]===void 0?r in n?t.value[r]=void 0:t.value[r]=e.value:t.issues.push(...xn(r,e.issues)):e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}const mw=W("$ZodObject",(e,t)=>{Xe.init(e,t);const r=Qi(()=>{const f=Object.keys(t.shape);for(const h of f)if(!(t.shape[h]instanceof Xe))throw new Error(`Invalid element at key "${h}": expected a Zod schema`);const p=qv(t.shape);return{shape:t.shape,keys:f,keySet:new Set(f),numKeys:f.length,optionalKeys:new Set(p)}});Ze(e._zod,"propValues",()=>{const f=t.shape,p={};for(const h in f){const g=f[h]._zod;if(g.values){p[h]??(p[h]=new Set);for(const v of g.values)p[h].add(v)}}return p});const n=f=>{const p=new A1(["shape","payload","ctx"]),h=r.value,g=y=>{const m=No(y);return`shape[${m}]._zod.run({ value: input[${m}], issues: [] }, ctx)`};p.write("const input = payload.value;");const v=Object.create(null);let _=0;for(const y of h.keys)v[y]=`key_${_++}`;p.write("const newResult = {}");for(const y of h.keys)if(h.optionalKeys.has(y)){const m=v[y];p.write(`const ${m} = ${g(y)};`);const C=No(y);p.write(`
5
+ `))}}const L1={major:4,minor:0,patch:0},Xe=G("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=L1;const n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(const o of n)for(const s of o._zod.onattach)s(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const o=(s,i,a)=>{let l=Ao(s),c;for(const u of i){if(u._zod.def.when){if(!u._zod.def.when(s))continue}else if(l)continue;const f=s.issues.length,p=u._zod.check(s);if(p instanceof Promise&&a?.async===!1)throw new Mo;if(c||p instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await p,s.issues.length!==f&&(l||(l=Ao(s,f)))});else{if(s.issues.length===f)continue;l||(l=Ao(s,f))}}return c?c.then(()=>s):s};e._zod.run=(s,i)=>{const a=e._zod.parse(s,i);if(a instanceof Promise){if(i.async===!1)throw new Mo;return a.then(l=>o(l,n,i))}return o(a,n,i)}}e["~standard"]={validate:o=>{try{const s=pp(e,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Gv(e,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),rl=G("$ZodString",(e,t)=>{Xe.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??_1(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),st=G("$ZodStringFormat",(e,t)=>{Bs.init(e,t),rl.init(e,t)}),j1=G("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=n1),st.init(e,t)}),D1=G("$ZodUUID",(e,t)=>{if(t.version){const n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=hp(n))}else t.pattern??(t.pattern=hp());st.init(e,t)}),U1=G("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=o1),st.init(e,t)}),z1=G("$ZodURL",(e,t)=>{st.init(e,t),e._zod.check=r=>{try{const n=r.value,o=new URL(n),s=o.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:p1.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),!n.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),F1=G("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=a1()),st.init(e,t)}),V1=G("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=t1),st.init(e,t)}),Z1=G("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Kv),st.init(e,t)}),B1=G("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Yv),st.init(e,t)}),H1=G("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Qv),st.init(e,t)}),J1=G("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Xv),st.init(e,t)}),W1=G("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=e1),st.init(e,t)}),G1=G("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=g1(t)),st.init(e,t)}),K1=G("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=h1),st.init(e,t)}),Y1=G("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=m1(t)),st.init(e,t)}),Q1=G("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=r1),st.init(e,t)}),X1=G("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=i1),st.init(e,t),e._zod.onattach.push(r=>{const n=r._zod.bag;n.format="ipv4"})}),ew=G("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=l1),st.init(e,t),e._zod.onattach.push(r=>{const n=r._zod.bag;n.format="ipv6"}),e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),tw=G("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=c1),st.init(e,t)}),rw=G("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=u1),st.init(e,t),e._zod.check=r=>{const[n,o]=r.value.split("/");try{if(!o)throw new Error;const s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function bp(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const nw=G("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=d1),st.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{bp(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function ow(e){if(!mp.test(e))return!1;const t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return bp(r)}const sw=G("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=mp),st.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{ow(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),aw=G("$ZodE164",(e,t)=>{t.pattern??(t.pattern=f1),st.init(e,t)});function iw(e,t=null){try{const r=e.split(".");if(r.length!==3)return!1;const[n]=r;if(!n)return!1;const o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}const lw=G("$ZodJWT",(e,t)=>{st.init(e,t),e._zod.check=r=>{iw(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),kp=G("$ZodNumber",(e,t)=>{Xe.init(e,t),e._zod.pattern=e._zod.bag.pattern??v1,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}const o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;const s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...s?{received:s}:{}}),r}}),cw=G("$ZodNumber",(e,t)=>{S1.init(e,t),kp.init(e,t)}),uw=G("$ZodBoolean",(e,t)=>{Xe.init(e,t),e._zod.pattern=w1,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=!!r.value}catch{}const o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),r}}),dw=G("$ZodNull",(e,t)=>{Xe.init(e,t),e._zod.pattern=b1,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{const o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),r}}),pw=G("$ZodAny",(e,t)=>{Xe.init(e,t),e._zod.parse=r=>r}),fw=G("$ZodUnknown",(e,t)=>{Xe.init(e,t),e._zod.parse=r=>r}),hw=G("$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 Tp(e,t,r){e.issues.length&&t.issues.push(...xn(r,e.issues)),t.value[r]=e.value}const mw=G("$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 s=[];for(let i=0;i<o.length;i++){const a=o[i],l=t.element._zod.run({value:a,issues:[]},n);l instanceof Promise?s.push(l.then(c=>Tp(c,r,i))):Tp(l,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function Hs(e,t,r){e.issues.length&&t.issues.push(...xn(r,e.issues)),t.value[r]=e.value}function Cp(e,t,r,n){e.issues.length?n[r]===void 0?r in n?t.value[r]=void 0:t.value[r]=e.value:t.issues.push(...xn(r,e.issues)):e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}const gw=G("$ZodObject",(e,t)=>{Xe.init(e,t);const r=Qi(()=>{const f=Object.keys(t.shape);for(const h of f)if(!(t.shape[h]instanceof Xe))throw new Error(`Invalid element at key "${h}": expected a Zod schema`);const p=Lv(t.shape);return{shape:t.shape,keys:f,keySet:new Set(f),numKeys:f.length,optionalKeys:new Set(p)}});Ze(e._zod,"propValues",()=>{const f=t.shape,p={};for(const h in f){const g=f[h]._zod;if(g.values){p[h]??(p[h]=new Set);for(const v of g.values)p[h].add(v)}}return p});const n=f=>{const p=new q1(["shape","payload","ctx"]),h=r.value,g=y=>{const m=No(y);return`shape[${m}]._zod.run({ value: input[${m}], issues: [] }, ctx)`};p.write("const input = payload.value;");const v=Object.create(null);let _=0;for(const y of h.keys)v[y]=`key_${_++}`;p.write("const newResult = {}");for(const y of h.keys)if(h.optionalKeys.has(y)){const m=v[y];p.write(`const ${m} = ${g(y)};`);const C=No(y);p.write(`
6
6
  if (${m}.issues.length) {
7
7
  if (input[${C}] === undefined) {
8
8
  if (${C} in input) {
@@ -25,17 +25,17 @@ Error message: ${Tn(r)}`,cause:r}),this[Kd]=!0,this.value=t,this.context=n}stati
25
25
  if (${m}.issues.length) payload.issues = payload.issues.concat(${m}.issues.map(iss => ({
26
26
  ...iss,
27
27
  path: iss.path ? [${No(y)}, ...iss.path] : [${No(y)}]
28
- })));`),p.write(`newResult[${No(y)}] = ${m}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");const w=p.compile();return(y,m)=>w(f,y,m)};let o;const s=Fs,i=!np.jitless,l=i&&Ov.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?kp(R,f,C,h):Hs(R,f,C))):I?kp(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 Tp(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 Cp=W("$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=>Tp(i,r,e,n)):Tp(s,r,e,n)}}),gw=W("$ZodDiscriminatedUnion",(e,t)=>{Cp.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)}}),_w=W("$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])=>Sp(r,l,c)):Sp(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 Sp(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 yw=W("$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}}),vw=W("$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=>Av.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}}),ww=W("$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}}),bw=W("$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}}),kw=W("$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)}),Tw=W("$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)}),Cw=W("$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=>Ip(s,t)):Ip(o,t)}});function Ip(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const Sw=W("$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))}),Iw=W("$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=>xp(s,e)):xp(o,e)}});function xp(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 xw=W("$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)}}),Ew=W("$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=>Ep(s,t,n)):Ep(o,t,n)}});function Ep(e,t,r){return Ao(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}const $w=W("$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($p):$p(o)}});function $p(e){return e.value=Object.freeze(e.value),e}const Rw=W("$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)}),Pw=W("$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=>Rp(s,r,n,e));Rp(o,r,n,e)}});function Rp(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 Pp{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 Mw(){return new Pp}const Lo=Mw();function Nw(e,t){return new e({type:"string",...fe(t)})}function Ow(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...fe(t)})}function Mp(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...fe(t)})}function Aw(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...fe(t)})}function qw(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...fe(t)})}function Lw(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...fe(t)})}function jw(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...fe(t)})}function Np(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...fe(t)})}function Dw(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...fe(t)})}function Uw(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...fe(t)})}function zw(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...fe(t)})}function Fw(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...fe(t)})}function Vw(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...fe(t)})}function Zw(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...fe(t)})}function Bw(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...fe(t)})}function Hw(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...fe(t)})}function Jw(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 Ww(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...fe(t)})}function Op(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...fe(t)})}function Kw(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...fe(t)})}function Yw(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...fe(t)})}function Qw(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...fe(t)})}function Xw(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...fe(t)})}function eb(e,t){return new e({type:"string",format:"date",check:"string_format",...fe(t)})}function tb(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...fe(t)})}function rb(e,t){return new e({type:"string",format:"duration",check:"string_format",...fe(t)})}function nb(e,t){return new e({type:"number",checks:[],...fe(t)})}function ob(e,t){return new e({type:"number",coerce:!0,checks:[],...fe(t)})}function sb(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...fe(t)})}function ab(e,t){return new e({type:"boolean",...fe(t)})}function ib(e,t){return new e({type:"null",...fe(t)})}function lb(e){return new e({type:"any"})}function cb(e){return new e({type:"unknown"})}function ub(e,t){return new e({type:"never",...fe(t)})}function Ap(e,t){return new _p({check:"less_than",...fe(t),value:e,inclusive:!1})}function ol(e,t){return new _p({check:"less_than",...fe(t),value:e,inclusive:!0})}function qp(e,t){return new yp({check:"greater_than",...fe(t),value:e,inclusive:!1})}function sl(e,t){return new yp({check:"greater_than",...fe(t),value:e,inclusive:!0})}function Lp(e,t){return new T1({check:"multiple_of",...fe(t),value:e})}function jp(e,t){return new S1({check:"max_length",...fe(t),maximum:e})}function Js(e,t){return new I1({check:"min_length",...fe(t),minimum:e})}function Dp(e,t){return new x1({check:"length_equals",...fe(t),length:e})}function db(e,t){return new E1({check:"string_format",format:"regex",...fe(t),pattern:e})}function pb(e){return new $1({check:"string_format",format:"lowercase",...fe(e)})}function fb(e){return new R1({check:"string_format",format:"uppercase",...fe(e)})}function hb(e,t){return new P1({check:"string_format",format:"includes",...fe(t),includes:e})}function mb(e,t){return new M1({check:"string_format",format:"starts_with",...fe(t),prefix:e})}function gb(e,t){return new N1({check:"string_format",format:"ends_with",...fe(t),suffix:e})}function jo(e){return new O1({check:"overwrite",tx:e})}function _b(e){return jo(t=>t.normalize(e))}function yb(){return jo(e=>e.trim())}function vb(){return jo(e=>e.toLowerCase())}function wb(){return jo(e=>e.toUpperCase())}function bb(e,t,r){return new e({type:"array",element:t,...fe(r)})}function kb(e,t,r){const n=fe(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function Tb(e,t,r){return new e({type:"custom",check:"custom",fn:t,...fe(r)})}class Up{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=op(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>
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
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 Cb(e,t){if(e instanceof Pp){const n=new Up(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 Up(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 Sb=W("ZodISODateTime",(e,t)=>{G1.init(e,t),ct.init(e,t)});function zp(e){return Xw(Sb,e)}const Ib=W("ZodISODate",(e,t)=>{W1.init(e,t),ct.init(e,t)});function xb(e){return eb(Ib,e)}const Eb=W("ZodISOTime",(e,t)=>{K1.init(e,t),ct.init(e,t)});function $b(e){return tb(Eb,e)}const Rb=W("ZodISODuration",(e,t)=>{Y1.init(e,t),ct.init(e,t)});function Pb(e){return rb(Rb,e)}const Gs=W("ZodError",(e,t)=>{ip.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>Bv(e,r)},flatten:{value:r=>Zv(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}),Mb=Hv(Gs),Nb=Jv(Gs),Ob=cp(Gs),Fp=dp(Gs),rt=W("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)=>Mb(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>Ob(e,r,n),e.parseAsync=async(r,n)=>Nb(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>Fp(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check(C3(r,n)),e.superRefine=r=>e.check(S3(r)),e.overwrite=r=>e.check(jo(r)),e.optional=()=>de(e),e.nullable=()=>Xp(e),e.nullish=()=>de(Xp(e)),e.nonoptional=r=>g3(e,r),e.array=()=>q(e),e.or=r=>ae([e,r]),e.and=r=>il(e,r),e.transform=r=>cl(e,Yp(r)),e.default=r=>f3(e,r),e.prefault=r=>m3(e,r),e.catch=r=>y3(e,r),e.pipe=r=>cl(e,r),e.readonly=()=>b3(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)),Vp=W("_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(db(...n)),e.includes=(...n)=>e.check(hb(...n)),e.startsWith=(...n)=>e.check(mb(...n)),e.endsWith=(...n)=>e.check(gb(...n)),e.min=(...n)=>e.check(Js(...n)),e.max=(...n)=>e.check(jp(...n)),e.length=(...n)=>e.check(Dp(...n)),e.nonempty=(...n)=>e.check(Js(1,...n)),e.lowercase=n=>e.check(pb(n)),e.uppercase=n=>e.check(fb(n)),e.trim=()=>e.check(yb()),e.normalize=(...n)=>e.check(_b(...n)),e.toLowerCase=()=>e.check(vb()),e.toUpperCase=()=>e.check(wb())}),Ab=W("ZodString",(e,t)=>{rl.init(e,t),Vp.init(e,t),e.email=r=>e.check(Ow(qb,r)),e.url=r=>e.check(Np(Bp,r)),e.jwt=r=>e.check(Qw(Yb,r)),e.emoji=r=>e.check(Dw(jb,r)),e.guid=r=>e.check(Mp(Zp,r)),e.uuid=r=>e.check(Aw(Ws,r)),e.uuidv4=r=>e.check(qw(Ws,r)),e.uuidv6=r=>e.check(Lw(Ws,r)),e.uuidv7=r=>e.check(jw(Ws,r)),e.nanoid=r=>e.check(Uw(Db,r)),e.guid=r=>e.check(Mp(Zp,r)),e.cuid=r=>e.check(zw(Ub,r)),e.cuid2=r=>e.check(Fw(zb,r)),e.ulid=r=>e.check(Vw(Fb,r)),e.base64=r=>e.check(Op(Hp,r)),e.base64url=r=>e.check(Kw(Wb,r)),e.xid=r=>e.check(Zw(Vb,r)),e.ksuid=r=>e.check(Bw(Zb,r)),e.ipv4=r=>e.check(Hw(Bb,r)),e.ipv6=r=>e.check(Jw(Hb,r)),e.cidrv4=r=>e.check(Gw(Jb,r)),e.cidrv6=r=>e.check(Ww(Gb,r)),e.e164=r=>e.check(Yw(Kb,r)),e.datetime=r=>e.check(zp(r)),e.date=r=>e.check(xb(r)),e.time=r=>e.check($b(r)),e.duration=r=>e.check(Pb(r))});function d(e){return Nw(Ab,e)}const ct=W("ZodStringFormat",(e,t)=>{st.init(e,t),Vp.init(e,t)}),qb=W("ZodEmail",(e,t)=>{D1.init(e,t),ct.init(e,t)}),Zp=W("ZodGUID",(e,t)=>{L1.init(e,t),ct.init(e,t)}),Ws=W("ZodUUID",(e,t)=>{j1.init(e,t),ct.init(e,t)}),Bp=W("ZodURL",(e,t)=>{U1.init(e,t),ct.init(e,t)});function Lb(e){return Np(Bp,e)}const jb=W("ZodEmoji",(e,t)=>{z1.init(e,t),ct.init(e,t)}),Db=W("ZodNanoID",(e,t)=>{F1.init(e,t),ct.init(e,t)}),Ub=W("ZodCUID",(e,t)=>{V1.init(e,t),ct.init(e,t)}),zb=W("ZodCUID2",(e,t)=>{Z1.init(e,t),ct.init(e,t)}),Fb=W("ZodULID",(e,t)=>{B1.init(e,t),ct.init(e,t)}),Vb=W("ZodXID",(e,t)=>{H1.init(e,t),ct.init(e,t)}),Zb=W("ZodKSUID",(e,t)=>{J1.init(e,t),ct.init(e,t)}),Bb=W("ZodIPv4",(e,t)=>{Q1.init(e,t),ct.init(e,t)}),Hb=W("ZodIPv6",(e,t)=>{X1.init(e,t),ct.init(e,t)}),Jb=W("ZodCIDRv4",(e,t)=>{ew.init(e,t),ct.init(e,t)}),Gb=W("ZodCIDRv6",(e,t)=>{tw.init(e,t),ct.init(e,t)}),Hp=W("ZodBase64",(e,t)=>{rw.init(e,t),ct.init(e,t)});function Jp(e){return Op(Hp,e)}const Wb=W("ZodBase64URL",(e,t)=>{ow.init(e,t),ct.init(e,t)}),Kb=W("ZodE164",(e,t)=>{sw.init(e,t),ct.init(e,t)}),Yb=W("ZodJWT",(e,t)=>{iw.init(e,t),ct.init(e,t)}),al=W("ZodNumber",(e,t)=>{wp.init(e,t),rt.init(e,t),e.gt=(n,o)=>e.check(qp(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(Ap(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(Gp(n)),e.safe=n=>e.check(Gp(n)),e.positive=n=>e.check(qp(0,n)),e.nonnegative=n=>e.check(sl(0,n)),e.negative=n=>e.check(Ap(0,n)),e.nonpositive=n=>e.check(ol(0,n)),e.multipleOf=(n,o)=>e.check(Lp(n,o)),e.step=(n,o)=>e.check(Lp(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 nb(al,e)}const Qb=W("ZodNumberFormat",(e,t)=>{lw.init(e,t),al.init(e,t)});function Gp(e){return sb(Qb,e)}const Xb=W("ZodBoolean",(e,t)=>{cw.init(e,t),rt.init(e,t)});function me(e){return ab(Xb,e)}const e3=W("ZodNull",(e,t)=>{uw.init(e,t),rt.init(e,t)});function Do(e){return ib(e3,e)}const t3=W("ZodAny",(e,t)=>{dw.init(e,t),rt.init(e,t)});function yt(){return lb(t3)}const r3=W("ZodUnknown",(e,t)=>{pw.init(e,t),rt.init(e,t)});function Ce(){return cb(r3)}const n3=W("ZodNever",(e,t)=>{fw.init(e,t),rt.init(e,t)});function o3(e){return ub(n3,e)}const s3=W("ZodArray",(e,t)=>{hw.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(jp(r,n)),e.length=(r,n)=>e.check(Dp(r,n)),e.unwrap=()=>e.element});function q(e,t){return bb(s3,e,t)}const Wp=W("ZodObject",(e,t)=>{mw.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:o3()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>Uv(e,r),e.merge=r=>zv(e,r),e.pick=r=>jv(e,r),e.omit=r=>Dv(e,r),e.partial=(...r)=>Fv(Qp,e,r[0]),e.required=(...r)=>Vv(ef,e,r[0])});function k(e,t){const r={type:"object",get shape(){return zs(this,"shape",{...e}),this.shape},...fe(t)};return new Wp(r)}function ut(e,t){return new Wp({type:"object",get shape(){return zs(this,"shape",{...e}),this.shape},catchall:Ce(),...fe(t)})}const Kp=W("ZodUnion",(e,t)=>{Cp.init(e,t),rt.init(e,t),e.options=t.options});function ae(e,t){return new Kp({type:"union",options:e,...fe(t)})}const a3=W("ZodDiscriminatedUnion",(e,t)=>{Kp.init(e,t),gw.init(e,t)});function ze(e,t,r){return new a3({type:"union",options:t,discriminator:e,...fe(r)})}const i3=W("ZodIntersection",(e,t)=>{_w.init(e,t),rt.init(e,t)});function il(e,t){return new i3({type:"intersection",left:e,right:t})}const l3=W("ZodRecord",(e,t)=>{yw.init(e,t),rt.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function ge(e,t,r){return new l3({type:"record",keyType:e,valueType:t,...fe(r)})}const ll=W("ZodEnum",(e,t)=>{vw.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 c3=W("ZodLiteral",(e,t)=>{ww.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 c3({type:"literal",values:Array.isArray(e)?e:[e],...fe(t)})}const u3=W("ZodTransform",(e,t)=>{bw.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 Yp(e){return new u3({type:"transform",transform:e})}const Qp=W("ZodOptional",(e,t)=>{kw.init(e,t),rt.init(e,t),e.unwrap=()=>e._zod.def.innerType});function de(e){return new Qp({type:"optional",innerType:e})}const d3=W("ZodNullable",(e,t)=>{Tw.init(e,t),rt.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Xp(e){return new d3({type:"nullable",innerType:e})}const p3=W("ZodDefault",(e,t)=>{Cw.init(e,t),rt.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function f3(e,t){return new p3({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const h3=W("ZodPrefault",(e,t)=>{Sw.init(e,t),rt.init(e,t),e.unwrap=()=>e._zod.def.innerType});function m3(e,t){return new h3({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const ef=W("ZodNonOptional",(e,t)=>{Iw.init(e,t),rt.init(e,t),e.unwrap=()=>e._zod.def.innerType});function g3(e,t){return new ef({type:"nonoptional",innerType:e,...fe(t)})}const _3=W("ZodCatch",(e,t)=>{xw.init(e,t),rt.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function y3(e,t){return new _3({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const v3=W("ZodPipe",(e,t)=>{Ew.init(e,t),rt.init(e,t),e.in=t.in,e.out=t.out});function cl(e,t){return new v3({type:"pipe",in:e,out:t})}const w3=W("ZodReadonly",(e,t)=>{$w.init(e,t),rt.init(e,t)});function b3(e){return new w3({type:"readonly",innerType:e})}const k3=W("ZodLazy",(e,t)=>{Rw.init(e,t),rt.init(e,t),e.unwrap=()=>e._zod.def.getter()});function Ks(e){return new k3({type:"lazy",getter:e})}const ul=W("ZodCustom",(e,t)=>{Pw.init(e,t),rt.init(e,t)});function T3(e){const t=new Bt({check:"custom"});return t._zod.check=e,t}function tf(e,t){return kb(ul,e??(()=>!0),t)}function C3(e,t={}){return Tb(ul,e,t)}function S3(e){const t=T3(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 rf(e,t){return cl(Yp(e),t)}const nf={custom:"custom"};function of(e){return ob(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 sf;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(sf||(sf={}));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 I3=dl;function x3(){return I3}const E3=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=x3(),n=E3({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}),af=e=>e.status==="aborted",lf=e=>e.status==="dirty",Qn=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 cf=(e,t)=>{if(Qn(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 cf(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 Qn(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=>Qn(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 cf(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 ro({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 no.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 ro({...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 Y3({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 $3=/^c[^\s-]{8,}$/i,R3=/^[0-9a-z]+$/,P3=/^[0-9A-HJKMNP-TV-Z]{26}$/i,M3=/^[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,N3=/^[a-z0-9_-]{21}$/i,O3=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,A3=/^[-+]?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)?)??$/,q3=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,L3="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let pl;const j3=/^(?:(?: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])$/,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])\/(3[0-2]|[12]?[0-9])$/,U3=/^(([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]))$/,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]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,F3=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,V3=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,uf="((\\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])))",Z3=new RegExp(`^${uf}$`);function df(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 B3(e){return new RegExp(`^${df(e)}$`)}function H3(e){let t=`${uf}T${df(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 J3(e,t){return!!((t==="v4"||!t)&&j3.test(e)||(t==="v6"||!t)&&U3.test(e))}function G3(e,t){if(!O3.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 W3(e,t){return!!((t==="v4"||!t)&&D3.test(e)||(t==="v6"||!t)&&z3.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")q3.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(L3,"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")M3.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")N3.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")$3.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")R3.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")P3.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"?H3(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"?Z3.test(t.data)||(o=this._getOrReturnCtx(t,o),le(o,{code:oe.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?B3(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"?A3.test(t.data)||(o=this._getOrReturnCtx(t,o),le(o,{validation:"duration",code:oe.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?J3(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"?W3(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"?F3.test(t.data)||(o=this._getOrReturnCtx(t,o),le(o,{validation:"base64",code:oe.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?V3.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 K3(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 Xn 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"?K3(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 Xn({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:he.toString(o)}]})}_addCheck(t){return new Xn({...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)}}Xn.create=e=>new Xn({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 pf 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)}}pf.create=e=>new pf({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 ff 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)}}ff.create=e=>new ff({typeName:se.ZodSymbol,...Ne(e)});class hf 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)}}hf.create=e=>new hf({typeName:se.ZodUndefined,...Ne(e)});class mf 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)}}mf.create=e=>new mf({typeName:se.ZodNull,...Ne(e)});class gf extends De{constructor(){super(...arguments),this._any=!0}_parse(t){return cr(t.data)}}gf.create=e=>new gf({typeName:se.ZodAny,...Ne(e)});class _f extends De{constructor(){super(...arguments),this._unknown=!0}_parse(t){return cr(t.data)}}_f.create=e=>new _f({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 yf 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)}}yf.create=e=>new yf({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 eo(e){if(e instanceof vt){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=sn.create(eo(n))}return new vt({...e._def,shape:()=>t})}else return e instanceof Nr?new Nr({...e._def,type:eo(e.element)}):e instanceof sn?sn.create(eo(e.unwrap())):e instanceof no?no.create(eo(e.unwrap())):e instanceof En?En.create(e.items.map(t=>eo(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 eo(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 kf(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(af(s)||af(i))return Ie;const a=fl(s.value,i.value);return a.valid?((lf(s)||lf(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 vf 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}}}}vf.create=(e,t,r)=>new vf({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 wf 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})}}wf.create=(e,t)=>new wf({getter:e,typeName:se.ZodLazy,...Ne(t)});class bf 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}}bf.create=(e,t)=>new bf({value:e,typeName:se.ZodLiteral,...Ne(t)});function kf(e,t){return new to({values:e,typeName:se.ZodEnum,...Ne(t)})}class to 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 to.create(t,{...this._def,...r})}exclude(t,r=this._def){return to.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}}to.create=kf;class Tf 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}}Tf.create=(e,t)=>new Tf({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 ro 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(!Qn(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=>Qn(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):Ie);Fe.assertNever(o)}}ro.create=(e,t,r)=>new ro({schema:e,typeName:se.ZodEffects,effect:t,...Ne(r)}),ro.createWithPreprocess=(e,t,r)=>new ro({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 no extends De{_parse(t){return this._getType(t)===pe.null?cr(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}no.create=(e,t)=>new no({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 Cf 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}}}Cf.create=e=>new Cf({typeName:se.ZodNaN,...Ne(e)});class Y3 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=>(Qn(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=Xn.create;on.create;const an=Nr.create,yr=vt.create,yl=ea.create;ta.create,En.create;const na=to.create;ra.create,sn.create,no.create;class Sf 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 If(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]=Q3(`${s}${_}`);for(const m of w)f(m);s=y,i=!1}function f(v){if(v===""){h();return}if(v.startsWith(":")){o&&o(v.slice(v.startsWith(": ")?2:1));return}const _=v.indexOf(":");if(_!==-1){const w=v.slice(0,_),y=v[_+1]===" "?2:1,m=v.slice(_+y);p(w,m,v);return}p(v,"",v)}function p(v,_,w){switch(v){case"event":c=_;break;case"data":l=`${l}${_}
31
- `;break;case"id":a=_.includes("\0")?void 0:_;break;case"retry":/^\d+$/.test(_)?n(parseInt(_,10)):r(new Sf(`Invalid \`retry\` value: "${_}"`,{type:"invalid-retry",value:_,line:w}));break;default:r(new Sf(`Unknown field "${v.length>20?`${v.slice(0,20)}…`:v}"`,{type:"unknown-field",field:v,value:_,line:w}));break}}function h(){l.length>0&&t({id:a,event:c||void 0,data:l.endsWith(`
32
- `)?l.slice(0,-1):l}),a=void 0,l="",c=""}function g(v={}){s&&v.consume&&f(s),i=!0,a=void 0,l="",c="",s=""}return{feed:u,reset:g}}function Q3(e){const t=[];let r="",n=0;for(;n<e.length;){const o=e.indexOf("\r",n),s=e.indexOf(`
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
+ `;break;case"id":a=_.includes("\0")?void 0:_;break;case"retry":/^\d+$/.test(_)?n(parseInt(_,10)):r(new xf(`Invalid \`retry\` value: "${_}"`,{type:"invalid-retry",value:_,line:w}));break;default:r(new xf(`Unknown field "${v.length>20?`${v.slice(0,20)}…`:v}"`,{type:"unknown-field",field:v,value:_,line:w}));break}}function h(){l.length>0&&t({id:a,event:c||void 0,data:l.endsWith(`
32
+ `)?l.slice(0,-1):l}),a=void 0,l="",c=""}function g(v={}){s&&v.consume&&f(s),i=!0,a=void 0,l="",c="",s=""}return{feed:u,reset:g}}function X3(e){const t=[];let r="",n=0;for(;n<e.length;){const o=e.indexOf("\r",n),s=e.indexOf(`
33
33
  `,n);let i=-1;if(o!==-1&&s!==-1?i=Math.min(o,s):o!==-1?o===e.length-1?i=-1:i=o:s!==-1&&(i=s),i===-1){r=e.slice(n);break}else{const a=e.slice(n,i);t.push(a),n=i+1,e[n-1]==="\r"&&e[n]===`
34
- `&&n++}}return[t,r]}class oo extends TransformStream{constructor({onError:t,onRetry:r,onComment:n}={}){let o;super({start(s){o=If({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 X3({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 e9(e,t){if(e==null)return Promise.resolve();const r=t?.abortSignal;return new Promise((n,o)=>{if(r?.aborted){o(xf());return}const s=setTimeout(()=>{i(),n()},e),i=()=>{clearTimeout(s),r?.removeEventListener("abort",a)},a=()=>{i(),o(xf())};r?.addEventListener("abort",a)})}function xf(){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 so(e){return Object.fromEntries([...e.headers])}var{btoa:t9,atob:r9}=globalThis;function ao(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=r9(t);return Uint8Array.from(r,n=>n.codePointAt(0))}function io(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return t9(t)}function lo(e){return e instanceof Uint8Array?io(e):e}function n9(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 Ef="AI_DownloadError",$f=`vercel.ai.error.${Ef}`,o9=Symbol.for($f),Rf,Pf,Ht=class extends(Pf=we,Rf=o9,Pf){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:Ef,message:o,cause:n}),this[Rf]=!0,this.url=e,this.statusCode=t,this.statusText=r}static isInstance(e){return we.hasMarker(e,$f)}},wl=2*1024*1024*1024;async function Mf({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!=="http:"&&t.protocol!=="https:")throw new Ht({url:e,message:`URL scheme must be http or https, 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(s9(n))throw new Ht({url:e,message:`URL with IPv6 address ${r} is not allowed`});return}if(Nf(r)){if(bl(r))throw new Ht({url:e,message:`URL with IP address ${r} is not allowed`});return}}function Nf(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 s9(e){const t=e.toLowerCase();if(t==="::1"||t==="::")return!0;if(t.startsWith("::ffff:")){const r=t.slice(7);if(Nf(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 Of(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 Mf({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 xd({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 a9=["fetch failed","failed to fetch"],i9=["ConnectionRefused","ConnectionClosed","FailedToOpenSocket","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE"];function l9(e){if(!(e instanceof Error))return!1;const t=e.code;return!!(typeof t=="string"&&i9.includes(t))}function Af({error:e,url:t,requestBodyValues:r}){if($n(e))return e;if(e instanceof TypeError&&a9.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 l9(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 c9(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(c9(e)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var qf="4.0.21",u9=()=>globalThis.fetch,sa=async({url:e,headers:t={},successfulResponseHandler:r,failedResponseHandler:n,abortSignal:o,fetch:s=u9()})=>{try{const i=await s(e,{method:"GET",headers:ln(t,`ai-sdk/provider-utils/${qf}`,Bo()),signal:o}),a=so(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 Af({error:i,url:e,requestBodyValues:{}})}};function Lf(e){return e!=null}function d9({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 p9({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 co({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 f9(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 h9=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,m9=/"(?: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 jf(e){const t=JSON.parse(e);return t===null||typeof t!="object"||h9.test(e)===!1&&m9.test(e)===!1?t:g9(t)}function g9(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 jf(e)}try{return jf(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 _9=Symbol("Let zodToJsonSchema decide on which parser to use"),Df={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"},y9=e=>typeof e=="string"?{...Df,name:e}:{...Df,...e};function er(){return{}}function v9(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 w9(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 b9(){return{type:"boolean"}}function Uf(e,t){return Je(e.type._def,t)}var k9=(e,t)=>Je(e.innerType._def,t);function zf(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>zf(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 T9(e)}}var T9=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 C9(e,t){return{...Je(e.innerType._def,t),default:e.defaultValue()}}function S9(e,t){return t.effectStrategy==="input"?Je(e.schema._def,t):er()}function I9(e){return{type:"string",enum:Array.from(e.values)}}var x9=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function E9(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(x9(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 $9(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 Ff(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"?P9(e):e}var R9=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function P9(e){let t="";for(let r=0;r<e.length;r++)R9.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: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 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
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
35
  ]))`;continue}else if(o[c]==="$"){s+=`($|(?=[\r
36
36
  ]))`;continue}}if(n.s&&o[c]==="."){s+=a?`${o[c]}\r
37
37
  `:`[${o[c]}\r
38
- ]`;continue}s+=o[c],o[c]==="\\"?i=!0:a&&o[c]==="]"?a=!1:!a&&o[c]==="["&&(a=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return s}function Zf(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}=Ff(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}=Uf(e.keyType._def,t);return{...l,propertyNames:u}}}return l}function M9(e,t){if(t.mapStrategy==="record")return Zf(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 N9(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 O9(){return{not:er()}}function A9(){return{type:"null"}}var xl={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function q9(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 L9(e,t)}var L9=(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 j9(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 D9(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 U9(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=F9(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=z9(e,t);return s!==void 0&&(r.additionalProperties=s),r}function z9(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 F9(e){try{return e.isOptional()}catch{return!0}}var V9=(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()},Z9=(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 B9(e,t){return Je(e.type._def,t)}function H9(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 J9(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 W9(){return er()}var K9=(e,t)=>Je(e.innerType._def,t),Y9=(e,t,r)=>{switch(t){case se.ZodString:return Ff(e,r);case se.ZodNumber:return D9(e);case se.ZodObject:return U9(e,r);case se.ZodBigInt:return w9(e);case se.ZodBoolean:return b9();case se.ZodDate:return zf(e,r);case se.ZodUndefined:return G9();case se.ZodNull:return A9();case se.ZodArray:return v9(e,r);case se.ZodUnion:case se.ZodDiscriminatedUnion:return q9(e,r);case se.ZodIntersection:return E9(e,r);case se.ZodTuple:return J9(e,r);case se.ZodRecord:return Zf(e,r);case se.ZodLiteral:return $9(e);case se.ZodEnum:return I9(e);case se.ZodNativeEnum:return N9(e);case se.ZodNullable:return j9(e,r);case se.ZodOptional:return V9(e,r);case se.ZodMap:return M9(e,r);case se.ZodSet:return H9(e,r);case se.ZodLazy:return()=>e.getter()._def;case se.ZodPromise:return B9(e,r);case se.ZodNaN:case se.ZodNever:return O9();case se.ZodEffects:return S9(e,r);case se.ZodAny:return er();case se.ZodUnknown:return W9();case se.ZodDefault:return C9(e,r);case se.ZodBranded:return Uf(e,r);case se.ZodReadonly:return K9(e,r);case se.ZodCatch:return k9(e,r);case se.ZodPipeline:return Z9(e,r);case se.ZodFunction:case se.ZodVoid:case se.ZodSymbol:return;default:return(n=>{})()}},Q9=(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!==_9)return l}if(o&&!r){const l=X9(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=Y9(e,e.typeName,t),a=typeof i=="function"?Je(i(),t):i;if(a&&e4(e,t,a),t.postProcess){const l=t.postProcess(a,e,t);return s.jsonSchema=a,l}return s.jsonSchema=a,a}var X9=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Q9(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}},e4=(e,t,r)=>(e.description&&(r.description=e.description),r),t4=e=>{const t=y9(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}]))}},r4=(e,t)=>{var r;const n=t4(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 uo(e,{validate:t}={}){return{[El]:!0,_type:void 0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}function n4(e){return typeof e=="object"&&e!==null&&El in e&&e[El]===!0&&"jsonSchema"in e&&"validate"in e}function Pn(e){return e==null?uo({properties:{},additionalProperties:!1}):n4(e)?e:"~standard"in e?e["~standard"].vendor==="zod"?ye(e):o4(e):e()}function o4(e){return uo(()=>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 s4(e,t){var r;const n=(r=void 0)!=null?r:!1;return uo(()=>r4(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 a4(e,t){var r;const n=(r=void 0)!=null?r:!1;return uo(()=>Cl(Cb(e,{target:"draft-7",io:"input",reused:n?"ref":"inline"})),{validate:async o=>{const s=await Fp(e,o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function i4(e){return"_zod"in e}function ye(e,t){return i4(e)?a4(e):s4(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=Pn(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 Bf({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 Hf(e){try{return Tl(e),!0}catch{return!1}}function Jf({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new oo).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 xd({argument:"providerOptions",message:`invalid ${e} provider options`,cause:n.error});return n.value}var l4=()=>globalThis.fetch,Jt=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i})=>Wf({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i}),Gf=async({url:e,headers:t,formData:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i})=>Wf({url:e,headers:t,body:{content:r,values:Object.fromEntries(r.entries())},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i}),Wf=async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:s,fetch:i=l4()})=>{try{const a=await i(e,{method:"POST",headers:ln(t,`ai-sdk/provider-utils/${qf}`,Bo()),body:r.content,signal:s}),l=so(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 Af({error:a,url:e,requestBodyValues:r.values})}};function a$(e){return e}function Kf(e){return{...e,type:"dynamic"}}function c4({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=so(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 Bf({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=so(t);if(t.body==null)throw new kv({});return{responseHeaders:r,value:Jf({stream:t.body,schema:e})}},Gt=e=>async({response:t,url:r,requestBodyValues:n})=>{const o=await t.text(),s=await dr({text:o,schema:e}),i=so(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}},u4=()=>async({response:e,url:t,requestBodyValues:r})=>{const n=so(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 Yf(e){return e?.replace(/\/$/,"")}function d4(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*p4({execute:e,input:t,options:r}){const n=e(t,r);if(d4(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 $l(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Rl,Qf;function f4(){if(Qf)return Rl;Qf=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}),Rl=i(a);const l=Symbol.for("@vercel/request-context");function c(){return globalThis[l]?.get?.()??{}}return Rl}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=(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}),Pl=i(a);var l=f4();async function c(){return""}function u(){return""}return Pl}var eh=h4(),m4="vercel.ai.gateway.error",Ml=Symbol.for(m4),th,rh,Ft=class mv extends(rh=Error,th=Ml,rh){constructor({message:t,statusCode:r=500,cause:n,generationId:o}){super(o?`${t} [${o}]`:t),this[th]=!0,this.statusCode=r,this.cause=n,this.generationId=o}static isInstance(t){return mv.hasMarker(t)}static hasMarker(t){return typeof t=="object"&&t!==null&&Ml in t&&t[Ml]===!0}},nh="GatewayAuthenticationError",g4=`vercel.ai.gateway.error.${nh}`,oh=Symbol.for(g4),sh,ah,Nl=class gv extends(ah=Ft,sh=oh,ah){constructor({message:t="Authentication failed",statusCode:r=401,cause:n,generationId:o}={}){super({message:t,statusCode:r,cause:n,generationId:o}),this[sh]=!0,this.name=nh,this.type="authentication_error"}static isInstance(t){return Ft.hasMarker(t)&&oh 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.
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.
39
39
 
40
40
  Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
41
41
 
@@ -50,9 +50,9 @@ Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
50
50
  Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
51
51
 
52
52
  Option 2 - OIDC token:
53
- Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new gv({message:a,statusCode:o,cause:s,generationId:i})}},ih="GatewayInvalidRequestError",_4=`vercel.ai.gateway.error.${ih}`,lh=Symbol.for(_4),ch,uh,y4=class extends(uh=Ft,ch=lh,uh){constructor({message:e="Invalid request",statusCode:t=400,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[ch]=!0,this.name=ih,this.type="invalid_request_error"}static isInstance(e){return Ft.hasMarker(e)&&lh in e}},dh="GatewayRateLimitError",v4=`vercel.ai.gateway.error.${dh}`,ph=Symbol.for(v4),fh,hh,w4=class extends(hh=Ft,fh=ph,hh){constructor({message:e="Rate limit exceeded",statusCode:t=429,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[fh]=!0,this.name=dh,this.type="rate_limit_exceeded"}static isInstance(e){return Ft.hasMarker(e)&&ph in e}},mh="GatewayModelNotFoundError",b4=`vercel.ai.gateway.error.${mh}`,gh=Symbol.for(b4),k4=ve(()=>ye(k({modelId:d()}))),_h,yh,T4=class extends(yh=Ft,_h=gh,yh){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[_h]=!0,this.name=mh,this.type="model_not_found",this.modelId=r}static isInstance(e){return Ft.hasMarker(e)&&gh in e}},vh="GatewayInternalServerError",C4=`vercel.ai.gateway.error.${vh}`,wh=Symbol.for(C4),bh,kh,Th=class extends(kh=Ft,bh=wh,kh){constructor({message:e="Internal server error",statusCode:t=500,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[bh]=!0,this.name=vh,this.type="internal_server_error"}static isInstance(e){return Ft.hasMarker(e)&&wh in e}},Ch="GatewayResponseError",S4=`vercel.ai.gateway.error.${Ch}`,Sh=Symbol.for(S4),Ih,xh,I4=class extends(xh=Ft,Ih=Sh,xh){constructor({message:e="Invalid response from Gateway",statusCode:t=502,response:r,validationError:n,cause:o,generationId:s}={}){super({message:e,statusCode:t,cause:o,generationId:s}),this[Ih]=!0,this.name=Ch,this.type="response_error",this.response=r,this.validationError=n}static isInstance(e){return Ft.hasMarker(e)&&Sh in e}};async function Eh({response:e,statusCode:t,defaultMessage:r="Gateway request failed",cause:n,authMethod:o}){var s;const i=await ur({value:e,schema:x4});if(!i.success){const f=typeof e=="object"&&e!==null&&"generationId"in e?e.generationId:void 0;return new I4({message:`Invalid error response format: ${r}`,statusCode:t,response:e,validationError:i.error,cause:n,generationId:f})}const a=i.value,l=a.error.type,c=a.error.message,u=(s=a.generationId)!=null?s:void 0;switch(l){case"authentication_error":return Nl.createContextualError({apiKeyProvided:o==="api-key",oidcTokenProvided:o==="oidc",statusCode:t,cause:n,generationId:u});case"invalid_request_error":return new y4({message:c,statusCode:t,cause:n,generationId:u});case"rate_limit_exceeded":return new w4({message:c,statusCode:t,cause:n,generationId:u});case"model_not_found":{const f=await ur({value:a.error.param,schema:k4});return new T4({message:c,statusCode:t,modelId:f.success?f.value.modelId:void 0,cause:n,generationId:u})}case"internal_server_error":return new Th({message:c,statusCode:t,cause:n,generationId:u});default:return new Th({message:c,statusCode:t,cause:n,generationId:u})}}var x4=ve(()=>ye(k({error:k({message:d(),type:d().nullish(),param:Ce().nullish(),code:ae([d(),O()]).nullish()}),generationId:d().nullish()}))),$h="GatewayTimeoutError",E4=`vercel.ai.gateway.error.${$h}`,Rh=Symbol.for(E4),Ph,Mh,Nh=class _v extends(Mh=Ft,Ph=Rh,Mh){constructor({message:t="Request timed out",statusCode:r=408,cause:n,generationId:o}={}){super({message:t,statusCode:r,cause:n,generationId:o}),this[Ph]=!0,this.name=$h,this.type="timeout_error"}static isInstance(t){return Ft.hasMarker(t)&&Rh in t}static createTimeoutError({originalMessage:t,statusCode:r=408,cause:n,generationId:o}){const s=`Gateway request timed out: ${t}
53
+ Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new _v({message:a,statusCode:o,cause:s,generationId:i})}},lh="GatewayInvalidRequestError",y4=`vercel.ai.gateway.error.${lh}`,ch=Symbol.for(y4),uh,dh,v4=class extends(dh=Ft,uh=ch,dh){constructor({message:e="Invalid request",statusCode:t=400,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[uh]=!0,this.name=lh,this.type="invalid_request_error"}static isInstance(e){return Ft.hasMarker(e)&&ch in e}},ph="GatewayRateLimitError",w4=`vercel.ai.gateway.error.${ph}`,fh=Symbol.for(w4),hh,mh,b4=class extends(mh=Ft,hh=fh,mh){constructor({message:e="Rate limit exceeded",statusCode:t=429,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[hh]=!0,this.name=ph,this.type="rate_limit_exceeded"}static isInstance(e){return Ft.hasMarker(e)&&fh in e}},gh="GatewayModelNotFoundError",k4=`vercel.ai.gateway.error.${gh}`,_h=Symbol.for(k4),T4=ve(()=>ye(k({modelId:d()}))),yh,vh,C4=class extends(vh=Ft,yh=_h,vh){constructor({message:e="Model not found",statusCode:t=404,modelId:r,cause:n,generationId:o}={}){super({message:e,statusCode:t,cause:n,generationId:o}),this[yh]=!0,this.name=gh,this.type="model_not_found",this.modelId=r}static isInstance(e){return Ft.hasMarker(e)&&_h in e}},wh="GatewayInternalServerError",S4=`vercel.ai.gateway.error.${wh}`,bh=Symbol.for(S4),kh,Th,Ch=class extends(Th=Ft,kh=bh,Th){constructor({message:e="Internal server error",statusCode:t=500,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[kh]=!0,this.name=wh,this.type="internal_server_error"}static isInstance(e){return Ft.hasMarker(e)&&bh in e}},Sh="GatewayResponseError",I4=`vercel.ai.gateway.error.${Sh}`,Ih=Symbol.for(I4),xh,Eh,x4=class extends(Eh=Ft,xh=Ih,Eh){constructor({message:e="Invalid response from Gateway",statusCode:t=502,response:r,validationError:n,cause:o,generationId:s}={}){super({message:e,statusCode:t,cause:o,generationId:s}),this[xh]=!0,this.name=Sh,this.type="response_error",this.response=r,this.validationError=n}static isInstance(e){return Ft.hasMarker(e)&&Ih in e}};async function $h({response:e,statusCode:t,defaultMessage:r="Gateway request failed",cause:n,authMethod:o}){var s;const i=await ur({value:e,schema:E4});if(!i.success){const f=typeof e=="object"&&e!==null&&"generationId"in e?e.generationId:void 0;return new x4({message:`Invalid error response format: ${r}`,statusCode:t,response:e,validationError:i.error,cause:n,generationId:f})}const a=i.value,l=a.error.type,c=a.error.message,u=(s=a.generationId)!=null?s:void 0;switch(l){case"authentication_error":return Ol.createContextualError({apiKeyProvided:o==="api-key",oidcTokenProvided:o==="oidc",statusCode:t,cause:n,generationId:u});case"invalid_request_error":return new v4({message:c,statusCode:t,cause:n,generationId:u});case"rate_limit_exceeded":return new b4({message:c,statusCode:t,cause:n,generationId:u});case"model_not_found":{const f=await ur({value:a.error.param,schema:T4});return new C4({message:c,statusCode:t,modelId:f.success?f.value.modelId:void 0,cause:n,generationId:u})}case"internal_server_error":return new Ch({message:c,statusCode:t,cause:n,generationId:u});default:return new Ch({message:c,statusCode:t,cause:n,generationId:u})}}var E4=ve(()=>ye(k({error:k({message:d(),type:d().nullish(),param:Ce().nullish(),code:ae([d(),O()]).nullish()}),generationId:d().nullish()}))),Rh="GatewayTimeoutError",$4=`vercel.ai.gateway.error.${Rh}`,Ph=Symbol.for($4),Mh,Nh,Oh=class yv extends(Nh=Ft,Mh=Ph,Nh){constructor({message:t="Request timed out",statusCode:r=408,cause:n,generationId:o}={}){super({message:t,statusCode:r,cause:n,generationId:o}),this[Mh]=!0,this.name=Rh,this.type="timeout_error"}static isInstance(t){return Ft.hasMarker(t)&&Ph in t}static createTimeoutError({originalMessage:t,statusCode:r=408,cause:n,generationId:o}){const s=`Gateway request timed out: ${t}
54
54
 
55
- This is a client-side timeout. To resolve this, increase your timeout configuration: https://vercel.com/docs/ai-gateway/capabilities/video-generation#extending-timeouts-for-node.js`;return new _v({message:s,statusCode:r,cause:n,generationId:o})}};function Oh(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:Oh(e)?Nh.createTimeoutError({originalMessage:e instanceof Error?e.message:"Unknown error",cause:e}):lt.isInstance(e)?e.cause&&Oh(e.cause)?Nh.createTimeoutError({originalMessage:e.message,cause:e}):await Eh({response:$4(e),statusCode:(r=e.statusCode)!=null?r:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):await Eh({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}function $4(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 Ah="ai-gateway-auth-method";async function Vr(e){const t=await ur({value:e[Ah],schema:R4});return t.success?t.value:void 0}var R4=ve(()=>ye(ae([P("api-key"),P("oidc")]))),qh=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:Gt(P4),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:Gt(M4),failedResponseHandler:Ar({errorSchema:yt(),errorToMessage:r=>r}),fetch:this.config.fetch});return t}catch(e){throw await tr(e)}}},P4=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()}))}))),M4=ve(()=>ye(k({balance:d(),total_used:d()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),N4=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:Gt(O4),failedResponseHandler:Ar({errorSchema:yt(),errorToMessage:o=>o}),fetch:this.config.fetch});return n}catch(t){throw await tr(t)}}},O4=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}:{}})))}))),A4=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:Gt(q4),failedResponseHandler:Ar({errorSchema:yt(),errorToMessage:n=>n}),fetch:this.config.fetch});return r}catch(t){throw await tr(t)}}},q4=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))),L4=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:Gt(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)}}},j4=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:Gt(D4),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}}},D4=ve(()=>ye(k({embeddings:q(q(O())),usage:k({tokens:O()}).nullish(),providerMetadata:ge(d(),ge(d(),Ce())).optional()}))),U4=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=>Lh(y))},...i&&{mask:Lh(i)}},successfulResponseHandler:Gt(Z4),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 Lh(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:io(e.data)}:e}var z4=k({images:q(Ce()).optional()}).catchall(Ce()),F4=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()})]),V4=k({inputTokens:O().nullish(),outputTokens:O().nullish(),totalTokens:O().nullish()}),Z4=k({images:q(d()),warnings:q(F4).optional(),providerMetadata:ge(d(),z4).optional(),usage:V4.optional()}),B4=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:H4(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=Jf({stream:v.body,schema:K4}).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 H4(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:io(e.data)}:e}var J4=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()})]),W4=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()})]),K4=ze("type",[k({type:P("result"),videos:q(G4),warnings:q(W4).optional(),providerMetadata:ge(d(),J4).optional()}),k({type:P("error"),message:d(),errorType:d(),statusCode:O(),param:Ce().nullable()})]),Y4=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.")}))),Q4=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()})]))),X4=pr({id:"gateway.parallel_search",inputSchema:Y4,outputSchema:Q4}),ek=(e={})=>X4(e),tk=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.")}))),rk=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()})]))),nk=pr({id:"gateway.perplexity_search",inputSchema:tk,outputSchema:rk}),ok=(e={})=>nk(e),sk={parallelSearch:ek,perplexitySearch:ok};async function ak(){var e;return(e=eh.getContext().headers)==null?void 0:e["x-vercel-id"]}var ik="3.0.83",lk="0.0.1";function ck(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=Yf(e.baseURL))!=null?r:"https://ai-gateway.vercel.sh/v3/ai",l=async()=>{try{const w=await dk(e);return ln({Authorization:`Bearer ${w.token}`,"ai-gateway-protocol-version":lk,[Ah]:w.authMethod,...e.headers},`ai-sdk/gateway/${ik}`)}catch(w){throw Nl.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:w})}},c=()=>{const w=co({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),y=co({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),m=co({settingValue:void 0,environmentVariableName:"VERCEL_REGION"}),C=co({settingValue:void 0,environmentVariableName:"VERCEL_PROJECT_ID"});return async()=>{const b=await ak();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 L4(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 qh({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 qh({baseURL:a,headers:l,fetch:e.fetch}).getCredits().catch(async w=>{throw await tr(w,await Vr(await l()))}),h=async w=>new N4({baseURL:a,headers:l,fetch:e.fetch}).getSpendReport(w).catch(async y=>{throw await tr(y,await Vr(await l()))}),g=async w=>new A4({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 U4(w,{provider:"gateway",baseURL:a,headers:l,fetch:e.fetch,o11yHeaders:c()}),v.languageModel=u;const _=w=>new j4(w,{provider:"gateway",baseURL:a,headers:l,fetch:e.fetch,o11yHeaders:c()});return v.embeddingModel=_,v.textEmbeddingModel=_,v.videoModel=w=>new B4(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=sk,v}var uk=ck();async function dk(e){const t=co({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});return t?{token:t,authMethod:"api-key"}:{token:await eh.getVercelOidcToken(),authMethod:"oidc"}}var pk=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},Mn="1.9.0",jh=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function fk(e){var t=new Set([e]),r=new Set,n=e.match(jh);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(jh);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 hk=fk(Mn),mk=Mn.split(".")[0],Ho=Symbol.for("opentelemetry.js.api."+mk),Jo=pk;function Go(e,t,r,n){var o;n===void 0&&(n=!1);var s=Jo[Ho]=(o=Jo[Ho])!==null&&o!==void 0?o:{version:Mn};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!==Mn){var i=new Error("@opentelemetry/api: Registration of version v"+s.version+" for "+e+" does not match previously registered API v"+Mn);return r.error(i.stack||i.message),!1}return s[e]=t,r.debug("@opentelemetry/api: Registered a global for "+e+" v"+Mn+"."),!0}function Nn(e){var t,r,n=(t=Jo[Ho])===null||t===void 0?void 0:t.version;if(!(!n||!hk(n)))return(r=Jo[Ho])===null||r===void 0?void 0:r[e]}function Wo(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+Mn+".");var r=Jo[Ho];r&&delete r[e]}var gk=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},_k=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))},yk=(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=Nn("diag");if(n)return r.unshift(t),n[e].apply(n,_k([],gk(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 vk(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 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},bk=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="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=Nn("diag");if(a)return a[o].apply(a,bk([],wk(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=Nn("diag"),f=vk((a=s.logLevel)!==null&&a!==void 0?a:rr.INFO,o);if(u&&!s.suppressOverrideMessage){var p=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";u.warn("Current logger will be overwritten from "+p),f.warn("Current logger will overwrite one already registered from "+p)}return Go("diag",f,r,!0)};r.setLogger=n,r.disable=function(){Wo(kk,r)},r.createComponentLogger=function(o){return new yk(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})(),Tk=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},Ck=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.")},Sk=(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=Tk(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=Ck(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 Ik(e){return e===void 0&&(e={}),new Sk(new Map(Object.entries(e)))}function Dh(e){return Symbol.for(e)}var xk=(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})(),Ek=new xk,On=(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)}})(),$k=(function(){function e(){}return e.prototype.createGauge=function(t,r){return Dk},e.prototype.createHistogram=function(t,r){return Uk},e.prototype.createCounter=function(t,r){return jk},e.prototype.createUpDownCounter=function(t,r){return zk},e.prototype.createObservableGauge=function(t,r){return Vk},e.prototype.createObservableCounter=function(t,r){return Fk},e.prototype.createObservableUpDownCounter=function(t,r){return Zk},e.prototype.addBatchObservableCallback=function(t,r){},e.prototype.removeBatchObservableCallback=function(t){},e})(),ia=(function(){function e(){}return e})(),Rk=(function(e){On(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(r,n){},t})(ia),Pk=(function(e){On(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(r,n){},t})(ia),Mk=(function(e){On(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(r,n){},t})(ia),Nk=(function(e){On(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(r,n){},t})(ia),Ol=(function(){function e(){}return e.prototype.addCallback=function(t){},e.prototype.removeCallback=function(t){},e})(),Ok=(function(e){On(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(Ol),Ak=(function(e){On(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(Ol),qk=(function(e){On(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(Ol),Lk=new $k,jk=new Rk,Dk=new Mk,Uk=new Nk,zk=new Pk,Fk=new Ok,Vk=new Ak,Zk=new qk,Bk={get:function(e,t){if(e!=null)return e[t]},keys:function(e){return e==null?[]:Object.keys(e)}},Hk={set:function(e,t,r){e!=null&&(e[t]=r)}},Jk=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))},Wk=(function(){function e(){}return e.prototype.active=function(){return Ek},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],Jk(o),!1))},e.prototype.bind=function(t,r){return r},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e})(),Kk=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))},Al="context",Qk=new Wk,la=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(t){return Go(Al,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,Yk([t,r,n],Kk(s),!1))},e.prototype.bind=function(t,r){return this._getContextManager().bind(t,r)},e.prototype._getContextManager=function(){return Nn(Al)||Qk},e.prototype.disable=function(){this._getContextManager().disable(),Wo(Al,qr.instance())},e})(),ql;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(ql||(ql={}));var Uh="0000000000000000",zh="00000000000000000000000000000000",Xk={traceId:zh,spanId:Uh,traceFlags:ql.NONE},Yo=(function(){function e(t){t===void 0&&(t=Xk),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})(),Ll=Dh("OpenTelemetry Context Key SPAN");function jl(e){return e.getValue(Ll)||void 0}function eT(){return jl(la.getInstance().active())}function Dl(e,t){return e.setValue(Ll,t)}function tT(e){return e.deleteValue(Ll)}function rT(e,t){return Dl(e,new Yo(t))}function Fh(e){var t;return(t=jl(e))===null||t===void 0?void 0:t.spanContext()}var nT=/^([0-9a-f]{32})$/i,oT=/^[0-9a-f]{16}$/i;function sT(e){return nT.test(e)&&e!==zh}function aT(e){return oT.test(e)&&e!==Uh}function Vh(e){return sT(e.traceId)&&aT(e.spanId)}function iT(e){return new Yo(e)}var Ul=la.getInstance(),Zh=(function(){function e(){}return e.prototype.startSpan=function(t,r,n){n===void 0&&(n=Ul.active());var o=!!r?.root;if(o)return new Yo;var s=n&&Fh(n);return lT(s)&&Vh(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??Ul.active(),c=this.startSpan(t,s,l),u=Dl(l,c);return Ul.with(u,a,void 0,c)}},e})();function lT(e){return typeof e=="object"&&typeof e.spanId=="string"&&typeof e.traceId=="string"&&typeof e.traceFlags=="number"}var cT=new Zh,uT=(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):cT},e})(),dT=(function(){function e(){}return e.prototype.getTracer=function(t,r,n){return new Zh},e})(),pT=new dT,Bh=(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 uT(this,t,r,n)},e.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:pT},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 Hh=la.getInstance();qr.instance();var fT=(function(){function e(){}return e.prototype.getMeter=function(t,r,n){return Lk},e})(),hT=new fT,zl="metrics",mT=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalMeterProvider=function(t){return Go(zl,t,qr.instance())},e.prototype.getMeterProvider=function(){return Nn(zl)||hT},e.prototype.getMeter=function(t,r,n){return this.getMeterProvider().getMeter(t,r,n)},e.prototype.disable=function(){Wo(zl,qr.instance())},e})();mT.getInstance();var gT=(function(){function e(){}return e.prototype.inject=function(t,r){},e.prototype.extract=function(t,r){return t},e.prototype.fields=function(){return[]},e})(),Fl=Dh("OpenTelemetry Baggage Key");function Jh(e){return e.getValue(Fl)||void 0}function _T(){return Jh(la.getInstance().active())}function yT(e,t){return e.setValue(Fl,t)}function vT(e){return e.deleteValue(Fl)}var Vl="propagation",wT=new gT,bT=(function(){function e(){this.createBaggage=Ik,this.getBaggage=Jh,this.getActiveBaggage=_T,this.setBaggage=yT,this.deleteBaggage=vT}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalPropagator=function(t){return Go(Vl,t,qr.instance())},e.prototype.inject=function(t,r,n){return n===void 0&&(n=Hk),this._getGlobalPropagator().inject(t,r,n)},e.prototype.extract=function(t,r,n){return n===void 0&&(n=Bk),this._getGlobalPropagator().extract(t,r,n)},e.prototype.fields=function(){return this._getGlobalPropagator().fields()},e.prototype.disable=function(){Wo(Vl,qr.instance())},e.prototype._getGlobalPropagator=function(){return Nn(Vl)||wT},e})();bT.getInstance();var Zl="trace",kT=(function(){function e(){this._proxyTracerProvider=new Bh,this.wrapSpanContext=iT,this.isSpanContextValid=Vh,this.deleteSpan=tT,this.getSpan=jl,this.getActiveSpan=eT,this.getSpanContext=Fh,this.setSpan=Dl,this.setSpanContext=rT}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(t){var r=Go(Zl,this._proxyTracerProvider,qr.instance());return r&&this._proxyTracerProvider.setDelegate(t),r},e.prototype.getTracerProvider=function(){return Nn(Zl)||this._proxyTracerProvider},e.prototype.getTracer=function(t,r){return this.getTracerProvider().getTracer(t,r)},e.prototype.disable=function(){Wo(Zl,qr.instance()),this._proxyTracerProvider=new Bh},e})(),TT=kT.getInstance(),CT=Object.defineProperty,ST=(e,t)=>{for(var r in t)CT(e,r,{get:t[r],enumerable:!0})},Gh="AI_InvalidArgumentError",Wh=`vercel.ai.error.${Gh}`,IT=Symbol.for(Wh),Kh,Lr=class extends we{constructor({parameter:t,value:r,message:n}){super({name:Gh,message:`Invalid argument for parameter ${t}: ${n}`}),this[Kh]=!0,this.parameter=t,this.value=r}static isInstance(t){return we.hasMarker(t,Wh)}};Kh=IT;var Yh="AI_InvalidToolApprovalError",Qh=`vercel.ai.error.${Yh}`,xT=Symbol.for(Qh),Xh,ET=class extends we{constructor({approvalId:e}){super({name:Yh,message:`Tool approval response references unknown approvalId: "${e}". No matching tool-approval-request found in message history.`}),this[Xh]=!0,this.approvalId=e}static isInstance(e){return we.hasMarker(e,Qh)}};Xh=xT;var e0="AI_InvalidToolInputError",t0=`vercel.ai.error.${e0}`,$T=Symbol.for(t0),r0,Bl=class extends we{constructor({toolInput:e,toolName:t,cause:r,message:n=`Invalid input for tool ${t}: ${Tn(r)}`}){super({name:e0,message:n,cause:r}),this[r0]=!0,this.toolInput=e,this.toolName=t}static isInstance(e){return we.hasMarker(e,t0)}};r0=$T;var n0="AI_ToolCallNotFoundForApprovalError",o0=`vercel.ai.error.${n0}`,RT=Symbol.for(o0),s0,Hl=class extends we{constructor({toolCallId:e,approvalId:t}){super({name:n0,message:`Tool call "${e}" not found for approval request "${t}".`}),this[s0]=!0,this.toolCallId=e,this.approvalId=t}static isInstance(e){return we.hasMarker(e,o0)}};s0=RT;var a0="AI_MissingToolResultsError",i0=`vercel.ai.error.${a0}`,PT=Symbol.for(i0),l0,c0=class extends we{constructor({toolCallIds:e}){super({name:a0,message:`Tool result${e.length>1?"s are":" is"} missing for tool call${e.length>1?"s":""} ${e.join(", ")}.`}),this[l0]=!0,this.toolCallIds=e}static isInstance(e){return we.hasMarker(e,i0)}};l0=PT;var u0="AI_NoObjectGeneratedError",d0=`vercel.ai.error.${u0}`,MT=Symbol.for(d0),p0,cn=class extends we{constructor({message:e="No object generated.",cause:t,text:r,response:n,usage:o,finishReason:s}){super({name:u0,message:e,cause:t}),this[p0]=!0,this.text=r,this.response=n,this.usage=o,this.finishReason=s}static isInstance(e){return we.hasMarker(e,d0)}};p0=MT;var f0="AI_NoOutputGeneratedError",h0=`vercel.ai.error.${f0}`,NT=Symbol.for(h0),m0,g0=class extends we{constructor({message:e="No output generated.",cause:t}={}){super({name:f0,message:e,cause:t}),this[m0]=!0}static isInstance(e){return we.hasMarker(e,h0)}};m0=NT;var _0="AI_NoSuchToolError",y0=`vercel.ai.error.${_0}`,OT=Symbol.for(y0),v0,Jl=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:_0,message:r}),this[v0]=!0,this.toolName=e,this.availableTools=t}static isInstance(e){return we.hasMarker(e,y0)}};v0=OT;var w0="AI_ToolCallRepairError",b0=`vercel.ai.error.${w0}`,AT=Symbol.for(b0),k0,qT=class extends we{constructor({cause:e,originalError:t,message:r=`Error repairing tool call: ${Tn(e)}`}){super({name:w0,message:r,cause:e}),this[k0]=!0,this.originalError=t}static isInstance(e){return we.hasMarker(e,b0)}};k0=AT;var LT=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}},T0="AI_UIMessageStreamError",C0=`vercel.ai.error.${T0}`,jT=Symbol.for(C0),S0,po=class extends we{constructor({chunkType:e,chunkId:t,message:r}){super({name:T0,message:r}),this[S0]=!0,this.chunkType=e,this.chunkId=t}static isInstance(e){return we.hasMarker(e,C0)}};S0=jT;var I0="AI_InvalidMessageRoleError",x0=`vercel.ai.error.${I0}`,DT=Symbol.for(x0),E0,UT=class extends we{constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:I0,message:t}),this[E0]=!0,this.role=e}static isInstance(e){return we.hasMarker(e,x0)}};E0=DT;var $0="AI_RetryError",R0=`vercel.ai.error.${$0}`,zT=Symbol.for(R0),P0,M0=class extends we{constructor({message:e,reason:t,errors:r}){super({name:$0,message:e}),this[P0]=!0,this.reason=t,this.errors=r,this.lastError=r[r.length-1]}static isInstance(e){return we.hasMarker(e,R0)}};P0=zT;function An(e){return e===void 0?[]:Array.isArray(e)?e:[e]}async function br(e){for(const t of An(e.callbacks))if(t!=null)try{await t(e.event)}catch{}}function FT({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 VT="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",N0=!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}N0||(N0=!0,console.info(VT));for(const r of e.warnings)console.warn(FT({warning:r,provider:e.provider,model:e.model}))}};function ZT({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 BT(e){return e.specificationVersion==="v3"?e:(ZT({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:O0(o.finishReason),usage:A0(o.usage)}};case"doStream":return async(...n)=>{const o=await t.doStream(...n);return{...o,stream:HT(o.stream)}};default:return t[r]}}}))}function HT(e){return e.pipeThrough(new TransformStream({transform(t,r){switch(t.type){case"finish":r.enqueue({...t,finishReason:O0(t.finishReason),usage:A0(t.usage)});break;default:r.enqueue(t);break}}}))}function O0(e){return{unified:e==="unknown"?"other":e,raw:void 0}}function A0(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 LT({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return BT(e)}return JT().languageModel(e)}function JT(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:uk}function Wl(e){if(e!=null)return typeof e=="number"?e:e.totalMs}function q0(e){if(!(e==null||typeof e=="number"))return e.stepMs}function GT(e){if(!(e==null||typeof e=="number"))return e.chunkMs}var WT=[{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]}],KT=e=>{const t=typeof e=="string"?ao(e):e,r=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(r+10)};function YT(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?KT(e):e}function QT({data:e,signatures:t}){const r=YT(e),n=typeof r=="string"?ao(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 L0="6.0.141",XT=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/${L0}`,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 Mf({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})}},e6=(e=XT)=>t=>Promise.all(t.map(async r=>r.isUrlSupportedByModel?null:e(r)));function t6(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 j0=ae([d(),Ys(Uint8Array),Ys(ArrayBuffer),tf(e=>{var t,r;return(r=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?r:!1},{message:"Must be a Buffer"})]);function D0(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}=t6(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 r6(e){return typeof e=="string"?e:e instanceof ArrayBuffer?io(new Uint8Array(e)):io(e)}async function U0({prompt:e,supportedUrls:t,download:r=e6()}){const n=await o6(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}]:An(e.system).map(c=>({role:"system",content:c.content,providerOptions:c.providerOptions})):[],...e.messages.map(c=>n6({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 c0({toolCallIds:Array.from(l)});break}for(const c of s)l.delete(c);if(l.size>0)throw new c0({toolCallIds:Array.from(l)});return a.filter(c=>c.role!=="tool"||c.content.length>0)}function n6({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=>s6(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}=D0(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:z0(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:z0(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 UT({role:n})}}}async function o6(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&&d9({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 s6(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}=D0(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=QT({data:l,signatures:WT}))!=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 z0(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:F0(r)}:n?.toModelOutput?await n.toModelOutput({toolCallId:e,input:t,output:r}):typeof r=="string"?{type:"text",value:r}:{type:"json",value:F0(r)}}function F0(e){return e===void 0?null:e}function Kl({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 a6(e){return e!=null&&Object.keys(e).length>0}async function V0({tools:e,toolChoice:t,activeTools:r}){if(!a6(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 Pn(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())),Z0=k({type:P("text"),text:d(),providerOptions:dt.optional()}),i6=k({type:P("image"),image:ae([j0,Ys(URL)]),mediaType:d().optional(),providerOptions:dt.optional()}),B0=k({type:P("file"),data:ae([j0,Ys(URL)]),filename:d().optional(),mediaType:d(),providerOptions:dt.optional()}),l6=k({type:P("reasoning"),text:d(),providerOptions:dt.optional()}),c6=k({type:P("tool-call"),toolCallId:d(),toolName:d(),input:Ce(),providerOptions:dt.optional(),providerExecuted:me().optional()}),u6=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()})]))})]),H0=k({type:P("tool-result"),toolCallId:d(),toolName:d(),output:u6,providerOptions:dt.optional()}),d6=k({type:P("tool-approval-request"),approvalId:d(),toolCallId:d()}),p6=k({type:P("tool-approval-response"),approvalId:d(),approved:me(),reason:d().optional()}),f6=k({role:P("system"),content:d(),providerOptions:dt.optional()}),h6=k({role:P("user"),content:ae([d(),q(ae([Z0,i6,B0]))]),providerOptions:dt.optional()}),m6=k({role:P("assistant"),content:ae([d(),q(ae([Z0,B0,l6,c6,H0,d6]))]),providerOptions:dt.optional()}),g6=k({role:P("tool"),content:q(ae([H0,p6])),providerOptions:dt.optional()}),_6=ae([f6,h6,m6,g6]);async function J0(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"&&!An(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(_6)});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(!Nl.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
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
56
56
 
57
57
  To authenticate, set the \x1B[33mAI_GATEWAY_API_KEY\x1B[0m environment variable with your API key.
58
58
 
@@ -60,12 +60,12 @@ Alternatively, you can use a provider module instead of the AI Gateway.
60
60
 
61
61
  Learn more: \x1B[34m${r}\x1B[0m
62
62
 
63
- `),{name:"GatewayAuthenticationError"})}function es({operationId:e,telemetry:t}){return{"operation.name":`${e}${t?.functionId!=null?` ${t.functionId}`:""}`,"resource.name":t?.functionId,"ai.operationId":e,"ai.telemetry.functionId":t?.functionId}}function W0({model:e,settings:t,telemetry:r,headers:n}){var o;return{"ai.model.provider":e.provider,"ai.model.id":e.modelId,...Object.entries(t).reduce((s,[i,a])=>{if(i==="timeout"){const l=Wl(a);l!=null&&(s[`ai.settings.${i}`]=l)}else s[`ai.settings.${i}`]=a;return s},{}),...Object.entries((o=r?.metadata)!=null?o:{}).reduce((s,[i,a])=>(s[`ai.telemetry.metadata.${i}`]=a,s),{}),...Object.entries(n??{}).reduce((s,[i,a])=>(a!==void 0&&(s[`ai.request.headers.${i}`]=a),s),{})}}var y6={startSpan(){return da},startActiveSpan(e,t,r,n){if(typeof t=="function")return t(da);if(typeof r=="function")return r(da);if(typeof n=="function")return n(da)}},da={spanContext(){return v6},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}},v6={traceId:"",spanId:"",traceFlags:0};function K0({isEnabled:e=!1,tracer:t}={}){return e?t||TT.getTracer("ai"):y6}async function ts({name:e,tracer:t,attributes:r,fn:n,endWhenDone:o=!0}){return t.startActiveSpan(e,{attributes:await r},async s=>{const i=Hh.active();try{const a=await Hh.with(i,()=>n(s));return o&&s.end(),a}catch(a){try{Y0(s,a)}finally{s.end()}throw a}})}function Y0(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:ca.ERROR,message:t.message})):e.setStatus({code:ca.ERROR})}async function fr({telemetry:e,attributes:t}){if(e?.isEnabled!==!0)return{};const r={};for(const[n,o]of Object.entries(t))if(o!=null){if(typeof o=="object"&&"input"in o&&typeof o.input=="function"){if(e?.recordInputs===!1)continue;const s=await o.input();s!=null&&(r[n]=s);continue}if(typeof o=="object"&&"output"in o&&typeof o.output=="function"){if(e?.recordOutputs===!1)continue;const s=await o.output();s!=null&&(r[n]=s);continue}r[n]=o}return r}function Q0(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?r6(r.data):r.data}:r)})))}function w6(){var e;return(e=globalThis.AI_SDK_TELEMETRY_INTEGRATIONS)!=null?e:[]}function X0(){const e=w6();return t=>{const r=An(t),n=[...e,...r];function o(s){const i=n.map(s).filter(Boolean);return async a=>{for(const l of i)try{await l(a)}catch{}}}return{onStart:o(s=>s.onStart),onStepStart:o(s=>s.onStepStart),onToolCallStart:o(s=>s.onToolCallStart),onToolCallFinish:o(s=>s.onToolCallFinish),onStepFinish:o(s=>s.onStepFinish),onFinish:o(s=>s.onFinish)}}}function Yl(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:kr(e.inputTokens.total,e.outputTokens.total),raw:e.raw,reasoningTokens:e.outputTokens.reasoning,cachedInputTokens:e.inputTokens.cacheRead}}function Ql(){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 em(e,t){var r,n,o,s,i,a,l,c,u,f;return{inputTokens:kr(e.inputTokens,t.inputTokens),inputTokenDetails:{noCacheTokens:kr((r=e.inputTokenDetails)==null?void 0:r.noCacheTokens,(n=t.inputTokenDetails)==null?void 0:n.noCacheTokens),cacheReadTokens:kr((o=e.inputTokenDetails)==null?void 0:o.cacheReadTokens,(s=t.inputTokenDetails)==null?void 0:s.cacheReadTokens),cacheWriteTokens:kr((i=e.inputTokenDetails)==null?void 0:i.cacheWriteTokens,(a=t.inputTokenDetails)==null?void 0:a.cacheWriteTokens)},outputTokens:kr(e.outputTokens,t.outputTokens),outputTokenDetails:{textTokens:kr((l=e.outputTokenDetails)==null?void 0:l.textTokens,(c=t.outputTokenDetails)==null?void 0:c.textTokens),reasoningTokens:kr((u=e.outputTokenDetails)==null?void 0:u.reasoningTokens,(f=t.outputTokenDetails)==null?void 0:f.reasoningTokens)},totalTokens:kr(e.totalTokens,t.totalTokens),reasoningTokens:kr(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:kr(e.cachedInputTokens,t.cachedInputTokens)}}function kr(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}function pa(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;const r={...e};for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)){const o=t[n];if(o===void 0)continue;const s=n in e?e[n]:void 0,i=o!==null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp),a=s!=null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp);i&&a?r[n]=pa(s,o):r[n]=o}return r}function b6({error:e,exponentialBackoffDelay:t}){const r=e.responseHeaders;if(!r)return t;let n;const o=r["retry-after-ms"];if(o){const i=parseFloat(o);Number.isNaN(i)||(n=i)}const s=r["retry-after"];if(s&&n===void 0){const i=parseFloat(s);Number.isNaN(i)?n=Date.parse(s)-Date.now():n=i*1e3}return n!=null&&!Number.isNaN(n)&&0<=n&&(n<60*1e3||n<t)?n:t}var k6=({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:r=2,abortSignal:n}={})=>async o=>tm(o,{maxRetries:e,delayInMs:t,backoffFactor:r,abortSignal:n});async function tm(e,{maxRetries:t,delayInMs:r,backoffFactor:n,abortSignal:o},s=[]){try{return await e()}catch(i){if($n(i)||t===0)throw i;const a=kl(i),l=[...s,i],c=l.length;if(c>t)throw new M0({message:`Failed after ${c} attempts. Last error: ${a}`,reason:"maxRetriesExceeded",errors:l});if(i instanceof Error&&lt.isInstance(i)&&i.isRetryable===!0&&c<=t)return await e9(b6({error:i,exponentialBackoffDelay:r}),{abortSignal:o}),tm(e,{maxRetries:t,delayInMs:n*r,backoffFactor:n,abortSignal:o},l);throw c===1?i:new M0({message:`Failed after ${c} attempts with non-retryable error: '${a}'`,reason:"errorNotRetryable",errors:l})}}function rm({maxRetries:e,abortSignal:t}){if(e!=null){if(!Number.isInteger(e))throw new Lr({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});if(e<0)throw new Lr({parameter:"maxRetries",value:e,message:"maxRetries must be >= 0"})}const r=e??2;return{maxRetries:r,retry:k6({maxRetries:r,abortSignal:t})}}function nm({messages:e}){const t=e.at(-1);if(t?.role!="tool")return{approvedToolApprovals:[],deniedToolApprovals:[]};const r={};for(const l of e)if(l.role==="assistant"&&typeof l.content!="string"){const c=l.content;for(const u of c)u.type==="tool-call"&&(r[u.toolCallId]=u)}const n={};for(const l of e)if(l.role==="assistant"&&typeof l.content!="string"){const c=l.content;for(const u of c)u.type==="tool-approval-request"&&(n[u.approvalId]=u)}const o={};for(const l of t.content)l.type==="tool-result"&&(o[l.toolCallId]=l);const s=[],i=[],a=t.content.filter(l=>l.type==="tool-approval-response");for(const l of a){const c=n[l.approvalId];if(c==null)throw new ET({approvalId:l.approvalId});if(o[c.toolCallId]!=null)continue;const u=r[c.toolCallId];if(u==null)throw new Hl({toolCallId:c.toolCallId,approvalId:c.approvalId});const f={approvalRequest:c,approvalResponse:l,toolCall:u};l.approved?s.push(f):i.push(f)}return{approvedToolApprovals:s,deniedToolApprovals:i}}function fa(){var e,t;return(t=(e=globalThis?.performance)==null?void 0:e.now())!=null?t:Date.now()}async function Xl({toolCall:e,tools:t,tracer:r,telemetry:n,messages:o,abortSignal:s,experimental_context:i,stepNumber:a,model:l,onPreliminaryToolResult:c,onToolCallStart:u,onToolCallFinish:f}){const{toolName:p,toolCallId:h,input:g}=e,v=t?.[p];if(v?.execute==null)return;const _={stepNumber:a,model:l,toolCall:e,messages:o,abortSignal:s,functionId:n?.functionId,metadata:n?.metadata,experimental_context:i};return ts({name:"ai.toolCall",attributes:fr({telemetry:n,attributes:{...es({operationId:"ai.toolCall",telemetry:n}),"ai.toolCall.name":p,"ai.toolCall.id":h,"ai.toolCall.args":{output:()=>JSON.stringify(g)}}}),tracer:r,fn:async w=>{let y;await br({event:_,callbacks:u});const m=fa();try{const b=p4({execute:v.execute.bind(v),input:g,options:{toolCallId:h,messages:o,abortSignal:s,experimental_context:i}});for await(const T of b)T.type==="preliminary"?c?.({...e,type:"tool-result",output:T.output,preliminary:!0}):y=T.output}catch(b){const T=fa()-m;return await br({event:{..._,success:!1,error:b,durationMs:T},callbacks:f}),Y0(w,b),{type:"tool-error",toolCallId:h,toolName:p,input:g,error:b,dynamic:v.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{}}}const C=fa()-m;await br({event:{..._,success:!0,output:y,durationMs:C},callbacks:f});try{w.setAttributes(await fr({telemetry:n,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(y)}}}))}catch{}return{type:"tool-result",toolCallId:h,toolName:p,input:g,output:y,dynamic:v.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{}}}})}function om(e){const t=e.filter(r=>r.type==="reasoning");return t.length===0?void 0:t.map(r=>r.text).join(`
64
- `)}function sm(e){const t=e.filter(r=>r.type==="text");if(t.length!==0)return t.map(r=>r.text).join("")}var am=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=io(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=ao(this.base64Data)),this.uint8ArrayData}},T6=class extends am{constructor(e){super(e),this.type="file"}};async function im({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 C6={};ST(C6,{array:()=>x6,choice:()=>E6,json:()=>$6,object:()=>I6,text:()=>ha});function S6(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:S6(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(){}}),I6=({schema:e,name:t,description:r})=>{const n=Pn(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(){}}},x6=({element:e,name:t,description:r})=>{const n=Pn(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])}})}}},E6=({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(){}}),$6=({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 lm({toolCall:e,tools:t,repairToolCall:r,system:n,messages:o}){var s;try{if(t==null){if(e.providerExecuted&&e.dynamic)return await cm(e);throw new Jl({toolName:e.toolName})}try{return await um({toolCall:e,tools:t})}catch(i){if(r==null||!(Jl.isInstance(i)||Bl.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 Pn(c).jsonSchema},system:n,messages:o,error:i})}catch(l){throw new qT({cause:l,originalError:i})}if(a==null)throw i;return await um({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 cm(e){const t=e.input.trim()===""?{success:!0,value:{}}:await dr({text:e.input});if(t.success===!1)throw new Bl({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 um({toolCall:e,tools:t}){const r=e.toolName,n=t[r];if(n==null){if(e.providerExecuted&&e.dynamic)return await cm(e);throw new Jl({toolName:e.toolName,availableTools:Object.keys(t)})}const o=Pn(n.inputSchema),s=e.input.trim()===""?await ur({value:{},schema:o}):await dr({text:e.input,schema:o});if(s.success===!1)throw new Bl({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 dm=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 ec(e){return({steps:t})=>t.length===e}async function pm({stopConditions:e,steps:t}){return(await Promise.all(e.map(r=>r({steps:t})))).some(r=>r)}async function tc({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 fm(...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 R6=Zo({prefix:"aitxt",size:24});async function hm({model:e,tools:t,toolChoice:r,system:n,prompt:o,messages:s,maxRetries:i,abortSignal:a,timeout:l,headers:c,stopWhen:u=ec(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=R6}={},experimental_onStart:R,experimental_onStepStart:S,experimental_onToolCallStart:j,experimental_onToolCallFinish:N,onStepFinish:L,onFinish:z,...B}){const X=ua(e),ee=X0(),Q=An(u),Z=Wl(l),ne=q0(l),D=ne!=null?new AbortController:void 0,E=fm(a,Z!=null?AbortSignal.timeout(Z):void 0,D?.signal),{maxRetries:U,retry:F}=rm({maxRetries:i,abortSignal:E}),x=Kl(B),M=ln(c??{},`ai/${L0}`),H=W0({model:X,telemetry:h,headers:M,settings:{...x,maxRetries:U}}),re={provider:X.provider,modelId:X.modelId},te=await J0({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 G=K0(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:G,fn:async A=>{var V,J,Y,ue,Te,Be,it,gt,tt,nt,Lt,_t,Rr,Yt,We,_r,$,K,qe,Ee;const ot=te.messages,wt=[],{approvedToolApprovals:Zt,deniedToolApprovals:sr}=nm({messages:ot}),ar=Zt.filter(ht=>!ht.toolCall.providerExecuted);if(sr.length>0||ar.length>0){const ht=await mm({toolCalls:ar.map(Me=>Me.toolCall),tools:t,tracer:G,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=Kl(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 U0({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 V0({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:()=>Q0(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:G,fn:async Dt=>{var Kn,ir,Ps,Wi,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=(Kn=Qe.response)==null?void 0:Kn.id)!=null?ir:I(),timestamp:(Wi=(Ps=Qe.response)==null?void 0:Ps.timestamp)!=null?Wi: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=Yl(Qe.usage);return Dt.setAttributes(await fr({telemetry:h,attributes:{"ai.response.finishReason":Qe.finishReason.unified,"ai.response.text":{output:()=>sm(Qe.content)},"ai.response.reasoning":{output:()=>om(Qe.content)},"ai.response.toolCalls":{output:()=>{const Ct=gm(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=>lm({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 im({tool:Dt,toolCall:Oe,messages:jt,experimental_context:b})&&($o[Oe.toolCallId]={type:"tool-approval-request",approvalId:I(),toolCall:Oe}))}const Gi=wn.filter(Oe=>Oe.invalid&&Oe.dynamic);$e=[];for(const Oe of Gi)$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 mm({toolCalls:pt.filter(Oe=>!Oe.invalid&&$o[Oe.toolCallId]==null),tools:t,tracer:G,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 Wn=M6({content:Le.content,toolCalls:wn,toolOutputs:$e,toolApprovalRequests:Object.values($o),tools:t});wt.push(...await tc({content:Wn,tools:t}));const $s=(tt=T?.requestBody)==null||tt?(nt=Le.request)!=null?nt:{}:{...Le.request,body:void 0},ad={...Le.response,messages:structuredClone(wt),body:(Lt=T?.responseBody)==null||Lt?(_t=Le.response)==null?void 0:_t.body:void 0},id=je.length,Rs=new dm({stepNumber:id,model:yn,functionId:h?.functionId,metadata:h?.metadata,experimental_context:b,content:Wn,finishReason:Le.finishReason.unified,rawFinishReason:Le.finishReason.raw,usage:Yl(Le.usage),warnings:Le.warnings,providerMetadata:Le.providerMetadata,request:$s,response:ad});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 pm({stopConditions:Q,steps:je}));A.setAttributes(await fr({telemetry:h,attributes:{"ai.response.finishReason":Le.finishReason.unified,"ai.response.text":{output:()=>sm(Le.content)},"ai.response.reasoning":{output:()=>om(Le.content)},"ai.response.toolCalls":{output:()=>{const ht=gm(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)=>em(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":(We=Ye.inputTokenDetails)==null?void 0:We.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 P6({steps:je,totalUsage:Ye,output:ft})}})}catch(A){throw G0(A)}}async function mm({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=>Xl({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 P6=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 g0;return this._output}};function gm(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 M6({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 am(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 Hl({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 N6({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 _m({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 O6({response:e,status:t,statusText:r,headers:n,textStream:o}){_m({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 ym=class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
63
+ `),{name:"GatewayAuthenticationError"})}function es({operationId:e,telemetry:t}){return{"operation.name":`${e}${t?.functionId!=null?` ${t.functionId}`:""}`,"resource.name":t?.functionId,"ai.operationId":e,"ai.telemetry.functionId":t?.functionId}}function K0({model:e,settings:t,telemetry:r,headers:n}){var o;return{"ai.model.provider":e.provider,"ai.model.id":e.modelId,...Object.entries(t).reduce((s,[i,a])=>{if(i==="timeout"){const l=Kl(a);l!=null&&(s[`ai.settings.${i}`]=l)}else s[`ai.settings.${i}`]=a;return s},{}),...Object.entries((o=r?.metadata)!=null?o:{}).reduce((s,[i,a])=>(s[`ai.telemetry.metadata.${i}`]=a,s),{}),...Object.entries(n??{}).reduce((s,[i,a])=>(a!==void 0&&(s[`ai.request.headers.${i}`]=a),s),{})}}var v6={startSpan(){return da},startActiveSpan(e,t,r,n){if(typeof t=="function")return t(da);if(typeof r=="function")return r(da);if(typeof n=="function")return n(da)}},da={spanContext(){return w6},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}},w6={traceId:"",spanId:"",traceFlags:0};function Y0({isEnabled:e=!1,tracer:t}={}){return e?t||CT.getTracer("ai"):v6}async function ts({name:e,tracer:t,attributes:r,fn:n,endWhenDone:o=!0}){return t.startActiveSpan(e,{attributes:await r},async s=>{const i=Jh.active();try{const a=await Jh.with(i,()=>n(s));return o&&s.end(),a}catch(a){try{Q0(s,a)}finally{s.end()}throw a}})}function Q0(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:ca.ERROR,message:t.message})):e.setStatus({code:ca.ERROR})}async function fr({telemetry:e,attributes:t}){if(e?.isEnabled!==!0)return{};const r={};for(const[n,o]of Object.entries(t))if(o!=null){if(typeof o=="object"&&"input"in o&&typeof o.input=="function"){if(e?.recordInputs===!1)continue;const s=await o.input();s!=null&&(r[n]=s);continue}if(typeof o=="object"&&"output"in o&&typeof o.output=="function"){if(e?.recordOutputs===!1)continue;const s=await o.output();s!=null&&(r[n]=s);continue}r[n]=o}return r}function X0(e){return JSON.stringify(e.map(t=>({...t,content:typeof t.content=="string"?t.content:t.content.map(r=>r.type==="file"?{...r,data:r.data instanceof Uint8Array?n6(r.data):r.data}:r)})))}function b6(){var e;return(e=globalThis.AI_SDK_TELEMETRY_INTEGRATIONS)!=null?e:[]}function em(){const e=b6();return t=>{const r=qn(t),n=[...e,...r];function o(s){const i=n.map(s).filter(Boolean);return async a=>{for(const l of i)try{await l(a)}catch{}}}return{onStart:o(s=>s.onStart),onStepStart:o(s=>s.onStepStart),onToolCallStart:o(s=>s.onToolCallStart),onToolCallFinish:o(s=>s.onToolCallFinish),onStepFinish:o(s=>s.onStepFinish),onFinish:o(s=>s.onFinish)}}}function Ql(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:kr(e.inputTokens.total,e.outputTokens.total),raw:e.raw,reasoningTokens:e.outputTokens.reasoning,cachedInputTokens:e.inputTokens.cacheRead}}function Xl(){return{inputTokens:void 0,inputTokenDetails:{noCacheTokens:void 0,cacheReadTokens:void 0,cacheWriteTokens:void 0},outputTokens:void 0,outputTokenDetails:{textTokens:void 0,reasoningTokens:void 0},totalTokens:void 0,raw:void 0}}function tm(e,t){var r,n,o,s,i,a,l,c,u,f;return{inputTokens:kr(e.inputTokens,t.inputTokens),inputTokenDetails:{noCacheTokens:kr((r=e.inputTokenDetails)==null?void 0:r.noCacheTokens,(n=t.inputTokenDetails)==null?void 0:n.noCacheTokens),cacheReadTokens:kr((o=e.inputTokenDetails)==null?void 0:o.cacheReadTokens,(s=t.inputTokenDetails)==null?void 0:s.cacheReadTokens),cacheWriteTokens:kr((i=e.inputTokenDetails)==null?void 0:i.cacheWriteTokens,(a=t.inputTokenDetails)==null?void 0:a.cacheWriteTokens)},outputTokens:kr(e.outputTokens,t.outputTokens),outputTokenDetails:{textTokens:kr((l=e.outputTokenDetails)==null?void 0:l.textTokens,(c=t.outputTokenDetails)==null?void 0:c.textTokens),reasoningTokens:kr((u=e.outputTokenDetails)==null?void 0:u.reasoningTokens,(f=t.outputTokenDetails)==null?void 0:f.reasoningTokens)},totalTokens:kr(e.totalTokens,t.totalTokens),reasoningTokens:kr(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:kr(e.cachedInputTokens,t.cachedInputTokens)}}function kr(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}function pa(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;const r={...e};for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)){const o=t[n];if(o===void 0)continue;const s=n in e?e[n]:void 0,i=o!==null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp),a=s!=null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp);i&&a?r[n]=pa(s,o):r[n]=o}return r}function k6({error:e,exponentialBackoffDelay:t}){const r=e.responseHeaders;if(!r)return t;let n;const o=r["retry-after-ms"];if(o){const i=parseFloat(o);Number.isNaN(i)||(n=i)}const s=r["retry-after"];if(s&&n===void 0){const i=parseFloat(s);Number.isNaN(i)?n=Date.parse(s)-Date.now():n=i*1e3}return n!=null&&!Number.isNaN(n)&&0<=n&&(n<60*1e3||n<t)?n:t}var T6=({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:r=2,abortSignal:n}={})=>async o=>rm(o,{maxRetries:e,delayInMs:t,backoffFactor:r,abortSignal:n});async function rm(e,{maxRetries:t,delayInMs:r,backoffFactor:n,abortSignal:o},s=[]){try{return await e()}catch(i){if($n(i)||t===0)throw i;const a=kl(i),l=[...s,i],c=l.length;if(c>t)throw new N0({message:`Failed after ${c} attempts. Last error: ${a}`,reason:"maxRetriesExceeded",errors:l});if(i instanceof Error&&lt.isInstance(i)&&i.isRetryable===!0&&c<=t)return await t9(k6({error:i,exponentialBackoffDelay:r}),{abortSignal:o}),rm(e,{maxRetries:t,delayInMs:n*r,backoffFactor:n,abortSignal:o},l);throw c===1?i:new N0({message:`Failed after ${c} attempts with non-retryable error: '${a}'`,reason:"errorNotRetryable",errors:l})}}function nm({maxRetries:e,abortSignal:t}){if(e!=null){if(!Number.isInteger(e))throw new Lr({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});if(e<0)throw new Lr({parameter:"maxRetries",value:e,message:"maxRetries must be >= 0"})}const r=e??2;return{maxRetries:r,retry:T6({maxRetries:r,abortSignal:t})}}function om({messages:e}){const t=e.at(-1);if(t?.role!="tool")return{approvedToolApprovals:[],deniedToolApprovals:[]};const r={};for(const l of e)if(l.role==="assistant"&&typeof l.content!="string"){const c=l.content;for(const u of c)u.type==="tool-call"&&(r[u.toolCallId]=u)}const n={};for(const l of e)if(l.role==="assistant"&&typeof l.content!="string"){const c=l.content;for(const u of c)u.type==="tool-approval-request"&&(n[u.approvalId]=u)}const o={};for(const l of t.content)l.type==="tool-result"&&(o[l.toolCallId]=l);const s=[],i=[],a=t.content.filter(l=>l.type==="tool-approval-response");for(const l of a){const c=n[l.approvalId];if(c==null)throw new $T({approvalId:l.approvalId});if(o[c.toolCallId]!=null)continue;const u=r[c.toolCallId];if(u==null)throw new Jl({toolCallId:c.toolCallId,approvalId:c.approvalId});const f={approvalRequest:c,approvalResponse:l,toolCall:u};l.approved?s.push(f):i.push(f)}return{approvedToolApprovals:s,deniedToolApprovals:i}}function fa(){var e,t;return(t=(e=globalThis?.performance)==null?void 0:e.now())!=null?t:Date.now()}async function ec({toolCall:e,tools:t,tracer:r,telemetry:n,messages:o,abortSignal:s,experimental_context:i,stepNumber:a,model:l,onPreliminaryToolResult:c,onToolCallStart:u,onToolCallFinish:f}){const{toolName:p,toolCallId:h,input:g}=e,v=t?.[p];if(v?.execute==null)return;const _={stepNumber:a,model:l,toolCall:e,messages:o,abortSignal:s,functionId:n?.functionId,metadata:n?.metadata,experimental_context:i};return ts({name:"ai.toolCall",attributes:fr({telemetry:n,attributes:{...es({operationId:"ai.toolCall",telemetry:n}),"ai.toolCall.name":p,"ai.toolCall.id":h,"ai.toolCall.args":{output:()=>JSON.stringify(g)}}}),tracer:r,fn:async w=>{let y;await br({event:_,callbacks:u});const m=fa();try{const b=f4({execute:v.execute.bind(v),input:g,options:{toolCallId:h,messages:o,abortSignal:s,experimental_context:i}});for await(const T of b)T.type==="preliminary"?c?.({...e,type:"tool-result",output:T.output,preliminary:!0}):y=T.output}catch(b){const T=fa()-m;return await br({event:{..._,success:!1,error:b,durationMs:T},callbacks:f}),Q0(w,b),{type:"tool-error",toolCallId:h,toolName:p,input:g,error:b,dynamic:v.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{}}}const C=fa()-m;await br({event:{..._,success:!0,output:y,durationMs:C},callbacks:f});try{w.setAttributes(await fr({telemetry:n,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(y)}}}))}catch{}return{type:"tool-result",toolCallId:h,toolName:p,input:g,output:y,dynamic:v.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{}}}})}function sm(e){const t=e.filter(r=>r.type==="reasoning");return t.length===0?void 0:t.map(r=>r.text).join(`
64
+ `)}function am(e){const t=e.filter(r=>r.type==="text");if(t.length!==0)return t.map(r=>r.text).join("")}var im=class{constructor({data:e,mediaType:t}){const r=e instanceof Uint8Array;this.base64Data=r?void 0:e,this.uint8ArrayData=r?e:void 0,this.mediaType=t}get base64(){return this.base64Data==null&&(this.base64Data=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)}
65
65
 
66
66
  `)},flush(e){e.enqueue(`data: [DONE]
67
67
 
68
- `)}})}},vm={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function A6({status:e,statusText:t,headers:r,stream:n,consumeSseStream:o}){let s=n.pipeThrough(new ym);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,vm)})}function q6({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 L6(e){return e.type.startsWith("data-")}function rc(e){return e.type.startsWith("tool-")}function j6(e){return e.type==="dynamic-tool"}function wm(e){return rc(e)||j6(e)}function bm(e){return e.type.split("-").slice(1).join("-")}function D6({lastMessage:e,messageId:t}){return{message:e?.role==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function U6({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(wm).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=>rc(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(rc);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(wm).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:bm(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:bm(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(L6(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 z6({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=D6({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 U6({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 F6({response:e,status:t,statusText:r,headers:n,stream:o,consumeSseStream:s}){let i=o.pipeThrough(new ym);if(s){const[a,l]=i.tee();i=a,s({stream:l})}_m({response:e,status:t,statusText:r,headers:Object.fromEntries(ma(n,vm).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 V6({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 km(){let e,t;return{promise:new Promise((n,o)=>{e=n,t=o}),resolve:e,reject:t}}function Z6(){let e=[],t=null,r=!1,n=km();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=km(),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 B6({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 T6({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:Yl(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 Hl({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 lm({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 im({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),Xl({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 H6=Zo({prefix:"aitxt",size:24});function nc({model:e,tools:t,toolChoice:r,system:n,prompt:o,messages:s,maxRetries:i,abortSignal:a,timeout:l,headers:c,stopWhen:u=ec(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=H6}={},...ne}){const D=Wl(l),E=q0(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:fm(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:An(m),activeTools:w,repairToolCall:y,stopConditions:An(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 J6(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=X0()(t?.integrations);let H,re=[];const te=[];let _e,G,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 tc({content:re,tools:h}),Le=new dm({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,G=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 g0({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??Ql();$._finishReason.resolve(Le),$._rawFinishReason.resolve(G),$._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=Z6();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(J6(m??ha())).pipeThrough(gt);const{maxRetries:_t,retry:Rr}=rm({maxRetries:o,abortSignal:s}),Yt=K0(t),We=Kl(n),_r=W0({model:e,telemetry:t,headers:r,settings:{...We,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 J0({system:u,prompt:f,messages:p});await br({event:{model:K,system:u,prompt:f,messages:p,tools:h,toolChoice:g,activeTools:_,maxOutputTokens:We.maxOutputTokens,temperature:We.temperature,topP:We.topP,topK:We.topK,presencePenalty:We.presencePenalty,frequencyPenalty:We.frequencyPenalty,stopSequences:We.stopSequences,seed:We.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}=nm({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 Xl({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 U0({prompt:{system:(je=bt?.system)!=null?je:ot.system,messages:(_n=bt?.messages)!=null?_n:vn},supportedUrls:await Pr.supportedUrls,download:U}),Gi=(Se=bt?.activeTools)!=null?Se:_,{toolChoice:Wn,tools:$s}=await V0({tools:h,toolChoice:(Ye=bt?.toolChoice)!=null?Ye:g,activeTools:Gi});E=(ft=bt?.experimental_context)!=null?ft:E;const ad=(ht=bt?.messages)!=null?ht:vn,id=(jt=bt?.system)!=null?jt:ot.system,Rs=pa(C,bt?.providerOptions);await br({event:{stepNumber:Y.length,model:wn,system:id,messages:ad,tools:h,toolChoice:Wn,activeTools:Gi,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:Kn},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:()=>Q0($o)},"ai.prompt.tools":{input:()=>$s?.map(be=>JSON.stringify(be))},"ai.prompt.toolChoice":{input:()=>Wn!=null?JSON.stringify(Wn):void 0},"gen_ai.system":Pr.provider,"gen_ai.request.model":Pr.modelId,"gen_ai.request.frequency_penalty":We.frequencyPenalty,"gen_ai.request.max_tokens":We.maxOutputTokens,"gen_ai.request.presence_penalty":We.presencePenalty,"gen_ai.request.stop_sequences":We.stopSequences,"gen_ai.request.temperature":We.temperature,"gen_ai.request.top_k":We.topK,"gen_ai.request.top_p":We.topP}}),tracer:Yt,endWhenDone:!1,fn:async be=>({startTimestampMs:I(),doStreamSpan:be,result:await Pr.doStream({...We,tools:$s,toolChoice:Wn,responseFormat:await m?.responseFormat,prompt:$o,providerOptions:Rs,abortSignal:s,headers:r,includeRawChunks:Qt})})})),Wi=B6({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?Kn??{}:{...Kn,body:void 0},bn=[],kn=[];let Ro;const Qe={};let lr="other",Ms,Ct=Ql(),dv,pv=!0,Dr={id:R(),timestamp:new Date,modelId:K.modelId},n$="";$.addStream(Wi.pipeThrough(new TransformStream({async transform(be,Et){var Ns,Os,As,qs,Ls;if(Ji(),be.type==="stream-start"){Ro=be.warnings;return}if(pv){const St=I()-Ps;pv=!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}),n$+=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,dv=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:dv,response:{...Dr,headers:Dt?.headers}});const Po=em(pt,Ct);await H.promise;const ld=Y[Y.length-1];try{ir.setAttributes(await fr({telemetry:t,attributes:{"ai.response.text":{output:()=>ld.text},"ai.response.reasoning":{output:()=>ld.reasoningText},"ai.response.providerMetadata":JSON.stringify(ld.providerMetadata)}}))}catch{}finally{ir.end()}const fv=bn.filter(Ot=>Ot.providerExecuted!==!0),o$=kn.filter(Ot=>Ot.providerExecuted!==!0);for(const Ot of bn){if(Ot.providerExecuted!==!0)continue;const cd=h?.[Ot.toolName];cd?.type==="provider"&&cd.supportsDeferredResults&&(kn.some(ud=>(ud.type==="tool-result"||ud.type==="tool-error")&&ud.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(),(fv.length>0&&o$.length===fv.length||ue.size>0)&&!await pm({stopConditions:y,steps:Y})){Le.push(...await tc({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:Ql()})}}).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 V6({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?q6({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(z6({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}={}){F6({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){O6({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 A6({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 N6({textStream:this.textStream,...e})}};Zo({prefix:"aiobj",size:24}),Zo({prefix:"aiobj",size:24});let oc;oc=globalThis.crypto;async function W6(e){return(await oc).getRandomValues(new Uint8Array(e))}async function K6(e){const t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length;let n="";for(;n.length<e;){const o=await W6(e-n.length);for(const s of o)s<r&&(n+=t[s%t.length])}return n}async function Y6(e){return await K6(e)}async function Q6(e){const t=await(await oc).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function Tm(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;const t=await Y6(e),r=await Q6(t);return{code_verifier:t,code_challenge:r}}var X6="AI_MCPClientError",Cm=`vercel.ai.error.${X6}`,eC=Symbol.for(Cm),Sm,Im,Ve=class extends(Im=we,Sm=eC,Im){constructor({name:e="MCPClientError",message:t,cause:r,data:n,code:o}){super({name:e,message:t,cause:r}),this[Sm]=!0,this.data=n,this.code=o}static isInstance(e){return we.hasMarker(e,Cm)}},fo="2025-11-25",tC=[fo,"2025-06-18","2025-03-26","2024-11-05"],rC=de(ge(d(),Ce())),nC=ut({name:d(),version:d()}),ga=ut({_meta:de(k({}).loose())}),Zr=ga,xm=k({method:d(),params:de(ga)}),Em=k({applyDefaults:de(me())}).loose(),oC=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(Em)});k({elicitation:de(Em)}).loose();var sC=Zr.extend({protocolVersion:d(),capabilities:oC,serverInfo:nC,instructions:de(d())}),sc=Zr.extend({nextCursor:de(d())}),aC=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:rC}).loose(),iC=sc.extend({tools:q(aC)}),$m=k({type:P("text"),text:d()}).loose(),Rm=k({type:P("image"),data:Jp(),mimeType:d()}).loose(),lC=k({uri:d(),name:d(),title:de(d()),description:de(d()),mimeType:de(d()),size:de(O())}).loose(),cC=sc.extend({resources:q(lC)}),Pm=k({uri:d(),name:de(d()),title:de(d()),mimeType:de(d())}).loose(),Mm=Pm.extend({text:d()}),Nm=Pm.extend({blob:Jp()}),Om=k({type:P("resource"),resource:ae([Mm,Nm])}).loose(),uC=Zr.extend({content:q(ae([$m,Rm,Om])),structuredContent:de(Ce()),isError:me().default(!1).optional()}).or(Zr.extend({toolResult:Ce()})),dC=k({uriTemplate:d(),name:d(),title:de(d()),description:de(d()),mimeType:de(d())}).loose(),pC=Zr.extend({resourceTemplates:q(dC)}),fC=Zr.extend({contents:q(ae([Mm,Nm]))}),hC=k({name:d(),description:de(d()),required:de(me())}).loose(),mC=k({name:d(),title:de(d()),description:de(d()),arguments:de(q(hC))}).loose(),gC=sc.extend({prompts:q(mC)}),_C=k({role:ae([P("user"),P("assistant")]),content:ae([$m,Rm,Om])}).loose(),yC=Zr.extend({description:de(d()),messages:q(_C)}),vC=ga.extend({message:d(),requestedSchema:Ce()}),Am=xm.extend({method:P("elicitation/create"),params:vC}),wC=Zr.extend({action:ae([P("accept"),P("decline"),P("cancel")]),content:de(ge(d(),Ce()))}),_a="2.0",bC=k({jsonrpc:P(_a),id:ae([d(),O().int()])}).merge(xm).strict(),kC=k({jsonrpc:P(_a),id:ae([d(),O().int()]),result:Zr}).strict(),TC=k({jsonrpc:P(_a),id:ae([d(),O().int()]),error:k({code:O().int(),message:d(),data:de(Ce())})}).strict(),CC=k({jsonrpc:P(_a)}).merge(k({method:d(),params:de(ga)})).strict(),os=ae([bC,CC,kC,TC]),qm=typeof __PACKAGE_VERSION__<"u"?__PACKAGE_VERSION__:"0.0.0-test",Lm=k({access_token:d(),id_token:d().optional(),token_type:d(),expires_in:O().optional(),scope:d().optional(),refresh_token:d().optional()}).strip(),Wt=d().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:nf.custom,message:"URL must be parseable",fatal:!0}),rp}).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"}),SC=k({resource:d().url(),authorization_servers:q(Wt).optional(),jwks_uri:d().url().optional(),scopes_supported:q(d()).optional(),bearer_methods_supported:q(d()).optional(),resource_signing_alg_values_supported:q(d()).optional(),resource_name:d().optional(),resource_documentation:d().optional(),resource_policy_uri:d().url().optional(),resource_tos_uri:d().url().optional(),tls_client_certificate_bound_access_tokens: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(),jm=k({issuer:d(),authorization_endpoint:Wt,token_endpoint:Wt,registration_endpoint:Wt.optional(),scopes_supported:q(d()).optional(),response_types_supported:q(d()),grant_types_supported:q(d()).optional(),code_challenge_methods_supported:q(d()),token_endpoint_auth_methods_supported:q(d()).optional(),token_endpoint_auth_signing_alg_values_supported:q(d()).optional()}).passthrough(),IC=k({issuer:d(),authorization_endpoint:Wt,token_endpoint:Wt,userinfo_endpoint:Wt.optional(),jwks_uri:Wt,registration_endpoint:Wt.optional(),scopes_supported:q(d()).optional(),response_types_supported:q(d()),grant_types_supported:q(d()).optional(),subject_types_supported:q(d()),id_token_signing_alg_values_supported:q(d()),claims_supported:q(d()).optional(),token_endpoint_auth_methods_supported:q(d()).optional()}).passthrough(),xC=IC.merge(jm.pick({code_challenge_methods_supported:!0})),EC=k({client_id:d(),client_secret:d().optional(),client_id_issued_at:O().optional(),client_secret_expires_at:O().optional()}).strip(),$C=k({redirect_uris:q(Wt),token_endpoint_auth_method:d().optional(),grant_types:q(d()).optional(),response_types:q(d()).optional(),client_name:d().optional(),client_uri:Wt.optional(),logo_uri:Wt.optional(),scope:d().optional(),contacts:q(d()).optional(),tos_uri:Wt.optional(),policy_uri:d().optional(),jwks_uri:Wt.optional(),jwks:yt().optional(),software_id:d().optional(),software_version:d().optional(),software_statement:d().optional()}).strip(),RC=k({error:d(),error_description:d().optional(),error_uri:d().optional()}),PC=$C.merge(EC),MC="AI_MCPClientOAuthError",Dm=`vercel.ai.error.${MC}`,NC=Symbol.for(Dm),Um,zm,ss=class extends(zm=we,Um=NC,zm){constructor({name:e="MCPClientOAuthError",message:t,cause:r}){super({name:e,message:t,cause:r}),this[Um]=!0}static isInstance(e){return we.hasMarker(e,Dm)}},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 OC={[ho.errorCode]:ho,[ya.errorCode]:ya,[va.errorCode]:va,[wa.errorCode]:wa};function AC(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function qC({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 LC(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 Fm(e,t,r=fetch){return await ac(e,{"MCP-Protocol-Version":t},r)}function jC(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function DC(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=LC(t,i.pathname);l=new URL(u,(s=n?.metadataServerUrl)!=null?s:i),l.search=i.search}let c=await Fm(l,a,r);if(!n?.metadataUrl&&jC(c,i.pathname)){const u=new URL(`/.well-known/${t}`,i);c=await Fm(u,a,r)}return c}async function UC(e,t,r=fetch){const n=await DC(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 SC.parse(await n.json())}function zC(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 FC(e,{fetchFn:t=fetch,protocolVersion:r=fo}={}){var n;const o={"MCP-Protocol-Version":r},s=zC(e);for(const{url:i,type:a}of s){const l=await ac(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 jm.parse(await l.json());{const c=xC.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 VC(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 Tm(),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",i.href),{authorizationUrl:c,codeVerifier:f}}function Vm(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 Zm(e,t,r,n){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":ZC(o,s,r);return;case"client_secret_post":BC(o,s,n);return;case"none":HC(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function ZC(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 BC(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function HC(e,t){t.set("client_id",e)}async function ic(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=RC.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:i}=n,a=OC[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 JC(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:[],_=Vm(r,v);Zm(_,r,p,h)}i&&h.set("resource",i.href);const g=await(l??fetch)(f,{method:"POST",headers:p,body:h});if(!g.ok)throw await ic(g);return Lm.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=Vm(r,h);Zm(g,r,u,f)}o&&f.set("resource",o.href);const p=await(i??fetch)(c,{method:"POST",headers:u,body:f});if(!p.ok)throw await ic(p);return Lm.parse({refresh_token:n,...await p.json()})}async function WC(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 ic(s);return PC.parse(await s.json())}async function Ta(e,t){var r,n;try{return await lc(e,t)}catch(o){if(o instanceof ya||o instanceof wa)return await((r=e.invalidateCredentials)==null?void 0:r.call(e,"all")),await lc(e,t);if(o instanceof va)return await((n=e.invalidateCredentials)==null?void 0:n.call(e,"tokens")),await lc(e,t);throw o}}async function KC(e,t,r){const n=AC(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!qC({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:s,fetchFn:i}){let a,l;try{a=await UC(t,{resourceMetadataUrl:s},i),a.authorization_servers&&a.authorization_servers.length>0&&(l=a.authorization_servers[0])}catch{}l||(l=t);const c=await KC(t,e,a),u=await FC(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 WC(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 JC(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 VC(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 YC=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/${qm}`,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 oo).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()}},QC=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/${qm}`,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 oo).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 oo).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 XC(e){switch(e.type){case"sse":return new YC(e);case"http":return new QC(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 e5(e){return"start"in e&&typeof e.start=="function"&&"send"in e&&typeof e.send=="function"&&"close"in e&&typeof e.close=="function"}var t5="1.0.0";function Bm({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 r5(e){const t=new n5(e);return await t.init(),t}var n5=class{constructor({transport:e,name:t="ai-sdk-mcp-client",version:r=t5,onUncaughtError:n,capabilities:o}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this.isClosed=!0,this.onUncaughtError=n,this.clientCapabilities=o??{},e5(e)?this.transport=e:this.transport=XC(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:sC});if(e===void 0)throw new Ve({message:"Server sent invalid initialize result"});if(!tC.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:iC,options:t})}async callTool({name:e,args:t,options:r}){try{return this.request({request:{method:"tools/call",params:{name:e,arguments:t}},resultSchema:uC,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:cC,options:t})}catch(r){throw r}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:"resources/read",params:{uri:e}},resultSchema:fC,options:t})}catch(r){throw r}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:"resources/templates/list"},resultSchema:pC,options:e})}catch(t){throw t}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:"prompts/list",params:e},resultSchema:gC,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:yC,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"?Kf({description:a,title:f,inputSchema:uo({...l,properties:(n=l.properties)!=null?n:{},additionalProperties:!1}),execute:g,toModelOutput:Bm}):{description:a,title:f,inputSchema:t[s].inputSchema,...h!=null?{outputSchema:h}:{},execute:g,toModelOutput:Bm};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:Pn(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!==Am)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=Am.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=wC.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 Hm(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",o5=[Sa,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],qn="io.modelcontextprotocol/related-task",Ia="2.0",$t=tf(e=>e!==null&&(typeof e=="object"||typeof e=="function")),Jm=ae([d(),O().int()]),Gm=d();ut({ttl:ae([O(),Do()]).optional(),pollInterval:O().optional()});const s5=k({ttl:O().optional()}),a5=k({taskId:d()}),cc=ut({progressToken:Jm.optional(),[qn]:a5.optional()}),nr=k({_meta:cc.optional()}),as=nr.extend({task:s5.optional()}),i5=e=>as.safeParse(e).success,Rt=k({method:d(),params:nr.loose().optional()}),hr=k({_meta:cc.optional()}),mr=k({method:d(),params:hr.loose().optional()}),Pt=ut({_meta:cc.optional()}),xa=ae([d(),O().int()]),Wm=k({jsonrpc:P(Ia),id:xa,...Rt.shape}).strict(),uc=e=>Wm.safeParse(e).success,Km=k({jsonrpc:P(Ia),...mr.shape}).strict(),l5=e=>Km.safeParse(e).success,dc=k({jsonrpc:P(Ia),id:xa,result:Pt}).strict(),is=e=>dc.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 pc=k({jsonrpc:P(Ia),id:xa.optional(),error:k({code:O().int(),message:d(),data:Ce().optional()})}).strict(),c5=e=>pc.safeParse(e).success,Ln=ae([Wm,Km,dc,pc]);ae([dc,pc]);const jn=Pt.strict(),u5=hr.extend({requestId:xa.optional(),reason:d().optional()}),fc=mr.extend({method:P("notifications/cancelled"),params:u5}),d5=k({src:d(),mimeType:d().optional(),sizes:q(d()).optional(),theme:ce(["light","dark"]).optional()}),ls=k({icons:q(d5).optional()}),mo=k({name:d(),title:d().optional()}),Ym=mo.extend({...mo.shape,...ls.shape,version:d(),websiteUrl:d().optional(),description:d().optional()}),p5=il(k({applyDefaults:me().optional()}),ge(d(),Ce())),f5=rf(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,il(k({form:p5.optional(),url:$t.optional()}),ge(d(),Ce()).optional())),h5=ut({list:$t.optional(),cancel:$t.optional(),requests:ut({sampling:ut({createMessage:$t.optional()}).optional(),elicitation:ut({create:$t.optional()}).optional()}).optional()}),m5=ut({list:$t.optional(),cancel:$t.optional(),requests:ut({tools:ut({call:$t.optional()}).optional()}).optional()}),g5=k({experimental:ge(d(),$t).optional(),sampling:k({context:$t.optional(),tools:$t.optional()}).optional(),elicitation:f5.optional(),roots:k({listChanged:me().optional()}).optional(),tasks:h5.optional()}),_5=nr.extend({protocolVersion:d(),capabilities:g5,clientInfo:Ym}),y5=Rt.extend({method:P("initialize"),params:_5}),v5=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:m5.optional()}),Qm=Pt.extend({protocolVersion:d(),capabilities:v5,serverInfo:Ym,instructions:d().optional()}),Xm=mr.extend({method:P("notifications/initialized"),params:hr.optional()}),w5=e=>Xm.safeParse(e).success,hc=Rt.extend({method:P("ping"),params:nr.optional()}),b5=k({progress:O(),total:de(O()),message:de(d())}),k5=k({...hr.shape,...b5.shape,progressToken:Jm}),mc=mr.extend({method:P("notifications/progress"),params:k5}),T5=nr.extend({cursor:Gm.optional()}),cs=Rt.extend({params:T5.optional()}),us=Pt.extend({nextCursor:Gm.optional()}),C5=ce(["working","input_required","completed","failed","cancelled"]),ds=k({taskId:d(),status:C5,ttl:ae([O(),Do()]),createdAt:d(),lastUpdatedAt:d(),pollInterval:de(O()),statusMessage:de(d())}),ps=Pt.extend({task:ds}),S5=hr.merge(ds),Ea=mr.extend({method:P("notifications/tasks/status"),params:S5}),gc=Rt.extend({method:P("tasks/get"),params:nr.extend({taskId:d()})}),_c=Pt.merge(ds),yc=Rt.extend({method:P("tasks/result"),params:nr.extend({taskId:d()})});Pt.loose();const vc=cs.extend({method:P("tasks/list")}),wc=us.extend({tasks:q(ds)}),bc=Rt.extend({method:P("tasks/cancel"),params:nr.extend({taskId:d()})}),I5=Pt.merge(ds),e2=k({uri:d(),mimeType:de(d()),_meta:ge(d(),Ce()).optional()}),t2=e2.extend({text:d()}),kc=d().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),r2=e2.extend({blob:kc}),fs=ce(["user","assistant"]),go=k({audience:q(fs).optional(),priority:O().min(0).max(1).optional(),lastModified:zp({offset:!0}).optional()}),n2=k({...mo.shape,...ls.shape,uri:d(),description:de(d()),mimeType:de(d()),annotations:go.optional(),_meta:de(ut({}))}),x5=k({...mo.shape,...ls.shape,uriTemplate:d(),description:de(d()),mimeType:de(d()),annotations:go.optional(),_meta:de(ut({}))}),E5=cs.extend({method:P("resources/list")}),o2=us.extend({resources:q(n2)}),$5=cs.extend({method:P("resources/templates/list")}),s2=us.extend({resourceTemplates:q(x5)}),Tc=nr.extend({uri:d()}),R5=Tc,P5=Rt.extend({method:P("resources/read"),params:R5}),a2=Pt.extend({contents:q(ae([t2,r2]))}),Cc=mr.extend({method:P("notifications/resources/list_changed"),params:hr.optional()}),M5=Tc,N5=Rt.extend({method:P("resources/subscribe"),params:M5}),O5=Tc,A5=Rt.extend({method:P("resources/unsubscribe"),params:O5}),q5=hr.extend({uri:d()}),i2=mr.extend({method:P("notifications/resources/updated"),params:q5}),L5=k({name:d(),description:de(d()),required:de(me())}),j5=k({...mo.shape,...ls.shape,description:de(d()),arguments:de(q(L5)),_meta:de(ut({}))}),D5=cs.extend({method:P("prompts/list")}),l2=us.extend({prompts:q(j5)}),U5=nr.extend({name:d(),arguments:ge(d(),d()).optional()}),z5=Rt.extend({method:P("prompts/get"),params:U5}),Sc=k({type:P("text"),text:d(),annotations:go.optional(),_meta:ge(d(),Ce()).optional()}),Ic=k({type:P("image"),data:kc,mimeType:d(),annotations:go.optional(),_meta:ge(d(),Ce()).optional()}),xc=k({type:P("audio"),data:kc,mimeType:d(),annotations:go.optional(),_meta:ge(d(),Ce()).optional()}),F5=k({type:P("tool_use"),name:d(),id:d(),input:ge(d(),Ce()),_meta:ge(d(),Ce()).optional()}),V5=k({type:P("resource"),resource:ae([t2,r2]),annotations:go.optional(),_meta:ge(d(),Ce()).optional()}),Z5=n2.extend({type:P("resource_link")}),Ec=ae([Sc,Ic,xc,Z5,V5]),B5=k({role:fs,content:Ec}),c2=Pt.extend({description:d().optional(),messages:q(B5)}),$c=mr.extend({method:P("notifications/prompts/list_changed"),params:hr.optional()}),H5=k({title:d().optional(),readOnlyHint:me().optional(),destructiveHint:me().optional(),idempotentHint:me().optional(),openWorldHint:me().optional()}),J5=k({taskSupport:ce(["required","optional","forbidden"]).optional()}),u2=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:H5.optional(),execution:J5.optional(),_meta:ge(d(),Ce()).optional()}),G5=cs.extend({method:P("tools/list")}),d2=us.extend({tools:q(u2)}),hs=Pt.extend({content:q(Ec).default([]),structuredContent:ge(d(),Ce()).optional(),isError:me().optional()});hs.or(Pt.extend({toolResult:Ce()}));const W5=as.extend({name:d(),arguments:ge(d(),Ce()).optional()}),K5=Rt.extend({method:P("tools/call"),params:W5}),Rc=mr.extend({method:P("notifications/tools/list_changed"),params:hr.optional()}),Y5=k({autoRefresh:me().default(!0),debounceMs:O().int().nonnegative().default(300)}),p2=ce(["debug","info","notice","warning","error","critical","alert","emergency"]),Q5=nr.extend({level:p2}),X5=Rt.extend({method:P("logging/setLevel"),params:Q5}),eS=hr.extend({level:p2,logger:d().optional(),data:Ce()}),f2=mr.extend({method:P("notifications/message"),params:eS}),tS=k({name:d().optional()}),rS=k({hints:q(tS).optional(),costPriority:O().min(0).max(1).optional(),speedPriority:O().min(0).max(1).optional(),intelligencePriority:O().min(0).max(1).optional()}),nS=k({mode:ce(["auto","required","none"]).optional()}),oS=k({type:P("tool_result"),toolUseId:d().describe("The unique identifier for the corresponding tool call."),content:q(Ec).default([]),structuredContent:k({}).loose().optional(),isError:me().optional(),_meta:ge(d(),Ce()).optional()}),sS=ze("type",[Sc,Ic,xc]),$a=ze("type",[Sc,Ic,xc,F5,oS]),aS=k({role:fs,content:ae([$a,q($a)]),_meta:ge(d(),Ce()).optional()}),iS=as.extend({messages:q(aS),modelPreferences:rS.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(u2).optional(),toolChoice:nS.optional()}),Pc=Rt.extend({method:P("sampling/createMessage"),params:iS}),Mc=Pt.extend({model:d(),stopReason:de(ce(["endTurn","stopSequence","maxTokens"]).or(d())),role:fs,content:sS}),h2=Pt.extend({model:d(),stopReason:de(ce(["endTurn","stopSequence","maxTokens","toolUse"]).or(d())),role:fs,content:ae([$a,q($a)])}),lS=k({type:P("boolean"),title:d().optional(),description:d().optional(),default:me().optional()}),cS=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()}),uS=k({type:ce(["number","integer"]),title:d().optional(),description:d().optional(),minimum:O().optional(),maximum:O().optional(),default:O().optional()}),dS=k({type:P("string"),title:d().optional(),description:d().optional(),enum:q(d()),default:d().optional()}),pS=k({type:P("string"),title:d().optional(),description:d().optional(),oneOf:q(k({const:d(),title:d()})),default:d().optional()}),fS=k({type:P("string"),title:d().optional(),description:d().optional(),enum:q(d()),enumNames:q(d()).optional(),default:d().optional()}),hS=ae([dS,pS]),mS=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()}),gS=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()}),_S=ae([mS,gS]),yS=ae([fS,hS,_S]),vS=ae([yS,lS,cS,uS]),wS=as.extend({mode:P("form").optional(),message:d(),requestedSchema:k({type:P("object"),properties:ge(d(),vS),required:q(d()).optional()})}),bS=as.extend({mode:P("url"),message:d(),elicitationId:d(),url:d().url()}),kS=ae([wS,bS]),Nc=Rt.extend({method:P("elicitation/create"),params:kS}),TS=hr.extend({elicitationId:d()}),CS=mr.extend({method:P("notifications/elicitation/complete"),params:TS}),Oc=Pt.extend({action:ce(["accept","decline","cancel"]),content:rf(e=>e===null?void 0:e,ge(d(),ae([d(),O(),me(),q(d())])).optional())}),SS=k({type:P("ref/resource"),uri:d()}),IS=k({type:P("ref/prompt"),name:d()}),xS=nr.extend({ref:ae([IS,SS]),argument:k({name:d(),value:d()}),context:k({arguments:ge(d(),d()).optional()}).optional()}),ES=Rt.extend({method:P("completion/complete"),params:xS}),m2=Pt.extend({completion:ut({values:q(d()).max(100),total:de(O().int()),hasMore:de(me())})}),$S=k({uri:d().startsWith("file://"),name:d().optional(),_meta:ge(d(),Ce()).optional()}),g2=Rt.extend({method:P("roots/list"),params:nr.optional()}),_2=Pt.extend({roots:q($S)}),RS=mr.extend({method:P("notifications/roots/list_changed"),params:hr.optional()});ae([hc,y5,ES,X5,z5,D5,E5,$5,P5,N5,A5,K5,G5,gc,yc,vc,bc]),ae([fc,mc,Xm,RS,Ea]),ae([jn,Mc,h2,Oc,_2,_c,wc,ps]),ae([hc,Pc,Nc,g2,gc,yc,vc,bc]),ae([fc,mc,f2,i2,Cc,Rc,$c,Ea,CS]),ae([jn,Qm,m2,c2,l2,o2,s2,a2,hs,d2,_c,wc,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 PS(o.elicitations,r)}return new ke(t,r,n)}}class PS 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=Lb().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:nf.custom,message:"URL must be parseable",fatal:!0}),rp}).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"}),MS=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()}),y2=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()}),NS=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()}),OS=k({...NS.shape,...y2.pick({code_challenge_methods_supported:!0}).shape}),AS=k({access_token:d(),id_token:d().optional(),token_type:d(),expires_in:of().optional(),scope:d().optional(),refresh_token:d().optional()}).strip(),qS=k({error:d(),error_description:d().optional(),error_uri:d().optional()}),v2=Mt.optional().or(P("").transform(()=>{})),LS=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:v2,scope:d().optional(),contacts:q(d()).optional(),tos_uri:v2,policy_uri:d().optional(),jwks_uri:Mt.optional(),jwks:yt().optional(),software_id:d().optional(),software_version:d().optional(),software_statement:d().optional()}).strip(),jS=k({client_id:d(),client_secret:d().optional(),client_id_issued_at:O().optional(),client_secret_expires_at:O().optional()}).strip(),DS=LS.merge(jS);k({error:d(),error_description:d().optional()}).strip(),k({token:d(),token_type_hint:d().optional()}).strip();function US(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function zS({requestedResource:e,configuredResource:t}){const r=typeof e=="string"?new URL(e):new URL(e.href),n=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;const o=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return o.startsWith(s)}class 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 Ac extends It{}Ac.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 qc extends It{}qc.errorCode="unsupported_grant_type";class Lc extends It{}Lc.errorCode="invalid_scope";class jc extends It{}jc.errorCode="access_denied";class _o extends It{}_o.errorCode="server_error";class Dc extends It{}Dc.errorCode="temporarily_unavailable";class Uc extends It{}Uc.errorCode="unsupported_response_type";class zc extends It{}zc.errorCode="unsupported_token_type";class Fc extends It{}Fc.errorCode="invalid_token";class Vc extends It{}Vc.errorCode="method_not_allowed";class Zc extends It{}Zc.errorCode="too_many_requests";class Na extends It{}Na.errorCode="invalid_client_metadata";class Bc extends It{}Bc.errorCode="insufficient_scope";class Hc extends It{}Hc.errorCode="invalid_target";const FS={[Ac.errorCode]:Ac,[Ra.errorCode]:Ra,[Pa.errorCode]:Pa,[Ma.errorCode]:Ma,[qc.errorCode]:qc,[Lc.errorCode]:Lc,[jc.errorCode]:jc,[_o.errorCode]:_o,[Dc.errorCode]:Dc,[Uc.errorCode]:Uc,[zc.errorCode]:zc,[Fc.errorCode]:Fc,[Vc.errorCode]:Vc,[Zc.errorCode]:Zc,[Na.errorCode]:Na,[Bc.errorCode]:Bc,[Hc.errorCode]:Hc};class gr extends Error{constructor(t){super(t??"Unauthorized")}}function VS(e){return["client_secret_basic","client_secret_post","none"].includes(e)}const Jc="code",Gc="S256";function ZS(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&&VS(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 BS(e,t,r,n){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":HS(o,s,r);return;case"client_secret_post":JS(o,s,n);return;case"none":GS(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function HS(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 JS(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 w2(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=qS.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:i}=n,a=FS[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 Dn(e,t){try{return await Wc(e,t)}catch(r){if(r instanceof Ra||r instanceof Ma)return await e.invalidateCredentials?.("all"),await Wc(e,t);if(r instanceof Pa)return await e.invalidateCredentials?.("tokens"),await Wc(e,t);throw r}}async function Wc(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){let i,a;try{i=await YS(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 KS(t,e,i),c=await rI(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&&!WS(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 iI(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 aI(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 sI(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 nI(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 WS(e){if(!e)return!1;try{const t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function KS(e,t,r){const n=US(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!zS({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}function Oa(e){const t=e.headers.get("WWW-Authenticate");if(!t)return{};const[r,n]=t.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};const o=Kc(e,"resource_metadata")||void 0;let s;if(o)try{s=new URL(o)}catch{}const i=Kc(e,"scope")||void 0,a=Kc(e,"error")||void 0;return{resourceMetadataUrl:s,scope:i,error:a}}function Kc(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 YS(e,t,r=fetch){const n=await eI(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 MS.parse(await n.json())}async function Yc(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?Yc(e,void 0,r):void 0;throw n}}function QS(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function b2(e,t,r=fetch){return await Yc(e,{"MCP-Protocol-Version":t},r)}function XS(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function eI(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=QS(t,o.pathname);i=new URL(l,n?.metadataServerUrl??o),i.search=o.search}let a=await b2(i,s,r);if(!n?.metadataUrl&&XS(a,o.pathname)){const l=new URL(`/.well-known/${t}`,o);a=await b2(l,s,r)}return a}function tI(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 rI(e,{fetchFn:t=fetch,protocolVersion:r=Sa}={}){const n={"MCP-Protocol-Version":r,Accept:"application/json"},o=tI(e);for(const{url:s,type:i}of o){const a=await Yc(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"?y2.parse(await a.json()):OS.parse(await a.json())}}}async function nI(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(Jc))throw new Error(`Incompatible auth server: does not support response type ${Jc}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Gc))throw new Error(`Incompatible auth server: does not support code challenge method ${Gc}`)}else a=new URL("/authorize",e);const l=await Tm(),c=l.code_verifier,u=l.code_challenge;return a.searchParams.set("response_type",Jc),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",u),a.searchParams.set("code_challenge_method",Gc),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 oI(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function k2(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=ZS(n,u);BS(f,n,l,r)}const c=await(i??fetch)(a,{method:"POST",headers:l,body:r});if(!c.ok)throw await w2(c);return AS.parse(await c.json())}async function sI(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 k2(e,{metadata:t,tokenRequestParams:a,clientInformation:r,addClientAuthentication:s,resource:o,fetchFn:i});return{refresh_token:n,...l}}async function aI(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=oI(o,c,e.redirectUrl)}const l=await e.clientInformation();return k2(t,{metadata:r,tokenRequestParams:a,clientInformation:l??void 0,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:s})}async function iI(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 w2(s);return DS.parse(await s.json())}const lI={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=Hm(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??lI}async _authThenStart(){if(!this._authProvider)throw new gr("No auth provider");let t;try{t=await Dn(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 oo({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=Ln.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 Dn(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:uc(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 Dn(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 Dn(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(),w5(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=>Ln.parse(g)):[Ln.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 T2 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(C2(this),r)}[Symbol.for("Deno.customInspect")](t,r){return t(C2(this),r)}}function cI(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function Qc(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(Qc).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${Qc(e.cause)}`:e.message:`${e}`}function C2(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var S2=e=>{throw TypeError(e)},Xc=(e,t,r)=>t.has(e)||S2("Cannot "+r),Ae=(e,t,r)=>(Xc(e,t,"read from private field"),r?r.call(e):t.get(e)),Tt=(e,t,r)=>t.has(e)?S2("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),at=(e,t,r,n)=>(Xc(e,t,"write to private field"),t.set(e,r),r),Br=(e,t,r)=>(Xc(e,t,"access private method"),r),Kt,Un,vo,qa,La,ms,wo,gs,un,bo,ko,To,_s,Tr,eu,tu,ru,I2,nu,ou,ys,su,au;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,Un),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,tu,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,su).call(this))}while(g)}),Tt(this,ru,s=>{at(this,un,void 0),!(s.name==="AbortError"||s.type==="aborted")&&Br(this,Tr,su).call(this,Qc(s))}),Tt(this,nu,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,Un).origin,lastEventId:s.id||""});Ae(this,To)&&(!s.event||s.event==="message")&&Ae(this,To).call(this,i),this.dispatchEvent(i)}),Tt(this,ou,s=>{at(this,ms,s)}),Tt(this,au,()=>{at(this,wo,void 0),Ae(this,Kt)===this.CONNECTING&&Br(this,Tr,eu).call(this)});try{if(t instanceof URL)at(this,Un,t);else if(typeof t=="string")at(this,Un,new URL(t,uI()));else throw new Error("Invalid URL")}catch{throw cI("An invalid or illegal string was specified")}at(this,bo,If({onEvent:Ae(this,nu),onRetry:Ae(this,ou)})),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,eu).call(this)}get readyState(){return Ae(this,Kt)}get url(){return Ae(this,Un).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,Un=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,eu=function(){at(this,Kt,this.CONNECTING),at(this,un,new AbortController),Ae(this,La)(Ae(this,Un),Br(this,Tr,I2).call(this)).then(Ae(this,tu)).catch(Ae(this,ru))},tu=new WeakMap,ru=new WeakMap,I2=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},nu=new WeakMap,ou=new WeakMap,ys=function(e,t){var r;Ae(this,Kt)!==this.CLOSED&&at(this,Kt,this.CLOSED);const n=new T2("error",{code:t,message:e});(r=Ae(this,ko))==null||r.call(this,n),this.dispatchEvent(n)},su=function(e,t){var r;if(Ae(this,Kt)===this.CLOSED)return;at(this,Kt,this.CONNECTING);const n=new T2("error",{code:t,message:e});(r=Ae(this,ko))==null||r.call(this,n),this.dispatchEvent(n),at(this,wo,setTimeout(Ae(this,au),Ae(this,ms)))},au=new WeakMap,ja.CONNECTING=0,ja.OPEN=1,ja.CLOSED=2;function uI(){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 dI 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=Hm(r?.fetch,r?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new gr("No auth provider");let t;try{t=await Dn(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 dI(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=Ln.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 Dn(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 Dn(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 iu=k({error:k({message:d(),type:d().nullish(),param:yt().nullish(),code:ae([d(),O()]).nullish()})}),Cr=Ar({errorSchema:iu,errorToMessage:e=>e.error.message});function x2(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 E2(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 pI({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,${lo(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:lo(a.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:lo(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,${lo(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 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 $2(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 fI=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()}))),hI=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()}),iu]))),mI=ve(()=>ye(k({logitBias:ge(of(),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 gI({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 _I=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:mI}))!=null?h:{},C=x2(this.modelId),b=(g=m.forceReasoning)!=null?g:C.isReasoningModel;o!=null&&y.push({type:"unsupported",feature:"topK"});const{messages:T,warnings:I}=pI({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}=gI({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:Gt(fI),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:$2(h.finish_reason),raw:(a=h.finish_reason)!=null?a:void 0},usage:E2(f.usage),request:{body:l},response:{...lu(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(hI),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=lu(X);Object.values(Z).some(Boolean)&&(c=!0,h.enqueue({type:"response-metadata",...lu(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:$2(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}),Hf(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&&Hf(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:E2(l),...f!=null?{providerMetadata:f}:{}})}})),request:{body:n},response:{headers:o}}}};function R2(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 yI({prompt:e,user:t="user",assistant:r="assistant"}){let n="";e[0].role==="system"&&(n+=`${e[0].content}
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}
69
69
 
70
70
  `,e=e.slice(1));for(const{role:o,content:s}of e)switch(o){case"system":throw new Cn({message:"Unexpected system message in prompt: ${content}",prompt:e});case"user":{const i=s.map(a=>{switch(a.type){case"text":return a.text}}).filter(Boolean).join("");n+=`${t}:
71
71
  ${i}
@@ -75,16 +75,16 @@ ${i}
75
75
 
76
76
  `;break}case"tool":throw new Mr({functionality:"tool messages"});default:{const i=o;throw new Error(`Unsupported role: ${i}`)}}return n+=`${r}:
77
77
  `,{prompt:n,stopSequences:[`
78
- ${t}:`]}}function P2({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 M2(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 vI=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()}))),wI=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()}),iu]))),N2=ve(()=>ye(k({echo:me().optional(),logitBias:ge(d(),O()).optional(),suffix:d().optional(),user:d().optional(),logprobs:ae([me(),O()]).optional()}))),bI=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:N2}),...await Fr({provider:this.providerOptionsName,providerOptions:p,schema:N2})};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:_}=yI({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:Gt(vI),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:R2(s.usage),finishReason:{unified:M2(a.finish_reason),raw:(t=a.finish_reason)!=null?t:void 0},request:{body:r},response:{...P2(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(wI),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",...P2(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:M2(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:R2(l)})}})),request:{body:n},response:{headers:o}}}},kI=ve(()=>ye(k({dimensions:O().optional(),user:d().optional()}))),TI=ve(()=>ye(k({data:q(k({embedding:q(O())})),usage:k({prompt_tokens:O()}).nullish()}))),CI=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 $v({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const s=(o=await Fr({provider:"openai",providerOptions:n,schema:kI}))!=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:Gt(TI),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}}}},O2=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()}))),SI={"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},II=["chatgpt-image-","gpt-image-1-mini","gpt-image-1.5","gpt-image-1"];function xI(e){return II.some(t=>e.startsWith(t))}var EI=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get maxImagesPerCall(){var e;return(e=SI[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 Gf({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:At(this.config.headers(),l),formData:n9({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([ao(N.data)],{type:N.mediaType})],{type:N.mediaType}):Of(N.url))),mask:r!=null?await $I(r):void 0,n,size:o,...(h=a.openai)!=null?h:{}}),failedResponseHandler:Cr,successfulResponseHandler:Gt(O2),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,...A2((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:{},...xI(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:Cr,successfulResponseHandler:Gt(O2),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,...A2((ee=I.usage)==null?void 0:ee.input_tokens_details,j,I.data.length)}})}}}}};function A2(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 $I(e){if(!e)return;if(e.type==="url")return Of(e.url);const t=e.data instanceof Uint8Array?e.data:ao(e.data);return new Blob([t],{type:e.mediaType})}var q2=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()})])}))),L2=ve(()=>ye(k({status:ce(["completed","failed"]),output:d().optional()}))),RI=pr({id:"openai.apply_patch",inputSchema:q2,outputSchema:L2}),PI=RI,MI=ve(()=>ye(k({code:d().nullish(),containerId:d()}))),NI=ve(()=>ye(k({outputs:q(ze("type",[k({type:P("logs"),logs:d()}),k({type:P("image"),url:d()})])).nullish()}))),OI=ve(()=>ye(k({container:ae([d(),k({fileIds:q(d()).optional()})]).optional()}))),AI=pr({id:"openai.code_interpreter",inputSchema:MI,outputSchema:NI}),qI=(e={})=>AI(e),LI=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()}))),jI=ve(()=>ye(d())),DI=c4({id:"openai.custom",inputSchema:jI}),UI=e=>DI(e),j2=k({key:d(),type:ce(["eq","ne","gt","gte","lt","lte","in","nin"]),value:ae([d(),O(),me(),q(d())])}),D2=k({type:ce(["and","or"]),filters:q(ae([j2,Ks(()=>D2)]))}),zI=ve(()=>ye(k({vectorStoreIds:q(d()),maxNumResults:O().optional(),ranking:k({ranker:d().optional(),scoreThreshold:O().optional()}).optional(),filters:ae([j2,D2]).optional()}))),FI=ve(()=>ye(k({queries:q(d()),results:q(k({attributes:ge(d(),Ce()),fileId:d(),filename:d(),score:O(),text:d()})).nullable()}))),VI=pr({id:"openai.file_search",inputSchema:k({}),outputSchema:FI}),ZI=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())),BI=ve(()=>ye(k({}))),HI=ve(()=>ye(k({result:d()}))),JI=pr({id:"openai.image_generation",inputSchema:BI,outputSchema:HI}),GI=(e={})=>JI(e),U2=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()})}))),z2=ve(()=>ye(k({output:d()}))),WI=pr({id:"openai.local_shell",inputSchema:U2,outputSchema:z2}),F2=ve(()=>ye(k({action:k({commands:q(d()),timeoutMs:O().optional(),maxOutputLength:O().optional()})}))),cu=ve(()=>ye(k({output:q(k({stdout:d(),stderr:d(),outcome:ze("type",[k({type:P("timeout")}),k({type:P("exit"),exitCode:O()})])}))}))),KI=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(),YI=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:KI}),k({type:P("containerReference"),containerId:d()}),k({type:P("local").optional(),skills:q(k({name:d(),description:d(),path:d()})).optional()})]).optional()}))),QI=pr({id:"openai.shell",inputSchema:F2,outputSchema:cu}),XI=ve(()=>ye(k({execution:ce(["server","client"]).optional(),description:d().optional(),parameters:ge(d(),Ce()).optional()}))),uu=ve(()=>ye(k({arguments:Ce().optional(),call_id:d().nullish()}))),du=ve(()=>ye(k({tools:q(ge(d(),Ce()))}))),e8=pr({id:"openai.tool_search",inputSchema:uu,outputSchema:du}),t8=(e={})=>e8(e),r8=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()}))),n8=ve(()=>ye(k({}))),o8=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()}))),s8=pr({id:"openai.web_search",inputSchema:n8,outputSchema:o8}),a8=(e={})=>s8(e),i8=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()}))),l8=ve(()=>ye(k({}))),c8=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()}))),u8=pr({id:"openai.web_search_preview",inputSchema:l8,outputSchema:c8}),pu=Ks(()=>ae([d(),O(),me(),Do(),q(pu),ge(d(),pu)])),d8=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."))),p8=ve(()=>ye(k({}))),f8=ve(()=>ye(k({type:P("call"),serverLabel:d(),name:d(),arguments:d(),output:d().nullish(),error:ae([d(),pu]).optional()}))),h8=pr({id:"openai.mcp",inputSchema:p8,outputSchema:f8}),m8=e=>h8(e),g8={applyPatch:PI,customTool:UI,codeInterpreter:qI,fileSearch:VI,imageGeneration:GI,localShell:WI,shell:QI,webSearchPreview:u8,webSearch:a8,mcp:m8,toolSearch:t8};function V2(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 Z2(e,t){return t?t.some(r=>e.startsWith(r)):!1}async function _8({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"&&Z2(Q.data,o)?{file_id:Q.data}:{image_url:`data:${U};base64,${lo(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"&&Z2(Q.data,o)?{file_id:Q.data}:{filename:(E=Q.filename)!=null?E:`part-${Z}.pdf`,file_data:`data:application/pdf;base64,${lo(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 Bf({text:Z.input,schema:uu}):await mt({value:Z.input,schema:uu}),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:U2});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:F2});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:q2});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:du});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:cu});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:y8}),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:du});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:z2});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:cu});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:L2});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}`};default:z.push({type:"other",message:`unsupported custom tool content part type: ${U.type}`});return}}).filter(Lf);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}`};default:{z.push({type:"other",message:`unsupported tool content part type: ${E.type}`});return}}}).filter(Lf);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 y8=k({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 vs=Ks(()=>ae([d(),O(),me(),Do(),q(vs),ge(d(),vs.optional())])),v8=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}))]))),w8=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()}))),B2=20,H2=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(B2)]).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 b8({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:zI});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:YI});a.push({type:"shell",...f.environment&&{environment:k8(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:i8});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:r8});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:OI});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:ZI});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:d8}),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:LI});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:XI});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 k8(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:T8(r.skills)}}return{type:"local",skills:e.skills}}function T8(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 J2(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 C8=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=x2(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:H2});S==null&&R!=="openai"&&(S=await Fr({provider:"openai",providerOptions:c,schema:H2}));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=X3({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 b8({tools:u,toolChoice:f,toolNameMapping:N,customProviderToolNames:L}),{input:ee,warnings:Q}=await _8({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?B2: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=J2(e.prompt),{responseHeaders:E,value:U,rawValue:F}=await Jt({url:ne,headers:At(this.config.headers(),e.headers),body:z,failedResponseHandler:Cr,successfulResponseHandler:Gt(w8),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 G of U.output)switch(G.type){case"reasoning":{G.summary.length===0&&G.summary.push({type:"summary_text",text:""});for(const A of G.summary)x.push({type:"reasoning",text:A.text,providerMetadata:{[Q]:{itemId:G.id,reasoningEncryptedContent:(t=G.encrypted_content)!=null?t:null}}});break}case"image_generation_call":{x.push({type:"tool-call",toolCallId:G.id,toolName:ee.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),x.push({type:"tool-result",toolCallId:G.id,toolName:ee.toCustomToolName("image_generation"),result:{result:G.result}});break}case"tool_search_call":{const A=(r=G.call_id)!=null?r:G.id,V=G.execution==="server";V&&re.push(A),x.push({type:"tool-call",toolCallId:A,toolName:ee.toCustomToolName("tool_search"),input:JSON.stringify({arguments:G.arguments,call_id:G.call_id}),...V?{providerExecuted:!0}:{},providerMetadata:{[Q]:{itemId:G.id}}});break}case"tool_search_output":{const A=(o=(n=G.call_id)!=null?n:re.shift())!=null?o:G.id;x.push({type:"tool-result",toolCallId:A,toolName:ee.toCustomToolName("tool_search"),result:{tools:G.tools},providerMetadata:{[Q]:{itemId:G.id}}});break}case"local_shell_call":{x.push({type:"tool-call",toolCallId:G.call_id,toolName:ee.toCustomToolName("local_shell"),input:JSON.stringify({action:G.action}),providerMetadata:{[Q]:{itemId:G.id}}});break}case"shell_call":{x.push({type:"tool-call",toolCallId:G.call_id,toolName:ee.toCustomToolName("shell"),input:JSON.stringify({action:{commands:G.action.commands}}),...Z&&{providerExecuted:!0},providerMetadata:{[Q]:{itemId:G.id}}});break}case"shell_call_output":{x.push({type:"tool-result",toolCallId:G.call_id,toolName:ee.toCustomToolName("shell"),result:{output:G.output.map(A=>({stdout:A.stdout,stderr:A.stderr,outcome:A.outcome.type==="exit"?{type:"exit",exitCode:A.outcome.exit_code}:{type:"timeout"}}))}});break}case"message":{for(const A of G.content){(i=(s=e.providerOptions)==null?void 0:s[Q])!=null&&i.logprobs&&A.logprobs&&M.push(A.logprobs);const V={itemId:G.id,...G.phase!=null&&{phase:G.phase},...A.annotations.length>0&&{annotations:A.annotations}};x.push({type:"text",text:A.text,providerMetadata:{[Q]:V}});for(const J of A.annotations)J.type==="url_citation"?x.push({type:"source",sourceType:"url",id:(c=(l=(a=this.config).generateId)==null?void 0:l.call(a))!=null?c: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:G.call_id,toolName:G.name,input:G.arguments,providerMetadata:{[Q]:{itemId:G.id}}});break}case"custom_tool_call":{H=!0;const A=ee.toCustomToolName(G.name);x.push({type:"tool-call",toolCallId:G.call_id,toolName:A,input:JSON.stringify(G.input),providerMetadata:{[Q]:{itemId:G.id}}});break}case"web_search_call":{x.push({type:"tool-call",toolCallId:G.id,toolName:ee.toCustomToolName(X??"web_search"),input:JSON.stringify({}),providerExecuted:!0}),x.push({type:"tool-result",toolCallId:G.id,toolName:ee.toCustomToolName(X??"web_search"),result:W2(G.action)});break}case"mcp_call":{const A=G.approval_request_id!=null&&(m=D[G.approval_request_id])!=null?m:G.id,V=`mcp.${G.name}`;x.push({type:"tool-call",toolCallId:A,toolName:V,input:G.arguments,providerExecuted:!0,dynamic:!0}),x.push({type:"tool-result",toolCallId:A,toolName:V,result:{type:"call",serverLabel:G.server_label,name:G.name,arguments:G.arguments,...G.output!=null?{output:G.output}:{},...G.error!=null?{error:G.error}:{}},providerMetadata:{[Q]:{itemId:G.id}}});break}case"mcp_list_tools":break;case"mcp_approval_request":{const A=(C=G.approval_request_id)!=null?C:G.id,V=(I=(T=(b=this.config).generateId)==null?void 0:T.call(b))!=null?I:Ut(),J=`mcp.${G.name}`;x.push({type:"tool-call",toolCallId:V,toolName:J,input:G.arguments,providerExecuted:!0,dynamic:!0}),x.push({type:"tool-approval-request",approvalId:A,toolCallId:V});break}case"computer_call":{x.push({type:"tool-call",toolCallId:G.id,toolName:ee.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),x.push({type:"tool-result",toolCallId:G.id,toolName:ee.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:G.status||"completed"}});break}case"file_search_call":{x.push({type:"tool-call",toolCallId:G.id,toolName:ee.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),x.push({type:"tool-result",toolCallId:G.id,toolName:ee.toCustomToolName("file_search"),result:{queries:G.queries,results:(S=(R=G.results)==null?void 0:R.map(A=>({attributes:A.attributes,fileId:A.file_id,filename:A.filename,score:A.score,text:A.text})))!=null?S:null}});break}case"code_interpreter_call":{x.push({type:"tool-call",toolCallId:G.id,toolName:ee.toCustomToolName("code_interpreter"),input:JSON.stringify({code:G.code,containerId:G.container_id}),providerExecuted:!0}),x.push({type:"tool-result",toolCallId:G.id,toolName:ee.toCustomToolName("code_interpreter"),result:{outputs:G.outputs}});break}case"apply_patch_call":{x.push({type:"tool-call",toolCallId:G.call_id,toolName:ee.toCustomToolName("apply_patch"),input:JSON.stringify({callId:G.call_id,operation:G.operation}),providerMetadata:{[Q]:{itemId:G.id}}});break}}const te={[Q]:{responseId:U.id,...M.length>0?{logprobs:M}:{},...typeof U.service_tier=="string"?{serviceTier:U.service_tier}:{}}},_e=U.usage;return{content:x,finishReason:{unified:fu({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:V2(_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(v8),abortSignal:e.abortSignal,fetch:this.config.fetch}),u=this,f=J2(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,G,A,V,J,Y,ue,Te,Be,it,gt,tt,nt,Lt,_t,Rr,Yt,We,_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":"${zn(K)}","operation":{"type":"${zn(qe.type)}","path":"${zn(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(I8($)){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:W2($.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:zn($.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(R8($)){const K=w[$.output_index];K!=null&&S.enqueue({type:"tool-input-delta",id:K.toolCallId,delta:$.delta})}else if(P8($)){const K=w[$.output_index];K!=null&&S.enqueue({type:"tool-input-delta",id:K.toolCallId,delta:$.delta})}else if(A8($)){const K=w[$.output_index];K?.applyPatch&&(S.enqueue({type:"tool-input-delta",id:K.toolCallId,delta:zn($.delta)}),K.applyPatch.hasDiff=!0)}else if(q8($)){const K=w[$.output_index];K?.applyPatch&&!K.applyPatch.endEmitted&&(K.applyPatch.hasDiff||(S.enqueue({type:"tool-input-delta",id:K.toolCallId,delta:zn($.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(M8($))S.enqueue({type:"tool-result",toolCallId:$.item_id,toolName:o.toCustomToolName("image_generation"),result:{result:$.partial_image_b64},preliminary:!0});else if(N8($)){const K=w[$.output_index];K!=null&&S.enqueue({type:"tool-input-delta",id:K.toolCallId,delta:zn($.delta)})}else if(O8($)){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($8($))_=$.response.id,S.enqueue({type:"response-metadata",id:$.response.id,timestamp:new Date($.response.created_at*1e3),modelId:$.response.model});else if(S8($))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:(G=(_e=b[$.item_id])==null?void 0:_e.encryptedContent)!=null?G:null}}})}}else if($.type==="response.reasoning_summary_text.delta")S.enqueue({type:"reasoning-delta",id:`${$.item_id}:${$.summary_index}`,delta:$.delta,providerMetadata:{[i]:{itemId:$.item_id}}});else if($.type==="response.reasoning_summary_part.done")s?(S.enqueue({type:"reasoning-end",id:`${$.item_id}:${$.summary_index}`,providerMetadata:{[i]:{itemId:$.item_id}}}),b[$.item_id].summaryParts[$.summary_index]="concluded"):b[$.item_id].summaryParts[$.summary_index]="can-conclude";else if(x8($))h={unified:fu({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(E8($)){const K=(Y=$.response.incomplete_details)==null?void 0:Y.reason;h={unified:K?fu({finishReason:K,hasFunctionCall:C}):"error",raw:K??"error"},g=(ue=$.response.usage)!=null?ue:void 0}else L8($)?(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=(We=(Yt=u.config).generateId)==null?void 0:We.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}}})):j8($)&&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:V2(g),providerMetadata:S})}})),request:{body:t},response:{headers:l}}}};function S8(e){return e.type==="response.output_text.delta"}function I8(e){return e.type==="response.output_item.done"}function x8(e){return e.type==="response.completed"||e.type==="response.incomplete"}function E8(e){return e.type==="response.failed"}function $8(e){return e.type==="response.created"}function R8(e){return e.type==="response.function_call_arguments.delta"}function P8(e){return e.type==="response.custom_tool_call_input.delta"}function M8(e){return e.type==="response.image_generation_call.partial_image"}function N8(e){return e.type==="response.code_interpreter_call_code.delta"}function O8(e){return e.type==="response.code_interpreter_call_code.done"}function A8(e){return e.type==="response.apply_patch_call_operation_diff.delta"}function q8(e){return e.type==="response.apply_patch_call_operation_diff.done"}function G2(e){return e.type==="response.output_item.added"}function L8(e){return e.type==="response.output_text.annotation.added"}function j8(e){return e.type==="error"}function W2(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 zn(e){return JSON.stringify(e).slice(1,-1)}var D8=ve(()=>ye(k({instructions:d().nullish(),speed:O().min(.25).max(4).default(1).nullish()}))),U8=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:D8}),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:u4(),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}}}},z8=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()}))),F8=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()}))),K2={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"},V8=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:F8}),s=new FormData,i=e instanceof Uint8Array?new Blob([e]):new Blob([ao(e)]);s.append("model",this.modelId);const a=f9(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 Gf({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:At(this.config.headers(),e.headers),formData:u,failedResponseHandler:Cr,successfulResponseHandler:Gt(z8),abortSignal:e.abortSignal,fetch:this.config.fetch}),v=p.language!=null&&p.language in K2?K2[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}}}},Z8="3.0.48";function Y2(e={}){var t,r;const n=(t=Yf(co({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 ${p9({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${Z8}`),i=v=>new _I(v,{provider:`${o}.chat`,url:({path:_})=>`${n}${_}`,headers:s,fetch:e.fetch}),a=v=>new bI(v,{provider:`${o}.completion`,url:({path:_})=>`${n}${_}`,headers:s,fetch:e.fetch}),l=v=>new CI(v,{provider:`${o}.embedding`,url:({path:_})=>`${n}${_}`,headers:s,fetch:e.fetch}),c=v=>new EI(v,{provider:`${o}.image`,url:({path:_})=>`${n}${_}`,headers:s,fetch:e.fetch}),u=v=>new V8(v,{provider:`${o}.transcription`,url:({path:_})=>`${n}${_}`,headers:s,fetch:e.fetch}),f=v=>new U8(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 C8(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=g8,g}Y2();var Q2="vercel.ai.error",B8=Symbol.for(Q2),X2,H8=class yv extends Error{constructor({name:t,message:r,cause:n}){super(r),this[X2]=!0,this.name=t,this.cause=n}static isInstance(t){return yv.hasMarker(t,Q2)}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}};X2=B8;var xt=H8,eg="AI_APICallError",tg=`vercel.ai.error.${eg}`,J8=Symbol.for(tg),rg,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:eg,message:e,cause:i}),this[rg]=!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,tg)}};rg=J8;var ng="AI_EmptyResponseBodyError",og=`vercel.ai.error.${ng}`,G8=Symbol.for(og),sg,W8=class extends xt{constructor({message:e="Empty response body"}={}){super({name:ng,message:e}),this[sg]=!0}static isInstance(e){return xt.hasMarker(e,og)}};sg=G8;function ag(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var ig="AI_InvalidArgumentError",lg=`vercel.ai.error.${ig}`,K8=Symbol.for(lg),cg,ug=class extends xt{constructor({message:e,cause:t,argument:r}){super({name:ig,message:e,cause:t}),this[cg]=!0,this.argument=r}static isInstance(e){return xt.hasMarker(e,lg)}};cg=K8;var dg="AI_InvalidResponseDataError",pg=`vercel.ai.error.${dg}`,Y8=Symbol.for(pg),fg,hg=class extends xt{constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:dg,message:t}),this[fg]=!0,this.data=e}static isInstance(e){return xt.hasMarker(e,pg)}};fg=Y8;var mg="AI_JSONParseError",gg=`vercel.ai.error.${mg}`,Q8=Symbol.for(gg),_g,za=class extends xt{constructor({text:e,cause:t}){super({name:mg,message:`JSON parsing failed: Text: ${e}.
79
- Error message: ${ag(t)}`,cause:t}),this[_g]=!0,this.text=e}static isInstance(e){return xt.hasMarker(e,gg)}};_g=Q8;var yg="AI_LoadAPIKeyError",vg=`vercel.ai.error.${yg}`,X8=Symbol.for(vg),wg,Fa=class extends xt{constructor({message:e}){super({name:yg,message:e}),this[wg]=!0}static isInstance(e){return xt.hasMarker(e,vg)}};wg=X8;var bg="AI_NoSuchModelError",kg=`vercel.ai.error.${bg}`,ex=Symbol.for(kg),Tg,Cg=class extends xt{constructor({errorName:e=bg,modelId:t,modelType:r,message:n=`No such ${r}: ${t}`}){super({name:e,message:n}),this[Tg]=!0,this.modelId=t,this.modelType=r}static isInstance(e){return xt.hasMarker(e,kg)}};Tg=ex;var Sg="AI_TypeValidationError",Ig=`vercel.ai.error.${Sg}`,tx=Symbol.for(Ig),xg,rx=class pd extends xt{constructor({value:t,cause:r}){super({name:Sg,message:`Type validation failed: Value: ${JSON.stringify(t)}.
80
- Error message: ${ag(r)}`,cause:r}),this[xg]=!0,this.value=t}static isInstance(t){return xt.hasMarker(t,Ig)}static wrap({value:t,cause:r}){return pd.isInstance(r)&&r.value===t?r:new pd({value:t,cause:r})}};xg=tx;var ws=rx,Eg="AI_UnsupportedFunctionalityError",$g=`vercel.ai.error.${Eg}`,nx=Symbol.for($g),Rg,Pg=class extends xt{constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:Eg,message:t}),this[Rg]=!0,this.functionality=e}static isInstance(e){return xt.hasMarker(e,$g)}};Rg=nx;function Mg(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}function Va(e){return Object.fromEntries([...e.headers])}var ox=({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 ug({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${e}${n}${o()}`},Za=ox();function hu(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var sx=["fetch failed","failed to fetch"];function ax({error:e,url:t,requestBodyValues:r}){if(hu(e))return e;if(e instanceof TypeError&&sx.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 ix(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 lx(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 Ng(e,...t){const r=new Headers(lx(e)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var cx="3.0.18";function ux({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 dx=/"__proto__"\s*:/,px=/"constructor"\s*:/;function Og(e){const t=JSON.parse(e);return t===null||typeof t!="object"||dx.test(e)===!1&&px.test(e)===!1?t:fx(t)}function fx(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 mu(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return Og(e)}try{return Og(e)}finally{Error.stackTraceLimit=t}}var gu=Symbol.for("vercel.ai.validator");function hx(e){return{[gu]:!0,validate:e}}function mx(e){return typeof e=="object"&&e!==null&&gu in e&&e[gu]===!0&&"validate"in e}function gx(e){return mx(e)?e:typeof e=="function"?e():_x(e)}function _x(e){return hx(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 yx({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=gx(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 vx({text:e,schema:t}){try{const r=mu(e);return t==null?r:yx({value:r,schema:t})}catch(r){throw za.isInstance(r)||ws.isInstance(r)?r:new za({text:e,cause:r})}}async function Ag({text:e,schema:t}){try{const r=mu(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 qg(e){try{return mu(e),!0}catch{return!1}}function wx({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new oo).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await Ag({text:r,schema:t}))}}))}async function Lg({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 ug({argument:"providerOptions",message:`invalid ${e} provider options`,cause:n.error});return n.value}var bx=()=>globalThis.fetch,jg=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i})=>kx({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i}),kx=async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:s,fetch:i=bx()})=>{try{const a=await i(e,{method:"POST",headers:Ng(t,`ai-sdk/provider-utils/${cx}`,ix()),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 hu(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&&(hu(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 ax({error:a,url:e,requestBodyValues:r.values})}},Tx=({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 vx({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)})}}},Cx=e=>async({response:t})=>{const r=Va(t);if(t.body==null)throw new W8({});return{responseHeaders:r,value:wx({stream:t.body,schema:e})}},Sx=e=>async({response:t,url:r,requestBodyValues:n})=>{const o=await t.text(),s=await Ag({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:Ix}=globalThis;function xx(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return Ix(t)}function Ex(e){return e instanceof Uint8Array?xx(e):e}function $x(e){return e?.replace(/\/$/,"")}function ks(e){var t,r;return(r=(t=e?.providerOptions)==null?void 0:t.openaiCompatible)!=null?r:{}}function Rx(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,${Ex(i.data)}`},...a}}else throw new Pg({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 Dg({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 Ug(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 _u=k({user:d().optional(),reasoningEffort:d().optional(),textVerbosity:d().optional()}),Px=k({error:k({message:d(),type:d().nullish(),param:yt().nullish(),code:ae([d(),O()]).nullish()})}),Mx={errorSchema:Px,errorToMessage:e=>e.error.message};function Nx({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 Pg({functionality:`tool choice type: ${s}`})}}}var Ox=class{constructor(e,t){this.specificationVersion="v2";var r,n;this.modelId=e,this.config=t;const o=(r=t.errorStructure)!=null?r:Mx;this.chunkSchema=qx(o.errorSchema),this.failedResponseHandler=Tx(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 Lg({provider:"openai-compatible",providerOptions:a,schema:_u}))!=null?h:{},(g=await Lg({provider:this.providerOptionsName,providerOptions:a,schema:_u}))!=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}=Nx({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(_u.shape).includes(T))),reasoning_effort:y.reasoningEffort,verbosity:y.textVerbosity,messages:Rx(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 jg({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Mg(this.config.headers(),e.headers),body:y,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:Sx(Ax),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:Ug(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:{...Dg(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 jg({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Mg(this.config.headers(),e.headers),body:o,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:Cx(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",...Dg(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=Ug(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 hg({data:Z,message:"Expected 'id' to be a string."});if(((y=Z.function)==null?void 0:y.name)==null)throw new hg({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}),qg(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&&qg(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}}}},zg=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(),Ax=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:zg}),qx=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:zg}),e]);k({echo:me().optional(),logitBias:ge(d(),O()).optional(),suffix:d().optional(),user:d().optional()});var Lx=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:Lx.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 Fg=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}}},jx={extractMetadata:async({parsedBody:e})=>{const t=await bs({value:e,schema:Dx});return!t.success||t.value.usage==null?void 0:Fg(t.value.usage)},createStreamExtractor:()=>{let e;return{processChunk:async t=>{var r,n;const o=await bs({value:t,schema:Ux});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:()=>Fg(e)}}},Vg=k({prompt_cache_hit_tokens:O().nullish(),prompt_cache_miss_tokens:O().nullish()}),Dx=k({usage:Vg.nullish()}),Ux=k({choices:q(k({finish_reason:d().nullish()})).nullish(),usage:Vg.nullish()}),zx="1.0.30";function Zg(e={}){var t;const r=$x((t=e.baseURL)!=null?t:"https://api.deepseek.com/v1"),n=()=>Ng({Authorization:`Bearer ${ux({apiKey:e.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...e.headers},`ai-sdk/deepseek/${zx}`);class o extends Ox{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:jx}),i=a=>s(a);return i.languageModel=s,i.chat=s,i.textEmbeddingModel=a=>{throw new Cg({modelId:a,modelType:"textEmbeddingModel"})},i.imageModel=a=>{throw new Cg({modelId:a,modelType:"imageModel"})},i}Zg();const Fx=(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})},Vx=(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 Zx{constructor(t){this._isStarted=!1,this._isClosed=!1,this.targetSessionId=t,this._messageListener=Vx("mcp-server-to-client",r=>{try{if(r.sessionId!==this.targetSessionId)return;const n=Ln.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}`),Fx("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)?up(e,t):e.safeParse(t)}function Bg(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 Bx(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 Fn(e){return e==="completed"||e==="failed"||e==="cancelled"}new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Hg(e){const r=Bg(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const n=Bx(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Jg(e,t){const r=dn(e,t);if(!r.success)throw r.error;return r.data}const Hx=6e4;class Jx{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(mc,r=>{this._onprogress(r)}),this.setRequestHandler(hc,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(gc,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(yc,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(!Fn(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Fn(i.status)){const a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[qn]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(vc,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(bc,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(Fn(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)||c5(s)?this._onresponse(s):uc(s)?this._onrequest(s,i):l5(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?.[qn]?.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=i5(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},Fn(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||{},[qn]: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??Hx,_=()=>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},_c,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},I5,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||{},[qn]: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||{},[qn]: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||{},[qn]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(t,r){const n=Hg(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{const i=Jg(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=Hg(t);this._notificationHandlers.set(n,o=>{const s=Jg(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"&&uc(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),Fn(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(Fn(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),Fn(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:{}},yu={},Jr={},Vn={},vu={},wu={},bu={},Wg;function Ja(){return Wg||(Wg=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=_})(bu)),bu}var ku={},Kg;function Yg(){return Kg||(Kg=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})(ku)),ku}var Qg;function Re(){return Qg||(Qg=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=Yg();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=Yg();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`,G=>{this.var(te,(0,t._)`${_e}[${G}]`),H(te)})}return this._for(new b("of",re,te,M),()=>H(te))}forIn(x,M,H,re=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(x,(0,t._)`Object.keys(${M})`,H);const te=this._scope.toName(x);return this._for(new b("in",re,te,M),()=>H(te))}endFor(){return this._endBlockNode(y)}label(x){return this._leafNode(new c(x))}break(x){return this._leafNode(new u(x))}return(x){const M=new I;if(this._blockNode(M),this.code(x),M.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(I)}try(x,M,H){if(!M&&!H)throw new Error('CodeGen: "try" without "catch" and "finally"');const re=new R;if(this._blockNode(re),this.code(x),M){const te=this.name("e");this._currNode=re.catch=new S(te),M(te)}return H&&(this._currNode=re.finally=new j,this.code(H)),this._endBlockNode(S,j)}throw(x){return this._leafNode(new f(x))}block(x,M){return this._blockStarts.push(this._nodes.length),x&&this.code(x).endBlock(M),this}endBlock(x){const M=this._blockStarts.pop();if(M===void 0)throw new Error("CodeGen: not in self-balancing block");const H=this._nodes.length-M;if(H<0||x!==void 0&&H!==x)throw new Error(`CodeGen: wrong number of nodes: ${H} vs ${x} expected`);return this._nodes.length=M,this}func(x,M=t.nil,H,re){return this._blockNode(new T(x,M,H)),re&&this.code(re).endFunc(),this}endFunc(){return this._endBlockNode(T)}optimize(x=1){for(;x-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(x){return this._currNode.nodes.push(x),this}_blockNode(x){this._currNode.nodes.push(x),this._nodes.push(x)}_endBlockNode(x,M){const H=this._currNode;if(H instanceof x||M&&H instanceof M)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${M?`${x.kind}/${M.kind}`:x.kind}"`)}_elseNode(x){const M=this._currNode;if(!(M instanceof w))throw new Error('CodeGen: "else" without "if"');return this._currNode=M.else=x,this}get _root(){return this._nodes[0]}get _currNode(){const x=this._nodes;return x[x.length-1]}set _currNode(x){const M=this._nodes;M[M.length-1]=x}}e.CodeGen=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})`}})(wu)),wu}var Pe={},Xg;function Ue(){if(Xg)return Pe;Xg=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 Ga={},e_;function pn(){if(e_)return Ga;e_=1,Object.defineProperty(Ga,"__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 Ga.default=t,Ga}var t_;function Wa(){return t_||(t_=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])}})(vu)),vu}var r_;function Wx(){if(r_)return Vn;r_=1,Object.defineProperty(Vn,"__esModule",{value:!0}),Vn.boolOrEmptySchema=Vn.topBoolOrEmptySchema=void 0;const e=Wa(),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))}Vn.topBoolOrEmptySchema=o;function s(a,l){const{gen:c,schema:u}=a;u===!1?(c.var(l,!1),i(a)):c.var(l,!0)}Vn.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 Vn}var Nt={},Zn={},n_;function o_(){if(n_)return Zn;n_=1,Object.defineProperty(Zn,"__esModule",{value:!0}),Zn.getRules=Zn.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)}Zn.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 Zn.getRules=n,Zn}var Gr={},s_;function a_(){if(s_)return Gr;s_=1,Object.defineProperty(Gr,"__esModule",{value:!0}),Gr.shouldUseRule=Gr.shouldUseGroup=Gr.schemaHasRulesForType=void 0;function e({schema:n,self:o},s){const i=o.RULES.types[s];return i&&i!==!0&&t(n,i)}Gr.schemaHasRulesForType=e;function t(n,o){return o.rules.some(s=>r(n,s))}Gr.shouldUseGroup=t;function r(n,o){var s;return n[o.keyword]!==void 0||((s=o.definition.implements)===null||s===void 0?void 0:s.some(i=>n[i]!==void 0))}return Gr.shouldUseRule=r,Gr}var i_;function Ka(){if(i_)return Nt;i_=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=o_(),t=a_(),r=Wa(),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
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: ${ig(t)}`,cause:t}),this[yg]=!0,this.text=e}static isInstance(e){return xt.hasMarker(e,_g)}};yg=X8;var vg="AI_LoadAPIKeyError",wg=`vercel.ai.error.${vg}`,ex=Symbol.for(wg),bg,Fa=class extends xt{constructor({message:e}){super({name:vg,message:e}),this[bg]=!0}static isInstance(e){return xt.hasMarker(e,wg)}};bg=ex;var kg="AI_NoSuchModelError",Tg=`vercel.ai.error.${kg}`,tx=Symbol.for(Tg),Cg,Sg=class extends xt{constructor({errorName:e=kg,modelId:t,modelType:r,message:n=`No such ${r}: ${t}`}){super({name:e,message:n}),this[Cg]=!0,this.modelId=t,this.modelType=r}static isInstance(e){return xt.hasMarker(e,Tg)}};Cg=tx;var Ig="AI_TypeValidationError",xg=`vercel.ai.error.${Ig}`,rx=Symbol.for(xg),Eg,nx=class hd extends xt{constructor({value:t,cause:r}){super({name:Ig,message:`Type validation failed: Value: ${JSON.stringify(t)}.
80
+ Error message: ${ig(r)}`,cause:r}),this[Eg]=!0,this.value=t}static isInstance(t){return 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
82
  || (${R} == "string" && ${T} && ${T} == +${T})`).assign(S,(0,n._)`+${T}`);return;case"integer":b.elseIf((0,n._)`${R} === "boolean" || ${T} === null
83
83
  || (${R} === "string" && ${T} && ${T} == +${T} && !(${T} % 1))`).assign(S,(0,n._)`+${T}`);return;case"boolean":b.elseIf((0,n._)`${T} === "false" || ${T} === 0 || ${T} === null`).assign(S,!1).elseIf((0,n._)`${T} === "true" || ${T} === 1`).assign(S,!0);return;case"null":b.elseIf((0,n._)`${T} === "" || ${T} === 0 || ${T} === false`),b.assign(S,null);return;case"array":b.elseIf((0,n._)`${R} === "string" || ${R} === "number"
84
- || ${R} === "boolean" || ${T} === null`).assign(S,(0,n._)`[${T}]`)}}}function p({gen:y,parentData:m,parentDataProperty:C},b){y.if((0,n._)`${m} !== undefined`,()=>y.assign((0,n._)`${m}[${C}]`,b))}function h(y,m,C,b=s.Correct){const T=b===s.Correct?n.operators.EQ:n.operators.NEQ;let I;switch(y){case"null":return(0,n._)`${m} ${T} null`;case"array":I=(0,n._)`Array.isArray(${m})`;break;case"object":I=(0,n._)`${m} && typeof ${m} == "object" && !Array.isArray(${m})`;break;case"integer":I=R((0,n._)`!(${m} % 1) && !isNaN(${m})`);break;case"number":I=R();break;default:return(0,n._)`typeof ${m} ${T} ${y}`}return b===s.Correct?I:(0,n.not)(I);function R(S=n.nil){return(0,n.and)((0,n._)`typeof ${m} == "number"`,S,C?(0,n._)`isFinite(${m})`:n.nil)}}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={},l_;function Kx(){if(l_)return Ts;l_=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={},Ge={},c_;function Ir(){if(c_)return Ge;c_=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=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()})}Ge.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}`)))}Ge.checkMissingProp=s;function i(y,m){y.setParams({missingProperty:m},!0),y.error()}Ge.reportMissingProp=i;function a(y){return y.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,e._)`Object.prototype.hasOwnProperty`})}Ge.hasPropFunc=a;function l(y,m,C){return(0,e._)`${a(y)}.call(${m}, ${C})`}Ge.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}Ge.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}Ge.noPropertyInData=u;function f(y){return y?Object.keys(y).filter(m=>m!=="__proto__"):[]}Ge.allSchemaProperties=f;function p(y,m){return f(m).filter(C=>!(0,t.alwaysValidSchema)(y,m[C]))}Ge.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})`}Ge.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})`})}Ge.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)})}}Ge.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 Ge.validateUnion=w,Ge}var u_;function Yx(){if(u_)return Sr;u_=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=Wa();function o(p,h){const{gen:g,keyword:v,schema:_,parentSchema:w,it:y}=p,m=h.macro.call(y.self,_,w,y),C=c(g,v,m);y.opts.validateSchema!==!1&&y.self.validateSchema(m,!0);const b=g.name("valid");p.subschema({schema:m,schemaPath:e.nil,errSchemaPath:`${y.errSchemaPath}/${v}`,topSchemaRef:C,compositeRule:!0},b),p.pass(b,()=>p.error(!0))}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 Wr={},d_;function Qx(){if(d_)return Wr;d_=1,Object.defineProperty(Wr,"__esModule",{value:!0}),Wr.extendSubschemaMode=Wr.extendSubschemaData=Wr.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')}Wr.getSubschema=r;function n(s,i,{dataProp:a,dataPropType:l,data:c,dataTypes:u,propertyName:f}){if(c!==void 0&&a!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:p}=i;if(a!==void 0){const{errorPath:g,dataPathArr:v,opts:_}=i,w=p.let("data",(0,e._)`${i.data}${(0,e.getProperty)(a)}`,!0);h(w),s.errorPath=(0,e.str)`${g}${(0,t.getErrorPath)(a,l,_.jsPropertySyntax)}`,s.parentDataProperty=(0,e._)`${a}`,s.dataPathArr=[...v,s.parentDataProperty]}if(c!==void 0){const g=c instanceof e.Name?c:p.let("data",c,!0);h(g),f!==void 0&&(s.propertyName=f)}u&&(s.dataTypes=u);function h(g){s.data=g,s.dataLevel=i.dataLevel+1,s.dataTypes=[],i.definedProperties=new Set,s.parentData=i.data,s.dataNames=[...i.dataNames,g]}}Wr.extendSubschemaData=n;function o(s,{jtdDiscriminator:i,jtdMetadata:a,compositeRule:l,createErrors:c,allErrors:u}){l!==void 0&&(s.compositeRule=l),c!==void 0&&(s.createErrors=c),u!==void 0&&(s.allErrors=u),s.jtdDiscriminator=i,s.jtdMetadata=a}return Wr.extendSubschemaMode=o,Wr}var Vt={},Tu,p_;function f_(){return p_||(p_=1,Tu=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}),Tu}var Cu={exports:{}},h_;function Xx(){if(h_)return Cu.exports;h_=1;var e=Cu.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 Cu.exports}var m_;function Ya(){if(m_)return Vt;m_=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=f_(),r=Xx(),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 g_;function Qa(){if(g_)return Jr;g_=1,Object.defineProperty(Jr,"__esModule",{value:!0}),Jr.getData=Jr.KeywordCxt=Jr.validateFunctionCode=void 0;const e=Wx(),t=Ka(),r=a_(),n=Ka(),o=Kx(),s=Yx(),i=Qx(),a=Re(),l=pn(),c=Ya(),u=Ue(),f=Wa();function p(A){if(b(A)&&(I(A),C(A))){_(A);return}h(A,()=>(0,e.topBoolOrEmptySchema)(A))}Jr.validateFunctionCode=p;function h({gen:A,validateName:V,schema:J,schemaEnv:Y,opts:ue},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",G(this.$data,V));else if(this.schemaCode=this.schemaValue,!(0,s.validSchemaType)(this.schema,J.schemaType,J.allowUndefined))throw new Error(`${Y} value must be ${JSON.stringify(J.schemaType)}`);("code"in J?J.trackErrors:J.errors!==!1)&&(this.errsCount=V.gen.const("_errs",l.default.errors))}result(V,J,Y){this.failResult((0,a.not)(V),J,Y)}failResult(V,J,Y){this.gen.if(V),Y?Y():this.error(),J?(this.gen.else(),J(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(V,J){this.failResult((0,a.not)(V),void 0,J)}fail(V){if(V===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(V),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(V){if(!this.$data)return this.fail(V);const{schemaCode:J}=this;this.fail((0,a._)`${J} !== undefined && (${(0,a.or)(this.invalid$data(),V)})`)}error(V,J,Y){if(J){this.setParams(J),this._error(V,Y),this.setParams({});return}this._error(V,Y)}_error(V,J){(V?f.reportExtraError:f.reportError)(this,this.def.error,J)}$dataError(){(0,f.reportError)(this,this.def.$dataError||f.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,f.resetErrorsCount)(this.gen,this.errsCount)}ok(V){this.allErrors||this.gen.if(V)}setParams(V,J){J?Object.assign(this.params,V):this.params=V}block$data(V,J,Y=a.nil){this.gen.block(()=>{this.check$data(V,Y),J()})}check$data(V=a.nil,J=a.nil){if(!this.$data)return;const{gen:Y,schemaCode:ue,schemaType: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 G(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=G,Jr}var Xa={},__;function Su(){if(__)return Xa;__=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={},y_;function ti(){if(y_)return ei;y_=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={},v_;function Iu(){if(v_)return or;v_=1,Object.defineProperty(or,"__esModule",{value:!0}),or.resolveSchema=or.getCompilingSchema=or.resolveRef=or.compileSchema=or.SchemaEnv=void 0;const e=Re(),t=Su(),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 e7={$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:{}},xu,w_;function b_(){if(w_)return xu;w_=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 xu={nonSimpleDomain:n,recomposeAuthority:f,normalizeComponentEncoding:u,removeDotSegments:c,isIPv4:t,isUUID:e,normalizeIPv6:a,stringArrayToHexStripped:r},xu}var Eu,k_;function t7(){if(k_)return Eu;k_=1;const{isUUID:e}=b_(),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 Eu={wsIsSecure:o,SCHEMES:m,isValidSchemeName:n,getSchemeHandler:C},Eu}var T_;function r7(){if(T_)return Cs.exports;T_=1;const{normalizeIPv6:e,removeDotSegments:t,recomposeAuthority:r,normalizeComponentEncoding:n,isIPv4:o,nonSimpleDomain:s}=b_(),{SCHEMES:i,getSchemeHandler:a}=t7();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 C_;function n7(){if(C_)return ri;C_=1,Object.defineProperty(ri,"__esModule",{value:!0});const e=r7();return e.code='require("ajv/dist/runtime/uri").default',ri.default=e,ri}var S_;function o7(){return S_||(S_=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=Su(),o=ti(),s=o_(),i=Iu(),a=Re(),l=Ya(),c=Ka(),u=Ue(),f=e7,p=n7(),h=(D,E)=>new RegExp(D,E);h.code="new RegExp";const g=["removeAdditional","useDefaults","coerceTypes"],v=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),_={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},w={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},y=200;function m(D){var E,U,F,x,M,H,re,te,_e,G,A,V,J,Y,ue,Te,Be,it,gt,tt,nt,Lt,_t,Rr,Yt;const We=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:We)!==null&&H!==void 0?H:!0,strictNumbers:(te=(re=D.strictNumbers)!==null&&re!==void 0?re:We)!==null&&te!==void 0?te:!0,strictTypes:(G=(_e=D.strictTypes)!==null&&_e!==void 0?_e:We)!==null&&G!==void 0?G:"log",strictTuples:(V=(A=D.strictTuples)!==null&&A!==void 0?A:We)!==null&&V!==void 0?V:"log",strictRequired:(Y=(J=D.strictRequired)!==null&&J!==void 0?J:We)!==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&&gt!==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(G,A){await M.call(this,G.$schema);const V=this._addSchema(G,A);return V.validate||H.call(this,V)}async function M(G){G&&!this.getSchema(G)&&await x.call(this,{$ref:G},!0)}async function H(G){try{return this._compileSchemaEnv(G)}catch(A){if(!(A instanceof o.default))throw A;return re.call(this,A),await te.call(this,A.missingSchema),H.call(this,G)}}function re({missingSchema:G,missingRef:A}){if(this.refs[G])throw new Error(`AnySchema ${G} is loaded but ${A} cannot be resolved`)}async function te(G){const A=await _e.call(this,G);this.refs[G]||await M.call(this,A.$schema),this.refs[G]||this.addSchema(A,G,U)}async function _e(G){const A=this._loading[G];if(A)return A;try{return await(this._loading[G]=F(G))}finally{delete this._loading[G]}}}addSchema(E,U,F,x=this.opts.validateSchema){if(Array.isArray(E)){for(const H of E)this.addSchema(H,void 0,F,x);return this}let M;if(typeof E=="object"){const{schemaId:H}=this.opts;if(M=E[H],M!==void 0&&typeof M!="string")throw new Error(`schema ${H} must be string`)}return U=(0,l.normalizeId)(U||M),this._checkUnique(U),this.schemas[U]=this._addSchema(E,F,U,x,!0),this}addMetaSchema(E,U,F=this.opts.validateSchema){return this.addSchema(E,U,!0,F),this}validateSchema(E,U){if(typeof E=="boolean")return!0;let F;if(F=E.$schema,F!==void 0&&typeof F!="string")throw new Error("$schema must be a string");if(F=F||this.opts.defaultMeta||this.defaultMeta(),!F)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const x=this.validate(F,E);if(!x&&U){const M="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(M);else throw new Error(M)}return x}getSchema(E){let U;for(;typeof(U=T.call(this,E))=="string";)E=U;if(U===void 0){const{schemaId:F}=this.opts,x=new i.SchemaEnv({schema:{},schemaId:F});if(U=i.resolveSchema.call(this,x,E),!U)return;this.refs[E]=U}return U.validate||this._compileSchemaEnv(U)}removeSchema(E){if(E instanceof RegExp)return this._removeAllSchemas(this.schemas,E),this._removeAllSchemas(this.refs,E),this;switch(typeof E){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const U=T.call(this,E);return typeof U=="object"&&this._cache.delete(U.schema),delete this.schemas[E],delete this.refs[E],this}case"object":{const U=E;this._cache.delete(U);let F=E[this.opts.schemaId];return F&&(F=(0,l.normalizeId)(F),delete this.schemas[F],delete this.refs[F]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(E){for(const U of E)this.addKeyword(U);return this}addKeyword(E,U){let F;if(typeof E=="string")F=E,typeof U=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),U.keyword=F);else if(typeof E=="object"&&U===void 0){if(U=E,F=U.keyword,Array.isArray(F)&&!F.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(B.call(this,F,U),!U)return(0,u.eachItem)(F,M=>X.call(this,M)),this;Q.call(this,U);const x={...U,type:(0,c.getJSONTypes)(U.type),schemaType:(0,c.getJSONTypes)(U.schemaType)};return(0,u.eachItem)(F,x.type.length===0?M=>X.call(this,M,x):M=>x.type.forEach(H=>X.call(this,M,x,H))),this}getKeyword(E){const U=this.RULES.all[E];return typeof U=="object"?U.definition:!!U}removeKeyword(E){const{RULES:U}=this;delete U.keywords[E],delete U.all[E];for(const F of U.rules){const x=F.rules.findIndex(M=>M.keyword===E);x>=0&&F.rules.splice(x,1)}return this}addFormat(E,U){return typeof U=="string"&&(U=new RegExp(U)),this.formats[E]=U,this}errorsText(E=this.errors,{separator:U=", ",dataVar:F="data"}={}){return!E||E.length===0?"No errors":E.map(x=>`${F}${x.instancePath} ${x.message}`).reduce((x,M)=>x+U+M)}$dataMetaSchema(E,U){const F=this.RULES.all;E=JSON.parse(JSON.stringify(E));for(const x of U){const M=x.split("/").slice(1);let H=E;for(const re of M)H=H[re];for(const re in F){const te=F[re];if(typeof te!="object")continue;const{$data:_e}=te.definition,G=H[re];_e&&G&&(H[re]=ne(G))}}return E}_removeAllSchemas(E,U){for(const F in E){const x=E[F];(!U||U.test(F))&&(typeof x=="string"?delete E[F]:x&&!x.meta&&(this._cache.delete(x.schema),delete E[F]))}}_addSchema(E,U,F,x=this.opts.validateSchema,M=this.opts.addUsedSchema){let H;const{schemaId:re}=this.opts;if(typeof E=="object")H=E[re];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof E!="boolean")throw new Error("schema must be object or boolean")}let te=this._cache.get(E);if(te!==void 0)return te;F=(0,l.normalizeId)(H||F);const _e=l.getSchemaRefs.call(this,E,F);return te=new i.SchemaEnv({schema:E,schemaId:re,meta:U,baseId:F,localRefs:_e}),this._cache.set(te.schema,te),M&&!F.startsWith("#")&&(F&&this._checkUnique(F),this.refs[F]=te),x&&this.validateSchema(E,!0),te}_checkUnique(E){if(this.schemas[E]||this.refs[E])throw new Error(`schema with key or id "${E}" already exists`)}_compileSchemaEnv(E){if(E.meta?this._compileMetaSchema(E):i.compileSchema.call(this,E),!E.validate)throw new Error("ajv implementation error");return E.validate}_compileMetaSchema(E){const U=this.opts;this.opts=this._metaOpts;try{i.compileSchema.call(this,E)}finally{this.opts=U}}}C.ValidationError=n.default,C.MissingRefError=o.default,e.default=C;function b(D,E,U,F="error"){for(const x in D){const M=x;M in E&&this.logger[F](`${U}: option ${x}. ${D[M]}`)}}function T(D){return D=(0,l.normalizeId)(D),this.schemas[D]||this.refs[D]}function I(){const D=this.opts.schemas;if(D)if(Array.isArray(D))this.addSchema(D);else for(const E in D)this.addSchema(D[E],E)}function R(){for(const D in this.opts.formats){const E=this.opts.formats[D];E&&this.addFormat(D,E)}}function S(D){if(Array.isArray(D)){this.addVocabulary(D);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const E in D){const U=D[E];U.keyword||(U.keyword=E),this.addKeyword(U)}}function j(){const D={...this.opts};for(const E of g)delete D[E];return D}const 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]}}})(yu)),yu}var ni={},oi={},si={},I_;function s7(){if(I_)return si;I_=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={},x_;function a7(){if(x_)return fn;x_=1,Object.defineProperty(fn,"__esModule",{value:!0}),fn.callRef=fn.getValidate=void 0;const e=ti(),t=Ir(),r=Re(),n=pn(),o=Iu(),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 E_;function i7(){if(E_)return oi;E_=1,Object.defineProperty(oi,"__esModule",{value:!0});const e=s7(),t=a7(),r=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",e.default,t.default];return oi.default=r,oi}var ai={},ii={},$_;function l7(){if($_)return ii;$_=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={},R_;function c7(){if(R_)return li;R_=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={},P_;function u7(){if(P_)return ui;P_=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 M_;function d7(){if(M_)return ci;M_=1,Object.defineProperty(ci,"__esModule",{value:!0});const e=Re(),t=Ue(),r=u7(),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={},N_;function p7(){if(N_)return di;N_=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={},O_;function f7(){if(O_)return pi;O_=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={},A_;function h7(){if(A_)return fi;A_=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={},q_;function m7(){if(q_)return hi;q_=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={},L_;function $u(){if(L_)return gi;L_=1,Object.defineProperty(gi,"__esModule",{value:!0});const e=f_();return e.code='require("ajv/dist/runtime/equal").default',gi.default=e,gi}var j_;function g7(){if(j_)return mi;j_=1,Object.defineProperty(mi,"__esModule",{value:!0});const e=Ka(),t=Re(),r=Ue(),n=$u(),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={},D_;function _7(){if(D_)return _i;D_=1,Object.defineProperty(_i,"__esModule",{value:!0});const e=Re(),t=Ue(),r=$u(),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={},U_;function y7(){if(U_)return yi;U_=1,Object.defineProperty(yi,"__esModule",{value:!0});const e=Re(),t=Ue(),r=$u(),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 z_;function v7(){if(z_)return ai;z_=1,Object.defineProperty(ai,"__esModule",{value:!0});const e=l7(),t=c7(),r=d7(),n=p7(),o=f7(),s=h7(),i=m7(),a=g7(),l=_7(),c=y7(),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={},F_;function V_(){if(F_)return Co;F_=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={},Z_;function B_(){if(Z_)return So;Z_=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 H_;function w7(){if(H_)return wi;H_=1,Object.defineProperty(wi,"__esModule",{value:!0});const e=B_(),t={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,e.validateTuple)(r,"items")};return wi.default=t,wi}var bi={},J_;function b7(){if(J_)return bi;J_=1,Object.defineProperty(bi,"__esModule",{value:!0});const e=Re(),t=Ue(),r=Ir(),n=V_(),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 k7(){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 Ru={},W_;function T7(){return W_||(W_=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},
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&&gt!==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
85
  missingProperty: ${f},
86
86
  depsCount: ${c},
87
- deps: ${u}}`};const o={keyword:"dependencies",type:"object",schemaType:"object",error:e.error,code(l){const[c,u]=s(l);i(l,c),a(l,u)}};function s({schema:l}){const c={},u={};for(const f in l){if(f==="__proto__")continue;const p=Array.isArray(l[f])?c:u;p[f]=l[f]}return[c,u]}function i(l,c=l.schema){const{gen:u,data:f,it:p}=l;if(Object.keys(c).length===0)return;const h=u.let("missing");for(const g in c){const v=c[g];if(v.length===0)continue;const _=(0,n.propertyInData)(u,f,g,p.opts.ownProperties);l.setParams({property:g,depsCount:v.length,deps:v.join(", ")}),p.allErrors?u.if(_,()=>{for(const w of v)(0,n.checkReportMissingProp)(l,w)}):(u.if((0,t._)`${_} && (${(0,n.checkMissingProp)(l,v,h)})`),(0,n.reportMissingProp)(l,h),u.else())}}e.validatePropertyDeps=i;function a(l,c=l.schema){const{gen:u,data:f,keyword:p,it:h}=l,g=u.name("valid");for(const v in c)(0,r.alwaysValidSchema)(h,c[v])||(u.if((0,n.propertyInData)(u,f,v,h.opts.ownProperties),()=>{const _=l.subschema({keyword:p,schemaProp:v},g);l.mergeValidEvaluated(_,g)},()=>u.var(g,!0)),l.ok(g))}e.validateSchemaDeps=a,e.default=o})(Ru)),Ru}var Ti={},K_;function C7(){if(K_)return Ti;K_=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={},Y_;function Q_(){if(Y_)return Ci;Y_=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={},X_;function S7(){if(X_)return Si;X_=1,Object.defineProperty(Si,"__esModule",{value:!0});const e=Qa(),t=Ir(),r=Ue(),n=Q_(),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={},ey;function I7(){if(ey)return Ii;ey=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={},ty;function x7(){if(ty)return xi;ty=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={},ry;function E7(){if(ry)return Ei;ry=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={},ny;function $7(){if(ny)return $i;ny=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={},oy;function R7(){if(oy)return Ri;oy=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={},sy;function P7(){if(sy)return Pi;sy=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={},ay;function M7(){if(ay)return Mi;ay=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 iy;function N7(){if(iy)return vi;iy=1,Object.defineProperty(vi,"__esModule",{value:!0});const e=V_(),t=w7(),r=B_(),n=b7(),o=k7(),s=T7(),i=C7(),a=Q_(),l=S7(),c=I7(),u=x7(),f=E7(),p=$7(),h=R7(),g=P7(),v=M7();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={},ly;function O7(){if(ly)return Oi;ly=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 cy;function A7(){if(cy)return Ni;cy=1,Object.defineProperty(Ni,"__esModule",{value:!0});const t=[O7().default];return Ni.default=t,Ni}var Bn={},uy;function q7(){return uy||(uy=1,Object.defineProperty(Bn,"__esModule",{value:!0}),Bn.contentVocabulary=Bn.metadataVocabulary=void 0,Bn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],Bn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]),Bn}var dy;function L7(){if(dy)return ni;dy=1,Object.defineProperty(ni,"__esModule",{value:!0});const e=i7(),t=v7(),r=N7(),n=A7(),o=q7(),s=[e.default,t.default,(0,r.default)(),n.default,o.metadataVocabulary,o.contentVocabulary];return ni.default=s,ni}var Ai={},Ss={},py;function j7(){if(py)return Ss;py=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 fy;function D7(){if(fy)return Ai;fy=1,Object.defineProperty(Ai,"__esModule",{value:!0});const e=Re(),t=j7(),r=Iu(),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 U7={$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 hy;function my(){return hy||(hy=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=o7(),n=L7(),o=D7(),s=U7,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=Su();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return f.default}});var p=ti();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return p.default}})})(Ha,Ha.exports)),Ha.exports}var z7=my();const F7=$l(z7);var qi={exports:{}},Pu={},gy;function V7(){return gy||(gy=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}}})(Pu)),Pu}var Mu={},_y;function Z7(){return _y||(_y=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;const t=my(),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})(Mu)),Mu}var yy;function B7(){return yy||(yy=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r=V7(),n=Z7(),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 H7=B7();const J7=$l(H7);function G7(){const e=new F7({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return J7(e),e}class W7{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 K7{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 Y7(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 Q7(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 X7(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 Jx{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 W7,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Rc,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",$c,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Cc,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new K7(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=Bg(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(Nc,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}=X7(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(Oc,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(Pc,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?h2:Mc,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}},Qm,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!o5.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){Y7(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&Q7(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},jn,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},m2,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},jn,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},c2,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},l2,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},o2,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},s2,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},a2,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},jn,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},jn,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},d2,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,o){const s=Y5.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 eE="mcp";class vy{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,eE),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=Ln.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 tE=()=>{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}},rE=(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 wy{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=Ln.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 nE extends wy{constructor(t,r=tE()){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)](rE,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 oE=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))},sE=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,_2);break;case"sampling/createMessage":const g={};g[o(481)]=c,g[o(446)]=u,f=await t.request(g,Mc);break;case a[o(487)]:const v={};v.method=c,v[s(446)]=u,f=await t.request(v,Oc);break;case a.ypHTC:const _={};_.method=c,f=await t.request(_,jn);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 aE=(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)](oE,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)}}}},iE=(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)}}},lE=(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(sE,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)}}},cE=(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 uE=(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)}}},Nu=()=>{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},dE=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)](Nu);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)](Nu);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(Nu);e.fallbackNotificationHandler=o,e[t(444)]=s,e.removeNotificationListener=i,e[r(426)]=a}},pE=(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(dE,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)})},fE=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 hE=()=>{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)})},mE=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[fE(211)]=hE,hn.randomBytes=mE;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 gE=(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)](aE,e,t),iE(e,t);const s=o[n(283)](lE,t,e),i=o[n(294)](uE,t,e),a=o[r(277)](cE,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)}},Ou=(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(gE,e,t)},s={};s.afterInit=o,n.Qalmc(pE,t,s)},by=(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},ky=(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},Au=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 Au(e,t,r)}else throw a}},Ty=(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 _E=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)](by,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=Ty(l,f);I=await n[t(263)](Au,b,S,T)}else await b.connect(I);Ou(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},yE=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)](ky,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)](Ty,l,f);I=await n[t(296)](Au,b,S,T)}else await b[t(260)](I);n.PdsSn(Ou,b,o,I);const R={};return R.transport=I,R[r(286)]=I[r(286)],R},vE=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 vy(new URL(s+"?sessionId="+g+r(265)+i));await h.connect(v),n[t(259)](Ou,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 wE=()=>hn.randomBytes(-8746+-382*-23);class v${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(wE),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)}class bE{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,onError:a}=t;if(i===!0){const u={client:this.client,url:r,token:n,sessionId:o};let f;return await(async()=>{const{transport:h,sessionId:g}=s==="sse"?await _E(u):s==="socket"?await vE(u):await yE(u);h.onerror=async v=>{a?.(v)},f={transport:h,sessionId:g}})(),f}const l=new URL(r);let c;if(s==="channel"&&(c=new nE(r),await this.client.connect(c)),s==="sse"){const u=by(n,o);c=new Da(l,u),await this.client.connect(c)}if(s==="socket"&&(c=new vy(new URL(`${r}?sessionId=${o}&token=${n}`)),c.sessionId=o,await this.client.connect(c)),typeof c>"u"){const u=ky(n,o);c=new Aa(l,u),await this.client.connect(c)}return this.transport=c,{transport:this.transport,sessionId:this.transport.sessionId}}async close(){await this.client.close()}getServerCapabilities(){return this.client.getServerCapabilities()}getServerVersion(){return this.client.getServerVersion()}getInstructions(){return this.client.getInstructions()}async ping(t){return await this.client.ping(t)}async complete(t,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(Nc,t)}onCreateMessage(t){this.client.setRequestHandler(Pc,t)}onListRoots(t){this.client.setRequestHandler(g2,t)}onToolListChanged(t){this.client.setNotificationHandler(Rc,t)}onPromptListChanged(t){this.client.setNotificationHandler($c,t)}onResourceListChanged(t){this.client.setNotificationHandler(Cc,t)}onResourceUpdated(t){this.client.setNotificationHandler(i2,t)}onLoggingMessage(t){this.client.setNotificationHandler(f2,t)}async onPagehide(t){t.persisted||(kE(this.transport)?await this.transport.terminateSession():this.transport&&typeof this.transport.close=="function"&&await this.transport.close())}}const kE=e=>e instanceof Aa,Cy=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]=Kf({description:o,inputSchema:uo({...s,properties:s.properties??{},additionalProperties:!1}),execute:i})}return t}catch(r){throw r}};function TE(e){const t=Object.entries(e);if(t.length===0)return"";let r=`
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=`
88
88
  # 工具调用
89
89
 
90
90
  你可以根据需要调用以下工具:
@@ -120,23 +120,23 @@ Thought: 用户想要获取今天的日期,我需要调用日期相关的工
120
120
  - 必须严格按照 XML 格式调用工具
121
121
  - arguments 必须是有效的 JSON 格式
122
122
  - 如果不需要调用工具,直接给出最终答案即可
123
- `,r}function Sy(e,t){if(!e||typeof e!="string")return null;const r=e.match(/<tool_call>([\s\S]*?)<\/tool_call>/i);if(r)try{const n=r[1].trim(),o=JSON.parse(n),s=o.name||o.action||o.tool,i=o.arguments||o.args||o.input||{};if(s&&t[s])return{toolName:s,arguments:i}}catch{}return null}const CE={openai:Y2,deepseek:Zg};class SE{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=CE[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.toLocaleLowerCase()==="streamablehttp"){const o=t,s=o.headers?{headers:o.headers}:void 0;r=new Aa(new URL(o.url),{requestInit:s})}else if("type"in t&&t.type==="sse"){const o=t,s=o.headers?{headers:o.headers}:void 0;r=new Da(new URL(o.url),{requestInit:s})}else"type"in t&&t.type==="extension"?r=new Zx(t.sessionId):"transport"in t?r=t.transport:r=t;if(t.useAISdkClient??!1){const o=await r5({transport:r});return o.__transport__=r,o}else{const o=new bE({name:"mcp-web-client",version:"1.0.0"},{capabilities:{roots:{listChanged:!0},sampling:{},elicitation:{}}});return await o.connect(r),o.__transport__=r,o}}catch(r){return this.onError&&this.onError(r?.message||"Failed to create MCP client",r),console.error("Failed to create MCP client",t,r),null}}async _closeOneClient(t){try{const r=t.__transport__;if(r&&r instanceof Ua||r&&r instanceof wy)return;await r?.terminateSession?.(),await r?.close?.(),await t?.close?.()}catch{}}async _createMpcClients(){const t=Object.entries(this.mcpServers),r=await Promise.all(t.map(async([n,o])=>{const s=await this._createOneClient(o);return{serverName:n,client:s}}));this.mcpClients={},r.forEach(({serverName:n,client:o})=>{this.mcpClients[n]=o})}async _getClientTools(t,r){if(!t)return null;try{return typeof t.tools=="function"?await t.tools():await Cy(t)}catch(n){return this.onError&&this.onError(n?.message||`Failed to query tools for ${r}`,n),console.error(`Failed to query tools for ${r}`,n),null}}async _createMpcTools(){const t=Object.entries(this.mcpClients),r=await Promise.all(t.map(async([n,o])=>{const s=await this._getClientTools(o,n);return{serverName:n,tools:s}}));this.mcpTools={},r.forEach(({serverName:n,tools:o})=>{const s=o&&typeof o=="object"?o:{};this.mcpTools[n]=s})}async closeAll(){await Promise.all(Object.values(this.mcpClients).map(async t=>{try{await this._closeOneClient(t)}catch(r){this.onError&&this.onError(r?.message||"Failed to close client",r),console.error("Failed to close client",r)}}))}async initClientsAndTools(){await this._createMpcClients(),await this._createMpcTools(),this.onUpdatedTools?.()}async refreshTools(){await this._createMpcTools(),this.onUpdatedTools?.()}async updateMcpServers(t){await this.closeAll(),this.mcpServers=t||this.mcpServers,await this.initClientsAndTools()}async insertMcpServer(t,r){if(this.mcpServers[t])return!1;const n=await this._createOneClient(r);if(!n)return this.onError?.(`Failed to create MCP client: ${t}`),null;this.mcpClients[t]=n;const o=await this._getClientTools(n,t);return this.mcpTools[t]=o&&typeof o=="object"?o:{},this.mcpServers[t]=r,this.onUpdatedTools?.(),n}async removeMcpServer(t){if(!this.mcpServers[t])return;delete this.mcpServers[t];const r=this.mcpClients[t];delete this.mcpClients[t];try{await this._closeOneClient(r)}catch{}const n=this.mcpTools[t];delete this.mcpTools[t],n&&Object.keys(n).forEach(o=>{this.ignoreToolnames=this.ignoreToolnames.filter(s=>s!==o)}),this.onUpdatedTools?.()}_tempMergeTools(t={},r=!0){const n=Object.values(this.mcpTools).reduce((o,s)=>({...o,...s}),{});return Object.assign(n,t),r&&this.ignoreToolnames.forEach(o=>{delete n[o]}),n}_getActiveToolNames(t){return Object.keys(t).filter(r=>!this.ignoreToolnames.includes(r))}_generateReActSystemPrompt(t,r,n){const o=TE(t);return n?`${n}${o}`:`你是一个智能助手,可以通过调用工具来完成任务。
124
- ${o}`}async _executeReActToolCall(t,r,n){const o=n[t];if(!o)return{success:!1,error:`工具 ${t} 不存在`};try{const s=o,i=s.execute||s.call;return typeof i!="function"?{success:!1,error:`工具 ${t} 没有可执行的函数`}:{success:!0,result:await i(r,{})}}catch(s){return{success:!1,error:s?.message||String(s)||"工具执行失败"}}}async _chatReAct(t,{model:r,maxSteps:n=5,...o}){if(!this.llm)throw new Error("LLM is not initialized");await this.initClientsAndTools();const s=this._tempMergeTools(o.tools);if(Object.keys(s).length===0)return this._chat(t,{model:r,maxSteps:n,...o});let a=[];o.message&&!o.messages?a.push({role:"user",content:o.message}):o.messages?a=[...o.messages]:a=[...this.responseMessages];const l=typeof r=="string"?r:r?.modelId||"default-model",u={role:"system",content:this._generateReActSystemPrompt(s,l,o.system)},f=a[0]?.role==="system"?a:[u,...a];return t===nc?this._chatReActStream(f,s,l,n,o):this._chatReActNonStream(f,s,l,n,o)}_messageHasImage(t){return t&&Array.isArray(t)?t.some(r=>r&&r.type==="image"):!1}_removeImageFromMessage(t){if(!t||!t.content)return null;if(!Array.isArray(t.content))return t;const r=t.content.filter(n=>n&&n.type!=="image");return r.length===0?null:{...t,content:r}}_buildMessagesForModel(t,r,n=3){const o=[];t&&o.push(t);let s=0;const i=[];for(let a=r.length-1;a>=0;a--){const l=r[a];if(this._messageHasImage(l.content))if(s<n)i.unshift(l),s++;else{const u=this._removeImageFromMessage(l);u&&i.unshift(u)}else i.unshift(l)}return o.push(...i),o}async _chatReActNonStream(t,r,n,o,s){let i=[...t];const a=t[0]?.role==="system"?t[0]:null,l=a?t.slice(1):t;let c=0;const u=s.maxImages??3;for(;c<o;){c++;const p=this._buildMessagesForModel(a,l,u),{tools:h,...g}=s,_=(await hm({model:this.llm(n),messages:p,...g})).text,w={role:"assistant",content:_};l.push(w),i.push(w);const y=Sy(_,r);if(!y)return this.responseMessages=i,{text:_,response:{messages:i}};const m=await this._executeReActToolCall(y.toolName,y.arguments,r),T={role:"user",content:`<tool_response>
123
+ `,r}function Iy(e,t){if(!e||typeof e!="string")return null;const r=e.match(/<tool_call>([\s\S]*?)<\/tool_call>/i);if(r)try{const n=r[1].trim(),o=JSON.parse(n),s=o.name||o.action||o.tool,i=o.arguments||o.args||o.input||{};if(s&&t[s])return{toolName:s,arguments:i}}catch{}return null}const xE={openai:Q2,deepseek:Bg};class EE{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=xE[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:()=>SE(o),close:async()=>{}}}if("type"in t&&t.type.toLocaleLowerCase()==="streamablehttp"){const o=t,s=o.headers?{headers:o.headers}:void 0;r=new Aa(new URL(o.url),{requestInit:s})}else if("type"in t&&t.type==="sse"){const o=t,s=o.headers?{headers:o.headers}:void 0;r=new Da(new URL(o.url),{requestInit:s})}else"type"in t&&t.type==="extension"?r=new Bx(t.sessionId):"transport"in t?r=t.transport:r=t;if(t.useAISdkClient??!1){const o=await n5({transport:r});return o.__transport__=r,o}else{const o=new TE({name:"mcp-web-client",version:"1.0.0"},{capabilities:{roots:{listChanged:!0},sampling:{},elicitation:{}}});return await o.connect(r),o.__transport__=r,o}}catch(r){return this.onError&&this.onError(r?.message||"Failed to create MCP client",r),console.error("Failed to create MCP client",t,r),null}}async _closeOneClient(t){try{const r=t.__transport__;if(r&&r instanceof Ua||r&&r instanceof by)return;await r?.terminateSession?.(),await r?.close?.(),await t?.close?.()}catch{}}async _createMpcClients(){const t=Object.entries(this.mcpServers),r=await Promise.all(t.map(async([n,o])=>{const s=await this._createOneClient(o);return{serverName:n,client:s}}));this.mcpClients={},r.forEach(({serverName:n,client:o})=>{this.mcpClients[n]=o})}async _getClientTools(t,r){if(!t)return null;try{return typeof t.tools=="function"?await t.tools():await Sy(t)}catch(n){return this.onError&&this.onError(n?.message||`Failed to query tools for ${r}`,n),console.error(`Failed to query tools for ${r}`,n),null}}async _createMpcTools(){const t=Object.entries(this.mcpClients),r=await Promise.all(t.map(async([n,o])=>{const s=await this._getClientTools(o,n);return{serverName:n,tools:s}}));this.mcpTools={},r.forEach(({serverName:n,tools:o})=>{const s=o&&typeof o=="object"?o:{};this.mcpTools[n]=s})}async closeAll(){await Promise.all(Object.values(this.mcpClients).map(async t=>{try{await this._closeOneClient(t)}catch(r){this.onError&&this.onError(r?.message||"Failed to close client",r),console.error("Failed to close client",r)}}))}async initClientsAndTools(){await this._createMpcClients(),await this._createMpcTools(),this.onUpdatedTools?.()}async refreshTools(){await this._createMpcTools(),this.onUpdatedTools?.()}async updateMcpServers(t){await this.closeAll(),this.mcpServers=t||this.mcpServers,await this.initClientsAndTools()}async insertMcpServer(t,r){if(this.mcpServers[t])return!1;const n=await this._createOneClient(r);if(!n)return this.onError?.(`Failed to create MCP client: ${t}`),null;this.mcpClients[t]=n;const o=await this._getClientTools(n,t);return this.mcpTools[t]=o&&typeof o=="object"?o:{},this.mcpServers[t]=r,this.onUpdatedTools?.(),n}async removeMcpServer(t){if(!this.mcpServers[t])return;delete this.mcpServers[t];const r=this.mcpClients[t];delete this.mcpClients[t];try{await this._closeOneClient(r)}catch{}const n=this.mcpTools[t];delete this.mcpTools[t],n&&Object.keys(n).forEach(o=>{this.ignoreToolnames=this.ignoreToolnames.filter(s=>s!==o)}),this.onUpdatedTools?.()}_tempMergeTools(t={},r=!0){const n=Object.values(this.mcpTools).reduce((o,s)=>({...o,...s}),{});return Object.assign(n,t),r&&this.ignoreToolnames.forEach(o=>{delete n[o]}),n}_getActiveToolNames(t){return Object.keys(t).filter(r=>!this.ignoreToolnames.includes(r))}_generateReActSystemPrompt(t,r,n){const o=IE(t);return n?`${n}${o}`:`你是一个智能助手,可以通过调用工具来完成任务。
124
+ ${o}`}async _executeReActToolCall(t,r,n){const o=n[t];if(!o)return{success:!1,error:`工具 ${t} 不存在`};try{const s=o,i=s.execute||s.call;return typeof i!="function"?{success:!1,error:`工具 ${t} 没有可执行的函数`}:{success:!0,result:await i(r,{})}}catch(s){return{success:!1,error:s?.message||String(s)||"工具执行失败"}}}async _chatReAct(t,{model:r,maxSteps:n=5,...o}){if(!this.llm)throw new Error("LLM is not initialized");await this.initClientsAndTools();const s=this._tempMergeTools(o.tools);if(Object.keys(s).length===0)return this._chat(t,{model:r,maxSteps:n,...o});let a=[];o.message&&!o.messages?a.push({role:"user",content:o.message}):o.messages?a=[...o.messages]:a=[...this.responseMessages];const l=typeof r=="string"?r:r?.modelId||"default-model",u={role:"system",content:this._generateReActSystemPrompt(s,l,o.system)},f=a[0]?.role==="system"?a:[u,...a];return t===oc?this._chatReActStream(f,s,l,n,o):this._chatReActNonStream(f,s,l,n,o)}_messageHasImage(t){return t&&Array.isArray(t)?t.some(r=>r&&r.type==="image"):!1}_removeImageFromMessage(t){if(!t||!t.content)return null;if(!Array.isArray(t.content))return t;const r=t.content.filter(n=>n&&n.type!=="image");return r.length===0?null:{...t,content:r}}_buildMessagesForModel(t,r,n=3){const o=[];t&&o.push(t);let s=0;const i=[];for(let a=r.length-1;a>=0;a--){const l=r[a];if(this._messageHasImage(l.content))if(s<n)i.unshift(l),s++;else{const u=this._removeImageFromMessage(l);u&&i.unshift(u)}else i.unshift(l)}return o.push(...i),o}async _chatReActNonStream(t,r,n,o,s){let i=[...t];const a=t[0]?.role==="system"?t[0]:null,l=a?t.slice(1):t;let c=0;const u=s.maxImages??3;for(;c<o;){c++;const p=this._buildMessagesForModel(a,l,u),{tools:h,...g}=s,_=(await mm({model:this.llm(n),messages:p,...g})).text,w={role:"assistant",content:_};l.push(w),i.push(w);const y=Iy(_,r);if(!y)return this.responseMessages=i,{text:_,response:{messages:i}};const m=await this._executeReActToolCall(y.toolName,y.arguments,r),T={role:"user",content:`<tool_response>
125
125
  ${m.success?JSON.stringify(m.result):`工具执行失败 - ${m.error}`}
126
- </tool_response>`};l.push(T),i.push(T)}return this.responseMessages=i,{text:i[i.length-2]?.content||"",response:{messages:i}}}_chatReActStream(t,r,n,o,s){const i=this,a=this.llm(n);let l,c;const u=new Promise((p,h)=>{l=p,c=h});return{fullStream:new ReadableStream({async start(p){let h=[...t];const g=t[0]?.role==="system"?t[0]:null,v=g?t.slice(1):[...t];let _=0,w="";const y=s.maxImages??3;p.enqueue({type:"start"}),p.enqueue({type:"start-step"});try{for(;_<o;){_++;const m=i._buildMessagesForModel(g,v,y),{tools:C,...b}=s;delete b.system,delete b.onFinish;const T=await nc({...b,model:a,messages:m});let I="";for await(const ee of T.fullStream)ee.type==="text-delta"?(I+=ee.text||"",p.enqueue({type:"text-delta",text:ee.text})):ee.type==="text-start"?p.enqueue({type:"text-start"}):ee.type==="text-end"||ee.type==="finish-step"||ee.type==="finish"||ee.type==="start"||ee.type==="start-step"||p.enqueue(ee);w+=I;const R={role:"assistant",content:w};v.push(R),h.push(R);const S=Sy(w,r);if(!S){p.enqueue({type:"text-end"}),p.enqueue({type:"finish-step"}),p.enqueue({type:"finish"}),p.close(),i.responseMessages=h,l({messages:h});return}if(S.toolName==="computer"&&S.arguments?.action==="terminate"){p.enqueue({type:"text-end"}),p.enqueue({type:"finish-step"}),p.enqueue({type:"finish"}),p.close(),i.responseMessages=h,l({messages:h});return}const j=`react-${Date.now()}`;p.enqueue({type:"tool-input-start",id:j,toolName:S.toolName});const N=JSON.stringify(S.arguments,null,2);p.enqueue({type:"tool-input-delta",id:j,delta:N}),p.enqueue({type:"tool-input-end",id:j}),p.enqueue({type:"tool-call",toolCallId:j,toolName:S.toolName,input:S.arguments});const L=await i._executeReActToolCall(S.toolName,S.arguments,r);let z,B=L.result;if(L.success&&L.result&&typeof L.result=="object"&&L.result.screenshot){z=L.result.screenshot;const{screenshot:ee,...Q}=L.result;B=Q}let X="";if(L.success){B&&Array.isArray(B.content)&&B.content.length>0&&B.content[0].text?X=B.content[0].text:X=JSON.stringify(B);let ee=`<tool_response>
126
+ </tool_response>`};l.push(T),i.push(T)}return this.responseMessages=i,{text:i[i.length-2]?.content||"",response:{messages:i}}}_chatReActStream(t,r,n,o,s){const i=this,a=this.llm(n);let l,c;const u=new Promise((p,h)=>{l=p,c=h});return{fullStream:new ReadableStream({async start(p){let h=[...t];const g=t[0]?.role==="system"?t[0]:null,v=g?t.slice(1):[...t];let _=0,w="";const y=s.maxImages??3;p.enqueue({type:"start"}),p.enqueue({type:"start-step"});try{for(;_<o;){_++;const m=i._buildMessagesForModel(g,v,y),{tools:C,...b}=s;delete b.system,delete b.onFinish;const T=await oc({...b,model:a,messages:m});let I="";for await(const ee of T.fullStream)ee.type==="text-delta"?(I+=ee.text||"",p.enqueue({type:"text-delta",text:ee.text})):ee.type==="text-start"?p.enqueue({type:"text-start"}):ee.type==="text-end"||ee.type==="finish-step"||ee.type==="finish"||ee.type==="start"||ee.type==="start-step"||p.enqueue(ee);w+=I;const R={role:"assistant",content:w};v.push(R),h.push(R);const S=Iy(w,r);if(!S){p.enqueue({type:"text-end"}),p.enqueue({type:"finish-step"}),p.enqueue({type:"finish"}),p.close(),i.responseMessages=h,l({messages:h});return}if(S.toolName==="computer"&&S.arguments?.action==="terminate"){p.enqueue({type:"text-end"}),p.enqueue({type:"finish-step"}),p.enqueue({type:"finish"}),p.close(),i.responseMessages=h,l({messages:h});return}const j=`react-${Date.now()}`;p.enqueue({type:"tool-input-start",id:j,toolName:S.toolName});const N=JSON.stringify(S.arguments,null,2);p.enqueue({type:"tool-input-delta",id:j,delta:N}),p.enqueue({type:"tool-input-end",id:j}),p.enqueue({type:"tool-call",toolCallId:j,toolName:S.toolName,input:S.arguments});const L=await i._executeReActToolCall(S.toolName,S.arguments,r);let z,B=L.result;if(L.success&&L.result&&typeof L.result=="object"&&L.result.screenshot){z=L.result.screenshot;const{screenshot:ee,...Q}=L.result;B=Q}let X="";if(L.success){B&&Array.isArray(B.content)&&B.content.length>0&&B.content[0].text?X=B.content[0].text:X=JSON.stringify(B);let ee=`<tool_response>
127
127
  ${X}
128
128
  </tool_response>`;z&&(ee+=`
129
- 请检查截图以确认操作是否成功。如果成功,请继续下一步;如果失败,请重试。`),p.enqueue({type:"tool-result",toolCallId:j,result:ee});const Q=z?{role:"user",content:[{type:"text",text:ee},{type:"image",image:z}]}:{role:"user",content:ee};v.push(Q),h.push(Q),w=""}else X=`工具执行失败 - ${L.error}`,p.enqueue({type:"tool-error",toolCallId:j,input:S.arguments,error:{message:X}})}p.enqueue({type:"text-end"}),p.enqueue({type:"finish-step"}),p.enqueue({type:"finish"}),p.close(),i.responseMessages=h,l({messages:h})}catch(m){p.error(m),c(m)}}}),response:u}}async _chat(t,{model:r,maxSteps:n=5,...o}){if(this.useReActMode)return this._chatReAct(t,{model:r,maxSteps:n,...o});if(!this.llm)throw new Error("LLM is not initialized");await this.initClientsAndTools();const s=o.tools||{},i=this._tempMergeTools(s,!1),a=()=>{const h=this._tempMergeTools(s,!1);Object.entries(h).forEach(([g,v])=>{i[g]=v}),Object.keys(i).forEach(g=>{g in h||delete i[g]})},l=o.prepareStep,c=async h=>{a();const g=this._getActiveToolNames(i),v=typeof l=="function"?await l(h):void 0,_=v&&typeof v=="object"?v:{};return{..._,activeTools:Array.isArray(_.activeTools)?_.activeTools.filter(w=>g.includes(w)):g}},u={model:this.llm(r),stopWhen:ec(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(hm,t)}async chatStream(t){return this._chat(nc,t)}}var xo={},qu,Iy;function IE(){return Iy||(Iy=1,qu=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),qu}var Lu={},gn={},xy;function Hn(){if(xy)return gn;xy=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 ju={},Ey;function Du(){return Ey||(Ey=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}}})(ju)),ju}var Uu,$y;function xE(){if($y)return Uu;$y=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++}},Uu=e,Uu}var zu,Ry;function EE(){if(Ry)return zu;Ry=1;function e(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}return e.prototype.set=function(t,r,n,o){const s=t*this.size+r;this.data[s]=n,o&&(this.reservedBit[s]=!0)},e.prototype.get=function(t,r){return this.data[t*this.size+r]},e.prototype.xor=function(t,r,n){this.data[t*this.size+r]^=n},e.prototype.isReserved=function(t,r){return this.reservedBit[t*this.size+r]},zu=e,zu}var Fu={},Py;function $E(){return Py||(Py=1,(function(e){const t=Hn().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}})(Fu)),Fu}var Vu={},My;function RE(){if(My)return Vu;My=1;const e=Hn().getSymbolSize,t=7;return Vu.getPositions=function(n){const o=e(n);return[[0,0],[o-t,0],[0,o-t]]},Vu}var Zu={},Ny;function PE(){return Ny||(Ny=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}})(Zu)),Zu}var Hi={},Oy;function Ay(){if(Oy)return Hi;Oy=1;const e=Du(),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 Bu={},Es={},qy;function ME(){if(qy)return Es;qy=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 Ly;function NE(){return Ly||(Ly=1,(function(e){const t=ME();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}})(Bu)),Bu}var Hu,jy;function OE(){if(jy)return Hu;jy=1;const e=NE();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},Hu=t,Hu}var Ju={},Gu={},Wu={},Dy;function Uy(){return Dy||(Dy=1,Wu.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),Wu}var jr={},zy;function Fy(){if(zy)return jr;zy=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
- ]))+`;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+"$"),s=new RegExp("^"+e+"$"),i=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return jr.testKanji=function(l){return o.test(l)},jr.testNumeric=function(l){return s.test(l)},jr.testAlphanumeric=function(l){return i.test(l)},jr}var Vy;function Jn(){return Vy||(Vy=1,(function(e){const t=Uy(),r=Fy();e.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},e.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},e.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},e.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},e.MIXED={bit:-1},e.getCharCountIndicator=function(s,i){if(!s.ccBits)throw new Error("Invalid mode: "+s);if(!t.isValid(i))throw new Error("Invalid version: "+i);return i>=1&&i<10?s.ccBits[0]:i<27?s.ccBits[1]:s.ccBits[2]},e.getBestModeForData=function(s){return r.testNumeric(s)?e.NUMERIC:r.testAlphanumeric(s)?e.ALPHANUMERIC:r.testKanji(s)?e.KANJI:e.BYTE},e.toString=function(s){if(s&&s.id)return s.id;throw new Error("Invalid mode")},e.isValid=function(s){return s&&s.bit&&s.ccBits};function n(o){if(typeof o!="string")throw new Error("Param is not a string");switch(o.toLowerCase()){case"numeric":return e.NUMERIC;case"alphanumeric":return e.ALPHANUMERIC;case"kanji":return e.KANJI;case"byte":return e.BYTE;default:throw new Error("Unknown mode: "+o)}}e.from=function(s,i){if(e.isValid(s))return s;try{return n(s)}catch{return i}}})(Gu)),Gu}var Zy;function AE(){return Zy||(Zy=1,(function(e){const t=Hn(),r=Ay(),n=Du(),o=Jn(),s=Uy(),i=7973,a=t.getBCHDigit(i);function l(p,h,g){for(let v=1;v<=40;v++)if(h<=e.getCapacity(v,g,p))return v}function c(p,h){return o.getCharCountIndicator(p,h)+4}function u(p,h){let g=0;return p.forEach(function(v){const _=c(v.mode,h);g+=_+v.getBitsLength()}),g}function f(p,h){for(let g=1;g<=40;g++)if(u(p,g)<=e.getCapacity(g,h,o.MIXED))return g}e.from=function(h,g){return s.isValid(h)?parseInt(h,10):g},e.getCapacity=function(h,g,v){if(!s.isValid(h))throw new Error("Invalid QR Code version");typeof v>"u"&&(v=o.BYTE);const _=t.getSymbolTotalCodewords(h),w=r.getTotalCodewordsCount(h,g),y=(_-w)*8;if(v===o.MIXED)return y;const m=y-c(v,h);switch(v){case o.NUMERIC:return Math.floor(m/10*3);case o.ALPHANUMERIC:return Math.floor(m/11*2);case o.KANJI:return Math.floor(m/13);case o.BYTE:default:return Math.floor(m/8)}},e.getBestVersionForData=function(h,g){let v;const _=n.from(g,n.M);if(Array.isArray(h)){if(h.length>1)return f(h,_);if(h.length===0)return 1;v=h[0]}else v=h;return l(v.mode,v.getLength(),_)},e.getEncodedBits=function(h){if(!s.isValid(h)||h<7)throw new Error("Invalid QR Code version");let g=h<<12;for(;t.getBCHDigit(g)-a>=0;)g^=i<<t.getBCHDigit(g)-a;return h<<12|g}})(Ju)),Ju}var Ku={},By;function qE(){if(By)return Ku;By=1;const e=Hn(),t=1335,r=21522,n=e.getBCHDigit(t);return Ku.getEncodedBits=function(s,i){const a=s.bit<<3|i;let l=a<<10;for(;e.getBCHDigit(l)-n>=0;)l^=t<<e.getBCHDigit(l)-n;return(a<<10|l)^r},Ku}var Yu={},Qu,Hy;function LE(){if(Hy)return Qu;Hy=1;const e=Jn();function t(r){this.mode=e.NUMERIC,this.data=r.toString()}return t.getBitsLength=function(n){return 10*Math.floor(n/3)+(n%3?n%3*3+1:0)},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(n){let o,s,i;for(o=0;o+3<=this.data.length;o+=3)s=this.data.substr(o,3),i=parseInt(s,10),n.put(i,10);const a=this.data.length-o;a>0&&(s=this.data.substr(o),i=parseInt(s,10),n.put(i,a*3+1))},Qu=t,Qu}var Xu,Jy;function jE(){if(Jy)return Xu;Jy=1;const e=Jn(),t=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function r(n){this.mode=e.ALPHANUMERIC,this.data=n}return r.getBitsLength=function(o){return 11*Math.floor(o/2)+6*(o%2)},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(o){let s;for(s=0;s+2<=this.data.length;s+=2){let i=t.indexOf(this.data[s])*45;i+=t.indexOf(this.data[s+1]),o.put(i,11)}this.data.length%2&&o.put(t.indexOf(this.data[s]),6)},Xu=r,Xu}var ed,Gy;function DE(){if(Gy)return ed;Gy=1;const e=Jn();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)},ed=t,ed}var td,Wy;function UE(){if(Wy)return td;Wy=1;const e=Jn(),t=Hn();function r(n){this.mode=e.KANJI,this.data=n}return r.getBitsLength=function(o){return o*13},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(n){let o;for(o=0;o<this.data.length;o++){let s=t.toSJIS(this.data[o]);if(s>=33088&&s<=40956)s-=33088;else if(s>=57408&&s<=60351)s-=49472;else throw new Error("Invalid SJIS character: "+this.data[o]+`
131
- Make sure your charset is UTF-8`);s=(s>>>8&255)*192+(s&255),n.put(s,13)}},td=r,td}var rd={exports:{}},Ky;function zE(){return Ky||(Ky=1,(function(e){var t={single_source_shortest_paths:function(r,n,o){var s={},i={};i[n]=0;var a=t.PriorityQueue.make();a.push(n,0);for(var l,c,u,f,p,h,g,v,_;!a.empty();){l=a.pop(),c=l.value,f=l.cost,p=r[c]||{};for(u in p)p.hasOwnProperty(u)&&(h=p[u],g=f+h,v=i[u],_=typeof i[u]>"u",(_||v>g)&&(i[u]=g,a.push(u,g),s[u]=c))}if(typeof o<"u"&&typeof i[o]>"u"){var w=["Could not find a path from ",n," to ",o,"."].join("");throw new Error(w)}return s},extract_shortest_path_from_predecessor_list:function(r,n){for(var o=[],s=n;s;)o.push(s),r[s],s=r[s];return o.reverse(),o},find_path:function(r,n,o){var s=t.single_source_shortest_paths(r,n,o);return t.extract_shortest_path_from_predecessor_list(s,o)},PriorityQueue:{make:function(r){var n=t.PriorityQueue,o={},s;r=r||{};for(s in n)n.hasOwnProperty(s)&&(o[s]=n[s]);return o.queue=[],o.sorter=r.sorter||n.default_sorter,o},default_sorter:function(r,n){return r.cost-n.cost},push:function(r,n){var o={value:r,cost:n};this.queue.push(o),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};e.exports=t})(rd)),rd.exports}var Yy;function FE(){return Yy||(Yy=1,(function(e){const t=Jn(),r=LE(),n=jE(),o=DE(),s=UE(),i=Fy(),a=Hn(),l=zE();function c(w){return unescape(encodeURIComponent(w)).length}function u(w,y,m){const C=[];let b;for(;(b=w.exec(m))!==null;)C.push({data:b[0],index:b.index,mode:y,length:b[0].length});return C}function f(w){const y=u(i.NUMERIC,t.NUMERIC,w),m=u(i.ALPHANUMERIC,t.ALPHANUMERIC,w);let C,b;return a.isKanjiModeEnabled()?(C=u(i.BYTE,t.BYTE,w),b=u(i.KANJI,t.KANJI,w)):(C=u(i.BYTE_KANJI,t.BYTE,w),b=[]),y.concat(m,C,b).sort(function(I,R){return I.index-R.index}).map(function(I){return{data:I.data,mode:I.mode,length:I.length}})}function p(w,y){switch(y){case t.NUMERIC:return r.getBitsLength(w);case t.ALPHANUMERIC:return n.getBitsLength(w);case t.KANJI:return s.getBitsLength(w);case t.BYTE:return o.getBitsLength(w)}}function h(w){return w.reduce(function(y,m){const C=y.length-1>=0?y[y.length-1]:null;return C&&C.mode===m.mode?(y[y.length-1].data+=m.data,y):(y.push(m),y)},[])}function g(w){const y=[];for(let m=0;m<w.length;m++){const C=w[m];switch(C.mode){case t.NUMERIC:y.push([C,{data:C.data,mode:t.ALPHANUMERIC,length:C.length},{data:C.data,mode:t.BYTE,length:C.length}]);break;case t.ALPHANUMERIC:y.push([C,{data:C.data,mode:t.BYTE,length:C.length}]);break;case t.KANJI:y.push([C,{data:C.data,mode:t.BYTE,length:c(C.data)}]);break;case t.BYTE:y.push([{data:C.data,mode:t.BYTE,length:c(C.data)}])}}return y}function v(w,y){const m={},C={start:{}};let b=["start"];for(let T=0;T<w.length;T++){const I=w[T],R=[];for(let S=0;S<I.length;S++){const j=I[S],N=""+T+S;R.push(N),m[N]={node:j,lastCount:0},C[N]={};for(let L=0;L<b.length;L++){const z=b[L];m[z]&&m[z].node.mode===j.mode?(C[z][N]=p(m[z].lastCount+j.length,j.mode)-p(m[z].lastCount,j.mode),m[z].lastCount+=j.length):(m[z]&&(m[z].lastCount=j.length),C[z][N]=p(j.length,j.mode)+4+t.getCharCountIndicator(j.mode,y))}}b=R}for(let T=0;T<b.length;T++)C[b[T]].end=0;return{map:C,table:m}}function _(w,y){let m;const C=t.getBestModeForData(w);if(m=t.from(y,C),m!==t.BYTE&&m.bit<C.bit)throw new Error('"'+w+'" cannot be encoded with mode '+t.toString(m)+`.
132
- Suggested mode is: `+t.toString(C));switch(m===t.KANJI&&!a.isKanjiModeEnabled()&&(m=t.BYTE),m){case t.NUMERIC:return new r(w);case t.ALPHANUMERIC:return new n(w);case t.KANJI:return new s(w);case t.BYTE:return new o(w)}}e.fromArray=function(y){return y.reduce(function(m,C){return typeof C=="string"?m.push(_(C,null)):C.data&&m.push(_(C.data,C.mode)),m},[])},e.fromString=function(y,m){const C=f(y,a.isKanjiModeEnabled()),b=g(C),T=v(b,m),I=l.find_path(T.map,"start","end"),R=[];for(let S=1;S<I.length-1;S++)R.push(T.table[I[S]].node);return e.fromArray(h(R))},e.rawSplit=function(y){return e.fromArray(f(y,a.isKanjiModeEnabled()))}})(Yu)),Yu}var Qy;function VE(){if(Qy)return Lu;Qy=1;const e=Hn(),t=Du(),r=xE(),n=EE(),o=$E(),s=RE(),i=PE(),a=Ay(),l=OE(),c=AE(),u=qE(),f=Jn(),p=FE();function h(T,I){const R=T.size,S=s.getPositions(I);for(let j=0;j<S.length;j++){const N=S[j][0],L=S[j][1];for(let z=-1;z<=7;z++)if(!(N+z<=-1||R<=N+z))for(let B=-1;B<=7;B++)L+B<=-1||R<=L+B||(z>=0&&z<=6&&(B===0||B===6)||B>=0&&B<=6&&(z===0||z===6)||z>=2&&z<=4&&B>=2&&B<=4?T.set(N+z,L+B,!0,!0):T.set(N+z,L+B,!1,!0))}}function g(T){const I=T.size;for(let R=8;R<I-8;R++){const S=R%2===0;T.set(R,6,S,!0),T.set(6,R,S,!0)}}function v(T,I){const R=o.getPositions(I);for(let S=0;S<R.length;S++){const j=R[S][0],N=R[S][1];for(let L=-2;L<=2;L++)for(let z=-2;z<=2;z++)L===-2||L===2||z===-2||z===2||L===0&&z===0?T.set(j+L,N+z,!0,!0):T.set(j+L,N+z,!1,!0)}}function _(T,I){const R=T.size,S=c.getEncodedBits(I);let j,N,L;for(let z=0;z<18;z++)j=Math.floor(z/3),N=z%3+R-8-3,L=(S>>z&1)===1,T.set(j,N,L,!0),T.set(N,j,L,!0)}function w(T,I,R){const S=T.size,j=u.getEncodedBits(I,R);let N,L;for(N=0;N<15;N++)L=(j>>N&1)===1,N<6?T.set(N,8,L,!0):N<8?T.set(N+1,8,L,!0):T.set(S-15+N,8,L,!0),N<8?T.set(8,S-N-1,L,!0):N<9?T.set(8,15-N-1+1,L,!0):T.set(8,15-N-1,L,!0);T.set(S-8,8,1,!0)}function y(T,I){const R=T.size;let S=-1,j=R-1,N=7,L=0;for(let z=R-1;z>0;z-=2)for(z===6&&z--;;){for(let B=0;B<2;B++)if(!T.isReserved(j,z-B)){let X=!1;L<I.length&&(X=(I[L]>>>N&1)===1),T.set(j,z-B,X),N--,N===-1&&(L++,N=7)}if(j+=S,j<0||R<=j){j-=S,S=-S;break}}}function m(T,I,R){const S=new r;R.forEach(function(B){S.put(B.mode.bit,4),S.put(B.getLength(),f.getCharCountIndicator(B.mode,T)),B.write(S)});const j=e.getSymbolTotalCodewords(T),N=a.getTotalCodewordsCount(T,I),L=(j-N)*8;for(S.getLengthInBits()+4<=L&&S.put(0,4);S.getLengthInBits()%8!==0;)S.putBit(0);const z=(L-S.getLengthInBits())/8;for(let B=0;B<z;B++)S.put(B%2?17:236,8);return C(S,T,I)}function C(T,I,R){const S=e.getSymbolTotalCodewords(I),j=a.getTotalCodewordsCount(I,R),N=S-j,L=a.getBlocksCount(I,R),z=S%L,B=L-z,X=Math.floor(S/L),ee=Math.floor(N/L),Q=ee+1,Z=X-ee,ne=new l(Z);let D=0;const E=new Array(L),U=new Array(L);let F=0;const x=new Uint8Array(T.buffer);for(let _e=0;_e<L;_e++){const G=_e<B?ee:Q;E[_e]=x.slice(D,D+G),U[_e]=ne.encode(E[_e]),D+=G,F=Math.max(F,G)}const M=new Uint8Array(S);let H=0,re,te;for(re=0;re<F;re++)for(te=0;te<L;te++)re<E[te].length&&(M[H++]=E[te][re]);for(re=0;re<Z;re++)for(te=0;te<L;te++)M[H++]=U[te][re];return M}function b(T,I,R,S){let j;if(Array.isArray(T))j=p.fromArray(T);else if(typeof T=="string"){let X=I;if(!X){const ee=p.rawSplit(T);X=c.getBestVersionForData(ee,R)}j=p.fromString(T,X||40)}else throw new Error("Invalid data");const N=c.getBestVersionForData(j,R);if(!N)throw new Error("The amount of data is too big to be stored in a QR Code");if(!I)I=N;else if(I<N)throw new Error(`
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
+ ]))+`;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+"$"),s=new RegExp("^"+e+"$"),i=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return jr.testKanji=function(l){return o.test(l)},jr.testNumeric=function(l){return s.test(l)},jr.testAlphanumeric=function(l){return i.test(l)},jr}var Zy;function Wn(){return Zy||(Zy=1,(function(e){const t=zy(),r=Vy();e.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},e.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},e.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},e.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},e.MIXED={bit:-1},e.getCharCountIndicator=function(s,i){if(!s.ccBits)throw new Error("Invalid mode: "+s);if(!t.isValid(i))throw new Error("Invalid version: "+i);return i>=1&&i<10?s.ccBits[0]:i<27?s.ccBits[1]:s.ccBits[2]},e.getBestModeForData=function(s){return r.testNumeric(s)?e.NUMERIC:r.testAlphanumeric(s)?e.ALPHANUMERIC:r.testKanji(s)?e.KANJI:e.BYTE},e.toString=function(s){if(s&&s.id)return s.id;throw new Error("Invalid mode")},e.isValid=function(s){return s&&s.bit&&s.ccBits};function n(o){if(typeof o!="string")throw new Error("Param is not a string");switch(o.toLowerCase()){case"numeric":return e.NUMERIC;case"alphanumeric":return e.ALPHANUMERIC;case"kanji":return e.KANJI;case"byte":return e.BYTE;default:throw new Error("Unknown mode: "+o)}}e.from=function(s,i){if(e.isValid(s))return s;try{return n(s)}catch{return i}}})(Ku)),Ku}var By;function jE(){return By||(By=1,(function(e){const t=Jn(),r=qy(),n=zu(),o=Wn(),s=zy(),i=7973,a=t.getBCHDigit(i);function l(p,h,g){for(let v=1;v<=40;v++)if(h<=e.getCapacity(v,g,p))return v}function c(p,h){return o.getCharCountIndicator(p,h)+4}function u(p,h){let g=0;return p.forEach(function(v){const _=c(v.mode,h);g+=_+v.getBitsLength()}),g}function f(p,h){for(let g=1;g<=40;g++)if(u(p,g)<=e.getCapacity(g,h,o.MIXED))return g}e.from=function(h,g){return s.isValid(h)?parseInt(h,10):g},e.getCapacity=function(h,g,v){if(!s.isValid(h))throw new Error("Invalid QR Code version");typeof v>"u"&&(v=o.BYTE);const _=t.getSymbolTotalCodewords(h),w=r.getTotalCodewordsCount(h,g),y=(_-w)*8;if(v===o.MIXED)return y;const m=y-c(v,h);switch(v){case o.NUMERIC:return Math.floor(m/10*3);case o.ALPHANUMERIC:return Math.floor(m/11*2);case o.KANJI:return Math.floor(m/13);case o.BYTE:default:return Math.floor(m/8)}},e.getBestVersionForData=function(h,g){let v;const _=n.from(g,n.M);if(Array.isArray(h)){if(h.length>1)return f(h,_);if(h.length===0)return 1;v=h[0]}else v=h;return l(v.mode,v.getLength(),_)},e.getEncodedBits=function(h){if(!s.isValid(h)||h<7)throw new Error("Invalid QR Code version");let g=h<<12;for(;t.getBCHDigit(g)-a>=0;)g^=i<<t.getBCHDigit(g)-a;return h<<12|g}})(Gu)),Gu}var Qu={},Hy;function DE(){if(Hy)return Qu;Hy=1;const e=Jn(),t=1335,r=21522,n=e.getBCHDigit(t);return Qu.getEncodedBits=function(s,i){const a=s.bit<<3|i;let l=a<<10;for(;e.getBCHDigit(l)-n>=0;)l^=t<<e.getBCHDigit(l)-n;return(a<<10|l)^r},Qu}var Xu={},ed,Jy;function UE(){if(Jy)return ed;Jy=1;const e=Wn();function t(r){this.mode=e.NUMERIC,this.data=r.toString()}return t.getBitsLength=function(n){return 10*Math.floor(n/3)+(n%3?n%3*3+1:0)},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(n){let o,s,i;for(o=0;o+3<=this.data.length;o+=3)s=this.data.substr(o,3),i=parseInt(s,10),n.put(i,10);const a=this.data.length-o;a>0&&(s=this.data.substr(o),i=parseInt(s,10),n.put(i,a*3+1))},ed=t,ed}var td,Wy;function zE(){if(Wy)return td;Wy=1;const e=Wn(),t=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function r(n){this.mode=e.ALPHANUMERIC,this.data=n}return r.getBitsLength=function(o){return 11*Math.floor(o/2)+6*(o%2)},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(o){let s;for(s=0;s+2<=this.data.length;s+=2){let i=t.indexOf(this.data[s])*45;i+=t.indexOf(this.data[s+1]),o.put(i,11)}this.data.length%2&&o.put(t.indexOf(this.data[s]),6)},td=r,td}var rd,Gy;function FE(){if(Gy)return rd;Gy=1;const e=Wn();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)},rd=t,rd}var nd,Ky;function VE(){if(Ky)return nd;Ky=1;const e=Wn(),t=Jn();function r(n){this.mode=e.KANJI,this.data=n}return r.getBitsLength=function(o){return o*13},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(n){let o;for(o=0;o<this.data.length;o++){let s=t.toSJIS(this.data[o]);if(s>=33088&&s<=40956)s-=33088;else if(s>=57408&&s<=60351)s-=49472;else throw new Error("Invalid SJIS character: "+this.data[o]+`
131
+ Make sure your charset is UTF-8`);s=(s>>>8&255)*192+(s&255),n.put(s,13)}},nd=r,nd}var od={exports:{}},Yy;function ZE(){return Yy||(Yy=1,(function(e){var t={single_source_shortest_paths:function(r,n,o){var s={},i={};i[n]=0;var a=t.PriorityQueue.make();a.push(n,0);for(var l,c,u,f,p,h,g,v,_;!a.empty();){l=a.pop(),c=l.value,f=l.cost,p=r[c]||{};for(u in p)p.hasOwnProperty(u)&&(h=p[u],g=f+h,v=i[u],_=typeof i[u]>"u",(_||v>g)&&(i[u]=g,a.push(u,g),s[u]=c))}if(typeof o<"u"&&typeof i[o]>"u"){var w=["Could not find a path from ",n," to ",o,"."].join("");throw new Error(w)}return s},extract_shortest_path_from_predecessor_list:function(r,n){for(var o=[],s=n;s;)o.push(s),r[s],s=r[s];return o.reverse(),o},find_path:function(r,n,o){var s=t.single_source_shortest_paths(r,n,o);return t.extract_shortest_path_from_predecessor_list(s,o)},PriorityQueue:{make:function(r){var n=t.PriorityQueue,o={},s;r=r||{};for(s in n)n.hasOwnProperty(s)&&(o[s]=n[s]);return o.queue=[],o.sorter=r.sorter||n.default_sorter,o},default_sorter:function(r,n){return r.cost-n.cost},push:function(r,n){var o={value:r,cost:n};this.queue.push(o),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};e.exports=t})(od)),od.exports}var Qy;function BE(){return Qy||(Qy=1,(function(e){const t=Wn(),r=UE(),n=zE(),o=FE(),s=VE(),i=Vy(),a=Jn(),l=ZE();function c(w){return unescape(encodeURIComponent(w)).length}function u(w,y,m){const C=[];let b;for(;(b=w.exec(m))!==null;)C.push({data:b[0],index:b.index,mode:y,length:b[0].length});return C}function f(w){const y=u(i.NUMERIC,t.NUMERIC,w),m=u(i.ALPHANUMERIC,t.ALPHANUMERIC,w);let C,b;return a.isKanjiModeEnabled()?(C=u(i.BYTE,t.BYTE,w),b=u(i.KANJI,t.KANJI,w)):(C=u(i.BYTE_KANJI,t.BYTE,w),b=[]),y.concat(m,C,b).sort(function(I,R){return I.index-R.index}).map(function(I){return{data:I.data,mode:I.mode,length:I.length}})}function p(w,y){switch(y){case t.NUMERIC:return r.getBitsLength(w);case t.ALPHANUMERIC:return n.getBitsLength(w);case t.KANJI:return s.getBitsLength(w);case t.BYTE:return o.getBitsLength(w)}}function h(w){return w.reduce(function(y,m){const C=y.length-1>=0?y[y.length-1]:null;return C&&C.mode===m.mode?(y[y.length-1].data+=m.data,y):(y.push(m),y)},[])}function g(w){const y=[];for(let m=0;m<w.length;m++){const C=w[m];switch(C.mode){case t.NUMERIC:y.push([C,{data:C.data,mode:t.ALPHANUMERIC,length:C.length},{data:C.data,mode:t.BYTE,length:C.length}]);break;case t.ALPHANUMERIC:y.push([C,{data:C.data,mode:t.BYTE,length:C.length}]);break;case t.KANJI:y.push([C,{data:C.data,mode:t.BYTE,length:c(C.data)}]);break;case t.BYTE:y.push([{data:C.data,mode:t.BYTE,length:c(C.data)}])}}return y}function v(w,y){const m={},C={start:{}};let b=["start"];for(let T=0;T<w.length;T++){const I=w[T],R=[];for(let S=0;S<I.length;S++){const j=I[S],N=""+T+S;R.push(N),m[N]={node:j,lastCount:0},C[N]={};for(let L=0;L<b.length;L++){const z=b[L];m[z]&&m[z].node.mode===j.mode?(C[z][N]=p(m[z].lastCount+j.length,j.mode)-p(m[z].lastCount,j.mode),m[z].lastCount+=j.length):(m[z]&&(m[z].lastCount=j.length),C[z][N]=p(j.length,j.mode)+4+t.getCharCountIndicator(j.mode,y))}}b=R}for(let T=0;T<b.length;T++)C[b[T]].end=0;return{map:C,table:m}}function _(w,y){let m;const C=t.getBestModeForData(w);if(m=t.from(y,C),m!==t.BYTE&&m.bit<C.bit)throw new Error('"'+w+'" cannot be encoded with mode '+t.toString(m)+`.
132
+ Suggested mode is: `+t.toString(C));switch(m===t.KANJI&&!a.isKanjiModeEnabled()&&(m=t.BYTE),m){case t.NUMERIC:return new r(w);case t.ALPHANUMERIC:return new n(w);case t.KANJI:return new s(w);case t.BYTE:return new o(w)}}e.fromArray=function(y){return y.reduce(function(m,C){return typeof C=="string"?m.push(_(C,null)):C.data&&m.push(_(C.data,C.mode)),m},[])},e.fromString=function(y,m){const C=f(y,a.isKanjiModeEnabled()),b=g(C),T=v(b,m),I=l.find_path(T.map,"start","end"),R=[];for(let S=1;S<I.length-1;S++)R.push(T.table[I[S]].node);return e.fromArray(h(R))},e.rawSplit=function(y){return e.fromArray(f(y,a.isKanjiModeEnabled()))}})(Xu)),Xu}var Xy;function HE(){if(Xy)return Du;Xy=1;const e=Jn(),t=zu(),r=RE(),n=PE(),o=ME(),s=NE(),i=OE(),a=qy(),l=LE(),c=jE(),u=DE(),f=Wn(),p=BE();function h(T,I){const R=T.size,S=s.getPositions(I);for(let j=0;j<S.length;j++){const N=S[j][0],L=S[j][1];for(let z=-1;z<=7;z++)if(!(N+z<=-1||R<=N+z))for(let B=-1;B<=7;B++)L+B<=-1||R<=L+B||(z>=0&&z<=6&&(B===0||B===6)||B>=0&&B<=6&&(z===0||z===6)||z>=2&&z<=4&&B>=2&&B<=4?T.set(N+z,L+B,!0,!0):T.set(N+z,L+B,!1,!0))}}function g(T){const I=T.size;for(let R=8;R<I-8;R++){const S=R%2===0;T.set(R,6,S,!0),T.set(6,R,S,!0)}}function v(T,I){const R=o.getPositions(I);for(let S=0;S<R.length;S++){const j=R[S][0],N=R[S][1];for(let L=-2;L<=2;L++)for(let z=-2;z<=2;z++)L===-2||L===2||z===-2||z===2||L===0&&z===0?T.set(j+L,N+z,!0,!0):T.set(j+L,N+z,!1,!0)}}function _(T,I){const R=T.size,S=c.getEncodedBits(I);let j,N,L;for(let z=0;z<18;z++)j=Math.floor(z/3),N=z%3+R-8-3,L=(S>>z&1)===1,T.set(j,N,L,!0),T.set(N,j,L,!0)}function w(T,I,R){const S=T.size,j=u.getEncodedBits(I,R);let N,L;for(N=0;N<15;N++)L=(j>>N&1)===1,N<6?T.set(N,8,L,!0):N<8?T.set(N+1,8,L,!0):T.set(S-15+N,8,L,!0),N<8?T.set(8,S-N-1,L,!0):N<9?T.set(8,15-N-1+1,L,!0):T.set(8,15-N-1,L,!0);T.set(S-8,8,1,!0)}function y(T,I){const R=T.size;let S=-1,j=R-1,N=7,L=0;for(let z=R-1;z>0;z-=2)for(z===6&&z--;;){for(let B=0;B<2;B++)if(!T.isReserved(j,z-B)){let X=!1;L<I.length&&(X=(I[L]>>>N&1)===1),T.set(j,z-B,X),N--,N===-1&&(L++,N=7)}if(j+=S,j<0||R<=j){j-=S,S=-S;break}}}function m(T,I,R){const S=new r;R.forEach(function(B){S.put(B.mode.bit,4),S.put(B.getLength(),f.getCharCountIndicator(B.mode,T)),B.write(S)});const j=e.getSymbolTotalCodewords(T),N=a.getTotalCodewordsCount(T,I),L=(j-N)*8;for(S.getLengthInBits()+4<=L&&S.put(0,4);S.getLengthInBits()%8!==0;)S.putBit(0);const z=(L-S.getLengthInBits())/8;for(let B=0;B<z;B++)S.put(B%2?17:236,8);return C(S,T,I)}function C(T,I,R){const S=e.getSymbolTotalCodewords(I),j=a.getTotalCodewordsCount(I,R),N=S-j,L=a.getBlocksCount(I,R),z=S%L,B=L-z,X=Math.floor(S/L),ee=Math.floor(N/L),Q=ee+1,Z=X-ee,ne=new l(Z);let D=0;const E=new Array(L),U=new Array(L);let F=0;const x=new Uint8Array(T.buffer);for(let _e=0;_e<L;_e++){const W=_e<B?ee:Q;E[_e]=x.slice(D,D+W),U[_e]=ne.encode(E[_e]),D+=W,F=Math.max(F,W)}const M=new Uint8Array(S);let H=0,re,te;for(re=0;re<F;re++)for(te=0;te<L;te++)re<E[te].length&&(M[H++]=E[te][re]);for(re=0;re<Z;re++)for(te=0;te<L;te++)M[H++]=U[te][re];return M}function b(T,I,R,S){let j;if(Array.isArray(T))j=p.fromArray(T);else if(typeof T=="string"){let X=I;if(!X){const ee=p.rawSplit(T);X=c.getBestVersionForData(ee,R)}j=p.fromString(T,X||40)}else throw new Error("Invalid data");const N=c.getBestVersionForData(j,R);if(!N)throw new Error("The amount of data is too big to be stored in a QR Code");if(!I)I=N;else if(I<N)throw new Error(`
133
133
  The chosen QR Code version cannot contain this amount of data.
134
134
  Minimum version required to store current data is: `+N+`.
135
- `);const L=m(I,R,j),z=e.getSymbolSize(I),B=new n(z);return h(B,I),g(B),v(B,I),w(B,R,0),I>=7&&_(B,I),y(B,L),isNaN(S)&&(S=i.getBestMask(B,w.bind(null,B,R))),i.applyMask(S,B),w(B,R,S),{modules:B,version:I,errorCorrectionLevel:R,maskPattern:S,segments:j}}return Lu.create=function(I,R){if(typeof I>"u"||I==="")throw new Error("No input text");let S=t.M,j,N;return typeof R<"u"&&(S=t.from(R.errorCorrectionLevel,t.M),j=c.from(R.version),N=i.from(R.maskPattern),R.toSJISFunc&&e.setToSJISFunction(R.toSJISFunc)),b(I,j,S,N)},Lu}var nd={},od={},Xy;function ev(){return Xy||(Xy=1,(function(e){function t(r){if(typeof r=="number"&&(r=r.toString()),typeof r!="string")throw new Error("Color should be defined as hex string");let n=r.slice().replace("#","").split("");if(n.length<3||n.length===5||n.length>8)throw new Error("Invalid hex color: "+r);(n.length===3||n.length===4)&&(n=Array.prototype.concat.apply([],n.map(function(s){return[s,s]}))),n.length===6&&n.push("F","F");const o=parseInt(n.join(""),16);return{r:o>>24&255,g:o>>16&255,b:o>>8&255,a:o&255,hex:"#"+n.slice(0,6).join("")}}e.getOptions=function(n){n||(n={}),n.color||(n.color={});const o=typeof n.margin>"u"||n.margin===null||n.margin<0?4:n.margin,s=n.width&&n.width>=21?n.width:void 0,i=n.scale||4;return{width:s,scale:s?4:i,margin:o,color:{dark:t(n.color.dark||"#000000ff"),light:t(n.color.light||"#ffffffff")},type:n.type,rendererOpts:n.rendererOpts||{}}},e.getScale=function(n,o){return o.width&&o.width>=n+o.margin*2?o.width/(n+o.margin*2):o.scale},e.getImageWidth=function(n,o){const s=e.getScale(n,o);return Math.floor((n+o.margin*2)*s)},e.qrToImageData=function(n,o,s){const i=o.modules.size,a=o.modules.data,l=e.getScale(i,s),c=Math.floor((i+s.margin*2)*l),u=s.margin*l,f=[s.color.light,s.color.dark];for(let p=0;p<c;p++)for(let h=0;h<c;h++){let g=(p*c+h)*4,v=s.color.light;if(p>=u&&h>=u&&p<c-u&&h<c-u){const _=Math.floor((p-u)/l),w=Math.floor((h-u)/l);v=f[a[_*i+w]?1:0]}n[g++]=v.r,n[g++]=v.g,n[g++]=v.b,n[g]=v.a}}})(od)),od}var tv;function ZE(){return tv||(tv=1,(function(e){const t=ev();function r(o,s,i){o.clearRect(0,0,s.width,s.height),s.style||(s.style={}),s.height=i,s.width=i,s.style.height=i+"px",s.style.width=i+"px"}function n(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}e.render=function(s,i,a){let l=a,c=i;typeof l>"u"&&(!i||!i.getContext)&&(l=i,i=void 0),i||(c=n()),l=t.getOptions(l);const u=t.getImageWidth(s.modules.size,l),f=c.getContext("2d"),p=f.createImageData(u,u);return t.qrToImageData(p.data,s,l),r(f,c,u),f.putImageData(p,0,0),c},e.renderToDataURL=function(s,i,a){let l=a;typeof l>"u"&&(!i||!i.getContext)&&(l=i,i=void 0),l||(l={});const c=e.render(s,i,l),u=l.type||"image/png",f=l.rendererOpts||{};return c.toDataURL(u,f.quality)}})(nd)),nd}var sd={},rv;function BE(){if(rv)return sd;rv=1;const e=ev();function t(o,s){const i=o.a/255,a=s+'="'+o.hex+'"';return i<1?a+" "+s+'-opacity="'+i.toFixed(2).slice(1)+'"':a}function r(o,s,i){let a=o+s;return typeof i<"u"&&(a+=" "+i),a}function n(o,s,i){let a="",l=0,c=!1,u=0;for(let f=0;f<o.length;f++){const p=Math.floor(f%s),h=Math.floor(f/s);!p&&!c&&(c=!0),o[f]?(u++,f>0&&p>0&&o[f-1]||(a+=c?r("M",p+i,.5+h+i):r("m",l,0),l=0,c=!1),p+1<s&&o[f+1]||(a+=r("h",u),u=0)):l++}return a}return sd.render=function(s,i,a){const l=e.getOptions(i),c=s.modules.size,u=s.modules.data,f=c+l.margin*2,p=l.color.light.a?"<path "+t(l.color.light,"fill")+' d="M0 0h'+f+"v"+f+'H0z"/>':"",h="<path "+t(l.color.dark,"stroke")+' d="'+n(u,c,l.margin)+'"/>',g='viewBox="0 0 '+f+" "+f+'"',_='<svg xmlns="http://www.w3.org/2000/svg" '+(l.width?'width="'+l.width+'" height="'+l.width+'" ':"")+g+' shape-rendering="crispEdges">'+p+h+`</svg>
136
- `;return typeof a=="function"&&a(null,_),_},sd}var nv;function HE(){if(nv)return xo;nv=1;const e=IE(),t=VE(),r=ZE(),n=BE();function o(s,i,a,l,c){const u=[].slice.call(arguments,1),f=u.length,p=typeof u[f-1]=="function";if(!p&&!e())throw new Error("Callback required as last argument");if(p){if(f<2)throw new Error("Too few arguments provided");f===2?(c=a,a=i,i=l=void 0):f===3&&(i.getContext&&typeof c>"u"?(c=l,l=void 0):(c=l,l=a,a=i,i=void 0))}else{if(f<1)throw new Error("Too few arguments provided");return f===1?(a=i,i=l=void 0):f===2&&!i.getContext&&(l=a,a=i,i=void 0),new Promise(function(h,g){try{const v=t.create(a,l);h(s(v,i,l))}catch(v){g(v)}})}try{const h=t.create(a,l);c(null,s(h,i,l))}catch(h){c(h)}}return xo.create=t.create,xo.toCanvas=o.bind(null,r.render),xo.toDataURL=o.bind(null,r.renderToDataURL),xo.toString=o.bind(null,function(s,i,a){return n.render(s,a)}),xo}var JE=HE();const ov=$l(JE);class sv{constructor(t,{size:r=200,margin:n=4,color:o="#000",bgColor:s="#fff"}){this.value=t,this.size=r,this.margin=n,this.color=o,this.bgColor=s}get qrCodeOption(){return{width:this.size,margin:this.margin,color:{dark:this.color,light:this.bgColor}}}async toDataURL(){return ov.toDataURL(this.value,this.qrCodeOption)}async toCanvas(t){return ov.toCanvas(t,this.value,this.qrCodeOption)}async toImage(t){t.src=await this.toDataURL()}}const GE={content:"",placement:"top",trigger:"hover",delay:150,hideDelay:150,container:document.body,className:"tiny-remoter-native-tooltip"};class WE{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={...GE,...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=`
135
+ `);const L=m(I,R,j),z=e.getSymbolSize(I),B=new n(z);return h(B,I),g(B),v(B,I),w(B,R,0),I>=7&&_(B,I),y(B,L),isNaN(S)&&(S=i.getBestMask(B,w.bind(null,B,R))),i.applyMask(S,B),w(B,R,S),{modules:B,version:I,errorCorrectionLevel:R,maskPattern:S,segments:j}}return Du.create=function(I,R){if(typeof I>"u"||I==="")throw new Error("No input text");let S=t.M,j,N;return typeof R<"u"&&(S=t.from(R.errorCorrectionLevel,t.M),j=c.from(R.version),N=i.from(R.maskPattern),R.toSJISFunc&&e.setToSJISFunction(R.toSJISFunc)),b(I,j,S,N)},Du}var sd={},ad={},ev;function tv(){return ev||(ev=1,(function(e){function t(r){if(typeof r=="number"&&(r=r.toString()),typeof r!="string")throw new Error("Color should be defined as hex string");let n=r.slice().replace("#","").split("");if(n.length<3||n.length===5||n.length>8)throw new Error("Invalid hex color: "+r);(n.length===3||n.length===4)&&(n=Array.prototype.concat.apply([],n.map(function(s){return[s,s]}))),n.length===6&&n.push("F","F");const o=parseInt(n.join(""),16);return{r:o>>24&255,g:o>>16&255,b:o>>8&255,a:o&255,hex:"#"+n.slice(0,6).join("")}}e.getOptions=function(n){n||(n={}),n.color||(n.color={});const o=typeof n.margin>"u"||n.margin===null||n.margin<0?4:n.margin,s=n.width&&n.width>=21?n.width:void 0,i=n.scale||4;return{width:s,scale:s?4:i,margin:o,color:{dark:t(n.color.dark||"#000000ff"),light:t(n.color.light||"#ffffffff")},type:n.type,rendererOpts:n.rendererOpts||{}}},e.getScale=function(n,o){return o.width&&o.width>=n+o.margin*2?o.width/(n+o.margin*2):o.scale},e.getImageWidth=function(n,o){const s=e.getScale(n,o);return Math.floor((n+o.margin*2)*s)},e.qrToImageData=function(n,o,s){const i=o.modules.size,a=o.modules.data,l=e.getScale(i,s),c=Math.floor((i+s.margin*2)*l),u=s.margin*l,f=[s.color.light,s.color.dark];for(let p=0;p<c;p++)for(let h=0;h<c;h++){let g=(p*c+h)*4,v=s.color.light;if(p>=u&&h>=u&&p<c-u&&h<c-u){const _=Math.floor((p-u)/l),w=Math.floor((h-u)/l);v=f[a[_*i+w]?1:0]}n[g++]=v.r,n[g++]=v.g,n[g++]=v.b,n[g]=v.a}}})(ad)),ad}var rv;function JE(){return rv||(rv=1,(function(e){const t=tv();function r(o,s,i){o.clearRect(0,0,s.width,s.height),s.style||(s.style={}),s.height=i,s.width=i,s.style.height=i+"px",s.style.width=i+"px"}function n(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}e.render=function(s,i,a){let l=a,c=i;typeof l>"u"&&(!i||!i.getContext)&&(l=i,i=void 0),i||(c=n()),l=t.getOptions(l);const u=t.getImageWidth(s.modules.size,l),f=c.getContext("2d"),p=f.createImageData(u,u);return t.qrToImageData(p.data,s,l),r(f,c,u),f.putImageData(p,0,0),c},e.renderToDataURL=function(s,i,a){let l=a;typeof l>"u"&&(!i||!i.getContext)&&(l=i,i=void 0),l||(l={});const c=e.render(s,i,l),u=l.type||"image/png",f=l.rendererOpts||{};return c.toDataURL(u,f.quality)}})(sd)),sd}var id={},nv;function WE(){if(nv)return id;nv=1;const e=tv();function t(o,s){const i=o.a/255,a=s+'="'+o.hex+'"';return i<1?a+" "+s+'-opacity="'+i.toFixed(2).slice(1)+'"':a}function r(o,s,i){let a=o+s;return typeof i<"u"&&(a+=" "+i),a}function n(o,s,i){let a="",l=0,c=!1,u=0;for(let f=0;f<o.length;f++){const p=Math.floor(f%s),h=Math.floor(f/s);!p&&!c&&(c=!0),o[f]?(u++,f>0&&p>0&&o[f-1]||(a+=c?r("M",p+i,.5+h+i):r("m",l,0),l=0,c=!1),p+1<s&&o[f+1]||(a+=r("h",u),u=0)):l++}return a}return id.render=function(s,i,a){const l=e.getOptions(i),c=s.modules.size,u=s.modules.data,f=c+l.margin*2,p=l.color.light.a?"<path "+t(l.color.light,"fill")+' d="M0 0h'+f+"v"+f+'H0z"/>':"",h="<path "+t(l.color.dark,"stroke")+' d="'+n(u,c,l.margin)+'"/>',g='viewBox="0 0 '+f+" "+f+'"',_='<svg xmlns="http://www.w3.org/2000/svg" '+(l.width?'width="'+l.width+'" height="'+l.width+'" ':"")+g+' shape-rendering="crispEdges">'+p+h+`</svg>
136
+ `;return typeof a=="function"&&a(null,_),_},id}var ov;function GE(){if(ov)return xo;ov=1;const e=$E(),t=HE(),r=JE(),n=WE();function o(s,i,a,l,c){const u=[].slice.call(arguments,1),f=u.length,p=typeof u[f-1]=="function";if(!p&&!e())throw new Error("Callback required as last argument");if(p){if(f<2)throw new Error("Too few arguments provided");f===2?(c=a,a=i,i=l=void 0):f===3&&(i.getContext&&typeof c>"u"?(c=l,l=void 0):(c=l,l=a,a=i,i=void 0))}else{if(f<1)throw new Error("Too few arguments provided");return f===1?(a=i,i=l=void 0):f===2&&!i.getContext&&(l=a,a=i,i=void 0),new Promise(function(h,g){try{const v=t.create(a,l);h(s(v,i,l))}catch(v){g(v)}})}try{const h=t.create(a,l);c(null,s(h,i,l))}catch(h){c(h)}}return xo.create=t.create,xo.toCanvas=o.bind(null,r.render),xo.toDataURL=o.bind(null,r.renderToDataURL),xo.toString=o.bind(null,function(s,i,a){return n.render(s,a)}),xo}var KE=GE();const sv=Rl(KE);class av{constructor(t,{size:r=200,margin:n=4,color:o="#000",bgColor:s="#fff"}){this.value=t,this.size=r,this.margin=n,this.color=o,this.bgColor=s}get qrCodeOption(){return{width:this.size,margin:this.margin,color:{dark:this.color,light:this.bgColor}}}async toDataURL(){return sv.toDataURL(this.value,this.qrCodeOption)}async toCanvas(t){return sv.toCanvas(t,this.value,this.qrCodeOption)}async toImage(t){t.src=await this.toDataURL()}}const YE={content:"",placement:"top",trigger:"hover",delay:150,hideDelay:150,container:document.body,className:"tiny-remoter-native-tooltip"};class QE{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={...YE,...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
137
  <div class="${this.opts.className}__arrow"></div>
138
138
  <div class="${this.opts.className}__inner">${t}</div>
139
- `}reposition(){const t=this.placementList(this.opts.placement);for(const r of t){const n=this.calcStyle(r);if(this.checkViewport(n)){this.applyStyle(n),this.tip.className=`${this.opts.className} ${this.opts.className}--${r}`;return}}this.applyStyle(this.calcStyle("top"))}calcStyle(t){const r=this.el.getBoundingClientRect(),n=this.tip.getBoundingClientRect(),o=window.pageYOffset||document.documentElement.scrollTop,s=window.pageXOffset||document.documentElement.scrollLeft,i=6,[a,l="center"]=t.split("-");let c=0,u=0;return a==="top"?c=r.top+o-n.height-i:a==="bottom"?c=r.bottom+o+i:a==="left"?u=r.left+s-n.width-i:a==="right"&&(u=r.right+s+i),(a==="top"||a==="bottom")&&(l==="start"?u=r.left+s:l==="end"?u=r.right+s-n.width:u=(r.left+r.right)/2+s-n.width/2),(a==="left"||a==="right")&&(l==="start"?c=r.top+o:l==="end"?c=r.bottom+o-n.height:c=(r.top+r.bottom)/2+o-n.height/2),{top:Math.round(c),left:Math.round(u)}}applyStyle({top:t,left:r}){Object.assign(this.tip.style,{position:"absolute",top:`${t}px`,left:`${r}px`})}checkViewport({top:t,left:r}){const o=window.innerWidth,s=window.innerHeight,i=this.tip.getBoundingClientRect();return r>=5&&t>=5&&r+i.width<=o-5&&t+i.height<=s-5}placementList(t){const r={top:["top","bottom","top-start","bottom-start","top-end","bottom-end"],bottom:["bottom","top","bottom-start","top-start","bottom-end","top-end"],left:["left","right","left-start","right-start","left-end","right-end"],right:["right","left","right-start","left-start","right-end","left-end"]};return r[t.split("-")[0]]||r.top}attachExtraEvents(){this.opts.trigger==="click"?(this.clickOutside=t=>{const r=t.composedPath();!r.includes(this.el)&&!r.includes(this.tip)&&this.close()},document.addEventListener("mousedown",this.clickOutside)):this.opts.trigger==="hover"&&(this.tip.addEventListener("mouseenter",()=>this.clearTimer()),this.tip.addEventListener("mouseleave",()=>this.close()))}detachExtraEvents(){this.clickOutside&&(document.removeEventListener("mousedown",this.clickOutside),this.clickOutside=null)}clearTimer(){clearTimeout(this.showTimer),clearTimeout(this.hideTimer)}isShown(){return!!this.tip?.parentNode}}const av="tiny-remoter-native-tooltip-style";(()=>{if(document.getElementById(av))return;const e=document.createElement("style");e.id=av,e.textContent=`
139
+ `}reposition(){const t=this.placementList(this.opts.placement);for(const r of t){const n=this.calcStyle(r);if(this.checkViewport(n)){this.applyStyle(n),this.tip.className=`${this.opts.className} ${this.opts.className}--${r}`;return}}this.applyStyle(this.calcStyle("top"))}calcStyle(t){const r=this.el.getBoundingClientRect(),n=this.tip.getBoundingClientRect(),o=window.pageYOffset||document.documentElement.scrollTop,s=window.pageXOffset||document.documentElement.scrollLeft,i=6,[a,l="center"]=t.split("-");let c=0,u=0;return a==="top"?c=r.top+o-n.height-i:a==="bottom"?c=r.bottom+o+i:a==="left"?u=r.left+s-n.width-i:a==="right"&&(u=r.right+s+i),(a==="top"||a==="bottom")&&(l==="start"?u=r.left+s:l==="end"?u=r.right+s-n.width:u=(r.left+r.right)/2+s-n.width/2),(a==="left"||a==="right")&&(l==="start"?c=r.top+o:l==="end"?c=r.bottom+o-n.height:c=(r.top+r.bottom)/2+o-n.height/2),{top:Math.round(c),left:Math.round(u)}}applyStyle({top:t,left:r}){Object.assign(this.tip.style,{position:"absolute",top:`${t}px`,left:`${r}px`})}checkViewport({top:t,left:r}){const o=window.innerWidth,s=window.innerHeight,i=this.tip.getBoundingClientRect();return r>=5&&t>=5&&r+i.width<=o-5&&t+i.height<=s-5}placementList(t){const r={top:["top","bottom","top-start","bottom-start","top-end","bottom-end"],bottom:["bottom","top","bottom-start","top-start","bottom-end","top-end"],left:["left","right","left-start","right-start","left-end","right-end"],right:["right","left","right-start","left-start","right-end","left-end"]};return r[t.split("-")[0]]||r.top}attachExtraEvents(){this.opts.trigger==="click"?(this.clickOutside=t=>{const r=t.composedPath();!r.includes(this.el)&&!r.includes(this.tip)&&this.close()},document.addEventListener("mousedown",this.clickOutside)):this.opts.trigger==="hover"&&(this.tip.addEventListener("mouseenter",()=>this.clearTimer()),this.tip.addEventListener("mouseleave",()=>this.close()))}detachExtraEvents(){this.clickOutside&&(document.removeEventListener("mousedown",this.clickOutside),this.clickOutside=null)}clearTimer(){clearTimeout(this.showTimer),clearTimeout(this.hideTimer)}isShown(){return!!this.tip?.parentNode}}const iv="tiny-remoter-native-tooltip-style";(()=>{if(document.getElementById(iv))return;const e=document.createElement("style");e.id=iv,e.textContent=`
140
140
  .tiny-remoter-native-tooltip {
141
141
  position: absolute;
142
142
  z-index: 9999;
@@ -183,7 +183,7 @@ Minimum version required to store current data is: `+N+`.
183
183
  transform: translateY(-50%);
184
184
  border-right-color: rgba(0,0,0,.75);
185
185
  }
186
- `,document.head.appendChild(e)})();const iv="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",lv="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",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_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",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_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",KE="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",YE="https://chat.opentiny.design",QE="https://ai.opentiny.design/next-remoter",XE="https://ai.opentiny.design/next-remoter/svgs/logo-next-no-bg-left.svg",e$=e=>{const t=!!e.sessionId;return[{action:"qr-code",show:t,text:"扫码登录",desc:"使用手机遥控页面",icon:uv},{action:"ai-chat",show:!0,text:"打开对话框",desc:"支持在网页端操作AI",icon:iv},{action:"remote-url",show:t,text:"遥控器链接",desc:`${e.remoteUrl}`,active:!0,tip:e.remoteUrl,showCopyIcon:!0,icon:cv},{action:"remote-control",show:t,text:"识别码",desc:t?`${e.sessionId.slice(-6)}`:"",know:!0,showCopyIcon:!0,icon:lv}]};class t${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 WE(n,{content:"复制",placement:"top",trigger:"hover"})},this.options={...t,qrCodeUrl:t.qrCodeUrl||QE,remoteUrl:t.remoteUrl||YE,logoUrl:t.logoUrl||XE},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":uv,"ai-chat":iv,"remote-url":cv,"remote-control":lv};return t?t.map(n=>({...n,icon:n.icon??r[n.action]})):this.options.sessionId?e$(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=`
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=`
187
187
  <div class="tiny-remoter-floating-block__icon">
188
188
  <img style="display: block; width: 56px;" src="${this.options.logoUrl}" alt="icon" />
189
189
  </div>
@@ -198,14 +198,14 @@ Minimum version required to store current data is: `+N+`.
198
198
  <div>
199
199
  ${r.showCopyIcon?`
200
200
  <div class="tiny-remoter-copy-icon" id="${r.action}" data-action="${r.action}">
201
- <img src="${KE}"/>
201
+ <img src="${XE}"/>
202
202
  </div>
203
203
  `:""}
204
204
  </div>
205
205
  </div>
206
206
  </div>
207
207
  </div>
208
- `).join("");this.dropdownMenu.innerHTML=t,document.body.appendChild(this.dropdownMenu),this.renderItem(),this.readyTips("remote-control"),this.readyTips("remote-url")}bindEvents(){this.floatingBlock.addEventListener("click",()=>{this.showAIChat()}),this.floatingBlock.addEventListener("mouseenter",()=>{this.openDropdown(),this.closingTimer&&(window.clearTimeout(this.closingTimer),this.closingTimer=0)}),this.floatingBlock.addEventListener("mouseleave",()=>{this.shouldCloseDropdown()}),this.dropdownMenu.addEventListener("mouseenter",t=>{this.closingTimer&&(window.clearTimeout(this.closingTimer),this.closingTimer=0)}),this.dropdownMenu.addEventListener("mouseleave",t=>{this.shouldCloseDropdown()}),this.dropdownMenu.addEventListener("click",t=>{const r=t.target,n=r.closest(".tiny-remoter-copy-icon");if(n){t.stopPropagation();const i=n.dataset.action;i&&this.handleAction(i);return}const s=r.closest(".tiny-remoter-dropdown-item")?.dataset.action;s&&this.handleAction(s)}),document.addEventListener("click",t=>{const r=t.target;!this.floatingBlock.contains(r)&&!this.dropdownMenu.contains(r)&&this.closeDropdown()}),document.addEventListener("keydown",t=>{t.key==="Escape"&&this.closeDropdown()})}openDropdown(){!this.menuItems||this.menuItems&&this.menuItems.length===0||(this.isExpanded=!0,this.floatingBlock.classList.add("expanded"),this.dropdownMenu.classList.add("show"))}shouldCloseDropdown(){this.closingTimer=window.setTimeout(()=>{this.closeDropdown()},300)}closeDropdown(){this.isExpanded=!1,this.floatingBlock.classList.remove("expanded"),this.dropdownMenu.classList.remove("show")}handleAction(t){switch(t){case"qr-code":this.showQRCode();break;case"ai-chat":this.showAIChat();break;case"remote-control":this.copyRemoteControl();break;case"remote-url":this.copyRemoteURL();break}this.closeDropdown()}copyRemoteControl(){const t=this.menuItems.find(n=>n.action==="remote-control"),r=t?.desc||t?.text||(this.options.sessionId?this.options.sessionId.slice(-6):"");r&&this.copyToClipboard(r)}copyRemoteURL(){const t=this.menuItems.find(s=>s.action==="remote-url"),r=this.options.sessionId?this.options.remoteUrl+this.sessionPrefix+this.options.sessionId:"",o=(t?.desc&&t.desc!==this.options.remoteUrl?t.desc:void 0)||r||t?.text||"";o&&this.copyToClipboard(o)}async copyToClipboard(t){try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(t),this.showCopyFeedback(!0);else{const r=document.createElement("textarea");r.value=t,r.style.position="fixed",r.style.left="-999999px",r.style.top="-999999px",document.body.appendChild(r),r.focus(),r.select();const n=document.execCommand("copy");document.body.removeChild(r),n?this.showCopyFeedback(!0):this.showCopyFeedback(!1)}}catch(r){console.error("复制失败:",r),this.showCopyFeedback(!1)}}showCopyFeedback(t){const r=t?"复制成功!":"复制失败,请手动复制",n=document.createElement("div");n.className=`tiny-remoter-copy-feedback ${t?"success":"error"}`,n.textContent=r,document.body.appendChild(n),setTimeout(()=>n.classList.add("show"),10),setTimeout(()=>{n.classList.remove("show"),setTimeout(()=>{n.parentNode&&n.parentNode.removeChild(n)},300)},1500)}async showQRCode(){if(!this.options.sessionId)return;const r=await new sv((this.options.qrCodeUrl||"")+this.sessionPrefix+this.options.sessionId,{}).toDataURL(),n=this.createModal("扫码前往智能遥控器",`
208
+ `).join("");this.dropdownMenu.innerHTML=t,document.body.appendChild(this.dropdownMenu),this.renderItem(),this.readyTips("remote-control"),this.readyTips("remote-url")}bindEvents(){this.floatingBlock.addEventListener("click",()=>{this.showAIChat()}),this.floatingBlock.addEventListener("mouseenter",()=>{this.openDropdown(),this.closingTimer&&(window.clearTimeout(this.closingTimer),this.closingTimer=0)}),this.floatingBlock.addEventListener("mouseleave",()=>{this.shouldCloseDropdown()}),this.dropdownMenu.addEventListener("mouseenter",t=>{this.closingTimer&&(window.clearTimeout(this.closingTimer),this.closingTimer=0)}),this.dropdownMenu.addEventListener("mouseleave",t=>{this.shouldCloseDropdown()}),this.dropdownMenu.addEventListener("click",t=>{const r=t.target,n=r.closest(".tiny-remoter-copy-icon");if(n){t.stopPropagation();const i=n.dataset.action;i&&this.handleAction(i);return}const s=r.closest(".tiny-remoter-dropdown-item")?.dataset.action;s&&this.handleAction(s)}),document.addEventListener("click",t=>{const r=t.target;!this.floatingBlock.contains(r)&&!this.dropdownMenu.contains(r)&&this.closeDropdown()}),document.addEventListener("keydown",t=>{t.key==="Escape"&&this.closeDropdown()})}openDropdown(){!this.menuItems||this.menuItems&&this.menuItems.length===0||(this.isExpanded=!0,this.floatingBlock.classList.add("expanded"),this.dropdownMenu.classList.add("show"))}shouldCloseDropdown(){this.closingTimer=window.setTimeout(()=>{this.closeDropdown()},300)}closeDropdown(){this.isExpanded=!1,this.floatingBlock.classList.remove("expanded"),this.dropdownMenu.classList.remove("show")}handleAction(t){switch(t){case"qr-code":this.showQRCode();break;case"ai-chat":this.showAIChat();break;case"remote-control":this.copyRemoteControl();break;case"remote-url":this.copyRemoteURL();break}this.closeDropdown()}copyRemoteControl(){const t=this.menuItems.find(n=>n.action==="remote-control"),r=t?.desc||t?.text||(this.options.sessionId?this.options.sessionId.slice(-6):"");r&&this.copyToClipboard(r)}copyRemoteURL(){const t=this.menuItems.find(s=>s.action==="remote-url"),r=this.options.sessionId?this.options.remoteUrl+this.sessionPrefix+this.options.sessionId:"",o=(t?.desc&&t.desc!==this.options.remoteUrl?t.desc:void 0)||r||t?.text||"";o&&this.copyToClipboard(o)}async copyToClipboard(t){try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(t),this.showCopyFeedback(!0);else{const r=document.createElement("textarea");r.value=t,r.style.position="fixed",r.style.left="-999999px",r.style.top="-999999px",document.body.appendChild(r),r.focus(),r.select();const n=document.execCommand("copy");document.body.removeChild(r),n?this.showCopyFeedback(!0):this.showCopyFeedback(!1)}}catch(r){console.error("复制失败:",r),this.showCopyFeedback(!1)}}showCopyFeedback(t){const r=t?"复制成功!":"复制失败,请手动复制",n=document.createElement("div");n.className=`tiny-remoter-copy-feedback ${t?"success":"error"}`,n.textContent=r,document.body.appendChild(n),setTimeout(()=>n.classList.add("show"),10),setTimeout(()=>{n.classList.remove("show"),setTimeout(()=>{n.parentNode&&n.parentNode.removeChild(n)},300)},1500)}async showQRCode(){if(!this.options.sessionId)return;const r=await new av((this.options.qrCodeUrl||"")+this.sessionPrefix+this.options.sessionId,{}).toDataURL(),n=this.createModal("扫码前往智能遥控器",`
209
209
  <div style="text-align: center; padding: 32px;">
210
210
  <!-- 二维码容器 - 添加渐变背景和阴影效果 -->
211
211
  <div style="
@@ -631,4 +631,4 @@ Minimum version required to store current data is: `+N+`.
631
631
  color: white;
632
632
  }
633
633
  }
634
- `,document.head.appendChild(t)}destroy(){this.floatingBlock.parentNode&&this.floatingBlock.parentNode.removeChild(this.floatingBlock),this.dropdownMenu.parentNode&&this.dropdownMenu.parentNode.removeChild(this.dropdownMenu)}hide(){this.floatingBlock&&(this.floatingBlock.style.display="none"),this.closeDropdown()}show(){this.floatingBlock&&(this.floatingBlock.style.display="flex")}}const r$=(e={})=>new t$(e);Ur.AgentModelProvider=SE,Ur.QrCode=sv,Ur.createRemoter=r$,Ur.getAISDKTools=Cy,Object.defineProperty(Ur,Symbol.toStringTag,{value:"Module"})}));
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 s$=(e={})=>new o$(e);Ur.AgentModelProvider=EE,Ur.QrCode=av,Ur.createRemoter=s$,Ur.getAISDKTools=Sy,Object.defineProperty(Ur,Symbol.toStringTag,{value:"Module"})}));