@opentiny/next-sdk 0.1.12 → 0.1.14
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/agent/AgentModelProvider.ts +48 -16
- package/agent/type.ts +23 -14
- package/dist/WebMcpClient.d.ts +24 -360
- package/dist/agent/AgentModelProvider.d.ts +3 -2
- package/dist/agent/AgentModelProvider.js +41 -19
- package/dist/agent/type.d.ts +21 -15
- package/dist/index.d.ts +1 -0
- package/dist/index.es.dev.js +2448 -3251
- package/dist/index.es.js +10487 -11174
- package/dist/index.js +1 -0
- package/dist/index.umd.dev.js +2447 -3250
- package/dist/index.umd.js +47 -43
- package/dist/{mcpsdk@1.20.1.dev.js → mcpsdk@1.17.0.dev.js} +1281 -1453
- package/dist/{mcpsdk@1.20.1.es.dev.js → mcpsdk@1.17.0.es.dev.js} +1283 -1455
- package/dist/{mcpsdk@1.20.1.es.js → mcpsdk@1.17.0.es.js} +4045 -4140
- package/dist/mcpsdk@1.17.0.js +16 -0
- package/dist/webagent.dev.js +11961 -4535
- package/dist/webagent.es.dev.js +11968 -4542
- package/dist/webagent.es.js +17400 -13275
- package/dist/webagent.js +60 -56
- package/dist/webmcp-full.dev.js +451 -584
- package/dist/webmcp-full.es.dev.js +451 -584
- package/dist/webmcp-full.es.js +5985 -6078
- package/dist/webmcp-full.js +13 -13
- package/index.ts +1 -0
- package/package.json +1 -1
- package/dist/mcpsdk@1.20.1.js +0 -16
package/dist/webagent.js
CHANGED
|
@@ -1,77 +1,81 @@
|
|
|
1
|
-
(function(
|
|
2
|
-
Error message: ${yn(
|
|
3
|
-
Error message: ${yn(
|
|
4
|
-
`;break;case"id":i=m.includes("\0")?void 0:m;break;case"retry":/^\d+$/.test(m)?
|
|
5
|
-
`)?l.slice(0,-1):l}),i=void 0,l="",u=""}function f
|
|
6
|
-
`,
|
|
7
|
-
`&&r++}}return[t,n]}class Oo extends TransformStream{constructor({onError:t,onRetry:n,onComment:r}={}){let o;super({start(s){o=yp({onEvent:a=>{s.enqueue(a)},onError(a){t==="terminate"?s.error(a):typeof t=="function"&&t(a)},onRetry:n,onComment:r})},transform(s){o.feed(s)}})}}function E(e,t,n){function r(i,l){var u;Object.defineProperty(i,"_zod",{value:i._zod??{},enumerable:!1}),(u=i._zod).traits??(u.traits=new Set),i._zod.traits.add(e),t(i,l);for(const p in a.prototype)p in i||Object.defineProperty(i,p,{value:a.prototype[p].bind(i)});i._zod.constr=a,i._zod.def=l}const o=(n==null?void 0:n.Parent)??Object;class s extends o{}Object.defineProperty(s,"name",{value:e});function a(i){var l;const u=n!=null&&n.Parent?new s:this;r(u,i),(l=u._zod).deferred??(l.deferred=[]);for(const p of u._zod.deferred)p();return u}return Object.defineProperty(a,"init",{value:r}),Object.defineProperty(a,Symbol.hasInstance,{value:i=>{var l,u;return n!=null&&n.Parent&&i instanceof n.Parent?!0:(u=(l=i==null?void 0:i._zod)==null?void 0:l.traits)==null?void 0:u.has(e)}}),Object.defineProperty(a,"name",{value:e}),a}class Dn extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const ai={};function Ht(e){return ai}function ii(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,o])=>t.indexOf(+r)===-1).map(([r,o])=>o)}function wp(e,t){return typeof t=="bigint"?t.toString():t}function No(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Mo(e){return e==null}function Po(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function bp(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(e.toFixed(o).replace(".","")),a=Number.parseInt(t.toFixed(o).replace(".",""));return s%a/10**o}function pe(e,t,n){Object.defineProperty(e,t,{get(){{const r=n();return e[t]=r,r}},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function Cr(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Un(e){return JSON.stringify(e)}const li=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function Er(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const xp=No(()=>{var e;if(typeof navigator<"u"&&((e=navigator==null?void 0:navigator.userAgent)!=null&&e.includes("Cloudflare")))return!1;try{const t=Function;return new t(""),!0}catch{return!1}});function Rr(e){if(Er(e)===!1)return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(Er(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}const kp=new Set(["string","number","symbol"]);function Zn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function nn(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n!=null&&n.parent)&&(r._zod.parent=e),r}function q(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if((t==null?void 0:t.message)!==void 0){if((t==null?void 0:t.error)!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function Tp(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const Sp={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 Ip(e,t){const n={},r=e._zod.def;for(const o in t){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&(n[o]=r.shape[o])}return nn(e,{...e._zod.def,shape:n,checks:[]})}function Cp(e,t){const n={...e._zod.def.shape},r=e._zod.def;for(const o in t){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&delete n[o]}return nn(e,{...e._zod.def,shape:n,checks:[]})}function Ep(e,t){if(!Rr(t))throw new Error("Invalid input to extend: expected a plain object");const n={...e._zod.def,get shape(){const r={...e._zod.def.shape,...t};return Cr(this,"shape",r),r},checks:[]};return nn(e,n)}function Rp(e,t){return nn(e,{...e._zod.def,get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return Cr(this,"shape",n),n},catchall:t._zod.def.catchall,checks:[]})}function Ap(e,t,n){const r=t._zod.def.shape,o={...r};if(n)for(const s in n){if(!(s in r))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(o[s]=e?new e({type:"optional",innerType:r[s]}):r[s])}else for(const s in r)o[s]=e?new e({type:"optional",innerType:r[s]}):r[s];return nn(t,{...t._zod.def,shape:o,checks:[]})}function Op(e,t,n){const r=t._zod.def.shape,o={...r};if(n)for(const s in n){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(o[s]=new e({type:"nonoptional",innerType:r[s]}))}else for(const s in r)o[s]=new e({type:"nonoptional",innerType:r[s]});return nn(t,{...t._zod.def,shape:o,checks:[]})}function Ln(e,t=0){var n;for(let r=t;r<e.issues.length;r++)if(((n=e.issues[r])==null?void 0:n.continue)!==!0)return!0;return!1}function rn(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function Ar(e){return typeof e=="string"?e:e==null?void 0:e.message}function Jt(e,t,n){var o,s,a,i,l,u;const r={...e,path:e.path??[]};if(!e.message){const p=Ar((a=(s=(o=e.inst)==null?void 0:o._zod.def)==null?void 0:s.error)==null?void 0:a.call(s,e))??Ar((i=t==null?void 0:t.error)==null?void 0:i.call(t,e))??Ar((l=n.customError)==null?void 0:l.call(n,e))??Ar((u=n.localeError)==null?void 0:u.call(n,e))??"Invalid input";r.message=p}return delete r.inst,delete r.continue,t!=null&&t.reportInput||delete r.input,r}function $o(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function qn(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const ui=(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,wp,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},ci=E("$ZodError",ui),di=E("$ZodError",ui,{Parent:Error});function Np(e,t=n=>n.message){const n={},r=[];for(const o of e.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}function Mp(e,t){const n=t||function(s){return s.message},r={_errors:[]},o=s=>{for(const a of s.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(i=>o({issues:i}));else if(a.code==="invalid_key")o({issues:a.issues});else if(a.code==="invalid_element")o({issues:a.issues});else if(a.path.length===0)r._errors.push(n(a));else{let i=r,l=0;for(;l<a.path.length;){const u=a.path[l];l===a.path.length-1?(i[u]=i[u]||{_errors:[]},i[u]._errors.push(n(a))):i[u]=i[u]||{_errors:[]},i=i[u],l++}}};return o(e),r}const Pp=e=>(t,n,r,o)=>{const s=r?Object.assign(r,{async:!1}):{async:!1},a=t._zod.run({value:n,issues:[]},s);if(a instanceof Promise)throw new Dn;if(a.issues.length){const i=new((o==null?void 0:o.Err)??e)(a.issues.map(l=>Jt(l,s,Ht())));throw li(i,o==null?void 0:o.callee),i}return a.value},$p=e=>async(t,n,r,o)=>{const s=r?Object.assign(r,{async:!0}):{async:!0};let a=t._zod.run({value:n,issues:[]},s);if(a instanceof Promise&&(a=await a),a.issues.length){const i=new((o==null?void 0:o.Err)??e)(a.issues.map(l=>Jt(l,s,Ht())));throw li(i,o==null?void 0:o.callee),i}return a.value},pi=e=>(t,n,r)=>{const o=r?{...r,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new Dn;return s.issues.length?{success:!1,error:new(e??ci)(s.issues.map(a=>Jt(a,o,Ht())))}:{success:!0,data:s.value}},zp=pi(di),hi=e=>async(t,n,r)=>{const o=r?Object.assign(r,{async:!0}):{async:!0};let s=t._zod.run({value:n,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(a=>Jt(a,o,Ht())))}:{success:!0,data:s.value}},jp=hi(di),Dp=/^[cC][^\s-]{8,}$/,Up=/^[0-9a-z]+$/,Zp=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Lp=/^[0-9a-vA-V]{20}$/,qp=/^[A-Za-z0-9]{27}$/,Bp=/^[a-zA-Z0-9_-]{21}$/,Vp=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Fp=/^([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})$/,fi=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)$/,Hp=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Jp="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Gp(){return new RegExp(Jp,"u")}const Wp=/^(?:(?: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])$/,Kp=/^(([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})$/,Yp=/^((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])$/,Xp=/^(([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])$/,Qp=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,mi=/^[A-Za-z0-9_-]*$/,eh=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,th=/^\+(?:[0-9]){6,14}[0-9]$/,gi="(?:(?:\\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])))",nh=new RegExp(`^${gi}$`);function vi(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 rh(e){return new RegExp(`^${vi(e)}$`)}function oh(e){const t=vi({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-]\\d{2}:\\d{2})");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${gi}T(?:${r})$`)}const sh=e=>{const t=e?`[\\s\\S]{${(e==null?void 0:e.minimum)??0},${(e==null?void 0:e.maximum)??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},ah=/^\d+$/,ih=/^-?\d+(?:\.\d+)?/i,lh=/true|false/i,uh=/null/i,ch=/^[^A-Z]*$/,dh=/^[^a-z]*$/,Qe=E("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),yi={number:"number",bigint:"bigint",object:"date"},_i=E("$ZodCheckLessThan",(e,t)=>{Qe.init(e,t);const n=yi[typeof t.value];e._zod.onattach.push(r=>{const o=r._zod.bag,s=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),wi=E("$ZodCheckGreaterThan",(e,t)=>{Qe.init(e,t);const n=yi[typeof t.value];e._zod.onattach.push(r=>{const o=r._zod.bag,s=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),ph=E("$ZodCheckMultipleOf",(e,t)=>{Qe.init(e,t),e._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%t.value===BigInt(0):bp(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),hh=E("$ZodCheckNumberFormat",(e,t)=>{var a;Qe.init(e,t),t.format=t.format||"float64";const n=(a=t.format)==null?void 0:a.includes("int"),r=n?"int":"number",[o,s]=Sp[t.format];e._zod.onattach.push(i=>{const l=i._zod.bag;l.format=t.format,l.minimum=o,l.maximum=s,n&&(l.pattern=ah)}),e._zod.check=i=>{const l=i.value;if(n){if(!Number.isInteger(l)){i.issues.push({expected:r,format:t.format,code:"invalid_type",input:l,inst:e});return}if(!Number.isSafeInteger(l)){l>0?i.issues.push({input:l,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,continue:!t.abort}):i.issues.push({input:l,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,continue:!t.abort});return}}l<o&&i.issues.push({origin:"number",input:l,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),l>s&&i.issues.push({origin:"number",input:l,code:"too_big",maximum:s,inst:e})}}),fh=E("$ZodCheckMaxLength",(e,t)=>{var n;Qe.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!Mo(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(r._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{const o=r.value;if(o.length<=t.maximum)return;const a=$o(o);r.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),mh=E("$ZodCheckMinLength",(e,t)=>{var n;Qe.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!Mo(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const o=r.value;if(o.length>=t.minimum)return;const a=$o(o);r.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),gh=E("$ZodCheckLengthEquals",(e,t)=>{var n;Qe.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!Mo(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=r=>{const o=r.value,s=o.length;if(s===t.length)return;const a=$o(o),i=s>t.length;r.issues.push({origin:a,...i?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),Or=E("$ZodCheckStringFormat",(e,t)=>{var n,r;Qe.init(e,t),e._zod.onattach.push(o=>{const s=o._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),vh=E("$ZodCheckRegex",(e,t)=>{Or.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),yh=E("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=ch),Or.init(e,t)}),_h=E("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=dh),Or.init(e,t)}),wh=E("$ZodCheckIncludes",(e,t)=>{Qe.init(e,t);const n=Zn(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(o=>{const s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),bh=E("$ZodCheckStartsWith",(e,t)=>{Qe.init(e,t);const n=new RegExp(`^${Zn(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),xh=E("$ZodCheckEndsWith",(e,t)=>{Qe.init(e,t);const n=new RegExp(`.*${Zn(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),kh=E("$ZodCheckOverwrite",(e,t)=>{Qe.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class Th{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const r=t.split(`
|
|
8
|
-
`).filter(
|
|
9
|
-
`))}}const
|
|
10
|
-
if (${
|
|
1
|
+
(function(gr,gn){typeof exports=="object"&&typeof module<"u"?gn(exports):typeof define=="function"&&define.amd?define(["exports"],gn):(gr=typeof globalThis<"u"?globalThis:gr||self,gn(gr.WebAgent={}))})(this,function(gr){"use strict";var gn="vercel.ai.error",Km=Symbol.for(gn),Yl,Qm=class Jm extends Error{constructor({name:e,message:r,cause:a}){super(r),this[Yl]=!0,this.name=e,this.cause=a}static isInstance(e){return Jm.hasMarker(e,gn)}static hasMarker(e,r){const a=Symbol.for(r);return e!=null&&typeof e=="object"&&a in e&&typeof e[a]=="boolean"&&e[a]===!0}};Yl=Km;var he=Qm,Xl="AI_APICallError",eu=`vercel.ai.error.${Xl}`,Ym=Symbol.for(eu),tu,Ue=class extends he{constructor({message:t,url:e,requestBodyValues:r,statusCode:a,responseHeaders:n,responseBody:s,cause:o,isRetryable:i=a!=null&&(a===408||a===409||a===429||a>=500),data:l}){super({name:Xl,message:t,cause:o}),this[tu]=!0,this.url=e,this.requestBodyValues=r,this.statusCode=a,this.responseHeaders=n,this.responseBody=s,this.isRetryable=i,this.data=l}static isInstance(t){return he.hasMarker(t,eu)}};tu=Ym;var ru="AI_EmptyResponseBodyError",nu=`vercel.ai.error.${ru}`,Xm=Symbol.for(nu),au,su=class extends he{constructor({message:t="Empty response body"}={}){super({name:ru,message:t}),this[au]=!0}static isInstance(t){return he.hasMarker(t,nu)}};au=Xm;function yn(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}var ou="AI_InvalidArgumentError",iu=`vercel.ai.error.${ou}`,ev=Symbol.for(iu),lu,vo=class extends he{constructor({message:e,cause:r,argument:a}){super({name:ou,message:e,cause:r}),this[lu]=!0,this.argument=a}static isInstance(e){return he.hasMarker(e,iu)}};lu=ev;var uu="AI_InvalidPromptError",cu=`vercel.ai.error.${uu}`,tv=Symbol.for(cu),du,Br=class extends he{constructor({prompt:t,message:e,cause:r}){super({name:uu,message:`Invalid prompt: ${e}`,cause:r}),this[du]=!0,this.prompt=t}static isInstance(t){return he.hasMarker(t,cu)}};du=tv;var pu="AI_InvalidResponseDataError",hu=`vercel.ai.error.${pu}`,rv=Symbol.for(hu),fu,Zn=class extends he{constructor({data:t,message:e=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:pu,message:e}),this[fu]=!0,this.data=t}static isInstance(t){return he.hasMarker(t,hu)}};fu=rv;var mu="AI_JSONParseError",vu=`vercel.ai.error.${mu}`,nv=Symbol.for(vu),gu,Tr=class extends he{constructor({text:t,cause:e}){super({name:mu,message:`JSON parsing failed: Text: ${t}.
|
|
2
|
+
Error message: ${yn(e)}`,cause:e}),this[gu]=!0,this.text=t}static isInstance(t){return he.hasMarker(t,vu)}};gu=nv;var yu="AI_LoadAPIKeyError",_u=`vercel.ai.error.${yu}`,av=Symbol.for(_u),wu,La=class extends he{constructor({message:t}){super({name:yu,message:t}),this[wu]=!0}static isInstance(t){return he.hasMarker(t,_u)}};wu=av;var bu="AI_NoSuchModelError",xu=`vercel.ai.error.${bu}`,sv=Symbol.for(xu),Eu,go=class extends he{constructor({errorName:t=bu,modelId:e,modelType:r,message:a=`No such ${r}: ${e}`}){super({name:t,message:a}),this[Eu]=!0,this.modelId=e,this.modelType=r}static isInstance(t){return he.hasMarker(t,xu)}};Eu=sv;var Su="AI_TooManyEmbeddingValuesForCallError",Iu=`vercel.ai.error.${Su}`,ov=Symbol.for(Iu),Tu,iv=class extends he{constructor(t){super({name:Su,message:`Too many values for a single embedding call. The ${t.provider} model "${t.modelId}" can only embed up to ${t.maxEmbeddingsPerCall} values per call, but ${t.values.length} values were provided.`}),this[Tu]=!0,this.provider=t.provider,this.modelId=t.modelId,this.maxEmbeddingsPerCall=t.maxEmbeddingsPerCall,this.values=t.values}static isInstance(t){return he.hasMarker(t,Iu)}};Tu=ov;var ku="AI_TypeValidationError",Pu=`vercel.ai.error.${ku}`,lv=Symbol.for(Pu),Cu,uv=class Ql extends he{constructor({value:e,cause:r}){super({name:ku,message:`Type validation failed: Value: ${JSON.stringify(e)}.
|
|
3
|
+
Error message: ${yn(r)}`,cause:r}),this[Cu]=!0,this.value=e}static isInstance(e){return he.hasMarker(e,Pu)}static wrap({value:e,cause:r}){return Ql.isInstance(r)&&r.value===e?r:new Ql({value:e,cause:r})}};Cu=lv;var er=uv,Ru="AI_UnsupportedFunctionalityError",Ou=`vercel.ai.error.${Ru}`,cv=Symbol.for(Ou),$u,Nt=class extends he{constructor({functionality:t,message:e=`'${t}' functionality not supported.`}){super({name:Ru,message:e}),this[$u]=!0,this.functionality=t}static isInstance(t){return he.hasMarker(t,Ou)}};$u=cv;let Au=class extends Error{constructor(e,r){super(e),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}};function yo(t){}function dv(t){if(typeof t=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:e=yo,onError:r=yo,onRetry:a=yo,onComment:n}=t;let s="",o=!0,i,l="",u="";function d(f){const m=o?f.replace(/^\xEF\xBB\xBF/,""):f,[v,w]=pv(`${s}${m}`);for(const y of v)h(y);s=w,o=!1}function h(f){if(f===""){c();return}if(f.startsWith(":")){n&&n(f.slice(f.startsWith(": ")?2:1));return}const m=f.indexOf(":");if(m!==-1){const v=f.slice(0,m),w=f[m+1]===" "?2:1,y=f.slice(m+w);g(v,y,f);return}g(f,"",f)}function g(f,m,v){switch(f){case"event":u=m;break;case"data":l=`${l}${m}
|
|
4
|
+
`;break;case"id":i=m.includes("\0")?void 0:m;break;case"retry":/^\d+$/.test(m)?a(parseInt(m,10)):r(new Au(`Invalid \`retry\` value: "${m}"`,{type:"invalid-retry",value:m,line:v}));break;default:r(new Au(`Unknown field "${f.length>20?`${f.slice(0,20)}…`:f}"`,{type:"unknown-field",field:f,value:m,line:v}));break}}function c(){l.length>0&&e({id:i,event:u||void 0,data:l.endsWith(`
|
|
5
|
+
`)?l.slice(0,-1):l}),i=void 0,l="",u=""}function p(f={}){s&&f.consume&&h(s),o=!0,i=void 0,l="",u="",s=""}return{feed:d,reset:p}}function pv(t){const e=[];let r="",a=0;for(;a<t.length;){const n=t.indexOf("\r",a),s=t.indexOf(`
|
|
6
|
+
`,a);let o=-1;if(n!==-1&&s!==-1?o=Math.min(n,s):n!==-1?n===t.length-1?o=-1:o=n:s!==-1&&(o=s),o===-1){r=t.slice(a);break}else{const i=t.slice(a,o);e.push(i),a=o+1,t[a-1]==="\r"&&t[a]===`
|
|
7
|
+
`&&a++}}return[e,r]}let hv=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:a}={}){let n;super({start(s){n=dv({onEvent:o=>{s.enqueue(o)},onError(o){e==="terminate"?s.error(o):typeof e=="function"&&e(o)},onRetry:r,onComment:a})},transform(s){n.feed(s)}})}};function j(t,e,r){function a(i,l){var u;Object.defineProperty(i,"_zod",{value:i._zod??{},enumerable:!1}),(u=i._zod).traits??(u.traits=new Set),i._zod.traits.add(t),e(i,l);for(const d in o.prototype)d in i||Object.defineProperty(i,d,{value:o.prototype[d].bind(i)});i._zod.constr=o,i._zod.def=l}const n=(r==null?void 0:r.Parent)??Object;class s extends n{}Object.defineProperty(s,"name",{value:t});function o(i){var l;const u=r!=null&&r.Parent?new s:this;a(u,i),(l=u._zod).deferred??(l.deferred=[]);for(const d of u._zod.deferred)d();return u}return Object.defineProperty(o,"init",{value:a}),Object.defineProperty(o,Symbol.hasInstance,{value:i=>{var l,u;return r!=null&&r.Parent&&i instanceof r.Parent?!0:(u=(l=i==null?void 0:i._zod)==null?void 0:l.traits)==null?void 0:u.has(t)}}),Object.defineProperty(o,"name",{value:t}),o}class Vn extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const Nu={};function kr(t){return Nu}function Mu(t){const e=Object.values(t).filter(a=>typeof a=="number");return Object.entries(t).filter(([a,n])=>e.indexOf(+a)===-1).map(([a,n])=>n)}function fv(t,e){return typeof e=="bigint"?e.toString():e}function _o(t){return{get value(){{const e=t();return Object.defineProperty(this,"value",{value:e}),e}}}}function wo(t){return t==null}function bo(t){const e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function mv(t,e){const r=(t.toString().split(".")[1]||"").length,a=(e.toString().split(".")[1]||"").length,n=r>a?r:a,s=Number.parseInt(t.toFixed(n).replace(".","")),o=Number.parseInt(e.toFixed(n).replace(".",""));return s%o/10**n}function De(t,e,r){Object.defineProperty(t,e,{get(){{const a=r();return t[e]=a,a}},set(a){Object.defineProperty(t,e,{value:a})},configurable:!0})}function za(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Bn(t){return JSON.stringify(t)}const Du=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function Ua(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const vv=_o(()=>{var t;if(typeof navigator<"u"&&((t=navigator==null?void 0:navigator.userAgent)!=null&&t.includes("Cloudflare")))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Fa(t){if(Ua(t)===!1)return!1;const e=t.constructor;if(e===void 0)return!0;const r=e.prototype;return!(Ua(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}const gv=new Set(["string","number","symbol"]);function Hn(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Hr(t,e,r){const a=new t._zod.constr(e??t._zod.def);return(!e||r!=null&&r.parent)&&(a._zod.parent=t),a}function X(t){const e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if((e==null?void 0:e.message)!==void 0){if((e==null?void 0:e.error)!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function yv(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}const _v={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 wv(t,e){const r={},a=t._zod.def;for(const n in e){if(!(n in a.shape))throw new Error(`Unrecognized key: "${n}"`);e[n]&&(r[n]=a.shape[n])}return Hr(t,{...t._zod.def,shape:r,checks:[]})}function bv(t,e){const r={...t._zod.def.shape},a=t._zod.def;for(const n in e){if(!(n in a.shape))throw new Error(`Unrecognized key: "${n}"`);e[n]&&delete r[n]}return Hr(t,{...t._zod.def,shape:r,checks:[]})}function xv(t,e){if(!Fa(e))throw new Error("Invalid input to extend: expected a plain object");const r={...t._zod.def,get shape(){const a={...t._zod.def.shape,...e};return za(this,"shape",a),a},checks:[]};return Hr(t,r)}function Ev(t,e){return Hr(t,{...t._zod.def,get shape(){const r={...t._zod.def.shape,...e._zod.def.shape};return za(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function Sv(t,e,r){const a=e._zod.def.shape,n={...a};if(r)for(const s in r){if(!(s in a))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(n[s]=t?new t({type:"optional",innerType:a[s]}):a[s])}else for(const s in a)n[s]=t?new t({type:"optional",innerType:a[s]}):a[s];return Hr(e,{...e._zod.def,shape:n,checks:[]})}function Iv(t,e,r){const a=e._zod.def.shape,n={...a};if(r)for(const s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(n[s]=new t({type:"nonoptional",innerType:a[s]}))}else for(const s in a)n[s]=new t({type:"nonoptional",innerType:a[s]});return Hr(e,{...e._zod.def,shape:n,checks:[]})}function Jn(t,e=0){var r;for(let a=e;a<t.issues.length;a++)if(((r=t.issues[a])==null?void 0:r.continue)!==!0)return!0;return!1}function Jr(t,e){return e.map(r=>{var a;return(a=r).path??(a.path=[]),r.path.unshift(t),r})}function qa(t){return typeof t=="string"?t:t==null?void 0:t.message}function Pr(t,e,r){var n,s,o,i,l,u;const a={...t,path:t.path??[]};if(!t.message){const d=qa((o=(s=(n=t.inst)==null?void 0:n._zod.def)==null?void 0:s.error)==null?void 0:o.call(s,t))??qa((i=e==null?void 0:e.error)==null?void 0:i.call(e,t))??qa((l=r.customError)==null?void 0:l.call(r,t))??qa((u=r.localeError)==null?void 0:u.call(r,t))??"Invalid input";a.message=d}return delete a.inst,delete a.continue,e!=null&&e.reportInput||delete a.input,a}function xo(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Wn(...t){const[e,r,a]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:a}:{...e}}const ju=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,fv,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Lu=j("$ZodError",ju),zu=j("$ZodError",ju,{Parent:Error});function Tv(t,e=r=>r.message){const r={},a=[];for(const n of t.issues)n.path.length>0?(r[n.path[0]]=r[n.path[0]]||[],r[n.path[0]].push(e(n))):a.push(e(n));return{formErrors:a,fieldErrors:r}}function kv(t,e){const r=e||function(s){return s.message},a={_errors:[]},n=s=>{for(const o of s.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(i=>n({issues:i}));else if(o.code==="invalid_key")n({issues:o.issues});else if(o.code==="invalid_element")n({issues:o.issues});else if(o.path.length===0)a._errors.push(r(o));else{let i=a,l=0;for(;l<o.path.length;){const u=o.path[l];l===o.path.length-1?(i[u]=i[u]||{_errors:[]},i[u]._errors.push(r(o))):i[u]=i[u]||{_errors:[]},i=i[u],l++}}};return n(t),a}const Pv=t=>(e,r,a,n)=>{const s=a?Object.assign(a,{async:!1}):{async:!1},o=e._zod.run({value:r,issues:[]},s);if(o instanceof Promise)throw new Vn;if(o.issues.length){const i=new((n==null?void 0:n.Err)??t)(o.issues.map(l=>Pr(l,s,kr())));throw Du(i,n==null?void 0:n.callee),i}return o.value},Cv=t=>async(e,r,a,n)=>{const s=a?Object.assign(a,{async:!0}):{async:!0};let o=e._zod.run({value:r,issues:[]},s);if(o instanceof Promise&&(o=await o),o.issues.length){const i=new((n==null?void 0:n.Err)??t)(o.issues.map(l=>Pr(l,s,kr())));throw Du(i,n==null?void 0:n.callee),i}return o.value},Uu=t=>(e,r,a)=>{const n=a?{...a,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},n);if(s instanceof Promise)throw new Vn;return s.issues.length?{success:!1,error:new(t??Lu)(s.issues.map(o=>Pr(o,n,kr())))}:{success:!0,data:s.value}},Rv=Uu(zu),Fu=t=>async(e,r,a)=>{const n=a?Object.assign(a,{async:!0}):{async:!0};let s=e._zod.run({value:r,issues:[]},n);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(o=>Pr(o,n,kr())))}:{success:!0,data:s.value}},Ov=Fu(zu),$v=/^[cC][^\s-]{8,}$/,Av=/^[0-9a-z]+$/,Nv=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Mv=/^[0-9a-vA-V]{20}$/,Dv=/^[A-Za-z0-9]{27}$/,jv=/^[a-zA-Z0-9_-]{21}$/,Lv=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,zv=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,qu=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,Uv=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Fv="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function qv(){return new RegExp(Fv,"u")}const Zv=/^(?:(?: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])$/,Vv=/^(([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})$/,Bv=/^((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])$/,Hv=/^(([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])$/,Jv=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Zu=/^[A-Za-z0-9_-]*$/,Wv=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Gv=/^\+(?:[0-9]){6,14}[0-9]$/,Vu="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Kv=new RegExp(`^${Vu}$`);function Bu(t){const e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Qv(t){return new RegExp(`^${Bu(t)}$`)}function Yv(t){const e=Bu({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");const a=`${e}(?:${r.join("|")})`;return new RegExp(`^${Vu}T(?:${a})$`)}const Xv=t=>{const e=t?`[\\s\\S]{${(t==null?void 0:t.minimum)??0},${(t==null?void 0:t.maximum)??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},eg=/^\d+$/,tg=/^-?\d+(?:\.\d+)?/i,rg=/true|false/i,ng=/null/i,ag=/^[^A-Z]*$/,sg=/^[^a-z]*$/,Et=j("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Hu={number:"number",bigint:"bigint",object:"date"},Ju=j("$ZodCheckLessThan",(t,e)=>{Et.init(t,e);const r=Hu[typeof e.value];t._zod.onattach.push(a=>{const n=a._zod.bag,s=(e.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?n.maximum=e.value:n.exclusiveMaximum=e.value)}),t._zod.check=a=>{(e.inclusive?a.value<=e.value:a.value<e.value)||a.issues.push({origin:r,code:"too_big",maximum:e.value,input:a.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Wu=j("$ZodCheckGreaterThan",(t,e)=>{Et.init(t,e);const r=Hu[typeof e.value];t._zod.onattach.push(a=>{const n=a._zod.bag,s=(e.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?n.minimum=e.value:n.exclusiveMinimum=e.value)}),t._zod.check=a=>{(e.inclusive?a.value>=e.value:a.value>e.value)||a.issues.push({origin:r,code:"too_small",minimum:e.value,input:a.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),og=j("$ZodCheckMultipleOf",(t,e)=>{Et.init(t,e),t._zod.onattach.push(r=>{var a;(a=r._zod.bag).multipleOf??(a.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):mv(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),ig=j("$ZodCheckNumberFormat",(t,e)=>{var o;Et.init(t,e),e.format=e.format||"float64";const r=(o=e.format)==null?void 0:o.includes("int"),a=r?"int":"number",[n,s]=_v[e.format];t._zod.onattach.push(i=>{const l=i._zod.bag;l.format=e.format,l.minimum=n,l.maximum=s,r&&(l.pattern=eg)}),t._zod.check=i=>{const l=i.value;if(r){if(!Number.isInteger(l)){i.issues.push({expected:a,format:e.format,code:"invalid_type",input:l,inst:t});return}if(!Number.isSafeInteger(l)){l>0?i.issues.push({input:l,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:a,continue:!e.abort}):i.issues.push({input:l,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:a,continue:!e.abort});return}}l<n&&i.issues.push({origin:"number",input:l,code:"too_small",minimum:n,inclusive:!0,inst:t,continue:!e.abort}),l>s&&i.issues.push({origin:"number",input:l,code:"too_big",maximum:s,inst:t})}}),lg=j("$ZodCheckMaxLength",(t,e)=>{var r;Et.init(t,e),(r=t._zod.def).when??(r.when=a=>{const n=a.value;return!wo(n)&&n.length!==void 0}),t._zod.onattach.push(a=>{const n=a._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<n&&(a._zod.bag.maximum=e.maximum)}),t._zod.check=a=>{const n=a.value;if(n.length<=e.maximum)return;const o=xo(n);a.issues.push({origin:o,code:"too_big",maximum:e.maximum,inclusive:!0,input:n,inst:t,continue:!e.abort})}}),ug=j("$ZodCheckMinLength",(t,e)=>{var r;Et.init(t,e),(r=t._zod.def).when??(r.when=a=>{const n=a.value;return!wo(n)&&n.length!==void 0}),t._zod.onattach.push(a=>{const n=a._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>n&&(a._zod.bag.minimum=e.minimum)}),t._zod.check=a=>{const n=a.value;if(n.length>=e.minimum)return;const o=xo(n);a.issues.push({origin:o,code:"too_small",minimum:e.minimum,inclusive:!0,input:n,inst:t,continue:!e.abort})}}),cg=j("$ZodCheckLengthEquals",(t,e)=>{var r;Et.init(t,e),(r=t._zod.def).when??(r.when=a=>{const n=a.value;return!wo(n)&&n.length!==void 0}),t._zod.onattach.push(a=>{const n=a._zod.bag;n.minimum=e.length,n.maximum=e.length,n.length=e.length}),t._zod.check=a=>{const n=a.value,s=n.length;if(s===e.length)return;const o=xo(n),i=s>e.length;a.issues.push({origin:o,...i?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:a.value,inst:t,continue:!e.abort})}}),Za=j("$ZodCheckStringFormat",(t,e)=>{var r,a;Et.init(t,e),t._zod.onattach.push(n=>{const s=n._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:e.format,input:n.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(a=t._zod).check??(a.check=()=>{})}),dg=j("$ZodCheckRegex",(t,e)=>{Za.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),pg=j("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=ag),Za.init(t,e)}),hg=j("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=sg),Za.init(t,e)}),fg=j("$ZodCheckIncludes",(t,e)=>{Et.init(t,e);const r=Hn(e.includes),a=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=a,t._zod.onattach.push(n=>{const s=n._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(a)}),t._zod.check=n=>{n.value.includes(e.includes,e.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:n.value,inst:t,continue:!e.abort})}}),mg=j("$ZodCheckStartsWith",(t,e)=>{Et.init(t,e);const r=new RegExp(`^${Hn(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(a=>{const n=a._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),t._zod.check=a=>{a.value.startsWith(e.prefix)||a.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:a.value,inst:t,continue:!e.abort})}}),vg=j("$ZodCheckEndsWith",(t,e)=>{Et.init(t,e);const r=new RegExp(`.*${Hn(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(a=>{const n=a._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),t._zod.check=a=>{a.value.endsWith(e.suffix)||a.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:a.value,inst:t,continue:!e.abort})}}),gg=j("$ZodCheckOverwrite",(t,e)=>{Et.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});class yg{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}const a=e.split(`
|
|
8
|
+
`).filter(o=>o),n=Math.min(...a.map(o=>o.length-o.trimStart().length)),s=a.map(o=>o.slice(n)).map(o=>" ".repeat(this.indent*2)+o);for(const o of s)this.content.push(o)}compile(){const e=Function,r=this==null?void 0:this.args,n=[...((this==null?void 0:this.content)??[""]).map(s=>` ${s}`)];return new e(...r,n.join(`
|
|
9
|
+
`))}}const _g={major:4,minor:0,patch:0},Fe=j("$ZodType",(t,e)=>{var n;var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=_g;const a=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&a.unshift(t);for(const s of a)for(const o of s._zod.onattach)o(t);if(a.length===0)(r=t._zod).deferred??(r.deferred=[]),(n=t._zod.deferred)==null||n.push(()=>{t._zod.run=t._zod.parse});else{const s=(o,i,l)=>{let u=Jn(o),d;for(const h of i){if(h._zod.def.when){if(!h._zod.def.when(o))continue}else if(u)continue;const g=o.issues.length,c=h._zod.check(o);if(c instanceof Promise&&(l==null?void 0:l.async)===!1)throw new Vn;if(d||c instanceof Promise)d=(d??Promise.resolve()).then(async()=>{await c,o.issues.length!==g&&(u||(u=Jn(o,g)))});else{if(o.issues.length===g)continue;u||(u=Jn(o,g))}}return d?d.then(()=>o):o};t._zod.run=(o,i)=>{const l=t._zod.parse(o,i);if(l instanceof Promise){if(i.async===!1)throw new Vn;return l.then(u=>s(u,a,i))}return s(l,a,i)}}t["~standard"]={validate:s=>{var o;try{const i=Rv(t,s);return i.success?{value:i.data}:{issues:(o=i.error)==null?void 0:o.issues}}catch{return Ov(t,s).then(l=>{var u;return l.success?{value:l.data}:{issues:(u=l.error)==null?void 0:u.issues}})}},vendor:"zod",version:1}}),Eo=j("$ZodString",(t,e)=>{var r;Fe.init(t,e),t._zod.pattern=[...((r=t==null?void 0:t._zod.bag)==null?void 0:r.patterns)??[]].pop()??Xv(t._zod.bag),t._zod.parse=(a,n)=>{if(e.coerce)try{a.value=String(a.value)}catch{}return typeof a.value=="string"||a.issues.push({expected:"string",code:"invalid_type",input:a.value,inst:t}),a}}),Je=j("$ZodStringFormat",(t,e)=>{Za.init(t,e),Eo.init(t,e)}),wg=j("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=zv),Je.init(t,e)}),bg=j("$ZodUUID",(t,e)=>{if(e.version){const a={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(a===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=qu(a))}else e.pattern??(e.pattern=qu());Je.init(t,e)}),xg=j("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=Uv),Je.init(t,e)}),Eg=j("$ZodURL",(t,e)=>{Je.init(t,e),t._zod.check=r=>{try{const a=r.value,n=new URL(a),s=n.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(n.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Wv.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),!a.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),Sg=j("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=qv()),Je.init(t,e)}),Ig=j("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=jv),Je.init(t,e)}),Tg=j("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=$v),Je.init(t,e)}),kg=j("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Av),Je.init(t,e)}),Pg=j("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Nv),Je.init(t,e)}),Cg=j("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Mv),Je.init(t,e)}),Rg=j("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Dv),Je.init(t,e)}),Og=j("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Yv(e)),Je.init(t,e)}),$g=j("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Kv),Je.init(t,e)}),Ag=j("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Qv(e)),Je.init(t,e)}),Ng=j("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Lv),Je.init(t,e)}),Mg=j("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Zv),Je.init(t,e),t._zod.onattach.push(r=>{const a=r._zod.bag;a.format="ipv4"})}),Dg=j("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Vv),Je.init(t,e),t._zod.onattach.push(r=>{const a=r._zod.bag;a.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),jg=j("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Bv),Je.init(t,e)}),Lg=j("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Hv),Je.init(t,e),t._zod.check=r=>{const[a,n]=r.value.split("/");try{if(!n)throw new Error;const s=Number(n);if(`${s}`!==n)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${a}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});function Gu(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}const zg=j("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Jv),Je.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{Gu(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function Ug(t){if(!Zu.test(t))return!1;const e=t.replace(/[-_]/g,a=>a==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return Gu(r)}const Fg=j("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Zu),Je.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{Ug(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),qg=j("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Gv),Je.init(t,e)});function Zg(t,e=null){try{const r=t.split(".");if(r.length!==3)return!1;const[a]=r;if(!a)return!1;const n=JSON.parse(atob(a));return!("typ"in n&&(n==null?void 0:n.typ)!=="JWT"||!n.alg||e&&(!("alg"in n)||n.alg!==e))}catch{return!1}}const Vg=j("$ZodJWT",(t,e)=>{Je.init(t,e),t._zod.check=r=>{Zg(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),Ku=j("$ZodNumber",(t,e)=>{Fe.init(t,e),t._zod.pattern=t._zod.bag.pattern??tg,t._zod.parse=(r,a)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}const n=r.value;if(typeof n=="number"&&!Number.isNaN(n)&&Number.isFinite(n))return r;const s=typeof n=="number"?Number.isNaN(n)?"NaN":Number.isFinite(n)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:n,inst:t,...s?{received:s}:{}}),r}}),Bg=j("$ZodNumber",(t,e)=>{ig.init(t,e),Ku.init(t,e)}),Hg=j("$ZodBoolean",(t,e)=>{Fe.init(t,e),t._zod.pattern=rg,t._zod.parse=(r,a)=>{if(e.coerce)try{r.value=!!r.value}catch{}const n=r.value;return typeof n=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:n,inst:t}),r}}),Jg=j("$ZodNull",(t,e)=>{Fe.init(t,e),t._zod.pattern=ng,t._zod.values=new Set([null]),t._zod.parse=(r,a)=>{const n=r.value;return n===null||r.issues.push({expected:"null",code:"invalid_type",input:n,inst:t}),r}}),Wg=j("$ZodAny",(t,e)=>{Fe.init(t,e),t._zod.parse=r=>r}),Gg=j("$ZodUnknown",(t,e)=>{Fe.init(t,e),t._zod.parse=r=>r}),Kg=j("$ZodNever",(t,e)=>{Fe.init(t,e),t._zod.parse=(r,a)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});function Qu(t,e,r){t.issues.length&&e.issues.push(...Jr(r,t.issues)),e.value[r]=t.value}const Qg=j("$ZodArray",(t,e)=>{Fe.init(t,e),t._zod.parse=(r,a)=>{const n=r.value;if(!Array.isArray(n))return r.issues.push({expected:"array",code:"invalid_type",input:n,inst:t}),r;r.value=Array(n.length);const s=[];for(let o=0;o<n.length;o++){const i=n[o],l=e.element._zod.run({value:i,issues:[]},a);l instanceof Promise?s.push(l.then(u=>Qu(u,r,o))):Qu(l,r,o)}return s.length?Promise.all(s).then(()=>r):r}});function Va(t,e,r){t.issues.length&&e.issues.push(...Jr(r,t.issues)),e.value[r]=t.value}function Yu(t,e,r,a){t.issues.length?a[r]===void 0?r in a?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...Jr(r,t.issues)):t.value===void 0?r in a&&(e.value[r]=void 0):e.value[r]=t.value}const Yg=j("$ZodObject",(t,e)=>{Fe.init(t,e);const r=_o(()=>{const h=Object.keys(e.shape);for(const c of h)if(!(e.shape[c]instanceof Fe))throw new Error(`Invalid element at key "${c}": expected a Zod schema`);const g=yv(e.shape);return{shape:e.shape,keys:h,keySet:new Set(h),numKeys:h.length,optionalKeys:new Set(g)}});De(t._zod,"propValues",()=>{const h=e.shape,g={};for(const c in h){const p=h[c]._zod;if(p.values){g[c]??(g[c]=new Set);for(const f of p.values)g[c].add(f)}}return g});const a=h=>{const g=new yg(["shape","payload","ctx"]),c=r.value,p=w=>{const y=Bn(w);return`shape[${y}]._zod.run({ value: input[${y}], issues: [] }, ctx)`};g.write("const input = payload.value;");const f=Object.create(null);let m=0;for(const w of c.keys)f[w]=`key_${m++}`;g.write("const newResult = {}");for(const w of c.keys)if(c.optionalKeys.has(w)){const y=f[w];g.write(`const ${y} = ${p(w)};`);const _=Bn(w);g.write(`
|
|
10
|
+
if (${y}.issues.length) {
|
|
11
11
|
if (input[${_}] === undefined) {
|
|
12
12
|
if (${_} in input) {
|
|
13
13
|
newResult[${_}] = undefined;
|
|
14
14
|
}
|
|
15
15
|
} else {
|
|
16
16
|
payload.issues = payload.issues.concat(
|
|
17
|
-
${
|
|
17
|
+
${y}.issues.map((iss) => ({
|
|
18
18
|
...iss,
|
|
19
19
|
path: iss.path ? [${_}, ...iss.path] : [${_}],
|
|
20
20
|
}))
|
|
21
21
|
);
|
|
22
22
|
}
|
|
23
|
-
} else if (${
|
|
23
|
+
} else if (${y}.value === undefined) {
|
|
24
24
|
if (${_} in input) newResult[${_}] = undefined;
|
|
25
25
|
} else {
|
|
26
|
-
newResult[${_}] = ${
|
|
26
|
+
newResult[${_}] = ${y}.value;
|
|
27
27
|
}
|
|
28
|
-
`)}else{const
|
|
29
|
-
if (${
|
|
28
|
+
`)}else{const y=f[w];g.write(`const ${y} = ${p(w)};`),g.write(`
|
|
29
|
+
if (${y}.issues.length) payload.issues = payload.issues.concat(${y}.issues.map(iss => ({
|
|
30
30
|
...iss,
|
|
31
|
-
path: iss.path ? [${
|
|
32
|
-
})));`),w.write(`newResult[${Un(b)}] = ${v}.value`)}w.write("payload.value = newResult;"),w.write("return payload;");const c=w.compile();return(b,v)=>c(x,b,v)};let o;const s=Er,a=!ai.jitless,l=a&&xp.value,u=t.catchall;let p;e._zod.parse=(x,w)=>{p??(p=n.value);const h=x.value;if(!s(h))return x.issues.push({expected:"object",code:"invalid_type",input:h,inst:e}),x;const f=[];if(a&&l&&(w==null?void 0:w.async)===!1&&w.jitless!==!0)o||(o=r(t.shape)),x=o(x,w);else{x.value={};const v=p.shape;for(const _ of p.keys){const R=v[_],C=R._zod.run({value:h[_],issues:[]},w),T=R._zod.optin==="optional"&&R._zod.optout==="optional";C instanceof Promise?f.push(C.then(P=>T?Ti(P,x,_,h):Nr(P,x,_))):T?Ti(C,x,_,h):Nr(C,x,_)}}if(!u)return f.length?Promise.all(f).then(()=>x):x;const y=[],m=p.keySet,c=u._zod,b=c.def.type;for(const v of Object.keys(h)){if(m.has(v))continue;if(b==="never"){y.push(v);continue}const _=c.run({value:h[v],issues:[]},w);_ instanceof Promise?f.push(_.then(R=>Nr(R,x,v))):Nr(_,x,v)}return y.length&&x.issues.push({code:"unrecognized_keys",keys:y,input:h,inst:e}),f.length?Promise.all(f).then(()=>x):x}});function Si(e,t,n,r){for(const o of e)if(o.issues.length===0)return t.value=o.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(o=>o.issues.map(s=>Jt(s,r,Ht())))}),t}const Ii=E("$ZodUnion",(e,t)=>{ye.init(e,t),pe(e._zod,"optin",()=>t.options.some(n=>n._zod.optin==="optional")?"optional":void 0),pe(e._zod,"optout",()=>t.options.some(n=>n._zod.optout==="optional")?"optional":void 0),pe(e._zod,"values",()=>{if(t.options.every(n=>n._zod.values))return new Set(t.options.flatMap(n=>Array.from(n._zod.values)))}),pe(e._zod,"pattern",()=>{if(t.options.every(n=>n._zod.pattern)){const n=t.options.map(r=>r._zod.pattern);return new RegExp(`^(${n.map(r=>Po(r.source)).join("|")})$`)}}),e._zod.parse=(n,r)=>{let o=!1;const s=[];for(const a of t.options){const i=a._zod.run({value:n.value,issues:[]},r);if(i instanceof Promise)s.push(i),o=!0;else{if(i.issues.length===0)return i;s.push(i)}}return o?Promise.all(s).then(a=>Si(a,n,e,r)):Si(s,n,e,r)}}),sf=E("$ZodDiscriminatedUnion",(e,t)=>{Ii.init(e,t);const n=e._zod.parse;pe(e._zod,"propValues",()=>{const o={};for(const s of t.options){const a=s._zod.propValues;if(!a||Object.keys(a).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(const[i,l]of Object.entries(a)){o[i]||(o[i]=new Set);for(const u of l)o[i].add(u)}}return o});const r=No(()=>{const o=t.options,s=new Map;for(const a of o){const i=a._zod.propValues[t.discriminator];if(!i||i.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(a)}"`);for(const l of i){if(s.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);s.set(l,a)}}return s});e._zod.parse=(o,s)=>{const a=o.value;if(!Er(a))return o.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),o;const i=r.value.get(a==null?void 0:a[t.discriminator]);return i?i._zod.run(o,s):t.unionFallback?n(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:a,path:[t.discriminator],inst:e}),o)}}),af=E("$ZodIntersection",(e,t)=>{ye.init(e,t),e._zod.parse=(n,r)=>{const o=n.value,s=t.left._zod.run({value:o,issues:[]},r),a=t.right._zod.run({value:o,issues:[]},r);return s instanceof Promise||a instanceof Promise?Promise.all([s,a]).then(([l,u])=>Ci(n,l,u)):Ci(n,s,a)}});function jo(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(Rr(e)&&Rr(t)){const n=Object.keys(t),r=Object.keys(e).filter(s=>n.indexOf(s)!==-1),o={...e,...t};for(const s of r){const a=jo(e[s],t[s]);if(!a.valid)return{valid:!1,mergeErrorPath:[s,...a.mergeErrorPath]};o[s]=a.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const o=e[r],s=t[r],a=jo(o,s);if(!a.valid)return{valid:!1,mergeErrorPath:[r,...a.mergeErrorPath]};n.push(a.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Ci(e,t,n){if(t.issues.length&&e.issues.push(...t.issues),n.issues.length&&e.issues.push(...n.issues),Ln(e))return e;const r=jo(t.value,n.value);if(!r.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return e.value=r.data,e}const lf=E("$ZodRecord",(e,t)=>{ye.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!Rr(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),n;const s=[];if(t.keyType._zod.values){const a=t.keyType._zod.values;n.value={};for(const l of a)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){const u=t.valueType._zod.run({value:o[l],issues:[]},r);u instanceof Promise?s.push(u.then(p=>{p.issues.length&&n.issues.push(...rn(l,p.issues)),n.value[l]=p.value})):(u.issues.length&&n.issues.push(...rn(l,u.issues)),n.value[l]=u.value)}let i;for(const l in o)a.has(l)||(i=i??[],i.push(l));i&&i.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:i})}else{n.value={};for(const a of Reflect.ownKeys(o)){if(a==="__proto__")continue;const i=t.keyType._zod.run({value:a,issues:[]},r);if(i instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(i.issues.length){n.issues.push({origin:"record",code:"invalid_key",issues:i.issues.map(u=>Jt(u,r,Ht())),input:a,path:[a],inst:e}),n.value[i.value]=i.value;continue}const l=t.valueType._zod.run({value:o[a],issues:[]},r);l instanceof Promise?s.push(l.then(u=>{u.issues.length&&n.issues.push(...rn(a,u.issues)),n.value[i.value]=u.value})):(l.issues.length&&n.issues.push(...rn(a,l.issues)),n.value[i.value]=l.value)}}return s.length?Promise.all(s).then(()=>n):n}}),uf=E("$ZodEnum",(e,t)=>{ye.init(e,t);const n=ii(t.entries);e._zod.values=new Set(n),e._zod.pattern=new RegExp(`^(${n.filter(r=>kp.has(typeof r)).map(r=>typeof r=="string"?Zn(r):r.toString()).join("|")})$`),e._zod.parse=(r,o)=>{const s=r.value;return e._zod.values.has(s)||r.issues.push({code:"invalid_value",values:n,input:s,inst:e}),r}}),cf=E("$ZodLiteral",(e,t)=>{ye.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(n=>typeof n=="string"?Zn(n):n?n.toString():String(n)).join("|")})$`),e._zod.parse=(n,r)=>{const o=n.value;return e._zod.values.has(o)||n.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),n}}),df=E("$ZodTransform",(e,t)=>{ye.init(e,t),e._zod.parse=(n,r)=>{const o=t.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(a=>(n.value=a,n));if(o instanceof Promise)throw new Dn;return n.value=o,n}}),pf=E("$ZodOptional",(e,t)=>{ye.init(e,t),e._zod.optin="optional",e._zod.optout="optional",pe(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),pe(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Po(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>t.innerType._zod.optin==="optional"?t.innerType._zod.run(n,r):n.value===void 0?n:t.innerType._zod.run(n,r)}),hf=E("$ZodNullable",(e,t)=>{ye.init(e,t),pe(e._zod,"optin",()=>t.innerType._zod.optin),pe(e._zod,"optout",()=>t.innerType._zod.optout),pe(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Po(n.source)}|null)$`):void 0}),pe(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),ff=E("$ZodDefault",(e,t)=>{ye.init(e,t),e._zod.optin="optional",pe(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(n.value===void 0)return n.value=t.defaultValue,n;const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>Ei(s,t)):Ei(o,t)}});function Ei(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const mf=E("$ZodPrefault",(e,t)=>{ye.init(e,t),e._zod.optin="optional",pe(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>(n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,r))}),gf=E("$ZodNonOptional",(e,t)=>{ye.init(e,t),pe(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),e._zod.parse=(n,r)=>{const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>Ri(s,e)):Ri(o,e)}});function Ri(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 vf=E("$ZodCatch",(e,t)=>{ye.init(e,t),e._zod.optin="optional",pe(e._zod,"optout",()=>t.innerType._zod.optout),pe(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>(n.value=s.value,s.issues.length&&(n.value=t.catchValue({...n,error:{issues:s.issues.map(a=>Jt(a,r,Ht()))},input:n.value}),n.issues=[]),n)):(n.value=o.value,o.issues.length&&(n.value=t.catchValue({...n,error:{issues:o.issues.map(s=>Jt(s,r,Ht()))},input:n.value}),n.issues=[]),n)}}),yf=E("$ZodPipe",(e,t)=>{ye.init(e,t),pe(e._zod,"values",()=>t.in._zod.values),pe(e._zod,"optin",()=>t.in._zod.optin),pe(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(n,r)=>{const o=t.in._zod.run(n,r);return o instanceof Promise?o.then(s=>Ai(s,t,r)):Ai(o,t,r)}});function Ai(e,t,n){return Ln(e)?e:t.out._zod.run({value:e.value,issues:e.issues},n)}const _f=E("$ZodReadonly",(e,t)=>{ye.init(e,t),pe(e._zod,"propValues",()=>t.innerType._zod.propValues),pe(e._zod,"values",()=>t.innerType._zod.values),pe(e._zod,"optin",()=>t.innerType._zod.optin),pe(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(n,r)=>{const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(Oi):Oi(o)}});function Oi(e){return e.value=Object.freeze(e.value),e}const wf=E("$ZodLazy",(e,t)=>{ye.init(e,t),pe(e._zod,"innerType",()=>t.getter()),pe(e._zod,"pattern",()=>e._zod.innerType._zod.pattern),pe(e._zod,"propValues",()=>e._zod.innerType._zod.propValues),pe(e._zod,"optin",()=>e._zod.innerType._zod.optin),pe(e._zod,"optout",()=>e._zod.innerType._zod.optout),e._zod.parse=(n,r)=>e._zod.innerType._zod.run(n,r)}),bf=E("$ZodCustom",(e,t)=>{Qe.init(e,t),ye.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{const r=n.value,o=t.fn(r);if(o instanceof Promise)return o.then(s=>Ni(s,n,r,e));Ni(o,n,r,e)}});function Ni(e,t,n,r){if(!e){const o={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(o.params=r._zod.def.params),t.issues.push(qn(o))}}class Mi{constructor(){this._map=new Map,this._idmap=new Map}add(t,...n){const r=n[0];if(this._map.set(t,r),r&&typeof r=="object"&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,t)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const r={...this.get(n)??{}};return delete r.id,{...r,...this._map.get(t)}}return this._map.get(t)}has(t){return this._map.has(t)}}function xf(){return new Mi}const Bn=xf();function kf(e,t){return new e({type:"string",...q(t)})}function Tf(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...q(t)})}function Pi(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...q(t)})}function Sf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...q(t)})}function If(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...q(t)})}function Cf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...q(t)})}function Ef(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...q(t)})}function Rf(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...q(t)})}function Af(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...q(t)})}function Of(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...q(t)})}function Nf(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...q(t)})}function Mf(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...q(t)})}function Pf(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...q(t)})}function $f(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...q(t)})}function zf(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...q(t)})}function jf(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...q(t)})}function Df(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...q(t)})}function Uf(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...q(t)})}function Zf(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...q(t)})}function $i(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...q(t)})}function Lf(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...q(t)})}function qf(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...q(t)})}function Bf(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...q(t)})}function Vf(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...q(t)})}function Ff(e,t){return new e({type:"string",format:"date",check:"string_format",...q(t)})}function Hf(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...q(t)})}function Jf(e,t){return new e({type:"string",format:"duration",check:"string_format",...q(t)})}function Gf(e,t){return new e({type:"number",checks:[],...q(t)})}function Wf(e,t){return new e({type:"number",coerce:!0,checks:[],...q(t)})}function Kf(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...q(t)})}function Yf(e,t){return new e({type:"boolean",...q(t)})}function Xf(e,t){return new e({type:"null",...q(t)})}function Qf(e){return new e({type:"any"})}function em(e){return new e({type:"unknown"})}function tm(e,t){return new e({type:"never",...q(t)})}function zi(e,t){return new _i({check:"less_than",...q(t),value:e,inclusive:!1})}function Do(e,t){return new _i({check:"less_than",...q(t),value:e,inclusive:!0})}function ji(e,t){return new wi({check:"greater_than",...q(t),value:e,inclusive:!1})}function Uo(e,t){return new wi({check:"greater_than",...q(t),value:e,inclusive:!0})}function Di(e,t){return new ph({check:"multiple_of",...q(t),value:e})}function Ui(e,t){return new fh({check:"max_length",...q(t),maximum:e})}function Mr(e,t){return new mh({check:"min_length",...q(t),minimum:e})}function Zi(e,t){return new gh({check:"length_equals",...q(t),length:e})}function nm(e,t){return new vh({check:"string_format",format:"regex",...q(t),pattern:e})}function rm(e){return new yh({check:"string_format",format:"lowercase",...q(e)})}function om(e){return new _h({check:"string_format",format:"uppercase",...q(e)})}function sm(e,t){return new wh({check:"string_format",format:"includes",...q(t),includes:e})}function am(e,t){return new bh({check:"string_format",format:"starts_with",...q(t),prefix:e})}function im(e,t){return new xh({check:"string_format",format:"ends_with",...q(t),suffix:e})}function Vn(e){return new kh({check:"overwrite",tx:e})}function lm(e){return Vn(t=>t.normalize(e))}function um(){return Vn(e=>e.trim())}function cm(){return Vn(e=>e.toLowerCase())}function dm(){return Vn(e=>e.toUpperCase())}function pm(e,t,n){return new e({type:"array",element:t,...q(n)})}function hm(e,t,n){const r=q(n);return r.abort??(r.abort=!0),new e({type:"custom",check:"custom",fn:t,...r})}function fm(e,t,n){return new e({type:"custom",check:"custom",fn:t,...q(n)})}class Li{constructor(t){this.counter=0,this.metadataRegistry=(t==null?void 0:t.metadata)??Bn,this.target=(t==null?void 0:t.target)??"draft-2020-12",this.unrepresentable=(t==null?void 0:t.unrepresentable)??"throw",this.override=(t==null?void 0:t.override)??(()=>{}),this.io=(t==null?void 0:t.io)??"output",this.seen=new Map}process(t,n={path:[],schemaPath:[]}){var x,w,h;var r;const o=t._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},a=this.seen.get(t);if(a)return a.count++,n.schemaPath.includes(t)&&(a.cycle=n.path),a.schema;const i={schema:{},count:1,cycle:void 0,path:n.path};this.seen.set(t,i);const l=(w=(x=t._zod).toJSONSchema)==null?void 0:w.call(x);if(l)i.schema=l;else{const f={...n,schemaPath:[...n.schemaPath,t],path:n.path},y=t._zod.parent;if(y)i.ref=y,this.process(y,f),this.seen.get(y).isParent=!0;else{const m=i.schema;switch(o.type){case"string":{const c=m;c.type="string";const{minimum:b,maximum:v,format:_,patterns:R,contentEncoding:C}=t._zod.bag;if(typeof b=="number"&&(c.minLength=b),typeof v=="number"&&(c.maxLength=v),_&&(c.format=s[_]??_,c.format===""&&delete c.format),C&&(c.contentEncoding=C),R&&R.size>0){const T=[...R];T.length===1?c.pattern=T[0].source:T.length>1&&(i.schema.allOf=[...T.map(P=>({...this.target==="draft-7"?{type:"string"}:{},pattern:P.source}))])}break}case"number":{const c=m,{minimum:b,maximum:v,format:_,multipleOf:R,exclusiveMaximum:C,exclusiveMinimum:T}=t._zod.bag;typeof _=="string"&&_.includes("int")?c.type="integer":c.type="number",typeof T=="number"&&(c.exclusiveMinimum=T),typeof b=="number"&&(c.minimum=b,typeof T=="number"&&(T>=b?delete c.minimum:delete c.exclusiveMinimum)),typeof C=="number"&&(c.exclusiveMaximum=C),typeof v=="number"&&(c.maximum=v,typeof C=="number"&&(C<=v?delete c.maximum:delete c.exclusiveMaximum)),typeof R=="number"&&(c.multipleOf=R);break}case"boolean":{const c=m;c.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{m.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{m.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const c=m,{minimum:b,maximum:v}=t._zod.bag;typeof b=="number"&&(c.minItems=b),typeof v=="number"&&(c.maxItems=v),c.type="array",c.items=this.process(o.element,{...f,path:[...f.path,"items"]});break}case"object":{const c=m;c.type="object",c.properties={};const b=o.shape;for(const R in b)c.properties[R]=this.process(b[R],{...f,path:[...f.path,"properties",R]});const v=new Set(Object.keys(b)),_=new Set([...v].filter(R=>{const C=o.shape[R]._zod;return this.io==="input"?C.optin===void 0:C.optout===void 0}));_.size>0&&(c.required=Array.from(_)),((h=o.catchall)==null?void 0:h._zod.def.type)==="never"?c.additionalProperties=!1:o.catchall?o.catchall&&(c.additionalProperties=this.process(o.catchall,{...f,path:[...f.path,"additionalProperties"]})):this.io==="output"&&(c.additionalProperties=!1);break}case"union":{const c=m;c.anyOf=o.options.map((b,v)=>this.process(b,{...f,path:[...f.path,"anyOf",v]}));break}case"intersection":{const c=m,b=this.process(o.left,{...f,path:[...f.path,"allOf",0]}),v=this.process(o.right,{...f,path:[...f.path,"allOf",1]}),_=C=>"allOf"in C&&Object.keys(C).length===1,R=[..._(b)?b.allOf:[b],..._(v)?v.allOf:[v]];c.allOf=R;break}case"tuple":{const c=m;c.type="array";const b=o.items.map((R,C)=>this.process(R,{...f,path:[...f.path,"prefixItems",C]}));if(this.target==="draft-2020-12"?c.prefixItems=b:c.items=b,o.rest){const R=this.process(o.rest,{...f,path:[...f.path,"items"]});this.target==="draft-2020-12"?c.items=R:c.additionalItems=R}o.rest&&(c.items=this.process(o.rest,{...f,path:[...f.path,"items"]}));const{minimum:v,maximum:_}=t._zod.bag;typeof v=="number"&&(c.minItems=v),typeof _=="number"&&(c.maxItems=_);break}case"record":{const c=m;c.type="object",c.propertyNames=this.process(o.keyType,{...f,path:[...f.path,"propertyNames"]}),c.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 c=m,b=ii(o.entries);b.every(v=>typeof v=="number")&&(c.type="number"),b.every(v=>typeof v=="string")&&(c.type="string"),c.enum=b;break}case"literal":{const c=m,b=[];for(const v of o.values)if(v===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof v=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");b.push(Number(v))}else b.push(v);if(b.length!==0)if(b.length===1){const v=b[0];c.type=v===null?"null":typeof v,c.const=v}else b.every(v=>typeof v=="number")&&(c.type="number"),b.every(v=>typeof v=="string")&&(c.type="string"),b.every(v=>typeof v=="boolean")&&(c.type="string"),b.every(v=>v===null)&&(c.type="null"),c.enum=b;break}case"file":{const c=m,b={type:"string",format:"binary",contentEncoding:"binary"},{minimum:v,maximum:_,mime:R}=t._zod.bag;v!==void 0&&(b.minLength=v),_!==void 0&&(b.maxLength=_),R?R.length===1?(b.contentMediaType=R[0],Object.assign(c,b)):c.anyOf=R.map(C=>({...b,contentMediaType:C})):Object.assign(c,b);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const c=this.process(o.innerType,f);m.anyOf=[c,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,f),i.ref=o.innerType;break}case"success":{const c=m;c.type="boolean";break}case"default":{this.process(o.innerType,f),i.ref=o.innerType,m.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,f),i.ref=o.innerType,this.io==="input"&&(m._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,f),i.ref=o.innerType;let c;try{c=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}m.default=c;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const c=m,b=t._zod.pattern;if(!b)throw new Error("Pattern not found in template literal");c.type="string",c.pattern=b.source;break}case"pipe":{const c=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(c,f),i.ref=c;break}case"readonly":{this.process(o.innerType,f),i.ref=o.innerType,m.readOnly=!0;break}case"promise":{this.process(o.innerType,f),i.ref=o.innerType;break}case"optional":{this.process(o.innerType,f),i.ref=o.innerType;break}case"lazy":{const c=t._zod.innerType;this.process(c,f),i.ref=c;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const u=this.metadataRegistry.get(t);return u&&Object.assign(i.schema,u),this.io==="input"&&ze(t)&&(delete i.schema.examples,delete i.schema.default),this.io==="input"&&i.schema._prefault&&((r=i.schema).default??(r.default=i.schema._prefault)),delete i.schema._prefault,this.seen.get(t).schema}emit(t,n){var p,x,w,h,f,y;const r={cycles:(n==null?void 0:n.cycles)??"ref",reused:(n==null?void 0:n.reused)??"inline",external:(n==null?void 0:n.external)??void 0},o=this.seen.get(t);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=m=>{var R;const c=this.target==="draft-2020-12"?"$defs":"definitions";if(r.external){const C=(R=r.external.registry.get(m[0]))==null?void 0:R.id,T=r.external.uri??(D=>D);if(C)return{ref:T(C)};const P=m[1].defId??m[1].schema.id??`schema${this.counter++}`;return m[1].defId=P,{defId:P,ref:`${T("__shared")}#/${c}/${P}`}}if(m[1]===o)return{ref:"#"};const v=`#/${c}/`,_=m[1].schema.id??`__schema${this.counter++}`;return{defId:_,ref:v+_}},a=m=>{if(m[1].schema.$ref)return;const c=m[1],{ref:b,defId:v}=s(m);c.def={...c.schema},v&&(c.defId=v);const _=c.schema;for(const R in _)delete _[R];_.$ref=b};if(r.cycles==="throw")for(const m of this.seen.entries()){const c=m[1];if(c.cycle)throw new Error(`Cycle detected: #/${(p=c.cycle)==null?void 0:p.join("/")}/<root>
|
|
31
|
+
path: iss.path ? [${Bn(w)}, ...iss.path] : [${Bn(w)}]
|
|
32
|
+
})));`),g.write(`newResult[${Bn(w)}] = ${y}.value`)}g.write("payload.value = newResult;"),g.write("return payload;");const v=g.compile();return(w,y)=>v(h,w,y)};let n;const s=Ua,o=!Nu.jitless,l=o&&vv.value,u=e.catchall;let d;t._zod.parse=(h,g)=>{d??(d=r.value);const c=h.value;if(!s(c))return h.issues.push({expected:"object",code:"invalid_type",input:c,inst:t}),h;const p=[];if(o&&l&&(g==null?void 0:g.async)===!1&&g.jitless!==!0)n||(n=a(e.shape)),h=n(h,g);else{h.value={};const y=d.shape;for(const _ of d.keys){const E=y[_],I=E._zod.run({value:c[_],issues:[]},g),S=E._zod.optin==="optional"&&E._zod.optout==="optional";I instanceof Promise?p.push(I.then(R=>S?Yu(R,h,_,c):Va(R,h,_))):S?Yu(I,h,_,c):Va(I,h,_)}}if(!u)return p.length?Promise.all(p).then(()=>h):h;const f=[],m=d.keySet,v=u._zod,w=v.def.type;for(const y of Object.keys(c)){if(m.has(y))continue;if(w==="never"){f.push(y);continue}const _=v.run({value:c[y],issues:[]},g);_ instanceof Promise?p.push(_.then(E=>Va(E,h,y))):Va(_,h,y)}return f.length&&h.issues.push({code:"unrecognized_keys",keys:f,input:c,inst:t}),p.length?Promise.all(p).then(()=>h):h}});function Xu(t,e,r,a){for(const n of t)if(n.issues.length===0)return e.value=n.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(n=>n.issues.map(s=>Pr(s,a,kr())))}),e}const ec=j("$ZodUnion",(t,e)=>{Fe.init(t,e),De(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),De(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),De(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),De(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){const r=e.options.map(a=>a._zod.pattern);return new RegExp(`^(${r.map(a=>bo(a.source)).join("|")})$`)}}),t._zod.parse=(r,a)=>{let n=!1;const s=[];for(const o of e.options){const i=o._zod.run({value:r.value,issues:[]},a);if(i instanceof Promise)s.push(i),n=!0;else{if(i.issues.length===0)return i;s.push(i)}}return n?Promise.all(s).then(o=>Xu(o,r,t,a)):Xu(s,r,t,a)}}),Xg=j("$ZodDiscriminatedUnion",(t,e)=>{ec.init(t,e);const r=t._zod.parse;De(t._zod,"propValues",()=>{const n={};for(const s of e.options){const o=s._zod.propValues;if(!o||Object.keys(o).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(const[i,l]of Object.entries(o)){n[i]||(n[i]=new Set);for(const u of l)n[i].add(u)}}return n});const a=_o(()=>{const n=e.options,s=new Map;for(const o of n){const i=o._zod.propValues[e.discriminator];if(!i||i.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(o)}"`);for(const l of i){if(s.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);s.set(l,o)}}return s});t._zod.parse=(n,s)=>{const o=n.value;if(!Ua(o))return n.issues.push({code:"invalid_type",expected:"object",input:o,inst:t}),n;const i=a.value.get(o==null?void 0:o[e.discriminator]);return i?i._zod.run(n,s):e.unionFallback?r(n,s):(n.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:o,path:[e.discriminator],inst:t}),n)}}),ey=j("$ZodIntersection",(t,e)=>{Fe.init(t,e),t._zod.parse=(r,a)=>{const n=r.value,s=e.left._zod.run({value:n,issues:[]},a),o=e.right._zod.run({value:n,issues:[]},a);return s instanceof Promise||o instanceof Promise?Promise.all([s,o]).then(([l,u])=>tc(r,l,u)):tc(r,s,o)}});function So(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(Fa(t)&&Fa(e)){const r=Object.keys(e),a=Object.keys(t).filter(s=>r.indexOf(s)!==-1),n={...t,...e};for(const s of a){const o=So(t[s],e[s]);if(!o.valid)return{valid:!1,mergeErrorPath:[s,...o.mergeErrorPath]};n[s]=o.data}return{valid:!0,data:n}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let a=0;a<t.length;a++){const n=t[a],s=e[a],o=So(n,s);if(!o.valid)return{valid:!1,mergeErrorPath:[a,...o.mergeErrorPath]};r.push(o.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function tc(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),Jn(t))return t;const a=So(e.value,r.value);if(!a.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return t.value=a.data,t}const ty=j("$ZodRecord",(t,e)=>{Fe.init(t,e),t._zod.parse=(r,a)=>{const n=r.value;if(!Fa(n))return r.issues.push({expected:"record",code:"invalid_type",input:n,inst:t}),r;const s=[];if(e.keyType._zod.values){const o=e.keyType._zod.values;r.value={};for(const l of o)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){const u=e.valueType._zod.run({value:n[l],issues:[]},a);u instanceof Promise?s.push(u.then(d=>{d.issues.length&&r.issues.push(...Jr(l,d.issues)),r.value[l]=d.value})):(u.issues.length&&r.issues.push(...Jr(l,u.issues)),r.value[l]=u.value)}let i;for(const l in n)o.has(l)||(i=i??[],i.push(l));i&&i.length>0&&r.issues.push({code:"unrecognized_keys",input:n,inst:t,keys:i})}else{r.value={};for(const o of Reflect.ownKeys(n)){if(o==="__proto__")continue;const i=e.keyType._zod.run({value:o,issues:[]},a);if(i instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(i.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:i.issues.map(u=>Pr(u,a,kr())),input:o,path:[o],inst:t}),r.value[i.value]=i.value;continue}const l=e.valueType._zod.run({value:n[o],issues:[]},a);l instanceof Promise?s.push(l.then(u=>{u.issues.length&&r.issues.push(...Jr(o,u.issues)),r.value[i.value]=u.value})):(l.issues.length&&r.issues.push(...Jr(o,l.issues)),r.value[i.value]=l.value)}}return s.length?Promise.all(s).then(()=>r):r}}),ry=j("$ZodEnum",(t,e)=>{Fe.init(t,e);const r=Mu(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(a=>gv.has(typeof a)).map(a=>typeof a=="string"?Hn(a):a.toString()).join("|")})$`),t._zod.parse=(a,n)=>{const s=a.value;return t._zod.values.has(s)||a.issues.push({code:"invalid_value",values:r,input:s,inst:t}),a}}),ny=j("$ZodLiteral",(t,e)=>{Fe.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?Hn(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,a)=>{const n=r.value;return t._zod.values.has(n)||r.issues.push({code:"invalid_value",values:e.values,input:n,inst:t}),r}}),ay=j("$ZodTransform",(t,e)=>{Fe.init(t,e),t._zod.parse=(r,a)=>{const n=e.transform(r.value,r);if(a.async)return(n instanceof Promise?n:Promise.resolve(n)).then(o=>(r.value=o,r));if(n instanceof Promise)throw new Vn;return r.value=n,r}}),sy=j("$ZodOptional",(t,e)=>{Fe.init(t,e),t._zod.optin="optional",t._zod.optout="optional",De(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),De(t._zod,"pattern",()=>{const r=e.innerType._zod.pattern;return r?new RegExp(`^(${bo(r.source)})?$`):void 0}),t._zod.parse=(r,a)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,a):r.value===void 0?r:e.innerType._zod.run(r,a)}),oy=j("$ZodNullable",(t,e)=>{Fe.init(t,e),De(t._zod,"optin",()=>e.innerType._zod.optin),De(t._zod,"optout",()=>e.innerType._zod.optout),De(t._zod,"pattern",()=>{const r=e.innerType._zod.pattern;return r?new RegExp(`^(${bo(r.source)}|null)$`):void 0}),De(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,a)=>r.value===null?r:e.innerType._zod.run(r,a)}),iy=j("$ZodDefault",(t,e)=>{Fe.init(t,e),t._zod.optin="optional",De(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,a)=>{if(r.value===void 0)return r.value=e.defaultValue,r;const n=e.innerType._zod.run(r,a);return n instanceof Promise?n.then(s=>rc(s,e)):rc(n,e)}});function rc(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}const ly=j("$ZodPrefault",(t,e)=>{Fe.init(t,e),t._zod.optin="optional",De(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,a)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,a))}),uy=j("$ZodNonOptional",(t,e)=>{Fe.init(t,e),De(t._zod,"values",()=>{const r=e.innerType._zod.values;return r?new Set([...r].filter(a=>a!==void 0)):void 0}),t._zod.parse=(r,a)=>{const n=e.innerType._zod.run(r,a);return n instanceof Promise?n.then(s=>nc(s,t)):nc(n,t)}});function nc(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}const cy=j("$ZodCatch",(t,e)=>{Fe.init(t,e),t._zod.optin="optional",De(t._zod,"optout",()=>e.innerType._zod.optout),De(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,a)=>{const n=e.innerType._zod.run(r,a);return n instanceof Promise?n.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(o=>Pr(o,a,kr()))},input:r.value}),r.issues=[]),r)):(r.value=n.value,n.issues.length&&(r.value=e.catchValue({...r,error:{issues:n.issues.map(s=>Pr(s,a,kr()))},input:r.value}),r.issues=[]),r)}}),dy=j("$ZodPipe",(t,e)=>{Fe.init(t,e),De(t._zod,"values",()=>e.in._zod.values),De(t._zod,"optin",()=>e.in._zod.optin),De(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,a)=>{const n=e.in._zod.run(r,a);return n instanceof Promise?n.then(s=>ac(s,e,a)):ac(n,e,a)}});function ac(t,e,r){return Jn(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}const py=j("$ZodReadonly",(t,e)=>{Fe.init(t,e),De(t._zod,"propValues",()=>e.innerType._zod.propValues),De(t._zod,"values",()=>e.innerType._zod.values),De(t._zod,"optin",()=>e.innerType._zod.optin),De(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,a)=>{const n=e.innerType._zod.run(r,a);return n instanceof Promise?n.then(sc):sc(n)}});function sc(t){return t.value=Object.freeze(t.value),t}const hy=j("$ZodLazy",(t,e)=>{Fe.init(t,e),De(t._zod,"innerType",()=>e.getter()),De(t._zod,"pattern",()=>t._zod.innerType._zod.pattern),De(t._zod,"propValues",()=>t._zod.innerType._zod.propValues),De(t._zod,"optin",()=>t._zod.innerType._zod.optin),De(t._zod,"optout",()=>t._zod.innerType._zod.optout),t._zod.parse=(r,a)=>t._zod.innerType._zod.run(r,a)}),fy=j("$ZodCustom",(t,e)=>{Et.init(t,e),Fe.init(t,e),t._zod.parse=(r,a)=>r,t._zod.check=r=>{const a=r.value,n=e.fn(a);if(n instanceof Promise)return n.then(s=>oc(s,r,a,t));oc(n,r,a,t)}});function oc(t,e,r,a){if(!t){const n={code:"custom",input:r,inst:a,path:[...a._zod.def.path??[]],continue:!a._zod.def.abort};a._zod.def.params&&(n.params=a._zod.def.params),e.issues.push(Wn(n))}}class ic{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){const a=r[0];if(this._map.set(e,a),a&&typeof a=="object"&&"id"in a){if(this._idmap.has(a.id))throw new Error(`ID ${a.id} already exists in the registry`);this._idmap.set(a.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){const r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){const r=e._zod.parent;if(r){const a={...this.get(r)??{}};return delete a.id,{...a,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}}function my(){return new ic}const Gn=my();function vy(t,e){return new t({type:"string",...X(e)})}function gy(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...X(e)})}function lc(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...X(e)})}function yy(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...X(e)})}function _y(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...X(e)})}function wy(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...X(e)})}function by(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...X(e)})}function xy(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...X(e)})}function Ey(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...X(e)})}function Sy(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...X(e)})}function Iy(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...X(e)})}function Ty(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...X(e)})}function ky(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...X(e)})}function Py(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...X(e)})}function Cy(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...X(e)})}function Ry(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...X(e)})}function Oy(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...X(e)})}function $y(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...X(e)})}function Ay(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...X(e)})}function uc(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...X(e)})}function Ny(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...X(e)})}function My(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...X(e)})}function Dy(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...X(e)})}function jy(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...X(e)})}function Ly(t,e){return new t({type:"string",format:"date",check:"string_format",...X(e)})}function zy(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...X(e)})}function Uy(t,e){return new t({type:"string",format:"duration",check:"string_format",...X(e)})}function Fy(t,e){return new t({type:"number",checks:[],...X(e)})}function qy(t,e){return new t({type:"number",coerce:!0,checks:[],...X(e)})}function Zy(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...X(e)})}function Vy(t,e){return new t({type:"boolean",...X(e)})}function By(t,e){return new t({type:"null",...X(e)})}function Hy(t){return new t({type:"any"})}function Jy(t){return new t({type:"unknown"})}function Wy(t,e){return new t({type:"never",...X(e)})}function cc(t,e){return new Ju({check:"less_than",...X(e),value:t,inclusive:!1})}function Io(t,e){return new Ju({check:"less_than",...X(e),value:t,inclusive:!0})}function dc(t,e){return new Wu({check:"greater_than",...X(e),value:t,inclusive:!1})}function To(t,e){return new Wu({check:"greater_than",...X(e),value:t,inclusive:!0})}function pc(t,e){return new og({check:"multiple_of",...X(e),value:t})}function hc(t,e){return new lg({check:"max_length",...X(e),maximum:t})}function Ba(t,e){return new ug({check:"min_length",...X(e),minimum:t})}function fc(t,e){return new cg({check:"length_equals",...X(e),length:t})}function Gy(t,e){return new dg({check:"string_format",format:"regex",...X(e),pattern:t})}function Ky(t){return new pg({check:"string_format",format:"lowercase",...X(t)})}function Qy(t){return new hg({check:"string_format",format:"uppercase",...X(t)})}function Yy(t,e){return new fg({check:"string_format",format:"includes",...X(e),includes:t})}function Xy(t,e){return new mg({check:"string_format",format:"starts_with",...X(e),prefix:t})}function e_(t,e){return new vg({check:"string_format",format:"ends_with",...X(e),suffix:t})}function Kn(t){return new gg({check:"overwrite",tx:t})}function t_(t){return Kn(e=>e.normalize(t))}function r_(){return Kn(t=>t.trim())}function n_(){return Kn(t=>t.toLowerCase())}function a_(){return Kn(t=>t.toUpperCase())}function s_(t,e,r){return new t({type:"array",element:e,...X(r)})}function o_(t,e,r){const a=X(r);return a.abort??(a.abort=!0),new t({type:"custom",check:"custom",fn:e,...a})}function i_(t,e,r){return new t({type:"custom",check:"custom",fn:e,...X(r)})}class mc{constructor(e){this.counter=0,this.metadataRegistry=(e==null?void 0:e.metadata)??Gn,this.target=(e==null?void 0:e.target)??"draft-2020-12",this.unrepresentable=(e==null?void 0:e.unrepresentable)??"throw",this.override=(e==null?void 0:e.override)??(()=>{}),this.io=(e==null?void 0:e.io)??"output",this.seen=new Map}process(e,r={path:[],schemaPath:[]}){var h,g,c;var a;const n=e._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},o=this.seen.get(e);if(o)return o.count++,r.schemaPath.includes(e)&&(o.cycle=r.path),o.schema;const i={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(e,i);const l=(g=(h=e._zod).toJSONSchema)==null?void 0:g.call(h);if(l)i.schema=l;else{const p={...r,schemaPath:[...r.schemaPath,e],path:r.path},f=e._zod.parent;if(f)i.ref=f,this.process(f,p),this.seen.get(f).isParent=!0;else{const m=i.schema;switch(n.type){case"string":{const v=m;v.type="string";const{minimum:w,maximum:y,format:_,patterns:E,contentEncoding:I}=e._zod.bag;if(typeof w=="number"&&(v.minLength=w),typeof y=="number"&&(v.maxLength=y),_&&(v.format=s[_]??_,v.format===""&&delete v.format),I&&(v.contentEncoding=I),E&&E.size>0){const S=[...E];S.length===1?v.pattern=S[0].source:S.length>1&&(i.schema.allOf=[...S.map(R=>({...this.target==="draft-7"?{type:"string"}:{},pattern:R.source}))])}break}case"number":{const v=m,{minimum:w,maximum:y,format:_,multipleOf:E,exclusiveMaximum:I,exclusiveMinimum:S}=e._zod.bag;typeof _=="string"&&_.includes("int")?v.type="integer":v.type="number",typeof S=="number"&&(v.exclusiveMinimum=S),typeof w=="number"&&(v.minimum=w,typeof S=="number"&&(S>=w?delete v.minimum:delete v.exclusiveMinimum)),typeof I=="number"&&(v.exclusiveMaximum=I),typeof y=="number"&&(v.maximum=y,typeof I=="number"&&(I<=y?delete v.maximum:delete v.exclusiveMaximum)),typeof E=="number"&&(v.multipleOf=E);break}case"boolean":{const v=m;v.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{m.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{m.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const v=m,{minimum:w,maximum:y}=e._zod.bag;typeof w=="number"&&(v.minItems=w),typeof y=="number"&&(v.maxItems=y),v.type="array",v.items=this.process(n.element,{...p,path:[...p.path,"items"]});break}case"object":{const v=m;v.type="object",v.properties={};const w=n.shape;for(const E in w)v.properties[E]=this.process(w[E],{...p,path:[...p.path,"properties",E]});const y=new Set(Object.keys(w)),_=new Set([...y].filter(E=>{const I=n.shape[E]._zod;return this.io==="input"?I.optin===void 0:I.optout===void 0}));_.size>0&&(v.required=Array.from(_)),((c=n.catchall)==null?void 0:c._zod.def.type)==="never"?v.additionalProperties=!1:n.catchall?n.catchall&&(v.additionalProperties=this.process(n.catchall,{...p,path:[...p.path,"additionalProperties"]})):this.io==="output"&&(v.additionalProperties=!1);break}case"union":{const v=m;v.anyOf=n.options.map((w,y)=>this.process(w,{...p,path:[...p.path,"anyOf",y]}));break}case"intersection":{const v=m,w=this.process(n.left,{...p,path:[...p.path,"allOf",0]}),y=this.process(n.right,{...p,path:[...p.path,"allOf",1]}),_=I=>"allOf"in I&&Object.keys(I).length===1,E=[..._(w)?w.allOf:[w],..._(y)?y.allOf:[y]];v.allOf=E;break}case"tuple":{const v=m;v.type="array";const w=n.items.map((E,I)=>this.process(E,{...p,path:[...p.path,"prefixItems",I]}));if(this.target==="draft-2020-12"?v.prefixItems=w:v.items=w,n.rest){const E=this.process(n.rest,{...p,path:[...p.path,"items"]});this.target==="draft-2020-12"?v.items=E:v.additionalItems=E}n.rest&&(v.items=this.process(n.rest,{...p,path:[...p.path,"items"]}));const{minimum:y,maximum:_}=e._zod.bag;typeof y=="number"&&(v.minItems=y),typeof _=="number"&&(v.maxItems=_);break}case"record":{const v=m;v.type="object",v.propertyNames=this.process(n.keyType,{...p,path:[...p.path,"propertyNames"]}),v.additionalProperties=this.process(n.valueType,{...p,path:[...p.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 v=m,w=Mu(n.entries);w.every(y=>typeof y=="number")&&(v.type="number"),w.every(y=>typeof y=="string")&&(v.type="string"),v.enum=w;break}case"literal":{const v=m,w=[];for(const y of n.values)if(y===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof y=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");w.push(Number(y))}else w.push(y);if(w.length!==0)if(w.length===1){const y=w[0];v.type=y===null?"null":typeof y,v.const=y}else w.every(y=>typeof y=="number")&&(v.type="number"),w.every(y=>typeof y=="string")&&(v.type="string"),w.every(y=>typeof y=="boolean")&&(v.type="string"),w.every(y=>y===null)&&(v.type="null"),v.enum=w;break}case"file":{const v=m,w={type:"string",format:"binary",contentEncoding:"binary"},{minimum:y,maximum:_,mime:E}=e._zod.bag;y!==void 0&&(w.minLength=y),_!==void 0&&(w.maxLength=_),E?E.length===1?(w.contentMediaType=E[0],Object.assign(v,w)):v.anyOf=E.map(I=>({...w,contentMediaType:I})):Object.assign(v,w);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const v=this.process(n.innerType,p);m.anyOf=[v,{type:"null"}];break}case"nonoptional":{this.process(n.innerType,p),i.ref=n.innerType;break}case"success":{const v=m;v.type="boolean";break}case"default":{this.process(n.innerType,p),i.ref=n.innerType,m.default=JSON.parse(JSON.stringify(n.defaultValue));break}case"prefault":{this.process(n.innerType,p),i.ref=n.innerType,this.io==="input"&&(m._prefault=JSON.parse(JSON.stringify(n.defaultValue)));break}case"catch":{this.process(n.innerType,p),i.ref=n.innerType;let v;try{v=n.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}m.default=v;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const v=m,w=e._zod.pattern;if(!w)throw new Error("Pattern not found in template literal");v.type="string",v.pattern=w.source;break}case"pipe":{const v=this.io==="input"?n.in._zod.def.type==="transform"?n.out:n.in:n.out;this.process(v,p),i.ref=v;break}case"readonly":{this.process(n.innerType,p),i.ref=n.innerType,m.readOnly=!0;break}case"promise":{this.process(n.innerType,p),i.ref=n.innerType;break}case"optional":{this.process(n.innerType,p),i.ref=n.innerType;break}case"lazy":{const v=e._zod.innerType;this.process(v,p),i.ref=v;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const u=this.metadataRegistry.get(e);return u&&Object.assign(i.schema,u),this.io==="input"&&it(e)&&(delete i.schema.examples,delete i.schema.default),this.io==="input"&&i.schema._prefault&&((a=i.schema).default??(a.default=i.schema._prefault)),delete i.schema._prefault,this.seen.get(e).schema}emit(e,r){var d,h,g,c,p,f;const a={cycles:(r==null?void 0:r.cycles)??"ref",reused:(r==null?void 0:r.reused)??"inline",external:(r==null?void 0:r.external)??void 0},n=this.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=m=>{var E;const v=this.target==="draft-2020-12"?"$defs":"definitions";if(a.external){const I=(E=a.external.registry.get(m[0]))==null?void 0:E.id,S=a.external.uri??($=>$);if(I)return{ref:S(I)};const R=m[1].defId??m[1].schema.id??`schema${this.counter++}`;return m[1].defId=R,{defId:R,ref:`${S("__shared")}#/${v}/${R}`}}if(m[1]===n)return{ref:"#"};const y=`#/${v}/`,_=m[1].schema.id??`__schema${this.counter++}`;return{defId:_,ref:y+_}},o=m=>{if(m[1].schema.$ref)return;const v=m[1],{ref:w,defId:y}=s(m);v.def={...v.schema},y&&(v.defId=y);const _=v.schema;for(const E in _)delete _[E];_.$ref=w};if(a.cycles==="throw")for(const m of this.seen.entries()){const v=m[1];if(v.cycle)throw new Error(`Cycle detected: #/${(d=v.cycle)==null?void 0:d.join("/")}/<root>
|
|
33
33
|
|
|
34
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const m of this.seen.entries()){const c=m[1];if(t===m[0]){a(m);continue}if(r.external){const v=(x=r.external.registry.get(m[0]))==null?void 0:x.id;if(t!==m[0]&&v){a(m);continue}}if((w=this.metadataRegistry.get(m[0]))==null?void 0:w.id){a(m);continue}if(c.cycle){a(m);continue}if(c.count>1&&r.reused==="ref"){a(m);continue}}const i=(m,c)=>{const b=this.seen.get(m),v=b.def??b.schema,_={...v};if(b.ref===null)return;const R=b.ref;if(b.ref=null,R){i(R,c);const C=this.seen.get(R).schema;C.$ref&&c.target==="draft-7"?(v.allOf=v.allOf??[],v.allOf.push(C)):(Object.assign(v,C),Object.assign(v,_))}b.isParent||this.override({zodSchema:m,jsonSchema:v,path:b.path??[]})};for(const m of[...this.seen.entries()].reverse())i(m[0],{target:this.target});const l={};if(this.target==="draft-2020-12"?l.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?l.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),(h=r.external)!=null&&h.uri){const m=(f=r.external.registry.get(t))==null?void 0:f.id;if(!m)throw new Error("Schema is missing an `id` property");l.$id=r.external.uri(m)}Object.assign(l,o.def);const u=((y=r.external)==null?void 0:y.defs)??{};for(const m of this.seen.entries()){const c=m[1];c.def&&c.defId&&(u[c.defId]=c.def)}r.external||Object.keys(u).length>0&&(this.target==="draft-2020-12"?l.$defs=u:l.definitions=u);try{return JSON.parse(JSON.stringify(l))}catch{throw new Error("Error converting schema to JSON.")}}}function mm(e,t){if(e instanceof Mi){const r=new Li(t),o={};for(const i of e._idmap.entries()){const[l,u]=i;r.process(u)}const s={},a={registry:e,uri:t==null?void 0:t.uri,defs:o};for(const i of e._idmap.entries()){const[l,u]=i;s[l]=r.emit(u,{...t,external:a})}if(Object.keys(o).length>0){const i=r.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[i]:o}}return{schemas:s}}const n=new Li(t);return n.process(e),n.emit(e,t)}function ze(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const o=e._zod.def;switch(o.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return ze(o.element,n);case"object":{for(const s in o.shape)if(ze(o.shape[s],n))return!0;return!1}case"union":{for(const s of o.options)if(ze(s,n))return!0;return!1}case"intersection":return ze(o.left,n)||ze(o.right,n);case"tuple":{for(const s of o.items)if(ze(s,n))return!0;return!!(o.rest&&ze(o.rest,n))}case"record":return ze(o.keyType,n)||ze(o.valueType,n);case"map":return ze(o.keyType,n)||ze(o.valueType,n);case"set":return ze(o.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return ze(o.innerType,n);case"lazy":return ze(o.getter(),n);case"default":return ze(o.innerType,n);case"prefault":return ze(o.innerType,n);case"custom":return!1;case"transform":return!0;case"pipe":return ze(o.in,n)||ze(o.out,n);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${o.type}`)}const gm=E("ZodISODateTime",(e,t)=>{jh.init(e,t),Te.init(e,t)});function vm(e){return Vf(gm,e)}const ym=E("ZodISODate",(e,t)=>{Dh.init(e,t),Te.init(e,t)});function _m(e){return Ff(ym,e)}const wm=E("ZodISOTime",(e,t)=>{Uh.init(e,t),Te.init(e,t)});function bm(e){return Hf(wm,e)}const xm=E("ZodISODuration",(e,t)=>{Zh.init(e,t),Te.init(e,t)});function km(e){return Jf(xm,e)}const Pr=E("ZodError",(e,t)=>{ci.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>Mp(e,n)},flatten:{value:n=>Np(e,n)},addIssue:{value:n=>e.issues.push(n)},addIssues:{value:n=>e.issues.push(...n)},isEmpty:{get(){return e.issues.length===0}}})},{Parent:Error}),Tm=Pp(Pr),Sm=$p(Pr),Im=pi(Pr),qi=hi(Pr),be=E("ZodType",(e,t)=>(ye.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),e.clone=(n,r)=>nn(e,n,r),e.brand=()=>e,e.register=(n,r)=>(n.add(e,r),e),e.parse=(n,r)=>Tm(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>Im(e,n,r),e.parseAsync=async(n,r)=>Sm(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>qi(e,n,r),e.spa=e.safeParseAsync,e.refine=(n,r)=>e.check(wg(n,r)),e.superRefine=n=>e.check(bg(n)),e.overwrite=n=>e.check(Vn(n)),e.optional=()=>Ne(e),e.nullable=()=>Yi(e),e.nullish=()=>Ne(Yi(e)),e.nonoptional=n=>dg(e,n),e.array=()=>z(e),e.or=n=>ue([e,n]),e.and=n=>tg(e,n),e.transform=n=>Qi(e,sg(n)),e.default=n=>lg(e,n),e.prefault=n=>cg(e,n),e.catch=n=>hg(e,n),e.pipe=n=>Qi(e,n),e.readonly=()=>gg(e),e.describe=n=>{const r=e.clone();return Bn.add(r,{description:n}),r},Object.defineProperty(e,"description",{get(){var n;return(n=Bn.get(e))==null?void 0:n.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return Bn.get(e);const r=e.clone();return Bn.add(r,n[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),Bi=E("_ZodString",(e,t)=>{zo.init(e,t),be.init(e,t);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...r)=>e.check(nm(...r)),e.includes=(...r)=>e.check(sm(...r)),e.startsWith=(...r)=>e.check(am(...r)),e.endsWith=(...r)=>e.check(im(...r)),e.min=(...r)=>e.check(Mr(...r)),e.max=(...r)=>e.check(Ui(...r)),e.length=(...r)=>e.check(Zi(...r)),e.nonempty=(...r)=>e.check(Mr(1,...r)),e.lowercase=r=>e.check(rm(r)),e.uppercase=r=>e.check(om(r)),e.trim=()=>e.check(um()),e.normalize=(...r)=>e.check(lm(...r)),e.toLowerCase=()=>e.check(cm()),e.toUpperCase=()=>e.check(dm())}),Cm=E("ZodString",(e,t)=>{zo.init(e,t),Bi.init(e,t),e.email=n=>e.check(Tf(Em,n)),e.url=n=>e.check(Rf(Rm,n)),e.jwt=n=>e.check(Bf(Bm,n)),e.emoji=n=>e.check(Af(Am,n)),e.guid=n=>e.check(Pi(Vi,n)),e.uuid=n=>e.check(Sf($r,n)),e.uuidv4=n=>e.check(If($r,n)),e.uuidv6=n=>e.check(Cf($r,n)),e.uuidv7=n=>e.check(Ef($r,n)),e.nanoid=n=>e.check(Of(Om,n)),e.guid=n=>e.check(Pi(Vi,n)),e.cuid=n=>e.check(Nf(Nm,n)),e.cuid2=n=>e.check(Mf(Mm,n)),e.ulid=n=>e.check(Pf(Pm,n)),e.base64=n=>e.check($i(Fi,n)),e.base64url=n=>e.check(Lf(Lm,n)),e.xid=n=>e.check($f($m,n)),e.ksuid=n=>e.check(zf(zm,n)),e.ipv4=n=>e.check(jf(jm,n)),e.ipv6=n=>e.check(Df(Dm,n)),e.cidrv4=n=>e.check(Uf(Um,n)),e.cidrv6=n=>e.check(Zf(Zm,n)),e.e164=n=>e.check(qf(qm,n)),e.datetime=n=>e.check(vm(n)),e.date=n=>e.check(_m(n)),e.time=n=>e.check(bm(n)),e.duration=n=>e.check(km(n))});function d(e){return kf(Cm,e)}const Te=E("ZodStringFormat",(e,t)=>{ke.init(e,t),Bi.init(e,t)}),Em=E("ZodEmail",(e,t)=>{Eh.init(e,t),Te.init(e,t)}),Vi=E("ZodGUID",(e,t)=>{Ih.init(e,t),Te.init(e,t)}),$r=E("ZodUUID",(e,t)=>{Ch.init(e,t),Te.init(e,t)}),Rm=E("ZodURL",(e,t)=>{Rh.init(e,t),Te.init(e,t)}),Am=E("ZodEmoji",(e,t)=>{Ah.init(e,t),Te.init(e,t)}),Om=E("ZodNanoID",(e,t)=>{Oh.init(e,t),Te.init(e,t)}),Nm=E("ZodCUID",(e,t)=>{Nh.init(e,t),Te.init(e,t)}),Mm=E("ZodCUID2",(e,t)=>{Mh.init(e,t),Te.init(e,t)}),Pm=E("ZodULID",(e,t)=>{Ph.init(e,t),Te.init(e,t)}),$m=E("ZodXID",(e,t)=>{$h.init(e,t),Te.init(e,t)}),zm=E("ZodKSUID",(e,t)=>{zh.init(e,t),Te.init(e,t)}),jm=E("ZodIPv4",(e,t)=>{Lh.init(e,t),Te.init(e,t)}),Dm=E("ZodIPv6",(e,t)=>{qh.init(e,t),Te.init(e,t)}),Um=E("ZodCIDRv4",(e,t)=>{Bh.init(e,t),Te.init(e,t)}),Zm=E("ZodCIDRv6",(e,t)=>{Vh.init(e,t),Te.init(e,t)}),Fi=E("ZodBase64",(e,t)=>{Fh.init(e,t),Te.init(e,t)});function Hi(e){return $i(Fi,e)}const Lm=E("ZodBase64URL",(e,t)=>{Jh.init(e,t),Te.init(e,t)}),qm=E("ZodE164",(e,t)=>{Gh.init(e,t),Te.init(e,t)}),Bm=E("ZodJWT",(e,t)=>{Kh.init(e,t),Te.init(e,t)}),Zo=E("ZodNumber",(e,t)=>{xi.init(e,t),be.init(e,t),e.gt=(r,o)=>e.check(ji(r,o)),e.gte=(r,o)=>e.check(Uo(r,o)),e.min=(r,o)=>e.check(Uo(r,o)),e.lt=(r,o)=>e.check(zi(r,o)),e.lte=(r,o)=>e.check(Do(r,o)),e.max=(r,o)=>e.check(Do(r,o)),e.int=r=>e.check(Ji(r)),e.safe=r=>e.check(Ji(r)),e.positive=r=>e.check(ji(0,r)),e.nonnegative=r=>e.check(Uo(0,r)),e.negative=r=>e.check(zi(0,r)),e.nonpositive=r=>e.check(Do(0,r)),e.multipleOf=(r,o)=>e.check(Di(r,o)),e.step=(r,o)=>e.check(Di(r,o)),e.finite=()=>e;const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function I(e){return Gf(Zo,e)}const Vm=E("ZodNumberFormat",(e,t)=>{Yh.init(e,t),Zo.init(e,t)});function Ji(e){return Kf(Vm,e)}const Fm=E("ZodBoolean",(e,t)=>{Xh.init(e,t),be.init(e,t)});function Ae(e){return Yf(Fm,e)}const Hm=E("ZodNull",(e,t)=>{Qh.init(e,t),be.init(e,t)});function Jm(e){return Xf(Hm,e)}const Gm=E("ZodAny",(e,t)=>{ef.init(e,t),be.init(e,t)});function ut(){return Qf(Gm)}const Wm=E("ZodUnknown",(e,t)=>{tf.init(e,t),be.init(e,t)});function mt(){return em(Wm)}const Km=E("ZodNever",(e,t)=>{nf.init(e,t),be.init(e,t)});function Ym(e){return tm(Km,e)}const Xm=E("ZodArray",(e,t)=>{rf.init(e,t),be.init(e,t),e.element=t.element,e.min=(n,r)=>e.check(Mr(n,r)),e.nonempty=n=>e.check(Mr(1,n)),e.max=(n,r)=>e.check(Ui(n,r)),e.length=(n,r)=>e.check(Zi(n,r)),e.unwrap=()=>e.element});function z(e,t){return pm(Xm,e,t)}const Gi=E("ZodObject",(e,t)=>{of.init(e,t),be.init(e,t),pe(e,"shape",()=>t.shape),e.keyof=()=>Se(Object.keys(e._zod.def.shape)),e.catchall=n=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:mt()}),e.loose=()=>e.clone({...e._zod.def,catchall:mt()}),e.strict=()=>e.clone({...e._zod.def,catchall:Ym()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=n=>Ep(e,n),e.merge=n=>Rp(e,n),e.pick=n=>Ip(e,n),e.omit=n=>Cp(e,n),e.partial=(...n)=>Ap(Ki,e,n[0]),e.required=(...n)=>Op(Xi,e,n[0])});function g(e,t){const n={type:"object",get shape(){return Cr(this,"shape",{...e}),this.shape},...q(t)};return new Gi(n)}function _n(e,t){return new Gi({type:"object",get shape(){return Cr(this,"shape",{...e}),this.shape},catchall:mt(),...q(t)})}const Wi=E("ZodUnion",(e,t)=>{Ii.init(e,t),be.init(e,t),e.options=t.options});function ue(e,t){return new Wi({type:"union",options:e,...q(t)})}const Qm=E("ZodDiscriminatedUnion",(e,t)=>{Wi.init(e,t),sf.init(e,t)});function et(e,t,n){return new Qm({type:"union",options:t,discriminator:e,...q(n)})}const eg=E("ZodIntersection",(e,t)=>{af.init(e,t),be.init(e,t)});function tg(e,t){return new eg({type:"intersection",left:e,right:t})}const ng=E("ZodRecord",(e,t)=>{lf.init(e,t),be.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function Oe(e,t,n){return new ng({type:"record",keyType:e,valueType:t,...q(n)})}const Lo=E("ZodEnum",(e,t)=>{uf.init(e,t),be.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(r,o)=>{const s={};for(const a of r)if(n.has(a))s[a]=t.entries[a];else throw new Error(`Key ${a} not found in enum`);return new Lo({...t,checks:[],...q(o),entries:s})},e.exclude=(r,o)=>{const s={...t.entries};for(const a of r)if(n.has(a))delete s[a];else throw new Error(`Key ${a} not found in enum`);return new Lo({...t,checks:[],...q(o),entries:s})}});function Se(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new Lo({type:"enum",entries:n,...q(t)})}const rg=E("ZodLiteral",(e,t)=>{cf.init(e,t),be.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 A(e,t){return new rg({type:"literal",values:Array.isArray(e)?e:[e],...q(t)})}const og=E("ZodTransform",(e,t)=>{df.init(e,t),be.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=s=>{if(typeof s=="string")n.issues.push(qn(s,n.value,t));else{const a=s;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=n.value),a.inst??(a.inst=e),a.continue??(a.continue=!0),n.issues.push(qn(a))}};const o=t.transform(n.value,n);return o instanceof Promise?o.then(s=>(n.value=s,n)):(n.value=o,n)}});function sg(e){return new og({type:"transform",transform:e})}const Ki=E("ZodOptional",(e,t)=>{pf.init(e,t),be.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Ne(e){return new Ki({type:"optional",innerType:e})}const ag=E("ZodNullable",(e,t)=>{hf.init(e,t),be.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Yi(e){return new ag({type:"nullable",innerType:e})}const ig=E("ZodDefault",(e,t)=>{ff.init(e,t),be.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function lg(e,t){return new ig({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const ug=E("ZodPrefault",(e,t)=>{mf.init(e,t),be.init(e,t),e.unwrap=()=>e._zod.def.innerType});function cg(e,t){return new ug({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const Xi=E("ZodNonOptional",(e,t)=>{gf.init(e,t),be.init(e,t),e.unwrap=()=>e._zod.def.innerType});function dg(e,t){return new Xi({type:"nonoptional",innerType:e,...q(t)})}const pg=E("ZodCatch",(e,t)=>{vf.init(e,t),be.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function hg(e,t){return new pg({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const fg=E("ZodPipe",(e,t)=>{yf.init(e,t),be.init(e,t),e.in=t.in,e.out=t.out});function Qi(e,t){return new fg({type:"pipe",in:e,out:t})}const mg=E("ZodReadonly",(e,t)=>{_f.init(e,t),be.init(e,t)});function gg(e){return new mg({type:"readonly",innerType:e})}const vg=E("ZodLazy",(e,t)=>{wf.init(e,t),be.init(e,t),e.unwrap=()=>e._zod.def.getter()});function el(e){return new vg({type:"lazy",getter:e})}const qo=E("ZodCustom",(e,t)=>{bf.init(e,t),be.init(e,t)});function yg(e){const t=new Qe({check:"custom"});return t._zod.check=e,t}function _g(e,t){return hm(qo,e??(()=>!0),t)}function wg(e,t={}){return fm(qo,e,t)}function bg(e){const t=yg(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(qn(r,n.value,t._zod.def));else{const o=r;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=t),o.continue??(o.continue=!t._zod.def.abort),n.issues.push(qn(o))}},e(n.value,n)));return t}function zr(e,t={error:`Input not instance of ${e.name}`}){const n=new qo({type:"custom",check:"custom",fn:r=>r instanceof e,abort:!0,...q(t)});return n._zod.bag.Class=e,n}function xg(e){return Wf(Zo,e)}var le;(function(e){e.assertEqual=o=>{};function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{const s={};for(const a of o)s[a]=a;return s},e.getValidEnumValues=o=>{const s=e.objectKeys(o).filter(i=>typeof o[o[i]]!="number"),a={};for(const i of s)a[i]=o[i];return e.objectValues(a)},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 a in o)Object.prototype.hasOwnProperty.call(o,a)&&s.push(a);return s},e.find=(o,s)=>{for(const a of o)if(s(a))return a},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function r(o,s=" | "){return o.map(a=>typeof a=="string"?`'${a}'`:a).join(s)}e.joinValues=r,e.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(le||(le={}));var tl;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(tl||(tl={}));const U=le.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Gt=e=>{switch(typeof e){case"undefined":return U.undefined;case"string":return U.string;case"number":return Number.isNaN(e)?U.nan:U.number;case"boolean":return U.boolean;case"function":return U.function;case"bigint":return U.bigint;case"symbol":return U.symbol;case"object":return Array.isArray(e)?U.array:e===null?U.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?U.promise:typeof Map<"u"&&e instanceof Map?U.map:typeof Set<"u"&&e instanceof Set?U.set:typeof Date<"u"&&e instanceof Date?U.date:U.object;default:return U.unknown}},N=le.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 zt extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){const n=t||function(s){return s.message},r={_errors:[]},o=s=>{for(const a of s.issues)if(a.code==="invalid_union")a.unionErrors.map(o);else if(a.code==="invalid_return_type")o(a.returnTypeError);else if(a.code==="invalid_arguments")o(a.argumentsError);else if(a.path.length===0)r._errors.push(n(a));else{let i=r,l=0;for(;l<a.path.length;){const u=a.path[l];l===a.path.length-1?(i[u]=i[u]||{_errors:[]},i[u]._errors.push(n(a))):i[u]=i[u]||{_errors:[]},i=i[u],l++}}};return o(this),r}static assert(t){if(!(t instanceof zt))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,le.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){const n={},r=[];for(const o of this.issues)if(o.path.length>0){const s=o.path[0];n[s]=n[s]||[],n[s].push(t(o))}else r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}zt.create=e=>new zt(e);const Bo=(e,t)=>{let n;switch(e.code){case N.invalid_type:e.received===U.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case N.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,le.jsonStringifyReplacer)}`;break;case N.unrecognized_keys:n=`Unrecognized key(s) in object: ${le.joinValues(e.keys,", ")}`;break;case N.invalid_union:n="Invalid input";break;case N.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${le.joinValues(e.options)}`;break;case N.invalid_enum_value:n=`Invalid enum value. Expected ${le.joinValues(e.options)}, received '${e.received}'`;break;case N.invalid_arguments:n="Invalid function arguments";break;case N.invalid_return_type:n="Invalid function return type";break;case N.invalid_date:n="Invalid date";break;case N.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:le.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case N.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case N.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case N.custom:n="Invalid input";break;case N.invalid_intersection_types:n="Intersection results could not be merged";break;case N.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case N.not_finite:n="Number must be finite";break;default:n=t.defaultError,le.assertNever(e)}return{message:n}};let kg=Bo;function Tg(){return kg}const Sg=e=>{const{data:t,path:n,errorMaps:r,issueData:o}=e,s=[...n,...o.path||[]],a={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let i="";const l=r.filter(u=>!!u).slice().reverse();for(const u of l)i=u(a,{data:t,defaultError:i}).message;return{...o,path:s,message:i}};function j(e,t){const n=Tg(),r=Sg({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Bo?void 0:Bo].filter(o=>!!o)});e.common.issues.push(r)}class He{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){const r=[];for(const o of n){if(o.status==="aborted")return G;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const o of n){const s=await o.key,a=await o.value;r.push({key:s,value:a})}return He.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const o of n){const{key:s,value:a}=o;if(s.status==="aborted"||a.status==="aborted")return G;s.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof a.value<"u"||o.alwaysSet)&&(r[s.value]=a.value)}return{status:t.value,value:r}}}const G=Object.freeze({status:"aborted"}),Fn=e=>({status:"dirty",value:e}),ct=e=>({status:"valid",value:e}),nl=e=>e.status==="aborted",rl=e=>e.status==="dirty",wn=e=>e.status==="valid",jr=e=>typeof Promise<"u"&&e instanceof Promise;var B;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(B||(B={}));class xt{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,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 ol=(e,t)=>{if(wn(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 n=new zt(e.common.issues);return this._error=n,this._error}}};function Q(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:o}=e;if(t&&(n||r))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:(a,i)=>{const{message:l}=e;return a.code==="invalid_enum_value"?{message:l??i.defaultError}:typeof i.data>"u"?{message:l??r??i.defaultError}:a.code!=="invalid_type"?{message:i.defaultError}:{message:l??n??i.defaultError}},description:o}}class re{get description(){return this._def.description}_getType(t){return Gt(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Gt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new He,ctx:{common:t.parent.common,data:t.data,parsedType:Gt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(jr(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){const n=this._parse(t);return Promise.resolve(n)}parse(t,n){const r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){const r={common:{issues:[],async:(n==null?void 0:n.async)??!1,contextualErrorMap:n==null?void 0:n.errorMap},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Gt(t)},o=this._parseSync({data:t,path:r.path,parent:r});return ol(r,o)}"~validate"(t){var r,o;const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Gt(t)};if(!this["~standard"].async)try{const s=this._parseSync({data:t,path:[],parent:n});return wn(s)?{value:s.value}:{issues:n.common.issues}}catch(s){(o=(r=s==null?void 0:s.message)==null?void 0:r.toLowerCase())!=null&&o.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:n}).then(s=>wn(s)?{value:s.value}:{issues:n.common.issues})}async parseAsync(t,n){const r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){const r={common:{issues:[],contextualErrorMap:n==null?void 0:n.errorMap,async:!0},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Gt(t)},o=this._parse({data:t,path:r.path,parent:r}),s=await(jr(o)?o:Promise.resolve(o));return ol(r,s)}refine(t,n){const r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,s)=>{const a=t(o),i=()=>s.addIssue({code:N.custom,...r(o)});return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(i(),!1)):a?!0:(i(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new an({schema:this,typeName:M.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:n=>this["~validate"](n)}}optional(){return Ut.create(this,this._def)}nullable(){return ln.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return kt.create(this)}promise(){return Br.create(this,this._def)}or(t){return Ur.create([this,t],this._def)}and(t){return Zr.create(this,t,this._def)}transform(t){return new an({...Q(this._def),schema:this,typeName:M.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new Vr({...Q(this._def),innerType:this,defaultValue:n,typeName:M.ZodDefault})}brand(){return new pl({typeName:M.ZodBranded,type:this,...Q(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new Fr({...Q(this._def),innerType:this,catchValue:n,typeName:M.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return es.create(this,t)}readonly(){return Hr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Ig=/^c[^\s-]{8,}$/i,Cg=/^[0-9a-z]+$/,Eg=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Rg=/^[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,Ag=/^[a-z0-9_-]{21}$/i,Og=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Ng=/^[-+]?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)?)??$/,Mg=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Pg="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Vo;const $g=/^(?:(?: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])$/,zg=/^(?:(?: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])$/,jg=/^(([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]))$/,Dg=/^(([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])$/,Ug=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Zg=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,sl="((\\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])))",Lg=new RegExp(`^${sl}$`);function al(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);const n=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function qg(e){return new RegExp(`^${al(e)}$`)}function Bg(e){let t=`${sl}T${al(e)}`;const n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function Vg(e,t){return!!((t==="v4"||!t)&&$g.test(e)||(t==="v6"||!t)&&jg.test(e))}function Fg(e,t){if(!Og.test(e))return!1;try{const[n]=e.split(".");if(!n)return!1;const r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||"typ"in o&&(o==null?void 0:o.typ)!=="JWT"||!o.alg||t&&o.alg!==t)}catch{return!1}}function Hg(e,t){return!!((t==="v4"||!t)&&zg.test(e)||(t==="v6"||!t)&&Dg.test(e))}class jt extends re{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==U.string){const s=this._getOrReturnCtx(t);return j(s,{code:N.invalid_type,expected:U.string,received:s.parsedType}),G}const r=new He;let o;for(const s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(o=this._getOrReturnCtx(t,o),j(o,{code:N.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")t.data.length>s.value&&(o=this._getOrReturnCtx(t,o),j(o,{code:N.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){const a=t.data.length>s.value,i=t.data.length<s.value;(a||i)&&(o=this._getOrReturnCtx(t,o),a?j(o,{code:N.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):i&&j(o,{code:N.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")Mg.test(t.data)||(o=this._getOrReturnCtx(t,o),j(o,{validation:"email",code:N.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")Vo||(Vo=new RegExp(Pg,"u")),Vo.test(t.data)||(o=this._getOrReturnCtx(t,o),j(o,{validation:"emoji",code:N.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")Rg.test(t.data)||(o=this._getOrReturnCtx(t,o),j(o,{validation:"uuid",code:N.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")Ag.test(t.data)||(o=this._getOrReturnCtx(t,o),j(o,{validation:"nanoid",code:N.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")Ig.test(t.data)||(o=this._getOrReturnCtx(t,o),j(o,{validation:"cuid",code:N.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")Cg.test(t.data)||(o=this._getOrReturnCtx(t,o),j(o,{validation:"cuid2",code:N.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")Eg.test(t.data)||(o=this._getOrReturnCtx(t,o),j(o,{validation:"ulid",code:N.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),j(o,{validation:"url",code:N.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),j(o,{validation:"regex",code:N.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(t,o),j(o,{code:N.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.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),j(o,{code:N.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(o=this._getOrReturnCtx(t,o),j(o,{code:N.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?Bg(s).test(t.data)||(o=this._getOrReturnCtx(t,o),j(o,{code:N.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?Lg.test(t.data)||(o=this._getOrReturnCtx(t,o),j(o,{code:N.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?qg(s).test(t.data)||(o=this._getOrReturnCtx(t,o),j(o,{code:N.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?Ng.test(t.data)||(o=this._getOrReturnCtx(t,o),j(o,{validation:"duration",code:N.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?Vg(t.data,s.version)||(o=this._getOrReturnCtx(t,o),j(o,{validation:"ip",code:N.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?Fg(t.data,s.alg)||(o=this._getOrReturnCtx(t,o),j(o,{validation:"jwt",code:N.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?Hg(t.data,s.version)||(o=this._getOrReturnCtx(t,o),j(o,{validation:"cidr",code:N.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?Ug.test(t.data)||(o=this._getOrReturnCtx(t,o),j(o,{validation:"base64",code:N.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?Zg.test(t.data)||(o=this._getOrReturnCtx(t,o),j(o,{validation:"base64url",code:N.invalid_string,message:s.message}),r.dirty()):le.assertNever(s);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(o=>t.test(o),{validation:n,code:N.invalid_string,...B.errToObj(r)})}_addCheck(t){return new jt({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...B.errToObj(t)})}url(t){return this._addCheck({kind:"url",...B.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...B.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...B.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...B.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...B.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...B.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...B.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...B.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...B.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...B.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...B.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...B.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==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,offset:(t==null?void 0:t.offset)??!1,local:(t==null?void 0:t.local)??!1,...B.errToObj(t==null?void 0: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==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,...B.errToObj(t==null?void 0:t.message)})}duration(t){return this._addCheck({kind:"duration",...B.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...B.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n==null?void 0:n.position,...B.errToObj(n==null?void 0:n.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...B.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...B.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...B.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...B.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...B.errToObj(n)})}nonempty(t){return this.min(1,B.errToObj(t))}trim(){return new jt({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new jt({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new jt({...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 n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}}jt.create=e=>new jt({checks:[],typeName:M.ZodString,coerce:(e==null?void 0:e.coerce)??!1,...Q(e)});function Jg(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(e.toFixed(o).replace(".","")),a=Number.parseInt(t.toFixed(o).replace(".",""));return s%a/10**o}class bn extends re{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)!==U.number){const s=this._getOrReturnCtx(t);return j(s,{code:N.invalid_type,expected:U.number,received:s.parsedType}),G}let r;const o=new He;for(const s of this._def.checks)s.kind==="int"?le.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),j(r,{code:N.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),j(r,{code:N.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)&&(r=this._getOrReturnCtx(t,r),j(r,{code:N.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?Jg(t.data,s.value)!==0&&(r=this._getOrReturnCtx(t,r),j(r,{code:N.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),j(r,{code:N.not_finite,message:s.message}),o.dirty()):le.assertNever(s);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,B.toString(n))}gt(t,n){return this.setLimit("min",t,!1,B.toString(n))}lte(t,n){return this.setLimit("max",t,!0,B.toString(n))}lt(t,n){return this.setLimit("max",t,!1,B.toString(n))}setLimit(t,n,r,o){return new bn({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:B.toString(o)}]})}_addCheck(t){return new bn({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:B.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:B.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:B.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:B.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:B.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:B.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:B.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:B.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:B.toString(t)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&le.isInteger(t.value))}get isFinite(){let t=null,n=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}}bn.create=e=>new bn({checks:[],typeName:M.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...Q(e)});class Hn extends re{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)!==U.bigint)return this._getInvalidInput(t);let r;const o=new He;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),j(r,{code:N.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)&&(r=this._getOrReturnCtx(t,r),j(r,{code:N.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),j(r,{code:N.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):le.assertNever(s);return{status:o.value,value:t.data}}_getInvalidInput(t){const n=this._getOrReturnCtx(t);return j(n,{code:N.invalid_type,expected:U.bigint,received:n.parsedType}),G}gte(t,n){return this.setLimit("min",t,!0,B.toString(n))}gt(t,n){return this.setLimit("min",t,!1,B.toString(n))}lte(t,n){return this.setLimit("max",t,!0,B.toString(n))}lt(t,n){return this.setLimit("max",t,!1,B.toString(n))}setLimit(t,n,r,o){return new Hn({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:B.toString(o)}]})}_addCheck(t){return new Hn({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:B.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:B.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:B.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:B.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:B.toString(n)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}}Hn.create=e=>new Hn({checks:[],typeName:M.ZodBigInt,coerce:(e==null?void 0:e.coerce)??!1,...Q(e)});class Fo extends re{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==U.boolean){const r=this._getOrReturnCtx(t);return j(r,{code:N.invalid_type,expected:U.boolean,received:r.parsedType}),G}return ct(t.data)}}Fo.create=e=>new Fo({typeName:M.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...Q(e)});class Dr extends re{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==U.date){const s=this._getOrReturnCtx(t);return j(s,{code:N.invalid_type,expected:U.date,received:s.parsedType}),G}if(Number.isNaN(t.data.getTime())){const s=this._getOrReturnCtx(t);return j(s,{code:N.invalid_date}),G}const r=new He;let o;for(const s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(o=this._getOrReturnCtx(t,o),j(o,{code:N.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(o=this._getOrReturnCtx(t,o),j(o,{code:N.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):le.assertNever(s);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new Dr({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:B.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:B.toString(n)})}get minDate(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}}Dr.create=e=>new Dr({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:M.ZodDate,...Q(e)});class il extends re{_parse(t){if(this._getType(t)!==U.symbol){const r=this._getOrReturnCtx(t);return j(r,{code:N.invalid_type,expected:U.symbol,received:r.parsedType}),G}return ct(t.data)}}il.create=e=>new il({typeName:M.ZodSymbol,...Q(e)});class Ho extends re{_parse(t){if(this._getType(t)!==U.undefined){const r=this._getOrReturnCtx(t);return j(r,{code:N.invalid_type,expected:U.undefined,received:r.parsedType}),G}return ct(t.data)}}Ho.create=e=>new Ho({typeName:M.ZodUndefined,...Q(e)});class Jo extends re{_parse(t){if(this._getType(t)!==U.null){const r=this._getOrReturnCtx(t);return j(r,{code:N.invalid_type,expected:U.null,received:r.parsedType}),G}return ct(t.data)}}Jo.create=e=>new Jo({typeName:M.ZodNull,...Q(e)});class Go extends re{constructor(){super(...arguments),this._any=!0}_parse(t){return ct(t.data)}}Go.create=e=>new Go({typeName:M.ZodAny,...Q(e)});class Wo extends re{constructor(){super(...arguments),this._unknown=!0}_parse(t){return ct(t.data)}}Wo.create=e=>new Wo({typeName:M.ZodUnknown,...Q(e)});class Wt extends re{_parse(t){const n=this._getOrReturnCtx(t);return j(n,{code:N.invalid_type,expected:U.never,received:n.parsedType}),G}}Wt.create=e=>new Wt({typeName:M.ZodNever,...Q(e)});class ll extends re{_parse(t){if(this._getType(t)!==U.undefined){const r=this._getOrReturnCtx(t);return j(r,{code:N.invalid_type,expected:U.void,received:r.parsedType}),G}return ct(t.data)}}ll.create=e=>new ll({typeName:M.ZodVoid,...Q(e)});class kt extends re{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==U.array)return j(n,{code:N.invalid_type,expected:U.array,received:n.parsedType}),G;if(o.exactLength!==null){const a=n.data.length>o.exactLength.value,i=n.data.length<o.exactLength.value;(a||i)&&(j(n,{code:a?N.too_big:N.too_small,minimum:i?o.exactLength.value:void 0,maximum:a?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(j(n,{code:N.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(j(n,{code:N.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,i)=>o.type._parseAsync(new xt(n,a,n.path,i)))).then(a=>He.mergeArray(r,a));const s=[...n.data].map((a,i)=>o.type._parseSync(new xt(n,a,n.path,i)));return He.mergeArray(r,s)}get element(){return this._def.type}min(t,n){return new kt({...this._def,minLength:{value:t,message:B.toString(n)}})}max(t,n){return new kt({...this._def,maxLength:{value:t,message:B.toString(n)}})}length(t,n){return new kt({...this._def,exactLength:{value:t,message:B.toString(n)}})}nonempty(t){return this.min(1,t)}}kt.create=(e,t)=>new kt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:M.ZodArray,...Q(t)});function xn(e){if(e instanceof Me){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=Ut.create(xn(r))}return new Me({...e._def,shape:()=>t})}else return e instanceof kt?new kt({...e._def,type:xn(e.element)}):e instanceof Ut?Ut.create(xn(e.unwrap())):e instanceof ln?ln.create(xn(e.unwrap())):e instanceof on?on.create(e.items.map(t=>xn(t))):e}class Me extends re{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),n=le.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==U.object){const u=this._getOrReturnCtx(t);return j(u,{code:N.invalid_type,expected:U.object,received:u.parsedType}),G}const{status:r,ctx:o}=this._processInputParams(t),{shape:s,keys:a}=this._getCached(),i=[];if(!(this._def.catchall instanceof Wt&&this._def.unknownKeys==="strip"))for(const u in o.data)a.includes(u)||i.push(u);const l=[];for(const u of a){const p=s[u],x=o.data[u];l.push({key:{status:"valid",value:u},value:p._parse(new xt(o,x,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof Wt){const u=this._def.unknownKeys;if(u==="passthrough")for(const p of i)l.push({key:{status:"valid",value:p},value:{status:"valid",value:o.data[p]}});else if(u==="strict")i.length>0&&(j(o,{code:N.unrecognized_keys,keys:i}),r.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const p of i){const x=o.data[p];l.push({key:{status:"valid",value:p},value:u._parse(new xt(o,x,o.path,p)),alwaysSet:p in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const u=[];for(const p of l){const x=await p.key,w=await p.value;u.push({key:x,value:w,alwaysSet:p.alwaysSet})}return u}).then(u=>He.mergeObjectSync(r,u)):He.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return B.errToObj,new Me({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var s,a;const o=((a=(s=this._def).errorMap)==null?void 0:a.call(s,n,r).message)??r.defaultError;return n.code==="unrecognized_keys"?{message:B.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new Me({...this._def,unknownKeys:"strip"})}passthrough(){return new Me({...this._def,unknownKeys:"passthrough"})}extend(t){return new Me({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Me({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:M.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Me({...this._def,catchall:t})}pick(t){const n={};for(const r of le.objectKeys(t))t[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new Me({...this._def,shape:()=>n})}omit(t){const n={};for(const r of le.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new Me({...this._def,shape:()=>n})}deepPartial(){return xn(this)}partial(t){const n={};for(const r of le.objectKeys(this.shape)){const o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}return new Me({...this._def,shape:()=>n})}required(t){const n={};for(const r of le.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof Ut;)s=s._def.innerType;n[r]=s}return new Me({...this._def,shape:()=>n})}keyof(){return cl(le.objectKeys(this.shape))}}Me.create=(e,t)=>new Me({shape:()=>e,unknownKeys:"strip",catchall:Wt.create(),typeName:M.ZodObject,...Q(t)}),Me.strictCreate=(e,t)=>new Me({shape:()=>e,unknownKeys:"strict",catchall:Wt.create(),typeName:M.ZodObject,...Q(t)}),Me.lazycreate=(e,t)=>new Me({shape:e,unknownKeys:"strip",catchall:Wt.create(),typeName:M.ZodObject,...Q(t)});class Ur extends re{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function o(s){for(const i of s)if(i.result.status==="valid")return i.result;for(const i of s)if(i.result.status==="dirty")return n.common.issues.push(...i.ctx.common.issues),i.result;const a=s.map(i=>new zt(i.ctx.common.issues));return j(n,{code:N.invalid_union,unionErrors:a}),G}if(n.common.async)return Promise.all(r.map(async s=>{const a={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(o);{let s;const a=[];for(const l of r){const u={...n,common:{...n.common,issues:[]},parent:null},p=l._parseSync({data:n.data,path:n.path,parent:u});if(p.status==="valid")return p;p.status==="dirty"&&!s&&(s={result:p,ctx:u}),u.common.issues.length&&a.push(u.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;const i=a.map(l=>new zt(l));return j(n,{code:N.invalid_union,unionErrors:i}),G}}get options(){return this._def.options}}Ur.create=(e,t)=>new Ur({options:e,typeName:M.ZodUnion,...Q(t)});const Dt=e=>e instanceof Xo?Dt(e.schema):e instanceof an?Dt(e.innerType()):e instanceof qr?[e.value]:e instanceof sn?e.options:e instanceof Qo?le.objectValues(e.enum):e instanceof Vr?Dt(e._def.innerType):e instanceof Ho?[void 0]:e instanceof Jo?[null]:e instanceof Ut?[void 0,...Dt(e.unwrap())]:e instanceof ln?[null,...Dt(e.unwrap())]:e instanceof pl||e instanceof Hr?Dt(e.unwrap()):e instanceof Fr?Dt(e._def.innerType):[];class Ko extends re{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==U.object)return j(n,{code:N.invalid_type,expected:U.object,received:n.parsedType}),G;const r=this.discriminator,o=n.data[r],s=this.optionsMap.get(o);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(j(n,{code:N.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),G)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const o=new Map;for(const s of n){const a=Dt(s.shape[t]);if(!a.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const i of a){if(o.has(i))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(i)}`);o.set(i,s)}}return new Ko({typeName:M.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...Q(r)})}}function Yo(e,t){const n=Gt(e),r=Gt(t);if(e===t)return{valid:!0,data:e};if(n===U.object&&r===U.object){const o=le.objectKeys(t),s=le.objectKeys(e).filter(i=>o.indexOf(i)!==-1),a={...e,...t};for(const i of s){const l=Yo(e[i],t[i]);if(!l.valid)return{valid:!1};a[i]=l.data}return{valid:!0,data:a}}else if(n===U.array&&r===U.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let s=0;s<e.length;s++){const a=e[s],i=t[s],l=Yo(a,i);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return n===U.date&&r===U.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class Zr extends re{_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=(s,a)=>{if(nl(s)||nl(a))return G;const i=Yo(s.value,a.value);return i.valid?((rl(s)||rl(a))&&n.dirty(),{status:n.value,value:i.data}):(j(r,{code:N.invalid_intersection_types}),G)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,a])=>o(s,a)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}Zr.create=(e,t,n)=>new Zr({left:e,right:t,typeName:M.ZodIntersection,...Q(n)});class on extends re{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==U.array)return j(r,{code:N.invalid_type,expected:U.array,received:r.parsedType}),G;if(r.data.length<this._def.items.length)return j(r,{code:N.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),G;!this._def.rest&&r.data.length>this._def.items.length&&(j(r,{code:N.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const s=[...r.data].map((a,i)=>{const l=this._def.items[i]||this._def.rest;return l?l._parse(new xt(r,a,r.path,i)):null}).filter(a=>!!a);return r.common.async?Promise.all(s).then(a=>He.mergeArray(n,a)):He.mergeArray(n,s)}get items(){return this._def.items}rest(t){return new on({...this._def,rest:t})}}on.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new on({items:e,typeName:M.ZodTuple,rest:null,...Q(t)})};class Lr extends re{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==U.object)return j(r,{code:N.invalid_type,expected:U.object,received:r.parsedType}),G;const o=[],s=this._def.keyType,a=this._def.valueType;for(const i in r.data)o.push({key:s._parse(new xt(r,i,r.path,i)),value:a._parse(new xt(r,r.data[i],r.path,i)),alwaysSet:i in r.data});return r.common.async?He.mergeObjectAsync(n,o):He.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof re?new Lr({keyType:t,valueType:n,typeName:M.ZodRecord,...Q(r)}):new Lr({keyType:jt.create(),valueType:t,typeName:M.ZodRecord,...Q(n)})}}class ul extends re{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==U.map)return j(r,{code:N.invalid_type,expected:U.map,received:r.parsedType}),G;const o=this._def.keyType,s=this._def.valueType,a=[...r.data.entries()].map(([i,l],u)=>({key:o._parse(new xt(r,i,r.path,[u,"key"])),value:s._parse(new xt(r,l,r.path,[u,"value"]))}));if(r.common.async){const i=new Map;return Promise.resolve().then(async()=>{for(const l of a){const u=await l.key,p=await l.value;if(u.status==="aborted"||p.status==="aborted")return G;(u.status==="dirty"||p.status==="dirty")&&n.dirty(),i.set(u.value,p.value)}return{status:n.value,value:i}})}else{const i=new Map;for(const l of a){const u=l.key,p=l.value;if(u.status==="aborted"||p.status==="aborted")return G;(u.status==="dirty"||p.status==="dirty")&&n.dirty(),i.set(u.value,p.value)}return{status:n.value,value:i}}}}ul.create=(e,t,n)=>new ul({valueType:t,keyType:e,typeName:M.ZodMap,...Q(n)});class Jn extends re{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==U.set)return j(r,{code:N.invalid_type,expected:U.set,received:r.parsedType}),G;const o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(j(r,{code:N.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(j(r,{code:N.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());const s=this._def.valueType;function a(l){const u=new Set;for(const p of l){if(p.status==="aborted")return G;p.status==="dirty"&&n.dirty(),u.add(p.value)}return{status:n.value,value:u}}const i=[...r.data.values()].map((l,u)=>s._parse(new xt(r,l,r.path,u)));return r.common.async?Promise.all(i).then(l=>a(l)):a(i)}min(t,n){return new Jn({...this._def,minSize:{value:t,message:B.toString(n)}})}max(t,n){return new Jn({...this._def,maxSize:{value:t,message:B.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}Jn.create=(e,t)=>new Jn({valueType:e,minSize:null,maxSize:null,typeName:M.ZodSet,...Q(t)});class Xo extends re{get schema(){return this._def.getter()}_parse(t){const{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}Xo.create=(e,t)=>new Xo({getter:e,typeName:M.ZodLazy,...Q(t)});class qr extends re{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return j(n,{received:n.data,code:N.invalid_literal,expected:this._def.value}),G}return{status:"valid",value:t.data}}get value(){return this._def.value}}qr.create=(e,t)=>new qr({value:e,typeName:M.ZodLiteral,...Q(t)});function cl(e,t){return new sn({values:e,typeName:M.ZodEnum,...Q(t)})}class sn extends re{_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return j(n,{expected:le.joinValues(r),received:n.parsedType,code:N.invalid_type}),G}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){const n=this._getOrReturnCtx(t),r=this._def.values;return j(n,{received:n.data,code:N.invalid_enum_value,options:r}),G}return ct(t.data)}get options(){return this._def.values}get enum(){const t={};for(const n of this._def.values)t[n]=n;return t}get Values(){const t={};for(const n of this._def.values)t[n]=n;return t}get Enum(){const t={};for(const n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return sn.create(t,{...this._def,...n})}exclude(t,n=this._def){return sn.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}}sn.create=cl;class Qo extends re{_parse(t){const n=le.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==U.string&&r.parsedType!==U.number){const o=le.objectValues(n);return j(r,{expected:le.joinValues(o),received:r.parsedType,code:N.invalid_type}),G}if(this._cache||(this._cache=new Set(le.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const o=le.objectValues(n);return j(r,{received:r.data,code:N.invalid_enum_value,options:o}),G}return ct(t.data)}get enum(){return this._def.values}}Qo.create=(e,t)=>new Qo({values:e,typeName:M.ZodNativeEnum,...Q(t)});class Br extends re{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==U.promise&&n.common.async===!1)return j(n,{code:N.invalid_type,expected:U.promise,received:n.parsedType}),G;const r=n.parsedType===U.promise?n.data:Promise.resolve(n.data);return ct(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}}Br.create=(e,t)=>new Br({type:e,typeName:M.ZodPromise,...Q(t)});class an extends re{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===M.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,s={addIssue:a=>{j(r,a),a.fatal?n.abort():n.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){const a=o.transform(r.data,s);if(r.common.async)return Promise.resolve(a).then(async i=>{if(n.value==="aborted")return G;const l=await this._def.schema._parseAsync({data:i,path:r.path,parent:r});return l.status==="aborted"?G:l.status==="dirty"||n.value==="dirty"?Fn(l.value):l});{if(n.value==="aborted")return G;const i=this._def.schema._parseSync({data:a,path:r.path,parent:r});return i.status==="aborted"?G:i.status==="dirty"||n.value==="dirty"?Fn(i.value):i}}if(o.type==="refinement"){const a=i=>{const l=o.refinement(i,s);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return i};if(r.common.async===!1){const i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?G:(i.status==="dirty"&&n.dirty(),a(i.value),{status:n.value,value:i.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>i.status==="aborted"?G:(i.status==="dirty"&&n.dirty(),a(i.value).then(()=>({status:n.value,value:i.value}))))}if(o.type==="transform")if(r.common.async===!1){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!wn(a))return G;const i=o.transform(a.value,s);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:i}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>wn(a)?Promise.resolve(o.transform(a.value,s)).then(i=>({status:n.value,value:i})):G);le.assertNever(o)}}an.create=(e,t,n)=>new an({schema:e,typeName:M.ZodEffects,effect:t,...Q(n)}),an.createWithPreprocess=(e,t,n)=>new an({schema:t,effect:{type:"preprocess",transform:e},typeName:M.ZodEffects,...Q(n)});class Ut extends re{_parse(t){return this._getType(t)===U.undefined?ct(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Ut.create=(e,t)=>new Ut({innerType:e,typeName:M.ZodOptional,...Q(t)});class ln extends re{_parse(t){return this._getType(t)===U.null?ct(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}ln.create=(e,t)=>new ln({innerType:e,typeName:M.ZodNullable,...Q(t)});class Vr extends re{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===U.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}Vr.create=(e,t)=>new Vr({innerType:e,typeName:M.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Q(t)});class Fr extends re{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return jr(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new zt(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new zt(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Fr.create=(e,t)=>new Fr({innerType:e,typeName:M.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Q(t)});class dl extends re{_parse(t){if(this._getType(t)!==U.nan){const r=this._getOrReturnCtx(t);return j(r,{code:N.invalid_type,expected:U.nan,received:r.parsedType}),G}return{status:"valid",value:t.data}}}dl.create=e=>new dl({typeName:M.ZodNaN,...Q(e)});class pl extends re{_parse(t){const{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class es extends re{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?G:s.status==="dirty"?(n.dirty(),Fn(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?G:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new es({in:t,out:n,typeName:M.ZodPipeline})}}class Hr extends re{_parse(t){const n=this._def.innerType._parse(t),r=o=>(wn(o)&&(o.value=Object.freeze(o.value)),o);return jr(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}}Hr.create=(e,t)=>new Hr({innerType:e,typeName:M.ZodReadonly,...Q(t)});var M;(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"})(M||(M={}));const S=jt.create,Ue=bn.create,je=Fo.create,Gg=Go.create,Gn=Wo.create;Wt.create;const L=kt.create,$=Me.create,Je=Ur.create,Wg=Ko.create;Zr.create,on.create;const Wn=Lr.create,X=qr.create,Zt=sn.create;Br.create;const O=Ut.create;ln.create;const Kg=G;function Ge(...e){return e.reduce((t,n)=>({...t,...n??{}}),{})}async function Yg(e,t){if(e==null)return Promise.resolve();const n=t==null?void 0:t.abortSignal;return new Promise((r,o)=>{if(n!=null&&n.aborted){o(hl());return}const s=setTimeout(()=>{a(),r()},e),a=()=>{clearTimeout(s),n==null||n.removeEventListener("abort",i)},i=()=>{a(),o(hl())};n==null||n.addEventListener("abort",i)})}function hl(){return new DOMException("Delay was aborted","AbortError")}function kn(e){return Object.fromEntries([...e.headers])}var Kn=({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:r="-"}={})=>{const o=()=>{const s=n.length,a=new Array(t);for(let i=0;i<t;i++)a[i]=n[Math.random()*s|0];return a.join("")};if(e==null)return o;if(n.includes(r))throw new Pa({argument:"separator",message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${o()}`},tt=Kn();function ts(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}function un(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var Xg=["fetch failed","failed to fetch"];function fl({error:e,url:t,requestBodyValues:n}){if(un(e))return e;if(e instanceof TypeError&&Xg.includes(e.message.toLowerCase())){const r=e.cause;if(r!=null)return new De({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}function Yn(e=globalThis){var t,n,r;return e.window?"runtime/browser":(t=e.navigator)!=null&&t.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(r=(n=e.process)==null?void 0:n.versions)!=null&&r.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function Qg(e){return Object.fromEntries(Object.entries(e).filter(([t,n])=>n!=null))}function Lt(e,...t){const n=Qg(e??{}),r=new Headers(n),o=r.get("user-agent")||"";return r.set("user-agent",[o,...t].filter(Boolean).join(" ")),Object.fromEntries(r)}var ml="3.0.12",ev=()=>globalThis.fetch,gl=async({url:e,headers:t={},successfulResponseHandler:n,failedResponseHandler:r,abortSignal:o,fetch:s=ev()})=>{try{const a=await s(e,{method:"GET",headers:Lt(t,`ai-sdk/provider-utils/${ml}`,Yn()),signal:o}),i=kn(a);if(!a.ok){let l;try{l=await r({response:a,url:e,requestBodyValues:{}})}catch(u){throw un(u)||De.isInstance(u)?u:new De({message:"Failed to process error response",cause:u,statusCode:a.status,url:e,responseHeaders:i,requestBodyValues:{}})}throw l.value}try{return await n({response:a,url:e,requestBodyValues:{}})}catch(l){throw l instanceof Error&&(un(l)||De.isInstance(l))?l:new De({message:"Failed to process successful response",cause:l,statusCode:a.status,url:e,responseHeaders:i,requestBodyValues:{}})}}catch(a){throw fl({error:a,url:e,requestBodyValues:{}})}};function tv({mediaType:e,url:t,supportedUrls:n}){return t=t.toLowerCase(),e=e.toLowerCase(),Object.entries(n).map(([r,o])=>{const s=r.toLowerCase();return s==="*"||s==="*/*"?{mediaTypePrefix:"",regexes:o}:{mediaTypePrefix:s.replace(/\*/,""),regexes:o}}).filter(({mediaTypePrefix:r})=>e.startsWith(r)).flatMap(({regexes:r})=>r).some(r=>r.test(t))}function vl({apiKey:e,environmentVariableName:t,apiKeyParameterName:n="apiKey",description:r}){if(typeof e=="string")return e;if(e!=null)throw new Ir({message:`${r} API key must be a string.`});if(typeof process>"u")throw new Ir({message:`${r} API key is missing. Pass it using the '${n}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new Ir({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new Ir({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}function Xn({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 nv(e){var t;const[n,r=""]=e.toLowerCase().split("/");return(t={mpeg:"mp3","x-wav":"wav",opus:"ogg",mp4:"m4a","x-m4a":"m4a"}[r])!=null?t:r}var rv=/"__proto__"\s*:/,ov=/"constructor"\s*:/;function sv(e){const t=JSON.parse(e);return t===null||typeof t!="object"||rv.test(e)===!1&&ov.test(e)===!1?t:av(t)}function av(e){let t=[e];for(;t.length;){const n=t;t=[];for(const r of n){if(Object.prototype.hasOwnProperty.call(r,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(r,"constructor")&&Object.prototype.hasOwnProperty.call(r.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const o in r){const s=r[o];s&&typeof s=="object"&&t.push(s)}}}return e}function ns(e){const{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return sv(e)}finally{Error.stackTraceLimit=t}}var Jr=Symbol.for("vercel.ai.validator");function iv(e){return{[Jr]:!0,validate:e}}function lv(e){return typeof e=="object"&&e!==null&&Jr in e&&e[Jr]===!0&&"validate"in e}function Ee(e){let t;return()=>(t==null&&(t=e()),t)}function uv(e){return lv(e)?e:typeof e=="function"?e():cv(e)}function cv(e){return iv(async t=>{const n=await e["~standard"].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new jn({value:t,cause:n.issues})}})}async function Tt({value:e,schema:t}){const n=await gt({value:e,schema:t});if(!n.success)throw jn.wrap({value:e,cause:n.error});return n.value}async function gt({value:e,schema:t}){const n=uv(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};const r=await n.validate(e);return r.success?{success:!0,value:r.value,rawValue:e}:{success:!1,error:jn.wrap({value:e,cause:r.error}),rawValue:e}}catch(r){return{success:!1,error:jn.wrap({value:e,cause:r}),rawValue:e}}}async function dv({text:e,schema:t}){try{const n=ns(e);return t==null?n:Tt({value:n,schema:t})}catch(n){throw Sr.isInstance(n)||jn.isInstance(n)?n:new Sr({text:e,cause:n})}}async function cn({text:e,schema:t}){try{const n=ns(e);return t==null?{success:!0,value:n,rawValue:n}:await gt({value:n,schema:t})}catch(n){return{success:!1,error:Sr.isInstance(n)?n:new Sr({text:e,cause:n}),rawValue:void 0}}}function Gr(e){try{return ns(e),!0}catch{return!1}}function pv({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Oo).pipeThrough(new TransformStream({async transform({data:n},r){n!=="[DONE]"&&r.enqueue(await cn({text:n,schema:t}))}}))}async function St({provider:e,providerOptions:t,schema:n}){if((t==null?void 0:t[e])==null)return;const r=await gt({value:t[e],schema:n});if(!r.success)throw new Pa({argument:"providerOptions",message:`invalid ${e} provider options`,cause:r.error});return r.value}var hv=()=>globalThis.fetch,nt=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:o,abortSignal:s,fetch:a})=>yl({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:o,abortSignal:s,fetch:a}),fv=async({url:e,headers:t,formData:n,failedResponseHandler:r,successfulResponseHandler:o,abortSignal:s,fetch:a})=>yl({url:e,headers:t,body:{content:n,values:Object.fromEntries(n.entries())},failedResponseHandler:r,successfulResponseHandler:o,abortSignal:s,fetch:a}),yl=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:o,abortSignal:s,fetch:a=hv()})=>{try{const i=await a(e,{method:"POST",headers:Lt(t,`ai-sdk/provider-utils/${ml}`,Yn()),body:n.content,signal:s}),l=kn(i);if(!i.ok){let u;try{u=await o({response:i,url:e,requestBodyValues:n.values})}catch(p){throw un(p)||De.isInstance(p)?p:new De({message:"Failed to process error response",cause:p,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw u.value}try{return await r({response:i,url:e,requestBodyValues:n.values})}catch(u){throw u instanceof Error&&(un(u)||De.isInstance(u))?u:new De({message:"Failed to process successful response",cause:u,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(i){throw fl({error:i,url:e,requestBodyValues:n.values})}};function uS(e){return e}function _l(e){return{...e,type:"dynamic"}}function Tn({id:e,name:t,inputSchema:n,outputSchema:r}){return({execute:o,toModelOutput:s,onInputStart:a,onInputDelta:i,onInputAvailable:l,...u})=>({type:"provider-defined",id:e,name:t,args:u,inputSchema:n,outputSchema:r,execute:o,toModelOutput:s,onInputStart:a,onInputDelta:i,onInputAvailable:l})}async function Kt(e){return typeof e=="function"&&(e=e()),Promise.resolve(e)}var dn=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:o,requestBodyValues:s})=>{const a=await r.text(),i=kn(r);if(a.trim()==="")return{responseHeaders:i,value:new De({message:r.statusText,url:o,requestBodyValues:s,statusCode:r.status,responseHeaders:i,responseBody:a,isRetryable:n==null?void 0:n(r)})};try{const l=await dv({text:a,schema:e});return{responseHeaders:i,value:new De({message:t(l),url:o,requestBodyValues:s,statusCode:r.status,responseHeaders:i,responseBody:a,data:l,isRetryable:n==null?void 0:n(r,l)})}}catch{return{responseHeaders:i,value:new De({message:r.statusText,url:o,requestBodyValues:s,statusCode:r.status,responseHeaders:i,responseBody:a,isRetryable:n==null?void 0:n(r)})}}},Qn=e=>async({response:t})=>{const n=kn(t);if(t.body==null)throw new ap({});return{responseHeaders:n,value:pv({stream:t.body,schema:e})}},vt=e=>async({response:t,url:n,requestBodyValues:r})=>{const o=await t.text(),s=await cn({text:o,schema:e}),a=kn(t);if(!s.success)throw new De({message:"Invalid JSON response",cause:s.error,statusCode:t.status,responseHeaders:a,responseBody:o,url:n,requestBodyValues:r});return{responseHeaders:a,value:s.value,rawValue:s.rawValue}},mv=()=>async({response:e,url:t,requestBodyValues:n})=>{const r=kn(e);if(!e.body)throw new De({message:"Response body is empty",url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0});try{const o=await e.arrayBuffer();return{responseHeaders:r,value:new Uint8Array(o)}}catch(o){throw new De({message:"Failed to read response as array buffer",url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0,cause:o})}},gv=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join("/")},vv=Symbol("Let zodToJsonSchema decide on which parser to use"),wl={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"},yv=e=>typeof e=="string"?{...wl,name:e}:{...wl,...e};function ot(){return{}}function _v(e,t){var n,r,o;const s={type:"array"};return(n=e.type)!=null&&n._def&&((o=(r=e.type)==null?void 0:r._def)==null?void 0:o.typeName)!==M.ZodAny&&(s.items=fe(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 wv(e){const t={type:"integer",format:"int64"};if(!e.checks)return t;for(const n of e.checks)switch(n.kind){case"min":n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case"max":n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case"multipleOf":t.multipleOf=n.value;break}return t}function bv(){return{type:"boolean"}}function bl(e,t){return fe(e.type._def,t)}var xv=(e,t)=>fe(e.innerType._def,t);function xl(e,t,n){const r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((o,s)=>xl(e,t,o))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return kv(e)}}var kv=e=>{const t={type:"integer",format:"unix-time"};for(const n of e.checks)switch(n.kind){case"min":t.minimum=n.value;break;case"max":t.maximum=n.value;break}return t};function Tv(e,t){return{...fe(e.innerType._def,t),default:e.defaultValue()}}function Sv(e,t){return t.effectStrategy==="input"?fe(e.schema._def,t):ot()}function Iv(e){return{type:"string",enum:Array.from(e.values)}}var Cv=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function Ev(e,t){const n=[fe(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),fe(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(o=>!!o),r=[];return n.forEach(o=>{if(Cv(o))r.push(...o.allOf);else{let s=o;if("additionalProperties"in o&&o.additionalProperties===!1){const{additionalProperties:a,...i}=o;s=i}r.push(s)}}),r.length?{allOf:r}:void 0}function Rv(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 rs=void 0,yt={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:()=>(rs===void 0&&(rs=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),rs),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 kl(e,t){const n={type:"string"};if(e.checks)for(const r of e.checks)switch(r.kind){case"min":n.minLength=typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value;break;case"max":n.maxLength=typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value;break;case"email":switch(t.emailStrategy){case"format:email":_t(n,"email",r.message,t);break;case"format:idn-email":_t(n,"idn-email",r.message,t);break;case"pattern:zod":We(n,yt.email,r.message,t);break}break;case"url":_t(n,"uri",r.message,t);break;case"uuid":_t(n,"uuid",r.message,t);break;case"regex":We(n,r.regex,r.message,t);break;case"cuid":We(n,yt.cuid,r.message,t);break;case"cuid2":We(n,yt.cuid2,r.message,t);break;case"startsWith":We(n,RegExp(`^${os(r.value,t)}`),r.message,t);break;case"endsWith":We(n,RegExp(`${os(r.value,t)}$`),r.message,t);break;case"datetime":_t(n,"date-time",r.message,t);break;case"date":_t(n,"date",r.message,t);break;case"time":_t(n,"time",r.message,t);break;case"duration":_t(n,"duration",r.message,t);break;case"length":n.minLength=typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,n.maxLength=typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value;break;case"includes":{We(n,RegExp(os(r.value,t)),r.message,t);break}case"ip":{r.version!=="v6"&&_t(n,"ipv4",r.message,t),r.version!=="v4"&&_t(n,"ipv6",r.message,t);break}case"base64url":We(n,yt.base64url,r.message,t);break;case"jwt":We(n,yt.jwt,r.message,t);break;case"cidr":{r.version!=="v6"&&We(n,yt.ipv4Cidr,r.message,t),r.version!=="v4"&&We(n,yt.ipv6Cidr,r.message,t);break}case"emoji":We(n,yt.emoji(),r.message,t);break;case"ulid":{We(n,yt.ulid,r.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{_t(n,"binary",r.message,t);break}case"contentEncoding:base64":{n.contentEncoding="base64";break}case"pattern:zod":{We(n,yt.base64,r.message,t);break}}break}case"nanoid":We(n,yt.nanoid,r.message,t)}return n}function os(e,t){return t.patternStrategy==="escape"?Ov(e):e}var Av=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Ov(e){let t="";for(let n=0;n<e.length;n++)Av.has(e[n])||(t+="\\"),t+=e[n];return t}function _t(e,t,n,r){var o;e.format||(o=e.anyOf)!=null&&o.some(s=>s.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format}),delete e.format),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):e.format=t}function We(e,t,n,r){var o;e.pattern||(o=e.allOf)!=null&&o.some(s=>s.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern}),delete e.pattern),e.allOf.push({pattern:Tl(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):e.pattern=Tl(t,r)}function Tl(e,t){var n;if(!t.applyRegexFlags||!e.flags)return e.source;const r={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},o=r.i?e.source.toLowerCase():e.source;let s="",a=!1,i=!1,l=!1;for(let u=0;u<o.length;u++){if(a){s+=o[u],a=!1;continue}if(r.i){if(i){if(o[u].match(/[a-z]/)){l?(s+=o[u],s+=`${o[u-2]}-${o[u]}`.toUpperCase(),l=!1):o[u+1]==="-"&&((n=o[u+2])!=null&&n.match(/[a-z]/))?(s+=o[u],l=!0):s+=`${o[u]}${o[u].toUpperCase()}`;continue}}else if(o[u].match(/[a-z]/)){s+=`[${o[u]}${o[u].toUpperCase()}]`;continue}}if(r.m){if(o[u]==="^"){s+=`(^|(?<=[\r
|
|
35
|
-
]))`;continue}else if(
|
|
36
|
-
]))`;continue}}if(
|
|
37
|
-
`:`[${
|
|
38
|
-
]`;continue}s+=o[u],o[u]==="\\"?a=!0:i&&o[u]==="]"?i=!1:!i&&o[u]==="["&&(i=!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 Sl(e,t){var n,r,o,s,a,i;const l={type:"object",additionalProperties:(n=fe(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?n:t.allowedAdditionalProperties};if(((r=e.keyType)==null?void 0:r._def.typeName)===M.ZodString&&((o=e.keyType._def.checks)!=null&&o.length)){const{type:u,...p}=kl(e.keyType._def,t);return{...l,propertyNames:p}}else{if(((s=e.keyType)==null?void 0:s._def.typeName)===M.ZodEnum)return{...l,propertyNames:{enum:e.keyType._def.values}};if(((a=e.keyType)==null?void 0:a._def.typeName)===M.ZodBranded&&e.keyType._def.type._def.typeName===M.ZodString&&((i=e.keyType._def.type._def.checks)!=null&&i.length)){const{type:u,...p}=bl(e.keyType._def,t);return{...l,propertyNames:p}}}return l}function Nv(e,t){if(t.mapStrategy==="record")return Sl(e,t);const n=fe(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||ot(),r=fe(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||ot();return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}function Mv(e){const t=e.values,r=Object.keys(e.values).filter(s=>typeof t[t[s]]!="number").map(s=>t[s]),o=Array.from(new Set(r.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:r}}function Pv(){return{not:ot()}}function $v(){return{type:"null"}}var ss={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function zv(e,t){const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(r=>r._def.typeName in ss&&(!r._def.checks||!r._def.checks.length))){const r=n.reduce((o,s)=>{const a=ss[s._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){const r=n.reduce((o,s)=>{const a=typeof s._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(r.length===n.length){const o=r.filter((s,a,i)=>i.indexOf(s)===a);return{type:o.length>1?o:o[0],enum:n.reduce((s,a)=>s.includes(a._def.value)?s:[...s,a._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,o)=>[...r,...o._def.values.filter(s=>!r.includes(s))],[])};return jv(e,t)}var jv=(e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((r,o)=>fe(r._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter(r=>!!r&&(!t.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0};function Dv(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[ss[e.innerType._def.typeName],"null"]};const n=fe(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function Uv(e){const t={type:"number"};if(!e.checks)return t;for(const n of e.checks)switch(n.kind){case"int":t.type="integer";break;case"min":n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case"max":n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case"multipleOf":t.multipleOf=n.value;break}return t}function Zv(e,t){const n={type:"object",properties:{}},r=[],o=e.shape();for(const a in o){let i=o[a];if(i===void 0||i._def===void 0)continue;const l=qv(i),u=fe(i._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});u!==void 0&&(n.properties[a]=u,l||r.push(a))}r.length&&(n.required=r);const s=Lv(e,t);return s!==void 0&&(n.additionalProperties=s),n}function Lv(e,t){if(e.catchall._def.typeName!=="ZodNever")return fe(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 qv(e){try{return e.isOptional()}catch{return!0}}var Bv=(e,t)=>{var n;if(t.currentPath.toString()===((n=t.propertyPath)==null?void 0:n.toString()))return fe(e.innerType._def,t);const r=fe(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:ot()},r]}:ot()},Vv=(e,t)=>{if(t.pipeStrategy==="input")return fe(e.in._def,t);if(t.pipeStrategy==="output")return fe(e.out._def,t);const n=fe(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),r=fe(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(o=>o!==void 0)}};function Fv(e,t){return fe(e.type._def,t)}function Hv(e,t){const r={type:"array",uniqueItems:!0,items:fe(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&(r.minItems=e.minSize.value),e.maxSize&&(r.maxItems=e.maxSize.value),r}function Jv(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((n,r)=>fe(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:fe(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((n,r)=>fe(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}function Gv(){return{not:ot()}}function Wv(){return ot()}var Kv=(e,t)=>fe(e.innerType._def,t),Yv=(e,t,n)=>{switch(t){case M.ZodString:return kl(e,n);case M.ZodNumber:return Uv(e);case M.ZodObject:return Zv(e,n);case M.ZodBigInt:return wv(e);case M.ZodBoolean:return bv();case M.ZodDate:return xl(e,n);case M.ZodUndefined:return Gv();case M.ZodNull:return $v();case M.ZodArray:return _v(e,n);case M.ZodUnion:case M.ZodDiscriminatedUnion:return zv(e,n);case M.ZodIntersection:return Ev(e,n);case M.ZodTuple:return Jv(e,n);case M.ZodRecord:return Sl(e,n);case M.ZodLiteral:return Rv(e);case M.ZodEnum:return Iv(e);case M.ZodNativeEnum:return Mv(e);case M.ZodNullable:return Dv(e,n);case M.ZodOptional:return Bv(e,n);case M.ZodMap:return Nv(e,n);case M.ZodSet:return Hv(e,n);case M.ZodLazy:return()=>e.getter()._def;case M.ZodPromise:return Fv(e,n);case M.ZodNaN:case M.ZodNever:return Pv();case M.ZodEffects:return Sv(e,n);case M.ZodAny:return ot();case M.ZodUnknown:return Wv();case M.ZodDefault:return Tv(e,n);case M.ZodBranded:return bl(e,n);case M.ZodReadonly:return Kv(e,n);case M.ZodCatch:return xv(e,n);case M.ZodPipeline:return Vv(e,n);case M.ZodFunction:case M.ZodVoid:case M.ZodSymbol:return;default:return(r=>{})()}};function fe(e,t,n=!1){var r;const o=t.seen.get(e);if(t.override){const l=(r=t.override)==null?void 0:r.call(t,e,t,o,n);if(l!==vv)return l}if(o&&!n){const l=Xv(o,t);if(l!==void 0)return l}const s={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,s);const a=Yv(e,e.typeName,t),i=typeof a=="function"?fe(a(),t):a;if(i&&Qv(e,t,i),t.postProcess){const l=t.postProcess(i,e,t);return s.jsonSchema=i,l}return s.jsonSchema=i,i}var Xv=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:gv(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((n,r)=>t.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),ot()):t.$refStrategy==="seen"?ot():void 0}},Qv=(e,t,n)=>(e.description&&(n.description=e.description),n),ey=e=>{const t=yv(e),n=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([r,o])=>[o._def,{def:o._def,path:[...t.basePath,t.definitionPath,r],jsonSchema:void 0}]))}},ty=(e,t)=>{var n;const r=ey(t);let o=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((u,[p,x])=>{var w;return{...u,[p]:(w=fe(x._def,{...r,currentPath:[...r.basePath,r.definitionPath,p]},!0))!=null?w:ot()}},{}):void 0;const s=typeof t=="string"?t:(t==null?void 0:t.nameStrategy)==="title"||t==null?void 0:t.name,a=(n=fe(e._def,s===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,s]},!1))!=null?n:ot(),i=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;i!==void 0&&(a.title=i);const l=s===void 0?o?{...a,[r.definitionPath]:o}:a:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,s].join("/"),[r.definitionPath]:{...o,[s]:a}};return l.$schema="http://json-schema.org/draft-07/schema#",l},ny=ty;function ry(e,t){var n;const r=(n=void 0)!=null?n:!1;return er(()=>ny(e,{$refStrategy:r?"root":"none"}),{validate:async o=>{const s=await e.safeParseAsync(o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function oy(e,t){var n;const r=(n=void 0)!=null?n:!1;return er(()=>mm(e,{target:"draft-7",io:"output",reused:r?"ref":"inline"}),{validate:async o=>{const s=await qi(e,o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function sy(e){return"_zod"in e}function te(e,t){return sy(e)?oy(e):ry(e)}var as=Symbol.for("vercel.ai.schema");function Fe(e){let t;return()=>(t==null&&(t=e()),t)}function er(e,{validate:t}={}){return{[as]:!0,_type:void 0,[Jr]:!0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}function ay(e){return typeof e=="object"&&e!==null&&as in e&&e[as]===!0&&"jsonSchema"in e&&"validate"in e}function Wr(e){return e==null?er({properties:{},additionalProperties:!1}):ay(e)?e:typeof e=="function"?e():te(e)}var{btoa:iy,atob:ly}=globalThis;function Kr(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=ly(t);return Uint8Array.from(n,r=>r.codePointAt(0))}function Yr(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return iy(t)}function pn(e){return e instanceof Uint8Array?Yr(e):e}function is(e){return e==null?void 0:e.replace(/\/$/,"")}function uy(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*Il({execute:e,input:t,options:n}){const r=e(t,n);if(uy(r)){let o;for await(const s of r)o=s,yield{type:"preliminary",output:s};yield{type:"final",output:o}}else yield{type:"final",output:await r}}var ls=Object.defineProperty,cy=Object.getOwnPropertyDescriptor,dy=Object.getOwnPropertyNames,py=Object.prototype.hasOwnProperty,hy=(e,t)=>{for(var n in t)ls(e,n,{get:t[n],enumerable:!0})},fy=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of dy(t))!py.call(e,o)&&o!==n&&ls(e,o,{get:()=>t[o],enumerable:!(r=cy(t,o))||r.enumerable});return e},my=e=>fy(ls({},"__esModule",{value:!0}),e),Cl={};hy(Cl,{SYMBOL_FOR_REQ_CONTEXT:()=>El,getContext:()=>vy});var gy=my(Cl);const El=Symbol.for("@vercel/request-context");function vy(){var t,n;return((n=(t=globalThis[El])==null?void 0:t.get)==null?void 0:n.call(t))??{}}var us=Object.defineProperty,yy=Object.getOwnPropertyDescriptor,_y=Object.getOwnPropertyNames,wy=Object.prototype.hasOwnProperty,by=(e,t)=>{for(var n in t)us(e,n,{get:t[n],enumerable:!0})},xy=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of _y(t))!wy.call(e,o)&&o!==n&&us(e,o,{get:()=>t[o],enumerable:!(r=yy(t,o))||r.enumerable});return e},ky=e=>xy(us({},"__esModule",{value:!0}),e),Rl={};by(Rl,{getContext:()=>Ty.getContext,getVercelOidcToken:()=>Sy,getVercelOidcTokenSync:()=>Iy});var Al=ky(Rl),Ty=gy;async function Sy(){return""}function Iy(){return""}var Cy="vercel.ai.gateway.error",cs=Symbol.for(Cy),Ol,Nl,st=class ep extends(Nl=Error,Ol=cs,Nl){constructor({message:t,statusCode:n=500,cause:r}){super(t),this[Ol]=!0,this.statusCode=n,this.cause=r}static isInstance(t){return ep.hasMarker(t)}static hasMarker(t){return typeof t=="object"&&t!==null&&cs in t&&t[cs]===!0}},Ml="GatewayAuthenticationError",Ey=`vercel.ai.gateway.error.${Ml}`,Pl=Symbol.for(Ey),$l,zl,ds=class tp extends(zl=st,$l=Pl,zl){constructor({message:t="Authentication failed",statusCode:n=401,cause:r}={}){super({message:t,statusCode:n,cause:r}),this[$l]=!0,this.name=Ml,this.type="authentication_error"}static isInstance(t){return st.hasMarker(t)&&Pl in t}static createContextualError({apiKeyProvided:t,oidcTokenProvided:n,message:r="Authentication failed",statusCode:o=401,cause:s}){let a;return t?a=`AI Gateway authentication failed: Invalid API key.
|
|
34
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const m of this.seen.entries()){const v=m[1];if(e===m[0]){o(m);continue}if(a.external){const y=(h=a.external.registry.get(m[0]))==null?void 0:h.id;if(e!==m[0]&&y){o(m);continue}}if((g=this.metadataRegistry.get(m[0]))==null?void 0:g.id){o(m);continue}if(v.cycle){o(m);continue}if(v.count>1&&a.reused==="ref"){o(m);continue}}const i=(m,v)=>{const w=this.seen.get(m),y=w.def??w.schema,_={...y};if(w.ref===null)return;const E=w.ref;if(w.ref=null,E){i(E,v);const I=this.seen.get(E).schema;I.$ref&&v.target==="draft-7"?(y.allOf=y.allOf??[],y.allOf.push(I)):(Object.assign(y,I),Object.assign(y,_))}w.isParent||this.override({zodSchema:m,jsonSchema:y,path:w.path??[]})};for(const m of[...this.seen.entries()].reverse())i(m[0],{target:this.target});const l={};if(this.target==="draft-2020-12"?l.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?l.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),(c=a.external)!=null&&c.uri){const m=(p=a.external.registry.get(e))==null?void 0:p.id;if(!m)throw new Error("Schema is missing an `id` property");l.$id=a.external.uri(m)}Object.assign(l,n.def);const u=((f=a.external)==null?void 0:f.defs)??{};for(const m of this.seen.entries()){const v=m[1];v.def&&v.defId&&(u[v.defId]=v.def)}a.external||Object.keys(u).length>0&&(this.target==="draft-2020-12"?l.$defs=u:l.definitions=u);try{return JSON.parse(JSON.stringify(l))}catch{throw new Error("Error converting schema to JSON.")}}}function l_(t,e){if(t instanceof ic){const a=new mc(e),n={};for(const i of t._idmap.entries()){const[l,u]=i;a.process(u)}const s={},o={registry:t,uri:e==null?void 0:e.uri,defs:n};for(const i of t._idmap.entries()){const[l,u]=i;s[l]=a.emit(u,{...e,external:o})}if(Object.keys(n).length>0){const i=a.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[i]:n}}return{schemas:s}}const r=new mc(e);return r.process(t),r.emit(t,e)}function it(t,e){const r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);const n=t._zod.def;switch(n.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return it(n.element,r);case"object":{for(const s in n.shape)if(it(n.shape[s],r))return!0;return!1}case"union":{for(const s of n.options)if(it(s,r))return!0;return!1}case"intersection":return it(n.left,r)||it(n.right,r);case"tuple":{for(const s of n.items)if(it(s,r))return!0;return!!(n.rest&&it(n.rest,r))}case"record":return it(n.keyType,r)||it(n.valueType,r);case"map":return it(n.keyType,r)||it(n.valueType,r);case"set":return it(n.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return it(n.innerType,r);case"lazy":return it(n.getter(),r);case"default":return it(n.innerType,r);case"prefault":return it(n.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return it(n.in,r)||it(n.out,r);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${n.type}`)}const u_=j("ZodISODateTime",(t,e)=>{Og.init(t,e),Ye.init(t,e)});function c_(t){return jy(u_,t)}const d_=j("ZodISODate",(t,e)=>{$g.init(t,e),Ye.init(t,e)});function p_(t){return Ly(d_,t)}const h_=j("ZodISOTime",(t,e)=>{Ag.init(t,e),Ye.init(t,e)});function f_(t){return zy(h_,t)}const m_=j("ZodISODuration",(t,e)=>{Ng.init(t,e),Ye.init(t,e)});function v_(t){return Uy(m_,t)}const Ha=j("ZodError",(t,e)=>{Lu.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>kv(t,r)},flatten:{value:r=>Tv(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},{Parent:Error}),g_=Pv(Ha),y_=Cv(Ha),__=Uu(Ha),vc=Fu(Ha),Ve=j("ZodType",(t,e)=>(Fe.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(a=>typeof a=="function"?{_zod:{check:a,def:{check:"custom"},onattach:[]}}:a)]}),t.clone=(r,a)=>Hr(t,r,a),t.brand=()=>t,t.register=(r,a)=>(r.add(t,a),t),t.parse=(r,a)=>g_(t,r,a,{callee:t.parse}),t.safeParse=(r,a)=>__(t,r,a),t.parseAsync=async(r,a)=>y_(t,r,a,{callee:t.parseAsync}),t.safeParseAsync=async(r,a)=>vc(t,r,a),t.spa=t.safeParseAsync,t.refine=(r,a)=>t.check(h0(r,a)),t.superRefine=r=>t.check(f0(r)),t.overwrite=r=>t.check(Kn(r)),t.optional=()=>at(t),t.nullable=()=>Ic(t),t.nullish=()=>at(Ic(t)),t.nonoptional=r=>a0(t,r),t.array=()=>Y(t),t.or=r=>Ae([t,r]),t.and=r=>W_(t,r),t.transform=r=>kc(t,Y_(r)),t.default=r=>t0(t,r),t.prefault=r=>n0(t,r),t.catch=r=>o0(t,r),t.pipe=r=>kc(t,r),t.readonly=()=>u0(t),t.describe=r=>{const a=t.clone();return Gn.add(a,{description:r}),a},Object.defineProperty(t,"description",{get(){var r;return(r=Gn.get(t))==null?void 0:r.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Gn.get(t);const a=t.clone();return Gn.add(a,r[0]),a},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),gc=j("_ZodString",(t,e)=>{Eo.init(t,e),Ve.init(t,e);const r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...a)=>t.check(Gy(...a)),t.includes=(...a)=>t.check(Yy(...a)),t.startsWith=(...a)=>t.check(Xy(...a)),t.endsWith=(...a)=>t.check(e_(...a)),t.min=(...a)=>t.check(Ba(...a)),t.max=(...a)=>t.check(hc(...a)),t.length=(...a)=>t.check(fc(...a)),t.nonempty=(...a)=>t.check(Ba(1,...a)),t.lowercase=a=>t.check(Ky(a)),t.uppercase=a=>t.check(Qy(a)),t.trim=()=>t.check(r_()),t.normalize=(...a)=>t.check(t_(...a)),t.toLowerCase=()=>t.check(n_()),t.toUpperCase=()=>t.check(a_())}),w_=j("ZodString",(t,e)=>{Eo.init(t,e),gc.init(t,e),t.email=r=>t.check(gy(b_,r)),t.url=r=>t.check(xy(x_,r)),t.jwt=r=>t.check(Dy(D_,r)),t.emoji=r=>t.check(Ey(E_,r)),t.guid=r=>t.check(lc(yc,r)),t.uuid=r=>t.check(yy(Ja,r)),t.uuidv4=r=>t.check(_y(Ja,r)),t.uuidv6=r=>t.check(wy(Ja,r)),t.uuidv7=r=>t.check(by(Ja,r)),t.nanoid=r=>t.check(Sy(S_,r)),t.guid=r=>t.check(lc(yc,r)),t.cuid=r=>t.check(Iy(I_,r)),t.cuid2=r=>t.check(Ty(T_,r)),t.ulid=r=>t.check(ky(k_,r)),t.base64=r=>t.check(uc(_c,r)),t.base64url=r=>t.check(Ny(N_,r)),t.xid=r=>t.check(Py(P_,r)),t.ksuid=r=>t.check(Cy(C_,r)),t.ipv4=r=>t.check(Ry(R_,r)),t.ipv6=r=>t.check(Oy(O_,r)),t.cidrv4=r=>t.check($y($_,r)),t.cidrv6=r=>t.check(Ay(A_,r)),t.e164=r=>t.check(My(M_,r)),t.datetime=r=>t.check(c_(r)),t.date=r=>t.check(p_(r)),t.time=r=>t.check(f_(r)),t.duration=r=>t.check(v_(r))});function x(t){return vy(w_,t)}const Ye=j("ZodStringFormat",(t,e)=>{Je.init(t,e),gc.init(t,e)}),b_=j("ZodEmail",(t,e)=>{xg.init(t,e),Ye.init(t,e)}),yc=j("ZodGUID",(t,e)=>{wg.init(t,e),Ye.init(t,e)}),Ja=j("ZodUUID",(t,e)=>{bg.init(t,e),Ye.init(t,e)}),x_=j("ZodURL",(t,e)=>{Eg.init(t,e),Ye.init(t,e)}),E_=j("ZodEmoji",(t,e)=>{Sg.init(t,e),Ye.init(t,e)}),S_=j("ZodNanoID",(t,e)=>{Ig.init(t,e),Ye.init(t,e)}),I_=j("ZodCUID",(t,e)=>{Tg.init(t,e),Ye.init(t,e)}),T_=j("ZodCUID2",(t,e)=>{kg.init(t,e),Ye.init(t,e)}),k_=j("ZodULID",(t,e)=>{Pg.init(t,e),Ye.init(t,e)}),P_=j("ZodXID",(t,e)=>{Cg.init(t,e),Ye.init(t,e)}),C_=j("ZodKSUID",(t,e)=>{Rg.init(t,e),Ye.init(t,e)}),R_=j("ZodIPv4",(t,e)=>{Mg.init(t,e),Ye.init(t,e)}),O_=j("ZodIPv6",(t,e)=>{Dg.init(t,e),Ye.init(t,e)}),$_=j("ZodCIDRv4",(t,e)=>{jg.init(t,e),Ye.init(t,e)}),A_=j("ZodCIDRv6",(t,e)=>{Lg.init(t,e),Ye.init(t,e)}),_c=j("ZodBase64",(t,e)=>{zg.init(t,e),Ye.init(t,e)});function wc(t){return uc(_c,t)}const N_=j("ZodBase64URL",(t,e)=>{Fg.init(t,e),Ye.init(t,e)}),M_=j("ZodE164",(t,e)=>{qg.init(t,e),Ye.init(t,e)}),D_=j("ZodJWT",(t,e)=>{Vg.init(t,e),Ye.init(t,e)}),ko=j("ZodNumber",(t,e)=>{Ku.init(t,e),Ve.init(t,e),t.gt=(a,n)=>t.check(dc(a,n)),t.gte=(a,n)=>t.check(To(a,n)),t.min=(a,n)=>t.check(To(a,n)),t.lt=(a,n)=>t.check(cc(a,n)),t.lte=(a,n)=>t.check(Io(a,n)),t.max=(a,n)=>t.check(Io(a,n)),t.int=a=>t.check(bc(a)),t.safe=a=>t.check(bc(a)),t.positive=a=>t.check(dc(0,a)),t.nonnegative=a=>t.check(To(0,a)),t.negative=a=>t.check(cc(0,a)),t.nonpositive=a=>t.check(Io(0,a)),t.multipleOf=(a,n)=>t.check(pc(a,n)),t.step=(a,n)=>t.check(pc(a,n)),t.finite=()=>t;const r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function U(t){return Fy(ko,t)}const j_=j("ZodNumberFormat",(t,e)=>{Bg.init(t,e),ko.init(t,e)});function bc(t){return Zy(j_,t)}const L_=j("ZodBoolean",(t,e)=>{Hg.init(t,e),Ve.init(t,e)});function nt(t){return Vy(L_,t)}const z_=j("ZodNull",(t,e)=>{Jg.init(t,e),Ve.init(t,e)});function U_(t){return By(z_,t)}const F_=j("ZodAny",(t,e)=>{Wg.init(t,e),Ve.init(t,e)});function Mt(){return Hy(F_)}const q_=j("ZodUnknown",(t,e)=>{Gg.init(t,e),Ve.init(t,e)});function Cr(){return Jy(q_)}const Z_=j("ZodNever",(t,e)=>{Kg.init(t,e),Ve.init(t,e)});function V_(t){return Wy(Z_,t)}const B_=j("ZodArray",(t,e)=>{Qg.init(t,e),Ve.init(t,e),t.element=e.element,t.min=(r,a)=>t.check(Ba(r,a)),t.nonempty=r=>t.check(Ba(1,r)),t.max=(r,a)=>t.check(hc(r,a)),t.length=(r,a)=>t.check(fc(r,a)),t.unwrap=()=>t.element});function Y(t,e){return s_(B_,t,e)}const xc=j("ZodObject",(t,e)=>{Yg.init(t,e),Ve.init(t,e),De(t,"shape",()=>e.shape),t.keyof=()=>vt(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Cr()}),t.loose=()=>t.clone({...t._zod.def,catchall:Cr()}),t.strict=()=>t.clone({...t._zod.def,catchall:V_()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>xv(t,r),t.merge=r=>Ev(t,r),t.pick=r=>wv(t,r),t.omit=r=>bv(t,r),t.partial=(...r)=>Sv(Sc,t,r[0]),t.required=(...r)=>Iv(Tc,t,r[0])});function P(t,e){const r={type:"object",get shape(){return za(this,"shape",{...t}),this.shape},...X(e)};return new xc(r)}function _n(t,e){return new xc({type:"object",get shape(){return za(this,"shape",{...t}),this.shape},catchall:Cr(),...X(e)})}const Ec=j("ZodUnion",(t,e)=>{ec.init(t,e),Ve.init(t,e),t.options=e.options});function Ae(t,e){return new Ec({type:"union",options:t,...X(e)})}const H_=j("ZodDiscriminatedUnion",(t,e)=>{Ec.init(t,e),Xg.init(t,e)});function wn(t,e,r){return new H_({type:"union",options:e,discriminator:t,...X(r)})}const J_=j("ZodIntersection",(t,e)=>{ey.init(t,e),Ve.init(t,e)});function W_(t,e){return new J_({type:"intersection",left:t,right:e})}const G_=j("ZodRecord",(t,e)=>{ty.init(t,e),Ve.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function St(t,e,r){return new G_({type:"record",keyType:t,valueType:e,...X(r)})}const Po=j("ZodEnum",(t,e)=>{ry.init(t,e),Ve.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);const r=new Set(Object.keys(e.entries));t.extract=(a,n)=>{const s={};for(const o of a)if(r.has(o))s[o]=e.entries[o];else throw new Error(`Key ${o} not found in enum`);return new Po({...e,checks:[],...X(n),entries:s})},t.exclude=(a,n)=>{const s={...e.entries};for(const o of a)if(r.has(o))delete s[o];else throw new Error(`Key ${o} not found in enum`);return new Po({...e,checks:[],...X(n),entries:s})}});function vt(t,e){const r=Array.isArray(t)?Object.fromEntries(t.map(a=>[a,a])):t;return new Po({type:"enum",entries:r,...X(e)})}const K_=j("ZodLiteral",(t,e)=>{ny.init(t,e),Ve.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function H(t,e){return new K_({type:"literal",values:Array.isArray(t)?t:[t],...X(e)})}const Q_=j("ZodTransform",(t,e)=>{ay.init(t,e),Ve.init(t,e),t._zod.parse=(r,a)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(Wn(s,r.value,e));else{const o=s;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=t),o.continue??(o.continue=!0),r.issues.push(Wn(o))}};const n=e.transform(r.value,r);return n instanceof Promise?n.then(s=>(r.value=s,r)):(r.value=n,r)}});function Y_(t){return new Q_({type:"transform",transform:t})}const Sc=j("ZodOptional",(t,e)=>{sy.init(t,e),Ve.init(t,e),t.unwrap=()=>t._zod.def.innerType});function at(t){return new Sc({type:"optional",innerType:t})}const X_=j("ZodNullable",(t,e)=>{oy.init(t,e),Ve.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Ic(t){return new X_({type:"nullable",innerType:t})}const e0=j("ZodDefault",(t,e)=>{iy.init(t,e),Ve.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function t0(t,e){return new e0({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}const r0=j("ZodPrefault",(t,e)=>{ly.init(t,e),Ve.init(t,e),t.unwrap=()=>t._zod.def.innerType});function n0(t,e){return new r0({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}const Tc=j("ZodNonOptional",(t,e)=>{uy.init(t,e),Ve.init(t,e),t.unwrap=()=>t._zod.def.innerType});function a0(t,e){return new Tc({type:"nonoptional",innerType:t,...X(e)})}const s0=j("ZodCatch",(t,e)=>{cy.init(t,e),Ve.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function o0(t,e){return new s0({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}const i0=j("ZodPipe",(t,e)=>{dy.init(t,e),Ve.init(t,e),t.in=e.in,t.out=e.out});function kc(t,e){return new i0({type:"pipe",in:t,out:e})}const l0=j("ZodReadonly",(t,e)=>{py.init(t,e),Ve.init(t,e)});function u0(t){return new l0({type:"readonly",innerType:t})}const c0=j("ZodLazy",(t,e)=>{hy.init(t,e),Ve.init(t,e),t.unwrap=()=>t._zod.def.getter()});function Pc(t){return new c0({type:"lazy",getter:t})}const Co=j("ZodCustom",(t,e)=>{fy.init(t,e),Ve.init(t,e)});function d0(t){const e=new Et({check:"custom"});return e._zod.check=t,e}function p0(t,e){return o_(Co,t??(()=>!0),e)}function h0(t,e={}){return i_(Co,t,e)}function f0(t){const e=d0(r=>(r.addIssue=a=>{if(typeof a=="string")r.issues.push(Wn(a,r.value,e._zod.def));else{const n=a;n.fatal&&(n.continue=!1),n.code??(n.code="custom"),n.input??(n.input=r.value),n.inst??(n.inst=e),n.continue??(n.continue=!e._zod.def.abort),r.issues.push(Wn(n))}},t(r.value,r)));return e}function Wa(t,e={error:`Input not instance of ${t.name}`}){const r=new Co({type:"custom",check:"custom",fn:a=>a instanceof t,abort:!0,...X(e)});return r._zod.bag.Class=t,r}function m0(t){return qy(ko,t)}var $e;(function(t){t.assertEqual=n=>{};function e(n){}t.assertIs=e;function r(n){throw new Error}t.assertNever=r,t.arrayToEnum=n=>{const s={};for(const o of n)s[o]=o;return s},t.getValidEnumValues=n=>{const s=t.objectKeys(n).filter(i=>typeof n[n[i]]!="number"),o={};for(const i of s)o[i]=n[i];return t.objectValues(o)},t.objectValues=n=>t.objectKeys(n).map(function(s){return n[s]}),t.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{const s=[];for(const o in n)Object.prototype.hasOwnProperty.call(n,o)&&s.push(o);return s},t.find=(n,s)=>{for(const o of n)if(s(o))return o},t.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&Number.isFinite(n)&&Math.floor(n)===n;function a(n,s=" | "){return n.map(o=>typeof o=="string"?`'${o}'`:o).join(s)}t.joinValues=a,t.jsonStringifyReplacer=(n,s)=>typeof s=="bigint"?s.toString():s})($e||($e={}));var Cc;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Cc||(Cc={}));const Q=$e.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Rr=t=>{switch(typeof t){case"undefined":return Q.undefined;case"string":return Q.string;case"number":return Number.isNaN(t)?Q.nan:Q.number;case"boolean":return Q.boolean;case"function":return Q.function;case"bigint":return Q.bigint;case"symbol":return Q.symbol;case"object":return Array.isArray(t)?Q.array:t===null?Q.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?Q.promise:typeof Map<"u"&&t instanceof Map?Q.map:typeof Set<"u"&&t instanceof Set?Q.set:typeof Date<"u"&&t instanceof Date?Q.date:Q.object;default:return Q.unknown}},Z=$e.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class yr extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=a=>{this.issues=[...this.issues,a]},this.addIssues=(a=[])=>{this.issues=[...this.issues,...a]};const r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){const r=e||function(s){return s.message},a={_errors:[]},n=s=>{for(const o of s.issues)if(o.code==="invalid_union")o.unionErrors.map(n);else if(o.code==="invalid_return_type")n(o.returnTypeError);else if(o.code==="invalid_arguments")n(o.argumentsError);else if(o.path.length===0)a._errors.push(r(o));else{let i=a,l=0;for(;l<o.path.length;){const u=o.path[l];l===o.path.length-1?(i[u]=i[u]||{_errors:[]},i[u]._errors.push(r(o))):i[u]=i[u]||{_errors:[]},i=i[u],l++}}};return n(this),a}static assert(e){if(!(e instanceof yr))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,$e.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){const r={},a=[];for(const n of this.issues)if(n.path.length>0){const s=n.path[0];r[s]=r[s]||[],r[s].push(e(n))}else a.push(e(n));return{formErrors:a,fieldErrors:r}}get formErrors(){return this.flatten()}}yr.create=t=>new yr(t);const Ro=(t,e)=>{let r;switch(t.code){case Z.invalid_type:t.received===Q.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case Z.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,$e.jsonStringifyReplacer)}`;break;case Z.unrecognized_keys:r=`Unrecognized key(s) in object: ${$e.joinValues(t.keys,", ")}`;break;case Z.invalid_union:r="Invalid input";break;case Z.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${$e.joinValues(t.options)}`;break;case Z.invalid_enum_value:r=`Invalid enum value. Expected ${$e.joinValues(t.options)}, received '${t.received}'`;break;case Z.invalid_arguments:r="Invalid function arguments";break;case Z.invalid_return_type:r="Invalid function return type";break;case Z.invalid_date:r="Invalid date";break;case Z.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:$e.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case Z.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case Z.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case Z.custom:r="Invalid input";break;case Z.invalid_intersection_types:r="Intersection results could not be merged";break;case Z.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case Z.not_finite:r="Number must be finite";break;default:r=e.defaultError,$e.assertNever(t)}return{message:r}};let v0=Ro;function g0(){return v0}const y0=t=>{const{data:e,path:r,errorMaps:a,issueData:n}=t,s=[...r,...n.path||[]],o={...n,path:s};if(n.message!==void 0)return{...n,path:s,message:n.message};let i="";const l=a.filter(u=>!!u).slice().reverse();for(const u of l)i=u(o,{data:e,defaultError:i}).message;return{...n,path:s,message:i}};function G(t,e){const r=g0(),a=y0({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Ro?void 0:Ro].filter(n=>!!n)});t.common.issues.push(a)}class yt{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){const a=[];for(const n of r){if(n.status==="aborted")return ce;n.status==="dirty"&&e.dirty(),a.push(n.value)}return{status:e.value,value:a}}static async mergeObjectAsync(e,r){const a=[];for(const n of r){const s=await n.key,o=await n.value;a.push({key:s,value:o})}return yt.mergeObjectSync(e,a)}static mergeObjectSync(e,r){const a={};for(const n of r){const{key:s,value:o}=n;if(s.status==="aborted"||o.status==="aborted")return ce;s.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof o.value<"u"||n.alwaysSet)&&(a[s.value]=o.value)}return{status:e.value,value:a}}}const ce=Object.freeze({status:"aborted"}),Qn=t=>({status:"dirty",value:t}),Dt=t=>({status:"valid",value:t}),Rc=t=>t.status==="aborted",Oc=t=>t.status==="dirty",bn=t=>t.status==="valid",Ga=t=>typeof Promise<"u"&&t instanceof Promise;var te;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(te||(te={}));class tr{constructor(e,r,a,n){this._cachedPath=[],this.parent=e,this.data=r,this._path=a,this._key=n}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const $c=(t,e)=>{if(bn(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const r=new yr(t.common.issues);return this._error=r,this._error}}};function ge(t){if(!t)return{};const{errorMap:e,invalid_type_error:r,required_error:a,description:n}=t;if(e&&(r||a))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(o,i)=>{const{message:l}=t;return o.code==="invalid_enum_value"?{message:l??i.defaultError}:typeof i.data>"u"?{message:l??a??i.defaultError}:o.code!=="invalid_type"?{message:i.defaultError}:{message:l??r??i.defaultError}},description:n}}class Te{get description(){return this._def.description}_getType(e){return Rr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Rr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new yt,ctx:{common:e.parent.common,data:e.data,parsedType:Rr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const r=this._parse(e);if(Ga(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){const r=this._parse(e);return Promise.resolve(r)}parse(e,r){const a=this.safeParse(e,r);if(a.success)return a.data;throw a.error}safeParse(e,r){const a={common:{issues:[],async:(r==null?void 0:r.async)??!1,contextualErrorMap:r==null?void 0:r.errorMap},path:(r==null?void 0:r.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Rr(e)},n=this._parseSync({data:e,path:a.path,parent:a});return $c(a,n)}"~validate"(e){var a,n;const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Rr(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:r});return bn(s)?{value:s.value}:{issues:r.common.issues}}catch(s){(n=(a=s==null?void 0:s.message)==null?void 0:a.toLowerCase())!=null&&n.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(s=>bn(s)?{value:s.value}:{issues:r.common.issues})}async parseAsync(e,r){const a=await this.safeParseAsync(e,r);if(a.success)return a.data;throw a.error}async safeParseAsync(e,r){const a={common:{issues:[],contextualErrorMap:r==null?void 0:r.errorMap,async:!0},path:(r==null?void 0:r.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Rr(e)},n=this._parse({data:e,path:a.path,parent:a}),s=await(Ga(n)?n:Promise.resolve(n));return $c(a,s)}refine(e,r){const a=n=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(n):r;return this._refinement((n,s)=>{const o=e(n),i=()=>s.addIssue({code:Z.custom,...a(n)});return typeof Promise<"u"&&o instanceof Promise?o.then(l=>l?!0:(i(),!1)):o?!0:(i(),!1)})}refinement(e,r){return this._refinement((a,n)=>e(a)?!0:(n.addIssue(typeof r=="function"?r(a,n):r),!1))}_refinement(e){return new Kr({schema:this,typeName:V.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return br.create(this,this._def)}nullable(){return Qr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return rr.create(this)}promise(){return ts.create(this,this._def)}or(e){return Qa.create([this,e],this._def)}and(e){return Ya.create(this,e,this._def)}transform(e){return new Kr({...ge(this._def),schema:this,typeName:V.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const r=typeof e=="function"?e:()=>e;return new rs({...ge(this._def),innerType:this,defaultValue:r,typeName:V.ZodDefault})}brand(){return new Uc({typeName:V.ZodBranded,type:this,...ge(this._def)})}catch(e){const r=typeof e=="function"?e:()=>e;return new ns({...ge(this._def),innerType:this,catchValue:r,typeName:V.ZodCatch})}describe(e){const r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Fo.create(this,e)}readonly(){return as.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const _0=/^c[^\s-]{8,}$/i,w0=/^[0-9a-z]+$/,b0=/^[0-9A-HJKMNP-TV-Z]{26}$/i,x0=/^[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,E0=/^[a-z0-9_-]{21}$/i,S0=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,I0=/^[-+]?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)?)??$/,T0=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,k0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Oo;const P0=/^(?:(?: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])$/,C0=/^(?:(?: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])$/,R0=/^(([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]))$/,O0=/^(([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])$/,$0=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,A0=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ac="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",N0=new RegExp(`^${Ac}$`);function Nc(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);const r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function M0(t){return new RegExp(`^${Nc(t)}$`)}function D0(t){let e=`${Ac}T${Nc(t)}`;const r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function j0(t,e){return!!((e==="v4"||!e)&&P0.test(t)||(e==="v6"||!e)&&R0.test(t))}function L0(t,e){if(!S0.test(t))return!1;try{const[r]=t.split(".");if(!r)return!1;const a=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),n=JSON.parse(atob(a));return!(typeof n!="object"||n===null||"typ"in n&&(n==null?void 0:n.typ)!=="JWT"||!n.alg||e&&n.alg!==e)}catch{return!1}}function z0(t,e){return!!((e==="v4"||!e)&&C0.test(t)||(e==="v6"||!e)&&O0.test(t))}class _r extends Te{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==Q.string){const s=this._getOrReturnCtx(e);return G(s,{code:Z.invalid_type,expected:Q.string,received:s.parsedType}),ce}const a=new yt;let n;for(const s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(n=this._getOrReturnCtx(e,n),G(n,{code:Z.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),a.dirty());else if(s.kind==="max")e.data.length>s.value&&(n=this._getOrReturnCtx(e,n),G(n,{code:Z.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),a.dirty());else if(s.kind==="length"){const o=e.data.length>s.value,i=e.data.length<s.value;(o||i)&&(n=this._getOrReturnCtx(e,n),o?G(n,{code:Z.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):i&&G(n,{code:Z.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),a.dirty())}else if(s.kind==="email")T0.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:"email",code:Z.invalid_string,message:s.message}),a.dirty());else if(s.kind==="emoji")Oo||(Oo=new RegExp(k0,"u")),Oo.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:"emoji",code:Z.invalid_string,message:s.message}),a.dirty());else if(s.kind==="uuid")x0.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:"uuid",code:Z.invalid_string,message:s.message}),a.dirty());else if(s.kind==="nanoid")E0.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:"nanoid",code:Z.invalid_string,message:s.message}),a.dirty());else if(s.kind==="cuid")_0.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:"cuid",code:Z.invalid_string,message:s.message}),a.dirty());else if(s.kind==="cuid2")w0.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:"cuid2",code:Z.invalid_string,message:s.message}),a.dirty());else if(s.kind==="ulid")b0.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:"ulid",code:Z.invalid_string,message:s.message}),a.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),G(n,{validation:"url",code:Z.invalid_string,message:s.message}),a.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:"regex",code:Z.invalid_string,message:s.message}),a.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(n=this._getOrReturnCtx(e,n),G(n,{code:Z.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),a.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(n=this._getOrReturnCtx(e,n),G(n,{code:Z.invalid_string,validation:{startsWith:s.value},message:s.message}),a.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(n=this._getOrReturnCtx(e,n),G(n,{code:Z.invalid_string,validation:{endsWith:s.value},message:s.message}),a.dirty()):s.kind==="datetime"?D0(s).test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{code:Z.invalid_string,validation:"datetime",message:s.message}),a.dirty()):s.kind==="date"?N0.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{code:Z.invalid_string,validation:"date",message:s.message}),a.dirty()):s.kind==="time"?M0(s).test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{code:Z.invalid_string,validation:"time",message:s.message}),a.dirty()):s.kind==="duration"?I0.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:"duration",code:Z.invalid_string,message:s.message}),a.dirty()):s.kind==="ip"?j0(e.data,s.version)||(n=this._getOrReturnCtx(e,n),G(n,{validation:"ip",code:Z.invalid_string,message:s.message}),a.dirty()):s.kind==="jwt"?L0(e.data,s.alg)||(n=this._getOrReturnCtx(e,n),G(n,{validation:"jwt",code:Z.invalid_string,message:s.message}),a.dirty()):s.kind==="cidr"?z0(e.data,s.version)||(n=this._getOrReturnCtx(e,n),G(n,{validation:"cidr",code:Z.invalid_string,message:s.message}),a.dirty()):s.kind==="base64"?$0.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:"base64",code:Z.invalid_string,message:s.message}),a.dirty()):s.kind==="base64url"?A0.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:"base64url",code:Z.invalid_string,message:s.message}),a.dirty()):$e.assertNever(s);return{status:a.value,value:e.data}}_regex(e,r,a){return this.refinement(n=>e.test(n),{validation:r,code:Z.invalid_string,...te.errToObj(a)})}_addCheck(e){return new _r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...te.errToObj(e)})}url(e){return this._addCheck({kind:"url",...te.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...te.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...te.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...te.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...te.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...te.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...te.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...te.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...te.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...te.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...te.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...te.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(e==null?void 0:e.offset)??!1,local:(e==null?void 0:e.local)??!1,...te.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...te.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...te.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...te.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r==null?void 0:r.position,...te.errToObj(r==null?void 0:r.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...te.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...te.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...te.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...te.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...te.errToObj(r)})}nonempty(e){return this.min(1,te.errToObj(e))}trim(){return new _r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new _r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new _r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}_r.create=t=>new _r({checks:[],typeName:V.ZodString,coerce:(t==null?void 0:t.coerce)??!1,...ge(t)});function U0(t,e){const r=(t.toString().split(".")[1]||"").length,a=(e.toString().split(".")[1]||"").length,n=r>a?r:a,s=Number.parseInt(t.toFixed(n).replace(".","")),o=Number.parseInt(e.toFixed(n).replace(".",""));return s%o/10**n}class xn extends Te{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==Q.number){const s=this._getOrReturnCtx(e);return G(s,{code:Z.invalid_type,expected:Q.number,received:s.parsedType}),ce}let a;const n=new yt;for(const s of this._def.checks)s.kind==="int"?$e.isInteger(e.data)||(a=this._getOrReturnCtx(e,a),G(a,{code:Z.invalid_type,expected:"integer",received:"float",message:s.message}),n.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(a=this._getOrReturnCtx(e,a),G(a,{code:Z.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),n.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(a=this._getOrReturnCtx(e,a),G(a,{code:Z.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),n.dirty()):s.kind==="multipleOf"?U0(e.data,s.value)!==0&&(a=this._getOrReturnCtx(e,a),G(a,{code:Z.not_multiple_of,multipleOf:s.value,message:s.message}),n.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(a=this._getOrReturnCtx(e,a),G(a,{code:Z.not_finite,message:s.message}),n.dirty()):$e.assertNever(s);return{status:n.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,te.toString(r))}gt(e,r){return this.setLimit("min",e,!1,te.toString(r))}lte(e,r){return this.setLimit("max",e,!0,te.toString(r))}lt(e,r){return this.setLimit("max",e,!1,te.toString(r))}setLimit(e,r,a,n){return new xn({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:a,message:te.toString(n)}]})}_addCheck(e){return new xn({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:te.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:te.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:te.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:te.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:te.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:te.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:te.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:te.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:te.toString(e)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&$e.isInteger(e.value))}get isFinite(){let e=null,r=null;for(const a of this._def.checks){if(a.kind==="finite"||a.kind==="int"||a.kind==="multipleOf")return!0;a.kind==="min"?(r===null||a.value>r)&&(r=a.value):a.kind==="max"&&(e===null||a.value<e)&&(e=a.value)}return Number.isFinite(r)&&Number.isFinite(e)}}xn.create=t=>new xn({checks:[],typeName:V.ZodNumber,coerce:(t==null?void 0:t.coerce)||!1,...ge(t)});class Yn extends Te{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==Q.bigint)return this._getInvalidInput(e);let a;const n=new yt;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(a=this._getOrReturnCtx(e,a),G(a,{code:Z.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),n.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(a=this._getOrReturnCtx(e,a),G(a,{code:Z.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),n.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(a=this._getOrReturnCtx(e,a),G(a,{code:Z.not_multiple_of,multipleOf:s.value,message:s.message}),n.dirty()):$e.assertNever(s);return{status:n.value,value:e.data}}_getInvalidInput(e){const r=this._getOrReturnCtx(e);return G(r,{code:Z.invalid_type,expected:Q.bigint,received:r.parsedType}),ce}gte(e,r){return this.setLimit("min",e,!0,te.toString(r))}gt(e,r){return this.setLimit("min",e,!1,te.toString(r))}lte(e,r){return this.setLimit("max",e,!0,te.toString(r))}lt(e,r){return this.setLimit("max",e,!1,te.toString(r))}setLimit(e,r,a,n){return new Yn({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:a,message:te.toString(n)}]})}_addCheck(e){return new Yn({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:te.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:te.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:te.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:te.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:te.toString(r)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}Yn.create=t=>new Yn({checks:[],typeName:V.ZodBigInt,coerce:(t==null?void 0:t.coerce)??!1,...ge(t)});class $o extends Te{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==Q.boolean){const a=this._getOrReturnCtx(e);return G(a,{code:Z.invalid_type,expected:Q.boolean,received:a.parsedType}),ce}return Dt(e.data)}}$o.create=t=>new $o({typeName:V.ZodBoolean,coerce:(t==null?void 0:t.coerce)||!1,...ge(t)});class Ka extends Te{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==Q.date){const s=this._getOrReturnCtx(e);return G(s,{code:Z.invalid_type,expected:Q.date,received:s.parsedType}),ce}if(Number.isNaN(e.data.getTime())){const s=this._getOrReturnCtx(e);return G(s,{code:Z.invalid_date}),ce}const a=new yt;let n;for(const s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(n=this._getOrReturnCtx(e,n),G(n,{code:Z.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),a.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(n=this._getOrReturnCtx(e,n),G(n,{code:Z.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),a.dirty()):$e.assertNever(s);return{status:a.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Ka({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:te.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:te.toString(r)})}get minDate(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}}Ka.create=t=>new Ka({checks:[],coerce:(t==null?void 0:t.coerce)||!1,typeName:V.ZodDate,...ge(t)});class Mc extends Te{_parse(e){if(this._getType(e)!==Q.symbol){const a=this._getOrReturnCtx(e);return G(a,{code:Z.invalid_type,expected:Q.symbol,received:a.parsedType}),ce}return Dt(e.data)}}Mc.create=t=>new Mc({typeName:V.ZodSymbol,...ge(t)});class Ao extends Te{_parse(e){if(this._getType(e)!==Q.undefined){const a=this._getOrReturnCtx(e);return G(a,{code:Z.invalid_type,expected:Q.undefined,received:a.parsedType}),ce}return Dt(e.data)}}Ao.create=t=>new Ao({typeName:V.ZodUndefined,...ge(t)});class No extends Te{_parse(e){if(this._getType(e)!==Q.null){const a=this._getOrReturnCtx(e);return G(a,{code:Z.invalid_type,expected:Q.null,received:a.parsedType}),ce}return Dt(e.data)}}No.create=t=>new No({typeName:V.ZodNull,...ge(t)});class Mo extends Te{constructor(){super(...arguments),this._any=!0}_parse(e){return Dt(e.data)}}Mo.create=t=>new Mo({typeName:V.ZodAny,...ge(t)});class Do extends Te{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Dt(e.data)}}Do.create=t=>new Do({typeName:V.ZodUnknown,...ge(t)});class Or extends Te{_parse(e){const r=this._getOrReturnCtx(e);return G(r,{code:Z.invalid_type,expected:Q.never,received:r.parsedType}),ce}}Or.create=t=>new Or({typeName:V.ZodNever,...ge(t)});class Dc extends Te{_parse(e){if(this._getType(e)!==Q.undefined){const a=this._getOrReturnCtx(e);return G(a,{code:Z.invalid_type,expected:Q.void,received:a.parsedType}),ce}return Dt(e.data)}}Dc.create=t=>new Dc({typeName:V.ZodVoid,...ge(t)});class rr extends Te{_parse(e){const{ctx:r,status:a}=this._processInputParams(e),n=this._def;if(r.parsedType!==Q.array)return G(r,{code:Z.invalid_type,expected:Q.array,received:r.parsedType}),ce;if(n.exactLength!==null){const o=r.data.length>n.exactLength.value,i=r.data.length<n.exactLength.value;(o||i)&&(G(r,{code:o?Z.too_big:Z.too_small,minimum:i?n.exactLength.value:void 0,maximum:o?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),a.dirty())}if(n.minLength!==null&&r.data.length<n.minLength.value&&(G(r,{code:Z.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),a.dirty()),n.maxLength!==null&&r.data.length>n.maxLength.value&&(G(r,{code:Z.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),a.dirty()),r.common.async)return Promise.all([...r.data].map((o,i)=>n.type._parseAsync(new tr(r,o,r.path,i)))).then(o=>yt.mergeArray(a,o));const s=[...r.data].map((o,i)=>n.type._parseSync(new tr(r,o,r.path,i)));return yt.mergeArray(a,s)}get element(){return this._def.type}min(e,r){return new rr({...this._def,minLength:{value:e,message:te.toString(r)}})}max(e,r){return new rr({...this._def,maxLength:{value:e,message:te.toString(r)}})}length(e,r){return new rr({...this._def,exactLength:{value:e,message:te.toString(r)}})}nonempty(e){return this.min(1,e)}}rr.create=(t,e)=>new rr({type:t,minLength:null,maxLength:null,exactLength:null,typeName:V.ZodArray,...ge(e)});function En(t){if(t instanceof st){const e={};for(const r in t.shape){const a=t.shape[r];e[r]=br.create(En(a))}return new st({...t._def,shape:()=>e})}else return t instanceof rr?new rr({...t._def,type:En(t.element)}):t instanceof br?br.create(En(t.unwrap())):t instanceof Qr?Qr.create(En(t.unwrap())):t instanceof Wr?Wr.create(t.items.map(e=>En(e))):t}class st extends Te{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),r=$e.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==Q.object){const u=this._getOrReturnCtx(e);return G(u,{code:Z.invalid_type,expected:Q.object,received:u.parsedType}),ce}const{status:a,ctx:n}=this._processInputParams(e),{shape:s,keys:o}=this._getCached(),i=[];if(!(this._def.catchall instanceof Or&&this._def.unknownKeys==="strip"))for(const u in n.data)o.includes(u)||i.push(u);const l=[];for(const u of o){const d=s[u],h=n.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new tr(n,h,n.path,u)),alwaysSet:u in n.data})}if(this._def.catchall instanceof Or){const u=this._def.unknownKeys;if(u==="passthrough")for(const d of i)l.push({key:{status:"valid",value:d},value:{status:"valid",value:n.data[d]}});else if(u==="strict")i.length>0&&(G(n,{code:Z.unrecognized_keys,keys:i}),a.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const d of i){const h=n.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new tr(n,h,n.path,d)),alwaysSet:d in n.data})}}return n.common.async?Promise.resolve().then(async()=>{const u=[];for(const d of l){const h=await d.key,g=await d.value;u.push({key:h,value:g,alwaysSet:d.alwaysSet})}return u}).then(u=>yt.mergeObjectSync(a,u)):yt.mergeObjectSync(a,l)}get shape(){return this._def.shape()}strict(e){return te.errToObj,new st({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,a)=>{var s,o;const n=((o=(s=this._def).errorMap)==null?void 0:o.call(s,r,a).message)??a.defaultError;return r.code==="unrecognized_keys"?{message:te.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new st({...this._def,unknownKeys:"strip"})}passthrough(){return new st({...this._def,unknownKeys:"passthrough"})}extend(e){return new st({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new st({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:V.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new st({...this._def,catchall:e})}pick(e){const r={};for(const a of $e.objectKeys(e))e[a]&&this.shape[a]&&(r[a]=this.shape[a]);return new st({...this._def,shape:()=>r})}omit(e){const r={};for(const a of $e.objectKeys(this.shape))e[a]||(r[a]=this.shape[a]);return new st({...this._def,shape:()=>r})}deepPartial(){return En(this)}partial(e){const r={};for(const a of $e.objectKeys(this.shape)){const n=this.shape[a];e&&!e[a]?r[a]=n:r[a]=n.optional()}return new st({...this._def,shape:()=>r})}required(e){const r={};for(const a of $e.objectKeys(this.shape))if(e&&!e[a])r[a]=this.shape[a];else{let s=this.shape[a];for(;s instanceof br;)s=s._def.innerType;r[a]=s}return new st({...this._def,shape:()=>r})}keyof(){return Lc($e.objectKeys(this.shape))}}st.create=(t,e)=>new st({shape:()=>t,unknownKeys:"strip",catchall:Or.create(),typeName:V.ZodObject,...ge(e)}),st.strictCreate=(t,e)=>new st({shape:()=>t,unknownKeys:"strict",catchall:Or.create(),typeName:V.ZodObject,...ge(e)}),st.lazycreate=(t,e)=>new st({shape:t,unknownKeys:"strip",catchall:Or.create(),typeName:V.ZodObject,...ge(e)});class Qa extends Te{_parse(e){const{ctx:r}=this._processInputParams(e),a=this._def.options;function n(s){for(const i of s)if(i.result.status==="valid")return i.result;for(const i of s)if(i.result.status==="dirty")return r.common.issues.push(...i.ctx.common.issues),i.result;const o=s.map(i=>new yr(i.ctx.common.issues));return G(r,{code:Z.invalid_union,unionErrors:o}),ce}if(r.common.async)return Promise.all(a.map(async s=>{const o={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:o}),ctx:o}})).then(n);{let s;const o=[];for(const l of a){const u={...r,common:{...r.common,issues:[]},parent:null},d=l._parseSync({data:r.data,path:r.path,parent:u});if(d.status==="valid")return d;d.status==="dirty"&&!s&&(s={result:d,ctx:u}),u.common.issues.length&&o.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;const i=o.map(l=>new yr(l));return G(r,{code:Z.invalid_union,unionErrors:i}),ce}}get options(){return this._def.options}}Qa.create=(t,e)=>new Qa({options:t,typeName:V.ZodUnion,...ge(e)});const wr=t=>t instanceof zo?wr(t.schema):t instanceof Kr?wr(t.innerType()):t instanceof es?[t.value]:t instanceof Gr?t.options:t instanceof Uo?$e.objectValues(t.enum):t instanceof rs?wr(t._def.innerType):t instanceof Ao?[void 0]:t instanceof No?[null]:t instanceof br?[void 0,...wr(t.unwrap())]:t instanceof Qr?[null,...wr(t.unwrap())]:t instanceof Uc||t instanceof as?wr(t.unwrap()):t instanceof ns?wr(t._def.innerType):[];class jo extends Te{_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==Q.object)return G(r,{code:Z.invalid_type,expected:Q.object,received:r.parsedType}),ce;const a=this.discriminator,n=r.data[a],s=this.optionsMap.get(n);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(G(r,{code:Z.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[a]}),ce)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,a){const n=new Map;for(const s of r){const o=wr(s.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const i of o){if(n.has(i))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(i)}`);n.set(i,s)}}return new jo({typeName:V.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:n,...ge(a)})}}function Lo(t,e){const r=Rr(t),a=Rr(e);if(t===e)return{valid:!0,data:t};if(r===Q.object&&a===Q.object){const n=$e.objectKeys(e),s=$e.objectKeys(t).filter(i=>n.indexOf(i)!==-1),o={...t,...e};for(const i of s){const l=Lo(t[i],e[i]);if(!l.valid)return{valid:!1};o[i]=l.data}return{valid:!0,data:o}}else if(r===Q.array&&a===Q.array){if(t.length!==e.length)return{valid:!1};const n=[];for(let s=0;s<t.length;s++){const o=t[s],i=e[s],l=Lo(o,i);if(!l.valid)return{valid:!1};n.push(l.data)}return{valid:!0,data:n}}else return r===Q.date&&a===Q.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class Ya extends Te{_parse(e){const{status:r,ctx:a}=this._processInputParams(e),n=(s,o)=>{if(Rc(s)||Rc(o))return ce;const i=Lo(s.value,o.value);return i.valid?((Oc(s)||Oc(o))&&r.dirty(),{status:r.value,value:i.data}):(G(a,{code:Z.invalid_intersection_types}),ce)};return a.common.async?Promise.all([this._def.left._parseAsync({data:a.data,path:a.path,parent:a}),this._def.right._parseAsync({data:a.data,path:a.path,parent:a})]).then(([s,o])=>n(s,o)):n(this._def.left._parseSync({data:a.data,path:a.path,parent:a}),this._def.right._parseSync({data:a.data,path:a.path,parent:a}))}}Ya.create=(t,e,r)=>new Ya({left:t,right:e,typeName:V.ZodIntersection,...ge(r)});class Wr extends Te{_parse(e){const{status:r,ctx:a}=this._processInputParams(e);if(a.parsedType!==Q.array)return G(a,{code:Z.invalid_type,expected:Q.array,received:a.parsedType}),ce;if(a.data.length<this._def.items.length)return G(a,{code:Z.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ce;!this._def.rest&&a.data.length>this._def.items.length&&(G(a,{code:Z.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const s=[...a.data].map((o,i)=>{const l=this._def.items[i]||this._def.rest;return l?l._parse(new tr(a,o,a.path,i)):null}).filter(o=>!!o);return a.common.async?Promise.all(s).then(o=>yt.mergeArray(r,o)):yt.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new Wr({...this._def,rest:e})}}Wr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Wr({items:t,typeName:V.ZodTuple,rest:null,...ge(e)})};class Xa extends Te{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:a}=this._processInputParams(e);if(a.parsedType!==Q.object)return G(a,{code:Z.invalid_type,expected:Q.object,received:a.parsedType}),ce;const n=[],s=this._def.keyType,o=this._def.valueType;for(const i in a.data)n.push({key:s._parse(new tr(a,i,a.path,i)),value:o._parse(new tr(a,a.data[i],a.path,i)),alwaysSet:i in a.data});return a.common.async?yt.mergeObjectAsync(r,n):yt.mergeObjectSync(r,n)}get element(){return this._def.valueType}static create(e,r,a){return r instanceof Te?new Xa({keyType:e,valueType:r,typeName:V.ZodRecord,...ge(a)}):new Xa({keyType:_r.create(),valueType:e,typeName:V.ZodRecord,...ge(r)})}}class jc extends Te{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:a}=this._processInputParams(e);if(a.parsedType!==Q.map)return G(a,{code:Z.invalid_type,expected:Q.map,received:a.parsedType}),ce;const n=this._def.keyType,s=this._def.valueType,o=[...a.data.entries()].map(([i,l],u)=>({key:n._parse(new tr(a,i,a.path,[u,"key"])),value:s._parse(new tr(a,l,a.path,[u,"value"]))}));if(a.common.async){const i=new Map;return Promise.resolve().then(async()=>{for(const l of o){const u=await l.key,d=await l.value;if(u.status==="aborted"||d.status==="aborted")return ce;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),i.set(u.value,d.value)}return{status:r.value,value:i}})}else{const i=new Map;for(const l of o){const u=l.key,d=l.value;if(u.status==="aborted"||d.status==="aborted")return ce;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),i.set(u.value,d.value)}return{status:r.value,value:i}}}}jc.create=(t,e,r)=>new jc({valueType:e,keyType:t,typeName:V.ZodMap,...ge(r)});class Xn extends Te{_parse(e){const{status:r,ctx:a}=this._processInputParams(e);if(a.parsedType!==Q.set)return G(a,{code:Z.invalid_type,expected:Q.set,received:a.parsedType}),ce;const n=this._def;n.minSize!==null&&a.data.size<n.minSize.value&&(G(a,{code:Z.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),r.dirty()),n.maxSize!==null&&a.data.size>n.maxSize.value&&(G(a,{code:Z.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),r.dirty());const s=this._def.valueType;function o(l){const u=new Set;for(const d of l){if(d.status==="aborted")return ce;d.status==="dirty"&&r.dirty(),u.add(d.value)}return{status:r.value,value:u}}const i=[...a.data.values()].map((l,u)=>s._parse(new tr(a,l,a.path,u)));return a.common.async?Promise.all(i).then(l=>o(l)):o(i)}min(e,r){return new Xn({...this._def,minSize:{value:e,message:te.toString(r)}})}max(e,r){return new Xn({...this._def,maxSize:{value:e,message:te.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}}Xn.create=(t,e)=>new Xn({valueType:t,minSize:null,maxSize:null,typeName:V.ZodSet,...ge(e)});class zo extends Te{get schema(){return this._def.getter()}_parse(e){const{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}}zo.create=(t,e)=>new zo({getter:t,typeName:V.ZodLazy,...ge(e)});class es extends Te{_parse(e){if(e.data!==this._def.value){const r=this._getOrReturnCtx(e);return G(r,{received:r.data,code:Z.invalid_literal,expected:this._def.value}),ce}return{status:"valid",value:e.data}}get value(){return this._def.value}}es.create=(t,e)=>new es({value:t,typeName:V.ZodLiteral,...ge(e)});function Lc(t,e){return new Gr({values:t,typeName:V.ZodEnum,...ge(e)})}class Gr extends Te{_parse(e){if(typeof e.data!="string"){const r=this._getOrReturnCtx(e),a=this._def.values;return G(r,{expected:$e.joinValues(a),received:r.parsedType,code:Z.invalid_type}),ce}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const r=this._getOrReturnCtx(e),a=this._def.values;return G(r,{received:r.data,code:Z.invalid_enum_value,options:a}),ce}return Dt(e.data)}get options(){return this._def.values}get enum(){const e={};for(const r of this._def.values)e[r]=r;return e}get Values(){const e={};for(const r of this._def.values)e[r]=r;return e}get Enum(){const e={};for(const r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return Gr.create(e,{...this._def,...r})}exclude(e,r=this._def){return Gr.create(this.options.filter(a=>!e.includes(a)),{...this._def,...r})}}Gr.create=Lc;class Uo extends Te{_parse(e){const r=$e.getValidEnumValues(this._def.values),a=this._getOrReturnCtx(e);if(a.parsedType!==Q.string&&a.parsedType!==Q.number){const n=$e.objectValues(r);return G(a,{expected:$e.joinValues(n),received:a.parsedType,code:Z.invalid_type}),ce}if(this._cache||(this._cache=new Set($e.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const n=$e.objectValues(r);return G(a,{received:a.data,code:Z.invalid_enum_value,options:n}),ce}return Dt(e.data)}get enum(){return this._def.values}}Uo.create=(t,e)=>new Uo({values:t,typeName:V.ZodNativeEnum,...ge(e)});class ts extends Te{unwrap(){return this._def.type}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==Q.promise&&r.common.async===!1)return G(r,{code:Z.invalid_type,expected:Q.promise,received:r.parsedType}),ce;const a=r.parsedType===Q.promise?r.data:Promise.resolve(r.data);return Dt(a.then(n=>this._def.type.parseAsync(n,{path:r.path,errorMap:r.common.contextualErrorMap})))}}ts.create=(t,e)=>new ts({type:t,typeName:V.ZodPromise,...ge(e)});class Kr extends Te{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===V.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:r,ctx:a}=this._processInputParams(e),n=this._def.effect||null,s={addIssue:o=>{G(a,o),o.fatal?r.abort():r.dirty()},get path(){return a.path}};if(s.addIssue=s.addIssue.bind(s),n.type==="preprocess"){const o=n.transform(a.data,s);if(a.common.async)return Promise.resolve(o).then(async i=>{if(r.value==="aborted")return ce;const l=await this._def.schema._parseAsync({data:i,path:a.path,parent:a});return l.status==="aborted"?ce:l.status==="dirty"||r.value==="dirty"?Qn(l.value):l});{if(r.value==="aborted")return ce;const i=this._def.schema._parseSync({data:o,path:a.path,parent:a});return i.status==="aborted"?ce:i.status==="dirty"||r.value==="dirty"?Qn(i.value):i}}if(n.type==="refinement"){const o=i=>{const l=n.refinement(i,s);if(a.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return i};if(a.common.async===!1){const i=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});return i.status==="aborted"?ce:(i.status==="dirty"&&r.dirty(),o(i.value),{status:r.value,value:i.value})}else return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then(i=>i.status==="aborted"?ce:(i.status==="dirty"&&r.dirty(),o(i.value).then(()=>({status:r.value,value:i.value}))))}if(n.type==="transform")if(a.common.async===!1){const o=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});if(!bn(o))return ce;const i=n.transform(o.value,s);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:i}}else return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then(o=>bn(o)?Promise.resolve(n.transform(o.value,s)).then(i=>({status:r.value,value:i})):ce);$e.assertNever(n)}}Kr.create=(t,e,r)=>new Kr({schema:t,typeName:V.ZodEffects,effect:e,...ge(r)}),Kr.createWithPreprocess=(t,e,r)=>new Kr({schema:e,effect:{type:"preprocess",transform:t},typeName:V.ZodEffects,...ge(r)});class br extends Te{_parse(e){return this._getType(e)===Q.undefined?Dt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}br.create=(t,e)=>new br({innerType:t,typeName:V.ZodOptional,...ge(e)});class Qr extends Te{_parse(e){return this._getType(e)===Q.null?Dt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Qr.create=(t,e)=>new Qr({innerType:t,typeName:V.ZodNullable,...ge(e)});class rs extends Te{_parse(e){const{ctx:r}=this._processInputParams(e);let a=r.data;return r.parsedType===Q.undefined&&(a=this._def.defaultValue()),this._def.innerType._parse({data:a,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}rs.create=(t,e)=>new rs({innerType:t,typeName:V.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ge(e)});class ns extends Te{_parse(e){const{ctx:r}=this._processInputParams(e),a={...r,common:{...r.common,issues:[]}},n=this._def.innerType._parse({data:a.data,path:a.path,parent:{...a}});return Ga(n)?n.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new yr(a.common.issues)},input:a.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new yr(a.common.issues)},input:a.data})}}removeCatch(){return this._def.innerType}}ns.create=(t,e)=>new ns({innerType:t,typeName:V.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ge(e)});class zc extends Te{_parse(e){if(this._getType(e)!==Q.nan){const a=this._getOrReturnCtx(e);return G(a,{code:Z.invalid_type,expected:Q.nan,received:a.parsedType}),ce}return{status:"valid",value:e.data}}}zc.create=t=>new zc({typeName:V.ZodNaN,...ge(t)});class Uc extends Te{_parse(e){const{ctx:r}=this._processInputParams(e),a=r.data;return this._def.type._parse({data:a,path:r.path,parent:r})}unwrap(){return this._def.type}}class Fo extends Te{_parse(e){const{status:r,ctx:a}=this._processInputParams(e);if(a.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:a.data,path:a.path,parent:a});return s.status==="aborted"?ce:s.status==="dirty"?(r.dirty(),Qn(s.value)):this._def.out._parseAsync({data:s.value,path:a.path,parent:a})})();{const n=this._def.in._parseSync({data:a.data,path:a.path,parent:a});return n.status==="aborted"?ce:n.status==="dirty"?(r.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:a.path,parent:a})}}static create(e,r){return new Fo({in:e,out:r,typeName:V.ZodPipeline})}}class as extends Te{_parse(e){const r=this._def.innerType._parse(e),a=n=>(bn(n)&&(n.value=Object.freeze(n.value)),n);return Ga(r)?r.then(n=>a(n)):a(r)}unwrap(){return this._def.innerType}}as.create=(t,e)=>new as({innerType:t,typeName:V.ZodReadonly,...ge(e)});var V;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(V||(V={}));const O=_r.create,dt=xn.create,lt=$o.create,F0=Mo.create,ea=Do.create;Or.create;const ee=rr.create,W=st.create,_t=Qa.create,q0=jo.create;Ya.create,Wr.create;const ta=Xa.create,me=es.create,xr=Gr.create;ts.create;const q=br.create;Qr.create;function qo(...t){return t.reduce((e,r)=>({...e,...r??{}}),{})}async function Z0(t,e){if(t==null)return Promise.resolve();const r=e==null?void 0:e.abortSignal;return new Promise((a,n)=>{if(r!=null&&r.aborted){n(Fc());return}const s=setTimeout(()=>{o(),a()},t),o=()=>{clearTimeout(s),r==null||r.removeEventListener("abort",i)},i=()=>{o(),n(Fc())};r==null||r.addEventListener("abort",i)})}function Fc(){return new DOMException("Delay was aborted","AbortError")}function ra(t){return Object.fromEntries([...t.headers])}var na=({prefix:t,size:e=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:a="-"}={})=>{const n=()=>{const s=r.length,o=new Array(e);for(let i=0;i<e;i++)o[i]=r[Math.random()*s|0];return o.join("")};if(t==null)return n;if(r.includes(a))throw new vo({argument:"separator",message:`The separator "${a}" must not be part of the alphabet "${r}".`});return()=>`${t}${a}${n()}`},V0=na();function Zo(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}function Yr(t){return(t instanceof Error||t instanceof DOMException)&&(t.name==="AbortError"||t.name==="ResponseAborted"||t.name==="TimeoutError")}var B0=["fetch failed","failed to fetch"];function qc({error:t,url:e,requestBodyValues:r}){if(Yr(t))return t;if(t instanceof TypeError&&B0.includes(t.message.toLowerCase())){const a=t.cause;if(a!=null)return new Ue({message:`Cannot connect to API: ${a.message}`,cause:a,url:e,requestBodyValues:r,isRetryable:!0})}return t}function Vo(t=globalThis){var e,r,a;return t.window?"runtime/browser":(e=t.navigator)!=null&&e.userAgent?`runtime/${t.navigator.userAgent.toLowerCase()}`:(a=(r=t.process)==null?void 0:r.versions)!=null&&a.node?`runtime/node.js/${t.process.version.substring(0)}`:t.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function H0(t){return Object.fromEntries(Object.entries(t).filter(([e,r])=>r!=null))}function aa(t,...e){const r=H0(t??{}),a=new Headers(r),n=a.get("user-agent")||"";return a.set("user-agent",[n,...e].filter(Boolean).join(" ")),Object.fromEntries(a)}var Zc="3.0.12",J0=()=>globalThis.fetch,Vc=async({url:t,headers:e={},successfulResponseHandler:r,failedResponseHandler:a,abortSignal:n,fetch:s=J0()})=>{try{const o=await s(t,{method:"GET",headers:aa(e,`ai-sdk/provider-utils/${Zc}`,Vo()),signal:n}),i=ra(o);if(!o.ok){let l;try{l=await a({response:o,url:t,requestBodyValues:{}})}catch(u){throw Yr(u)||Ue.isInstance(u)?u:new Ue({message:"Failed to process error response",cause:u,statusCode:o.status,url:t,responseHeaders:i,requestBodyValues:{}})}throw l.value}try{return await r({response:o,url:t,requestBodyValues:{}})}catch(l){throw l instanceof Error&&(Yr(l)||Ue.isInstance(l))?l:new Ue({message:"Failed to process successful response",cause:l,statusCode:o.status,url:t,responseHeaders:i,requestBodyValues:{}})}}catch(o){throw qc({error:o,url:t,requestBodyValues:{}})}};function W0({mediaType:t,url:e,supportedUrls:r}){return e=e.toLowerCase(),t=t.toLowerCase(),Object.entries(r).map(([a,n])=>{const s=a.toLowerCase();return s==="*"||s==="*/*"?{mediaTypePrefix:"",regexes:n}:{mediaTypePrefix:s.replace(/\*/,""),regexes:n}}).filter(({mediaTypePrefix:a})=>t.startsWith(a)).flatMap(({regexes:a})=>a).some(a=>a.test(e))}function ss({settingValue:t,environmentVariableName:e}){if(typeof t=="string")return t;if(!(t!=null||typeof process>"u")&&(t=process.env[e],!(t==null||typeof t!="string")))return t}var G0=/"__proto__"\s*:/,K0=/"constructor"\s*:/;function Q0(t){const e=JSON.parse(t);return e===null||typeof e!="object"||G0.test(t)===!1&&K0.test(t)===!1?e:Y0(e)}function Y0(t){let e=[t];for(;e.length;){const r=e;e=[];for(const a of r){if(Object.prototype.hasOwnProperty.call(a,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(a,"constructor")&&Object.prototype.hasOwnProperty.call(a.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const n in a){const s=a[n];s&&typeof s=="object"&&e.push(s)}}}return t}function Bc(t){const{stackTraceLimit:e}=Error;Error.stackTraceLimit=0;try{return Q0(t)}finally{Error.stackTraceLimit=e}}var os=Symbol.for("vercel.ai.validator");function X0(t){return{[os]:!0,validate:t}}function ew(t){return typeof t=="object"&&t!==null&&os in t&&t[os]===!0&&"validate"in t}function Sn(t){let e;return()=>(e==null&&(e=t()),e)}function tw(t){return ew(t)?t:typeof t=="function"?t():rw(t)}function rw(t){return X0(async e=>{const r=await t["~standard"].validate(e);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new er({value:e,cause:r.issues})}})}async function Bo({value:t,schema:e}){const r=await $r({value:t,schema:e});if(!r.success)throw er.wrap({value:t,cause:r.error});return r.value}async function $r({value:t,schema:e}){const r=tw(e);try{if(r.validate==null)return{success:!0,value:t,rawValue:t};const a=await r.validate(t);return a.success?{success:!0,value:a.value,rawValue:t}:{success:!1,error:er.wrap({value:t,cause:a.error}),rawValue:t}}catch(a){return{success:!1,error:er.wrap({value:t,cause:a}),rawValue:t}}}async function nw({text:t,schema:e}){try{const r=Bc(t);return e==null?r:Bo({value:r,schema:e})}catch(r){throw Tr.isInstance(r)||er.isInstance(r)?r:new Tr({text:t,cause:r})}}async function Xr({text:t,schema:e}){try{const r=Bc(t);return e==null?{success:!0,value:r,rawValue:r}:await $r({value:r,schema:e})}catch(r){return{success:!1,error:Tr.isInstance(r)?r:new Tr({text:t,cause:r}),rawValue:void 0}}}function aw({stream:t,schema:e}){return t.pipeThrough(new TextDecoderStream).pipeThrough(new hv).pipeThrough(new TransformStream({async transform({data:r},a){r!=="[DONE]"&&a.enqueue(await Xr({text:r,schema:e}))}}))}var sw=()=>globalThis.fetch,Ho=async({url:t,headers:e,body:r,failedResponseHandler:a,successfulResponseHandler:n,abortSignal:s,fetch:o})=>ow({url:t,headers:{"Content-Type":"application/json",...e},body:{content:JSON.stringify(r),values:r},failedResponseHandler:a,successfulResponseHandler:n,abortSignal:s,fetch:o}),ow=async({url:t,headers:e={},body:r,successfulResponseHandler:a,failedResponseHandler:n,abortSignal:s,fetch:o=sw()})=>{try{const i=await o(t,{method:"POST",headers:aa(e,`ai-sdk/provider-utils/${Zc}`,Vo()),body:r.content,signal:s}),l=ra(i);if(!i.ok){let u;try{u=await n({response:i,url:t,requestBodyValues:r.values})}catch(d){throw Yr(d)||Ue.isInstance(d)?d:new Ue({message:"Failed to process error response",cause:d,statusCode:i.status,url:t,responseHeaders:l,requestBodyValues:r.values})}throw u.value}try{return await a({response:i,url:t,requestBodyValues:r.values})}catch(u){throw u instanceof Error&&(Yr(u)||Ue.isInstance(u))?u:new Ue({message:"Failed to process successful response",cause:u,statusCode:i.status,url:t,responseHeaders:l,requestBodyValues:r.values})}}catch(i){throw qc({error:i,url:t,requestBodyValues:r.values})}};function iw(t){return{...t,type:"dynamic"}}async function Ar(t){return typeof t=="function"&&(t=t()),Promise.resolve(t)}var sa=({errorSchema:t,errorToMessage:e,isRetryable:r})=>async({response:a,url:n,requestBodyValues:s})=>{const o=await a.text(),i=ra(a);if(o.trim()==="")return{responseHeaders:i,value:new Ue({message:a.statusText,url:n,requestBodyValues:s,statusCode:a.status,responseHeaders:i,responseBody:o,isRetryable:r==null?void 0:r(a)})};try{const l=await nw({text:o,schema:t});return{responseHeaders:i,value:new Ue({message:e(l),url:n,requestBodyValues:s,statusCode:a.status,responseHeaders:i,responseBody:o,data:l,isRetryable:r==null?void 0:r(a,l)})}}catch{return{responseHeaders:i,value:new Ue({message:a.statusText,url:n,requestBodyValues:s,statusCode:a.status,responseHeaders:i,responseBody:o,isRetryable:r==null?void 0:r(a)})}}},lw=t=>async({response:e})=>{const r=ra(e);if(e.body==null)throw new su({});return{responseHeaders:r,value:aw({stream:e.body,schema:t})}},is=t=>async({response:e,url:r,requestBodyValues:a})=>{const n=await e.text(),s=await Xr({text:n,schema:t}),o=ra(e);if(!s.success)throw new Ue({message:"Invalid JSON response",cause:s.error,statusCode:e.status,responseHeaders:o,responseBody:n,url:r,requestBodyValues:a});return{responseHeaders:o,value:s.value,rawValue:s.rawValue}},uw=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")},cw=Symbol("Let zodToJsonSchema decide on which parser to use"),Hc={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"},dw=t=>typeof t=="string"?{...Hc,name:t}:{...Hc,...t};function Pt(){return{}}function pw(t,e){var r,a,n;const s={type:"array"};return(r=t.type)!=null&&r._def&&((n=(a=t.type)==null?void 0:a._def)==null?void 0:n.typeName)!==V.ZodAny&&(s.items=je(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&(s.minItems=t.minLength.value),t.maxLength&&(s.maxItems=t.maxLength.value),t.exactLength&&(s.minItems=t.exactLength.value,s.maxItems=t.exactLength.value),s}function hw(t){const e={type:"integer",format:"int64"};if(!t.checks)return e;for(const r of t.checks)switch(r.kind){case"min":r.inclusive?e.minimum=r.value:e.exclusiveMinimum=r.value;break;case"max":r.inclusive?e.maximum=r.value:e.exclusiveMaximum=r.value;break;case"multipleOf":e.multipleOf=r.value;break}return e}function fw(){return{type:"boolean"}}function Jc(t,e){return je(t.type._def,e)}var mw=(t,e)=>je(t.innerType._def,e);function Wc(t,e,r){const a=r??e.dateStrategy;if(Array.isArray(a))return{anyOf:a.map((n,s)=>Wc(t,e,n))};switch(a){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return vw(t)}}var vw=t=>{const e={type:"integer",format:"unix-time"};for(const r of t.checks)switch(r.kind){case"min":e.minimum=r.value;break;case"max":e.maximum=r.value;break}return e};function gw(t,e){return{...je(t.innerType._def,e),default:t.defaultValue()}}function yw(t,e){return e.effectStrategy==="input"?je(t.schema._def,e):Pt()}function _w(t){return{type:"string",enum:Array.from(t.values)}}var ww=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function bw(t,e){const r=[je(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),je(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(n=>!!n),a=[];return r.forEach(n=>{if(ww(n))a.push(...n.allOf);else{let s=n;if("additionalProperties"in n&&n.additionalProperties===!1){const{additionalProperties:o,...i}=n;s=i}a.push(s)}}),a.length?{allOf:a}:void 0}function xw(t){const e=typeof t.value;return e!=="bigint"&&e!=="number"&&e!=="boolean"&&e!=="string"?{type:Array.isArray(t.value)?"array":"object"}:{type:e==="bigint"?"integer":e,const:t.value}}var Jo=void 0,Jt={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:()=>(Jo===void 0&&(Jo=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Jo),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 Gc(t,e){const r={type:"string"};if(t.checks)for(const a of t.checks)switch(a.kind){case"min":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,a.value):a.value;break;case"max":r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,a.value):a.value;break;case"email":switch(e.emailStrategy){case"format:email":Wt(r,"email",a.message,e);break;case"format:idn-email":Wt(r,"idn-email",a.message,e);break;case"pattern:zod":wt(r,Jt.email,a.message,e);break}break;case"url":Wt(r,"uri",a.message,e);break;case"uuid":Wt(r,"uuid",a.message,e);break;case"regex":wt(r,a.regex,a.message,e);break;case"cuid":wt(r,Jt.cuid,a.message,e);break;case"cuid2":wt(r,Jt.cuid2,a.message,e);break;case"startsWith":wt(r,RegExp(`^${Wo(a.value,e)}`),a.message,e);break;case"endsWith":wt(r,RegExp(`${Wo(a.value,e)}$`),a.message,e);break;case"datetime":Wt(r,"date-time",a.message,e);break;case"date":Wt(r,"date",a.message,e);break;case"time":Wt(r,"time",a.message,e);break;case"duration":Wt(r,"duration",a.message,e);break;case"length":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,a.value):a.value,r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,a.value):a.value;break;case"includes":{wt(r,RegExp(Wo(a.value,e)),a.message,e);break}case"ip":{a.version!=="v6"&&Wt(r,"ipv4",a.message,e),a.version!=="v4"&&Wt(r,"ipv6",a.message,e);break}case"base64url":wt(r,Jt.base64url,a.message,e);break;case"jwt":wt(r,Jt.jwt,a.message,e);break;case"cidr":{a.version!=="v6"&&wt(r,Jt.ipv4Cidr,a.message,e),a.version!=="v4"&&wt(r,Jt.ipv6Cidr,a.message,e);break}case"emoji":wt(r,Jt.emoji(),a.message,e);break;case"ulid":{wt(r,Jt.ulid,a.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Wt(r,"binary",a.message,e);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{wt(r,Jt.base64,a.message,e);break}}break}case"nanoid":wt(r,Jt.nanoid,a.message,e)}return r}function Wo(t,e){return e.patternStrategy==="escape"?Sw(t):t}var Ew=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Sw(t){let e="";for(let r=0;r<t.length;r++)Ew.has(t[r])||(e+="\\"),e+=t[r];return e}function Wt(t,e,r,a){var n;t.format||(n=t.anyOf)!=null&&n.some(s=>s.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format}),delete t.format),t.anyOf.push({format:e,...r&&a.errorMessages&&{errorMessage:{format:r}}})):t.format=e}function wt(t,e,r,a){var n;t.pattern||(n=t.allOf)!=null&&n.some(s=>s.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern}),delete t.pattern),t.allOf.push({pattern:Kc(e,a),...r&&a.errorMessages&&{errorMessage:{pattern:r}}})):t.pattern=Kc(e,a)}function Kc(t,e){var r;if(!e.applyRegexFlags||!t.flags)return t.source;const a={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=a.i?t.source.toLowerCase():t.source;let s="",o=!1,i=!1,l=!1;for(let u=0;u<n.length;u++){if(o){s+=n[u],o=!1;continue}if(a.i){if(i){if(n[u].match(/[a-z]/)){l?(s+=n[u],s+=`${n[u-2]}-${n[u]}`.toUpperCase(),l=!1):n[u+1]==="-"&&((r=n[u+2])!=null&&r.match(/[a-z]/))?(s+=n[u],l=!0):s+=`${n[u]}${n[u].toUpperCase()}`;continue}}else if(n[u].match(/[a-z]/)){s+=`[${n[u]}${n[u].toUpperCase()}]`;continue}}if(a.m){if(n[u]==="^"){s+=`(^|(?<=[\r
|
|
35
|
+
]))`;continue}else if(n[u]==="$"){s+=`($|(?=[\r
|
|
36
|
+
]))`;continue}}if(a.s&&n[u]==="."){s+=i?`${n[u]}\r
|
|
37
|
+
`:`[${n[u]}\r
|
|
38
|
+
]`;continue}s+=n[u],n[u]==="\\"?o=!0:i&&n[u]==="]"?i=!1:!i&&n[u]==="["&&(i=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return s}function Qc(t,e){var r,a,n,s,o,i;const l={type:"object",additionalProperties:(r=je(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]}))!=null?r:e.allowedAdditionalProperties};if(((a=t.keyType)==null?void 0:a._def.typeName)===V.ZodString&&((n=t.keyType._def.checks)!=null&&n.length)){const{type:u,...d}=Gc(t.keyType._def,e);return{...l,propertyNames:d}}else{if(((s=t.keyType)==null?void 0:s._def.typeName)===V.ZodEnum)return{...l,propertyNames:{enum:t.keyType._def.values}};if(((o=t.keyType)==null?void 0:o._def.typeName)===V.ZodBranded&&t.keyType._def.type._def.typeName===V.ZodString&&((i=t.keyType._def.type._def.checks)!=null&&i.length)){const{type:u,...d}=Jc(t.keyType._def,e);return{...l,propertyNames:d}}}return l}function Iw(t,e){if(e.mapStrategy==="record")return Qc(t,e);const r=je(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Pt(),a=je(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Pt();return{type:"array",maxItems:125,items:{type:"array",items:[r,a],minItems:2,maxItems:2}}}function Tw(t){const e=t.values,a=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),n=Array.from(new Set(a.map(s=>typeof s)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:a}}function kw(){return{not:Pt()}}function Pw(){return{type:"null"}}var Go={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Cw(t,e){const r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(a=>a._def.typeName in Go&&(!a._def.checks||!a._def.checks.length))){const a=r.reduce((n,s)=>{const o=Go[s._def.typeName];return o&&!n.includes(o)?[...n,o]:n},[]);return{type:a.length>1?a:a[0]}}else if(r.every(a=>a._def.typeName==="ZodLiteral"&&!a.description)){const a=r.reduce((n,s)=>{const o=typeof s._def.value;switch(o){case"string":case"number":case"boolean":return[...n,o];case"bigint":return[...n,"integer"];case"object":if(s._def.value===null)return[...n,"null"];case"symbol":case"undefined":case"function":default:return n}},[]);if(a.length===r.length){const n=a.filter((s,o,i)=>i.indexOf(s)===o);return{type:n.length>1?n:n[0],enum:r.reduce((s,o)=>s.includes(o._def.value)?s:[...s,o._def.value],[])}}}else if(r.every(a=>a._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((a,n)=>[...a,...n._def.values.filter(s=>!a.includes(s))],[])};return Rw(t,e)}var Rw=(t,e)=>{const r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((a,n)=>je(a._def,{...e,currentPath:[...e.currentPath,"anyOf",`${n}`]})).filter(a=>!!a&&(!e.strictUnions||typeof a=="object"&&Object.keys(a).length>0));return r.length?{anyOf:r}:void 0};function Ow(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return{type:[Go[t.innerType._def.typeName],"null"]};const r=je(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function $w(t){const e={type:"number"};if(!t.checks)return e;for(const r of t.checks)switch(r.kind){case"int":e.type="integer";break;case"min":r.inclusive?e.minimum=r.value:e.exclusiveMinimum=r.value;break;case"max":r.inclusive?e.maximum=r.value:e.exclusiveMaximum=r.value;break;case"multipleOf":e.multipleOf=r.value;break}return e}function Aw(t,e){const r={type:"object",properties:{}},a=[],n=t.shape();for(const o in n){let i=n[o];if(i===void 0||i._def===void 0)continue;const l=Mw(i),u=je(i._def,{...e,currentPath:[...e.currentPath,"properties",o],propertyPath:[...e.currentPath,"properties",o]});u!==void 0&&(r.properties[o]=u,l||a.push(o))}a.length&&(r.required=a);const s=Nw(t,e);return s!==void 0&&(r.additionalProperties=s),r}function Nw(t,e){if(t.catchall._def.typeName!=="ZodNever")return je(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function Mw(t){try{return t.isOptional()}catch{return!0}}var Dw=(t,e)=>{var r;if(e.currentPath.toString()===((r=e.propertyPath)==null?void 0:r.toString()))return je(t.innerType._def,e);const a=je(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return a?{anyOf:[{not:Pt()},a]}:Pt()},jw=(t,e)=>{if(e.pipeStrategy==="input")return je(t.in._def,e);if(e.pipeStrategy==="output")return je(t.out._def,e);const r=je(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),a=je(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,a].filter(n=>n!==void 0)}};function Lw(t,e){return je(t.type._def,e)}function zw(t,e){const a={type:"array",uniqueItems:!0,items:je(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&(a.minItems=t.minSize.value),t.maxSize&&(a.maxItems=t.maxSize.value),a}function Uw(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,a)=>je(r._def,{...e,currentPath:[...e.currentPath,"items",`${a}`]})).reduce((r,a)=>a===void 0?r:[...r,a],[]),additionalItems:je(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,a)=>je(r._def,{...e,currentPath:[...e.currentPath,"items",`${a}`]})).reduce((r,a)=>a===void 0?r:[...r,a],[])}}function Fw(){return{not:Pt()}}function qw(){return Pt()}var Zw=(t,e)=>je(t.innerType._def,e),Vw=(t,e,r)=>{switch(e){case V.ZodString:return Gc(t,r);case V.ZodNumber:return $w(t);case V.ZodObject:return Aw(t,r);case V.ZodBigInt:return hw(t);case V.ZodBoolean:return fw();case V.ZodDate:return Wc(t,r);case V.ZodUndefined:return Fw();case V.ZodNull:return Pw();case V.ZodArray:return pw(t,r);case V.ZodUnion:case V.ZodDiscriminatedUnion:return Cw(t,r);case V.ZodIntersection:return bw(t,r);case V.ZodTuple:return Uw(t,r);case V.ZodRecord:return Qc(t,r);case V.ZodLiteral:return xw(t);case V.ZodEnum:return _w(t);case V.ZodNativeEnum:return Tw(t);case V.ZodNullable:return Ow(t,r);case V.ZodOptional:return Dw(t,r);case V.ZodMap:return Iw(t,r);case V.ZodSet:return zw(t,r);case V.ZodLazy:return()=>t.getter()._def;case V.ZodPromise:return Lw(t,r);case V.ZodNaN:case V.ZodNever:return kw();case V.ZodEffects:return yw(t,r);case V.ZodAny:return Pt();case V.ZodUnknown:return qw();case V.ZodDefault:return gw(t,r);case V.ZodBranded:return Jc(t,r);case V.ZodReadonly:return Zw(t,r);case V.ZodCatch:return mw(t,r);case V.ZodPipeline:return jw(t,r);case V.ZodFunction:case V.ZodVoid:case V.ZodSymbol:return;default:return(a=>{})()}};function je(t,e,r=!1){var a;const n=e.seen.get(t);if(e.override){const l=(a=e.override)==null?void 0:a.call(e,t,e,n,r);if(l!==cw)return l}if(n&&!r){const l=Bw(n,e);if(l!==void 0)return l}const s={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,s);const o=Vw(t,t.typeName,e),i=typeof o=="function"?je(o(),e):o;if(i&&Hw(t,e,i),e.postProcess){const l=e.postProcess(i,t,e);return s.jsonSchema=i,l}return s.jsonSchema=i,i}var Bw=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:uw(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,a)=>e.currentPath[a]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Pt()):e.$refStrategy==="seen"?Pt():void 0}},Hw=(t,e,r)=>(t.description&&(r.description=t.description),r),Jw=t=>{const e=dw(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([a,n])=>[n._def,{def:n._def,path:[...e.basePath,e.definitionPath,a],jsonSchema:void 0}]))}},Ww=(t,e)=>{var r;const a=Jw(e);let n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((u,[d,h])=>{var g;return{...u,[d]:(g=je(h._def,{...a,currentPath:[...a.basePath,a.definitionPath,d]},!0))!=null?g:Pt()}},{}):void 0;const s=typeof e=="string"?e:(e==null?void 0:e.nameStrategy)==="title"||e==null?void 0:e.name,o=(r=je(t._def,s===void 0?a:{...a,currentPath:[...a.basePath,a.definitionPath,s]},!1))!=null?r:Pt(),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(o.title=i);const l=s===void 0?n?{...o,[a.definitionPath]:n}:o:{$ref:[...a.$refStrategy==="relative"?[]:a.basePath,a.definitionPath,s].join("/"),[a.definitionPath]:{...n,[s]:o}};return l.$schema="http://json-schema.org/draft-07/schema#",l},Gw=Ww;function Kw(t,e){var r;const a=(r=void 0)!=null?r:!1;return ls(()=>Gw(t,{$refStrategy:a?"root":"none"}),{validate:async n=>{const s=await t.safeParseAsync(n);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function Qw(t,e){var r;const a=(r=void 0)!=null?r:!1;return ls(()=>l_(t,{target:"draft-7",io:"output",reused:a?"ref":"inline"}),{validate:async n=>{const s=await vc(t,n);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function Yw(t){return"_zod"in t}function en(t,e){return Yw(t)?Qw(t):Kw(t)}var Ko=Symbol.for("vercel.ai.schema");function ls(t,{validate:e}={}){return{[Ko]:!0,_type:void 0,[os]:!0,get jsonSchema(){return typeof t=="function"&&(t=t()),t},validate:e}}function Xw(t){return typeof t=="object"&&t!==null&&Ko in t&&t[Ko]===!0&&"jsonSchema"in t&&"validate"in t}function us(t){return t==null?ls({properties:{},additionalProperties:!1}):Xw(t)?t:typeof t=="function"?t():en(t)}var{btoa:eb,atob:tb}=globalThis;function Qo(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=tb(e);return Uint8Array.from(r,a=>a.codePointAt(0))}function Yo(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCodePoint(t[r]);return eb(e)}function rb(t){return t==null?void 0:t.replace(/\/$/,"")}function nb(t){return t!=null&&typeof t[Symbol.asyncIterator]=="function"}async function*Yc({execute:t,input:e,options:r}){const a=t(e,r);if(nb(a)){let n;for await(const s of a)n=s,yield{type:"preliminary",output:s};yield{type:"final",output:n}}else yield{type:"final",output:await a}}var ab=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function sb(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Xo=Object.defineProperty,ob=Object.getOwnPropertyDescriptor,ib=Object.getOwnPropertyNames,lb=Object.prototype.hasOwnProperty,ub=(t,e)=>{for(var r in e)Xo(t,r,{get:e[r],enumerable:!0})},cb=(t,e,r,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ib(e))!lb.call(t,n)&&n!==r&&Xo(t,n,{get:()=>e[n],enumerable:!(a=ob(e,n))||a.enumerable});return t},db=t=>cb(Xo({},"__esModule",{value:!0}),t),Xc={};ub(Xc,{SYMBOL_FOR_REQ_CONTEXT:()=>ed,getContext:()=>hb});var pb=db(Xc);const ed=Symbol.for("@vercel/request-context");function hb(){var e,r;return((r=(e=globalThis[ed])==null?void 0:e.get)==null?void 0:r.call(e))??{}}var ei=Object.defineProperty,fb=Object.getOwnPropertyDescriptor,mb=Object.getOwnPropertyNames,vb=Object.prototype.hasOwnProperty,gb=(t,e)=>{for(var r in e)ei(t,r,{get:e[r],enumerable:!0})},yb=(t,e,r,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of mb(e))!vb.call(t,n)&&n!==r&&ei(t,n,{get:()=>e[n],enumerable:!(a=fb(e,n))||a.enumerable});return t},_b=t=>yb(ei({},"__esModule",{value:!0}),t),td={};gb(td,{getContext:()=>wb.getContext,getVercelOidcToken:()=>bb,getVercelOidcTokenSync:()=>xb});var rd=_b(td),wb=pb;async function bb(){return""}function xb(){return""}var Eb="vercel.ai.gateway.error",ti=Symbol.for(Eb),nd,ad,Ct=class Wm extends(ad=Error,nd=ti,ad){constructor({message:e,statusCode:r=500,cause:a}){super(e),this[nd]=!0,this.statusCode=r,this.cause=a}static isInstance(e){return Wm.hasMarker(e)}static hasMarker(e){return typeof e=="object"&&e!==null&&ti in e&&e[ti]===!0}},sd="GatewayAuthenticationError",Sb=`vercel.ai.gateway.error.${sd}`,od=Symbol.for(Sb),id,ld,ri=class Gm extends(ld=Ct,id=od,ld){constructor({message:e="Authentication failed",statusCode:r=401,cause:a}={}){super({message:e,statusCode:r,cause:a}),this[id]=!0,this.name=sd,this.type="authentication_error"}static isInstance(e){return Ct.hasMarker(e)&&od in e}static createContextualError({apiKeyProvided:e,oidcTokenProvided:r,message:a="Authentication failed",statusCode:n=401,cause:s}){let o;return e?o=`AI Gateway authentication failed: Invalid API key.
|
|
39
39
|
|
|
40
40
|
Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
|
|
41
41
|
|
|
42
|
-
Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`:
|
|
42
|
+
Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`:r?o=`AI Gateway authentication failed: Invalid OIDC token.
|
|
43
43
|
|
|
44
44
|
Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.
|
|
45
45
|
|
|
46
|
-
Alternatively, use an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys`:
|
|
46
|
+
Alternatively, use an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys`:o=`AI Gateway authentication failed: No authentication provided.
|
|
47
47
|
|
|
48
48
|
Option 1 - API key:
|
|
49
49
|
Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
|
|
50
50
|
Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
|
|
51
51
|
|
|
52
52
|
Option 2 - OIDC token:
|
|
53
|
-
Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new tp({message:a,statusCode:o,cause:s})}},jl="GatewayInvalidRequestError",Ry=`vercel.ai.gateway.error.${jl}`,Dl=Symbol.for(Ry),Ul,Zl,Ay=class extends(Zl=st,Ul=Dl,Zl){constructor({message:e="Invalid request",statusCode:t=400,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[Ul]=!0,this.name=jl,this.type="invalid_request_error"}static isInstance(e){return st.hasMarker(e)&&Dl in e}},Ll="GatewayRateLimitError",Oy=`vercel.ai.gateway.error.${Ll}`,ql=Symbol.for(Oy),Bl,Vl,Ny=class extends(Vl=st,Bl=ql,Vl){constructor({message:e="Rate limit exceeded",statusCode:t=429,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[Bl]=!0,this.name=Ll,this.type="rate_limit_exceeded"}static isInstance(e){return st.hasMarker(e)&&ql in e}},Fl="GatewayModelNotFoundError",My=`vercel.ai.gateway.error.${Fl}`,Hl=Symbol.for(My),Py=Ee(()=>te(g({modelId:d()}))),Jl,Gl,Wl=class extends(Gl=st,Jl=Hl,Gl){constructor({message:e="Model not found",statusCode:t=404,modelId:n,cause:r}={}){super({message:e,statusCode:t,cause:r}),this[Jl]=!0,this.name=Fl,this.type="model_not_found",this.modelId=n}static isInstance(e){return st.hasMarker(e)&&Hl in e}},Kl="GatewayInternalServerError",$y=`vercel.ai.gateway.error.${Kl}`,Yl=Symbol.for($y),Xl,Ql,eu=class extends(Ql=st,Xl=Yl,Ql){constructor({message:e="Internal server error",statusCode:t=500,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[Xl]=!0,this.name=Kl,this.type="internal_server_error"}static isInstance(e){return st.hasMarker(e)&&Yl in e}},tu="GatewayResponseError",zy=`vercel.ai.gateway.error.${tu}`,nu=Symbol.for(zy),ru,ou,jy=class extends(ou=st,ru=nu,ou){constructor({message:e="Invalid response from Gateway",statusCode:t=502,response:n,validationError:r,cause:o}={}){super({message:e,statusCode:t,cause:o}),this[ru]=!0,this.name=tu,this.type="response_error",this.response=n,this.validationError=r}static isInstance(e){return st.hasMarker(e)&&nu in e}};async function su({response:e,statusCode:t,defaultMessage:n="Gateway request failed",cause:r,authMethod:o}){const s=await gt({value:e,schema:Dy});if(!s.success)return new jy({message:`Invalid error response format: ${n}`,statusCode:t,response:e,validationError:s.error,cause:r});const a=s.value,i=a.error.type,l=a.error.message;switch(i){case"authentication_error":return ds.createContextualError({apiKeyProvided:o==="api-key",oidcTokenProvided:o==="oidc",statusCode:t,cause:r});case"invalid_request_error":return new Ay({message:l,statusCode:t,cause:r});case"rate_limit_exceeded":return new Ny({message:l,statusCode:t,cause:r});case"model_not_found":{const u=await gt({value:a.error.param,schema:Py});return new Wl({message:l,statusCode:t,modelId:u.success?u.value.modelId:void 0,cause:r})}case"internal_server_error":return new eu({message:l,statusCode:t,cause:r});default:return new eu({message:l,statusCode:t,cause:r})}}var Dy=Ee(()=>te(g({error:g({message:d(),type:d().nullish(),param:mt().nullish(),code:ue([d(),I()]).nullish()})})));function hn(e,t){var n;return st.isInstance(e)?e:De.isInstance(e)?su({response:Uy(e),statusCode:(n=e.statusCode)!=null?n:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):su({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}function Uy(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 au="ai-gateway-auth-method";async function tr(e){const t=await gt({value:e[au],schema:Zy});return t.success?t.value:void 0}var Zy=Ee(()=>te(ue([A("api-key"),A("oidc")]))),iu=class{constructor(e){this.config=e}async getAvailableModels(){try{const{value:e}=await gl({url:`${this.config.baseURL}/config`,headers:await Kt(this.config.headers()),successfulResponseHandler:vt(Ly),failedResponseHandler:dn({errorSchema:ut(),errorToMessage:t=>t}),fetch:this.config.fetch});return e}catch(e){throw await hn(e)}}async getCredits(){try{const e=new URL(this.config.baseURL),{value:t}=await gl({url:`${e.origin}/v1/credits`,headers:await Kt(this.config.headers()),successfulResponseHandler:vt(qy),failedResponseHandler:dn({errorSchema:ut(),errorToMessage:n=>n}),fetch:this.config.fetch});return t}catch(e){throw await hn(e)}}},Ly=Ee(()=>te(g({models:z(g({id:d(),name:d(),description:d().nullish(),pricing:g({input:d(),output:d(),input_cache_read:d().nullish(),input_cache_write:d().nullish()}).transform(({input:e,output:t,input_cache_read:n,input_cache_write:r})=>({input:e,output:t,...n?{cachedInputTokens:n}:{},...r?{cacheCreationInputTokens:r}:{}})).nullish(),specification:g({specificationVersion:A("v2"),provider:d(),modelId:d()}),modelType:Se(["language","embedding","image"]).nullish()}))}))),qy=Ee(()=>te(g({balance:d(),total_used:d()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),By=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(e){const{abortSignal:t,...n}=e;return{args:this.maybeEncodeFileParts(n),warnings:[]}}async doGenerate(e){const{args:t,warnings:n}=await this.getArgs(e),{abortSignal:r}=e,o=await Kt(this.config.headers());try{const{responseHeaders:s,value:a,rawValue:i}=await nt({url:this.getUrl(),headers:Ge(o,e.headers,this.getModelConfigHeaders(this.modelId,!1),await Kt(this.config.o11yHeaders)),body:t,successfulResponseHandler:vt(ut()),failedResponseHandler:dn({errorSchema:ut(),errorToMessage:l=>l}),...r&&{abortSignal:r},fetch:this.config.fetch});return{...a,request:{body:t},response:{headers:s,body:i},warnings:n}}catch(s){throw await hn(s,await tr(o))}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),{abortSignal:r}=e,o=await Kt(this.config.headers());try{const{value:s,responseHeaders:a}=await nt({url:this.getUrl(),headers:Ge(o,e.headers,this.getModelConfigHeaders(this.modelId,!0),await Kt(this.config.o11yHeaders)),body:t,successfulResponseHandler:Qn(ut()),failedResponseHandler:dn({errorSchema:ut(),errorToMessage:i=>i}),...r&&{abortSignal:r},fetch:this.config.fetch});return{stream:s.pipeThrough(new TransformStream({start(i){n.length>0&&i.enqueue({type:"stream-start",warnings:n})},transform(i,l){if(i.success){const u=i.value;if(u.type==="raw"&&!e.includeRawChunks)return;u.type==="response-metadata"&&u.timestamp&&typeof u.timestamp=="string"&&(u.timestamp=new Date(u.timestamp)),l.enqueue(u)}else l.error(i.error)}})),request:{body:t},response:{headers:a}}}catch(s){throw await hn(s,await tr(o))}}isFilePart(e){return e&&typeof e=="object"&&"type"in e&&e.type==="file"}maybeEncodeFileParts(e){for(const t of e.prompt)for(const n of t.content)if(this.isFilePart(n)){const r=n;if(r.data instanceof Uint8Array){const o=Uint8Array.from(r.data),s=Buffer.from(o).toString("base64");r.data=new URL(`data:${r.mediaType||"application/octet-stream"};base64,${s}`)}}return e}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(e,t){return{"ai-language-model-specification-version":"2","ai-language-model-id":e,"ai-language-model-streaming":String(t)}}},Vy=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){var o;const s=await Kt(this.config.headers());try{const{responseHeaders:a,value:i,rawValue:l}=await nt({url:this.getUrl(),headers:Ge(s,t??{},this.getModelConfigHeaders(),await Kt(this.config.o11yHeaders)),body:{input:e.length===1?e[0]:e,...r?{providerOptions:r}:{}},successfulResponseHandler:vt(Fy),failedResponseHandler:dn({errorSchema:ut(),errorToMessage:u=>u}),...n&&{abortSignal:n},fetch:this.config.fetch});return{embeddings:i.embeddings,usage:(o=i.usage)!=null?o:void 0,providerMetadata:i.providerMetadata,response:{headers:a,body:l}}}catch(a){throw await hn(a,await tr(s))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"2","ai-model-id":this.modelId}}},Fy=Ee(()=>te(g({embeddings:z(z(I())),usage:g({tokens:I()}).nullish(),providerMetadata:Oe(d(),Oe(d(),mt())).optional()})));async function Hy(){var e;return(e=Al.getContext().headers)==null?void 0:e["x-vercel-id"]}var Jy="2.0.0",Gy="0.0.1";function Wy(e={}){var t,n;let r=null,o=null;const s=(t=e.metadataCacheRefreshMillis)!=null?t:1e3*60*5;let a=0;const i=(n=is(e.baseURL))!=null?n:"https://ai-gateway.vercel.sh/v1/ai",l=async()=>{const f=await Yy(e);if(f)return Lt({Authorization:`Bearer ${f.token}`,"ai-gateway-protocol-version":Gy,[au]:f.authMethod,...e.headers},`ai-sdk/gateway/${Jy}`);throw ds.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401})},u=()=>{const f=Xn({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),y=Xn({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),m=Xn({settingValue:void 0,environmentVariableName:"VERCEL_REGION"});return async()=>{const c=await Hy();return{...f&&{"ai-o11y-deployment-id":f},...y&&{"ai-o11y-environment":y},...m&&{"ai-o11y-region":m},...c&&{"ai-o11y-request-id":c}}}},p=f=>new By(f,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:u()}),x=async()=>{var f,y,m;const c=(m=(y=(f=e._internal)==null?void 0:f.currentDate)==null?void 0:y.call(f).getTime())!=null?m:Date.now();return(!r||c-a>s)&&(a=c,r=new iu({baseURL:i,headers:l,fetch:e.fetch}).getAvailableModels().then(b=>(o=b,b)).catch(async b=>{throw await hn(b,await tr(await l()))})),o?Promise.resolve(o):r},w=async()=>new iu({baseURL:i,headers:l,fetch:e.fetch}).getCredits().catch(async f=>{throw await hn(f,await tr(await l()))}),h=function(f){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return p(f)};return h.getAvailableModels=x,h.getCredits=w,h.imageModel=f=>{throw new Ro({modelId:f,modelType:"imageModel"})},h.languageModel=p,h.textEmbeddingModel=f=>new Vy(f,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:u()}),h}var Ky=Wy();async function Yy(e){const t=Xn({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});if(t)return{token:t,authMethod:"api-key"};try{return{token:await Al.getVercelOidcToken(),authMethod:"oidc"}}catch{return null}}var Xy=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},fn="1.9.0",lu=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function Qy(e){var t=new Set([e]),n=new Set,r=e.match(lu);if(!r)return function(){return!1};var o={major:+r[1],minor:+r[2],patch:+r[3],prerelease:r[4]};if(o.prerelease!=null)return function(l){return l===e};function s(i){return n.add(i),!1}function a(i){return t.add(i),!0}return function(l){if(t.has(l))return!0;if(n.has(l))return!1;var u=l.match(lu);if(!u)return s(l);var p={major:+u[1],minor:+u[2],patch:+u[3],prerelease:u[4]};return p.prerelease!=null||o.major!==p.major?s(l):o.major===0?o.minor===p.minor&&o.patch<=p.patch?a(l):s(l):o.minor<=p.minor?a(l):s(l)}}var e_=Qy(fn),t_=fn.split(".")[0],nr=Symbol.for("opentelemetry.js.api."+t_),rr=Xy;function or(e,t,n,r){var o;r===void 0&&(r=!1);var s=rr[nr]=(o=rr[nr])!==null&&o!==void 0?o:{version:fn};if(!r&&s[e]){var a=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+e);return n.error(a.stack||a.message),!1}if(s.version!==fn){var a=new Error("@opentelemetry/api: Registration of version v"+s.version+" for "+e+" does not match previously registered API v"+fn);return n.error(a.stack||a.message),!1}return s[e]=t,n.debug("@opentelemetry/api: Registered a global for "+e+" v"+fn+"."),!0}function mn(e){var t,n,r=(t=rr[nr])===null||t===void 0?void 0:t.version;if(!(!r||!e_(r)))return(n=rr[nr])===null||n===void 0?void 0:n[e]}function sr(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+fn+".");var n=rr[nr];n&&delete n[e]}var n_=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=r.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return s},r_=function(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))},o_=function(){function e(t){this._namespace=t.namespace||"DiagComponentLogger"}return e.prototype.debug=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return ar("debug",this._namespace,t)},e.prototype.error=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return ar("error",this._namespace,t)},e.prototype.info=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return ar("info",this._namespace,t)},e.prototype.warn=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return ar("warn",this._namespace,t)},e.prototype.verbose=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return ar("verbose",this._namespace,t)},e}();function ar(e,t,n){var r=mn("diag");if(r)return n.unshift(t),r[e].apply(r,r_([],n_(n),!1))}var at;(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"})(at||(at={}));function s_(e,t){e<at.NONE?e=at.NONE:e>at.ALL&&(e=at.ALL),t=t||{};function n(r,o){var s=t[r];return typeof s=="function"&&e>=o?s.bind(t):function(){}}return{error:n("error",at.ERROR),warn:n("warn",at.WARN),info:n("info",at.INFO),debug:n("debug",at.DEBUG),verbose:n("verbose",at.VERBOSE)}}var a_=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=r.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return s},i_=function(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))},l_="diag",It=function(){function e(){function t(o){return function(){for(var s=[],a=0;a<arguments.length;a++)s[a]=arguments[a];var i=mn("diag");if(i)return i[o].apply(i,i_([],a_(s),!1))}}var n=this,r=function(o,s){var a,i,l;if(s===void 0&&(s={logLevel:at.INFO}),o===n){var u=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return n.error((a=u.stack)!==null&&a!==void 0?a:u.message),!1}typeof s=="number"&&(s={logLevel:s});var p=mn("diag"),x=s_((i=s.logLevel)!==null&&i!==void 0?i:at.INFO,o);if(p&&!s.suppressOverrideMessage){var w=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";p.warn("Current logger will be overwritten from "+w),x.warn("Current logger will overwrite one already registered from "+w)}return or("diag",x,n,!0)};n.setLogger=r,n.disable=function(){sr(l_,n)},n.createComponentLogger=function(o){return new o_(o)},n.verbose=t("verbose"),n.debug=t("debug"),n.info=t("info"),n.warn=t("warn"),n.error=t("error")}return e.instance=function(){return this._instance||(this._instance=new e),this._instance},e}(),u_=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=r.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return s},c_=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},d_=function(){function e(t){this._entries=t?new Map(t):new Map}return e.prototype.getEntry=function(t){var n=this._entries.get(t);if(n)return Object.assign({},n)},e.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(t){var n=u_(t,2),r=n[0],o=n[1];return[r,o]})},e.prototype.setEntry=function(t,n){var r=new e(this._entries);return r._entries.set(t,n),r},e.prototype.removeEntry=function(t){var n=new e(this._entries);return n._entries.delete(t),n},e.prototype.removeEntries=function(){for(var t,n,r=[],o=0;o<arguments.length;o++)r[o]=arguments[o];var s=new e(this._entries);try{for(var a=c_(r),i=a.next();!i.done;i=a.next()){var l=i.value;s._entries.delete(l)}}catch(u){t={error:u}}finally{try{i&&!i.done&&(n=a.return)&&n.call(a)}finally{if(t)throw t.error}}return s},e.prototype.clear=function(){return new e},e}();It.instance();function p_(e){return e===void 0&&(e={}),new d_(new Map(Object.entries(e)))}function uu(e){return Symbol.for(e)}var h_=function(){function e(t){var n=this;n._currentContext=t?new Map(t):new Map,n.getValue=function(r){return n._currentContext.get(r)},n.setValue=function(r,o){var s=new e(n._currentContext);return s._currentContext.set(r,o),s},n.deleteValue=function(r){var o=new e(n._currentContext);return o._currentContext.delete(r),o}}return e}(),f_=new h_,gn=function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,o){r.__proto__=o}||function(r,o){for(var s in o)Object.prototype.hasOwnProperty.call(o,s)&&(r[s]=o[s])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}}(),m_=function(){function e(){}return e.prototype.createGauge=function(t,n){return S_},e.prototype.createHistogram=function(t,n){return I_},e.prototype.createCounter=function(t,n){return T_},e.prototype.createUpDownCounter=function(t,n){return C_},e.prototype.createObservableGauge=function(t,n){return R_},e.prototype.createObservableCounter=function(t,n){return E_},e.prototype.createObservableUpDownCounter=function(t,n){return A_},e.prototype.addBatchObservableCallback=function(t,n){},e.prototype.removeBatchObservableCallback=function(t){},e}(),Xr=function(){function e(){}return e}(),g_=function(e){gn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(n,r){},t}(Xr),v_=function(e){gn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(n,r){},t}(Xr),y_=function(e){gn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(n,r){},t}(Xr),__=function(e){gn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(n,r){},t}(Xr),ps=function(){function e(){}return e.prototype.addCallback=function(t){},e.prototype.removeCallback=function(t){},e}(),w_=function(e){gn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t}(ps),b_=function(e){gn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t}(ps),x_=function(e){gn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t}(ps),k_=new m_,T_=new g_,S_=new y_,I_=new __,C_=new v_,E_=new w_,R_=new b_,A_=new x_,O_={get:function(e,t){if(e!=null)return e[t]},keys:function(e){return e==null?[]:Object.keys(e)}},N_={set:function(e,t,n){e!=null&&(e[t]=n)}},M_=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=r.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return s},P_=function(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))},$_=function(){function e(){}return e.prototype.active=function(){return f_},e.prototype.with=function(t,n,r){for(var o=[],s=3;s<arguments.length;s++)o[s-3]=arguments[s];return n.call.apply(n,P_([r],M_(o),!1))},e.prototype.bind=function(t,n){return n},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e}(),z_=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=r.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return s},j_=function(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))},hs="context",D_=new $_,Qr=function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(t){return or(hs,t,It.instance())},e.prototype.active=function(){return this._getContextManager().active()},e.prototype.with=function(t,n,r){for(var o,s=[],a=3;a<arguments.length;a++)s[a-3]=arguments[a];return(o=this._getContextManager()).with.apply(o,j_([t,n,r],z_(s),!1))},e.prototype.bind=function(t,n){return this._getContextManager().bind(t,n)},e.prototype._getContextManager=function(){return mn(hs)||D_},e.prototype.disable=function(){this._getContextManager().disable(),sr(hs,It.instance())},e}(),fs;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(fs||(fs={}));var cu="0000000000000000",du="00000000000000000000000000000000",U_={traceId:du,spanId:cu,traceFlags:fs.NONE},ir=function(){function e(t){t===void 0&&(t=U_),this._spanContext=t}return e.prototype.spanContext=function(){return this._spanContext},e.prototype.setAttribute=function(t,n){return this},e.prototype.setAttributes=function(t){return this},e.prototype.addEvent=function(t,n){return this},e.prototype.addLink=function(t){return this},e.prototype.addLinks=function(t){return this},e.prototype.setStatus=function(t){return this},e.prototype.updateName=function(t){return this},e.prototype.end=function(t){},e.prototype.isRecording=function(){return!1},e.prototype.recordException=function(t,n){},e}(),ms=uu("OpenTelemetry Context Key SPAN");function gs(e){return e.getValue(ms)||void 0}function Z_(){return gs(Qr.getInstance().active())}function vs(e,t){return e.setValue(ms,t)}function L_(e){return e.deleteValue(ms)}function q_(e,t){return vs(e,new ir(t))}function pu(e){var t;return(t=gs(e))===null||t===void 0?void 0:t.spanContext()}var B_=/^([0-9a-f]{32})$/i,V_=/^[0-9a-f]{16}$/i;function F_(e){return B_.test(e)&&e!==du}function H_(e){return V_.test(e)&&e!==cu}function hu(e){return F_(e.traceId)&&H_(e.spanId)}function J_(e){return new ir(e)}var ys=Qr.getInstance(),fu=function(){function e(){}return e.prototype.startSpan=function(t,n,r){r===void 0&&(r=ys.active());var o=!!(n!=null&&n.root);if(o)return new ir;var s=r&&pu(r);return G_(s)&&hu(s)?new ir(s):new ir},e.prototype.startActiveSpan=function(t,n,r,o){var s,a,i;if(!(arguments.length<2)){arguments.length===2?i=n:arguments.length===3?(s=n,i=r):(s=n,a=r,i=o);var l=a??ys.active(),u=this.startSpan(t,s,l),p=vs(l,u);return ys.with(p,i,void 0,u)}},e}();function G_(e){return typeof e=="object"&&typeof e.spanId=="string"&&typeof e.traceId=="string"&&typeof e.traceFlags=="number"}var W_=new fu,K_=function(){function e(t,n,r,o){this._provider=t,this.name=n,this.version=r,this.options=o}return e.prototype.startSpan=function(t,n,r){return this._getTracer().startSpan(t,n,r)},e.prototype.startActiveSpan=function(t,n,r,o){var s=this._getTracer();return Reflect.apply(s.startActiveSpan,s,arguments)},e.prototype._getTracer=function(){if(this._delegate)return this._delegate;var t=this._provider.getDelegateTracer(this.name,this.version,this.options);return t?(this._delegate=t,this._delegate):W_},e}(),Y_=function(){function e(){}return e.prototype.getTracer=function(t,n,r){return new fu},e}(),X_=new Y_,mu=function(){function e(){}return e.prototype.getTracer=function(t,n,r){var o;return(o=this.getDelegateTracer(t,n,r))!==null&&o!==void 0?o:new K_(this,t,n,r)},e.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:X_},e.prototype.setDelegate=function(t){this._delegate=t},e.prototype.getDelegateTracer=function(t,n,r){var o;return(o=this._delegate)===null||o===void 0?void 0:o.getTracer(t,n,r)},e}(),eo;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(eo||(eo={})),Qr.getInstance(),It.instance();var Q_=function(){function e(){}return e.prototype.getMeter=function(t,n,r){return k_},e}(),ew=new Q_,_s="metrics",tw=function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalMeterProvider=function(t){return or(_s,t,It.instance())},e.prototype.getMeterProvider=function(){return mn(_s)||ew},e.prototype.getMeter=function(t,n,r){return this.getMeterProvider().getMeter(t,n,r)},e.prototype.disable=function(){sr(_s,It.instance())},e}();tw.getInstance();var nw=function(){function e(){}return e.prototype.inject=function(t,n){},e.prototype.extract=function(t,n){return t},e.prototype.fields=function(){return[]},e}(),ws=uu("OpenTelemetry Baggage Key");function gu(e){return e.getValue(ws)||void 0}function rw(){return gu(Qr.getInstance().active())}function ow(e,t){return e.setValue(ws,t)}function sw(e){return e.deleteValue(ws)}var bs="propagation",aw=new nw,iw=function(){function e(){this.createBaggage=p_,this.getBaggage=gu,this.getActiveBaggage=rw,this.setBaggage=ow,this.deleteBaggage=sw}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalPropagator=function(t){return or(bs,t,It.instance())},e.prototype.inject=function(t,n,r){return r===void 0&&(r=N_),this._getGlobalPropagator().inject(t,n,r)},e.prototype.extract=function(t,n,r){return r===void 0&&(r=O_),this._getGlobalPropagator().extract(t,n,r)},e.prototype.fields=function(){return this._getGlobalPropagator().fields()},e.prototype.disable=function(){sr(bs,It.instance())},e.prototype._getGlobalPropagator=function(){return mn(bs)||aw},e}();iw.getInstance();var xs="trace",lw=function(){function e(){this._proxyTracerProvider=new mu,this.wrapSpanContext=J_,this.isSpanContextValid=hu,this.deleteSpan=L_,this.getSpan=gs,this.getActiveSpan=Z_,this.getSpanContext=pu,this.setSpan=vs,this.setSpanContext=q_}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(t){var n=or(xs,this._proxyTracerProvider,It.instance());return n&&this._proxyTracerProvider.setDelegate(t),n},e.prototype.getTracerProvider=function(){return mn(xs)||this._proxyTracerProvider},e.prototype.getTracer=function(t,n){return this.getTracerProvider().getTracer(t,n)},e.prototype.disable=function(){sr(xs,It.instance()),this._proxyTracerProvider=new mu},e}(),uw=lw.getInstance(),cw=Object.defineProperty,dw=(e,t)=>{for(var n in t)cw(e,n,{get:t[n],enumerable:!0})},vu="AI_NoOutputSpecifiedError",yu=`vercel.ai.error.${vu}`,pw=Symbol.for(yu),_u,wu=class extends W{constructor({message:e="No output specified."}={}){super({name:vu,message:e}),this[_u]=!0}static isInstance(e){return W.hasMarker(e,yu)}};_u=pw;function hw(e){const t="AI SDK Warning:";switch(e.type){case"unsupported-setting":{let n=`${t} The "${e.setting}" setting is not supported by this model`;return e.details&&(n+=` - ${e.details}`),n}case"unsupported-tool":{const n="name"in e.tool?e.tool.name:"unknown tool";let r=`${t} The tool "${n}" is not supported by this model`;return e.details&&(r+=` - ${e.details}`),r}case"other":return`${t} ${e.message}`;default:return`${t} ${JSON.stringify(e,null,2)}`}}var fw="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",bu=!1,xu=e=>{if(e.length===0)return;const t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t=="function"){t(e);return}bu||(bu=!0,console.info(fw));for(const n of e)console.warn(hw(n))}},ku="AI_InvalidArgumentError",Tu=`vercel.ai.error.${ku}`,mw=Symbol.for(Tu),Su,Ct=class extends W{constructor({parameter:e,value:t,message:n}){super({name:ku,message:`Invalid argument for parameter ${e}: ${n}`}),this[Su]=!0,this.parameter=e,this.value=t}static isInstance(e){return W.hasMarker(e,Tu)}};Su=mw;var Iu="AI_InvalidToolInputError",Cu=`vercel.ai.error.${Iu}`,gw=Symbol.for(Cu),Eu,Ru=class extends W{constructor({toolInput:e,toolName:t,cause:n,message:r=`Invalid input for tool ${t}: ${yn(n)}`}){super({name:Iu,message:r,cause:n}),this[Eu]=!0,this.toolInput=e,this.toolName=t}static isInstance(e){return W.hasMarker(e,Cu)}};Eu=gw;var vw="AI_MCPClientError",Au=`vercel.ai.error.${vw}`,yw=Symbol.for(Au),Ou,Ze=class extends W{constructor({name:e="MCPClientError",message:t,cause:n,data:r,code:o}){super({name:e,message:t,cause:n}),this[Ou]=!0,this.data=r,this.code=o}static isInstance(e){return W.hasMarker(e,Au)}};Ou=yw;var Nu="AI_NoObjectGeneratedError",Mu=`vercel.ai.error.${Nu}`,_w=Symbol.for(Mu),Pu,$u=class extends W{constructor({message:e="No object generated.",cause:t,text:n,response:r,usage:o,finishReason:s}){super({name:Nu,message:e,cause:t}),this[Pu]=!0,this.text=n,this.response=r,this.usage=o,this.finishReason=s}static isInstance(e){return W.hasMarker(e,Mu)}};Pu=_w;var zu="AI_NoOutputGeneratedError",ju=`vercel.ai.error.${zu}`,ww=Symbol.for(ju),Du,bw=class extends W{constructor({message:e="No output generated.",cause:t}={}){super({name:zu,message:e,cause:t}),this[Du]=!0}static isInstance(e){return W.hasMarker(e,ju)}};Du=ww;var Uu="AI_NoSuchToolError",Zu=`vercel.ai.error.${Uu}`,xw=Symbol.for(Zu),Lu,ks=class extends W{constructor({toolName:e,availableTools:t=void 0,message:n=`Model tried to call unavailable tool '${e}'. ${t===void 0?"No tools are available.":`Available tools: ${t.join(", ")}.`}`}){super({name:Uu,message:n}),this[Lu]=!0,this.toolName=e,this.availableTools=t}static isInstance(e){return W.hasMarker(e,Zu)}};Lu=xw;var qu="AI_ToolCallRepairError",Bu=`vercel.ai.error.${qu}`,kw=Symbol.for(Bu),Vu,Tw=class extends W{constructor({cause:e,originalError:t,message:n=`Error repairing tool call: ${yn(e)}`}){super({name:qu,message:n,cause:e}),this[Vu]=!0,this.originalError=t}static isInstance(e){return W.hasMarker(e,Bu)}};Vu=kw;var Sw=class extends W{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}},Fu="AI_InvalidMessageRoleError",Hu=`vercel.ai.error.${Fu}`,Iw=Symbol.for(Hu),Ju,Cw=class extends W{constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:Fu,message:t}),this[Ju]=!0,this.role=e}static isInstance(e){return W.hasMarker(e,Hu)}};Ju=Iw;var Gu="AI_DownloadError",Wu=`vercel.ai.error.${Gu}`,Ew=Symbol.for(Wu),Ku,Ts=class extends W{constructor({url:e,statusCode:t,statusText:n,cause:r,message:o=r==null?`Failed to download ${e}: ${t} ${n}`:`Failed to download ${e}: ${r}`}){super({name:Gu,message:o,cause:r}),this[Ku]=!0,this.url=e,this.statusCode=t,this.statusText=n}static isInstance(e){return W.hasMarker(e,Wu)}};Ku=Ew;var Yu="AI_RetryError",Xu=`vercel.ai.error.${Yu}`,Rw=Symbol.for(Xu),Qu,ec=class extends W{constructor({message:e,reason:t,errors:n}){super({name:Yu,message:e}),this[Qu]=!0,this.reason=t,this.errors=n,this.lastError=n[n.length-1]}static isInstance(e){return W.hasMarker(e,Xu)}};Qu=Rw;function to(e){if(typeof e!="string"){if(e.specificationVersion!=="v2")throw new Sw({version:e.specificationVersion,provider:e.provider,modelId:e.modelId});return e}return Aw().languageModel(e)}function Aw(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:Ky}var Ow=[{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]}],Nw=e=>{const t=typeof e=="string"?Kr(e):e,n=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(n+10)};function Mw(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?Nw(e):e}function Pw({data:e,signatures:t}){const n=Mw(e),r=typeof n=="string"?Kr(n.substring(0,Math.min(n.length,24))):n;for(const o of t)if(r.length>=o.bytesPrefix.length&&o.bytesPrefix.every((s,a)=>s===null||r[a]===s))return o.mediaType}var no="5.0.76",$w=async({url:e})=>{var t;const n=e.toString();try{const r=await fetch(n,{headers:Lt({},`ai-sdk/${no}`,Yn())});if(!r.ok)throw new Ts({url:n,statusCode:r.status,statusText:r.statusText});return{data:new Uint8Array(await r.arrayBuffer()),mediaType:(t=r.headers.get("content-type"))!=null?t:void 0}}catch(r){throw Ts.isInstance(r)?r:new Ts({url:n,cause:r})}},zw=(e=$w)=>t=>Promise.all(t.map(async n=>n.isUrlSupportedByModel?null:e(n)));function jw(e){try{const[t,n]=e.split(",");return{mediaType:t.split(";")[0].split(":")[1],base64Content:n}}catch{return{mediaType:void 0,base64Content:void 0}}}var tc=ue([d(),zr(Uint8Array),zr(ArrayBuffer),_g(e=>{var t,n;return(n=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?n:!1},{message:"Must be a Buffer"})]);function nc(e){if(e instanceof Uint8Array)return{data:e,mediaType:void 0};if(e instanceof ArrayBuffer)return{data:new Uint8Array(e),mediaType:void 0};if(typeof e=="string")try{e=new URL(e)}catch{}if(e instanceof URL&&e.protocol==="data:"){const{mediaType:t,base64Content:n}=jw(e.toString());if(t==null||n==null)throw new W({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:n,mediaType:t}}return{data:e,mediaType:void 0}}function Dw(e){return typeof e=="string"?e:e instanceof ArrayBuffer?Yr(new Uint8Array(e)):Yr(e)}async function rc({prompt:e,supportedUrls:t,download:n=zw()}){const r=await Zw(e.messages,n,t);return[...e.system!=null?[{role:"system",content:e.system}]:[],...e.messages.map(o=>Uw({message:o,downloadedAssets:r}))]}function Uw({message:e,downloadedAssets:t}){const n=e.role;switch(n){case"system":return{role:"system",content:e.content,providerOptions:e.providerOptions};case"user":return typeof e.content=="string"?{role:"user",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions}:{role:"user",content:e.content.map(r=>Lw(r,t)).filter(r=>r.type!=="text"||r.text!==""),providerOptions:e.providerOptions};case"assistant":return typeof e.content=="string"?{role:"assistant",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions}:{role:"assistant",content:e.content.filter(r=>r.type!=="text"||r.text!==""||r.providerOptions!=null).map(r=>{const o=r.providerOptions;switch(r.type){case"file":{const{data:s,mediaType:a}=nc(r.data);return{type:"file",data:s,filename:r.filename,mediaType:a??r.mediaType,providerOptions:o}}case"reasoning":return{type:"reasoning",text:r.text,providerOptions:o};case"text":return{type:"text",text:r.text,providerOptions:o};case"tool-call":return{type:"tool-call",toolCallId:r.toolCallId,toolName:r.toolName,input:r.input,providerExecuted:r.providerExecuted,providerOptions:o};case"tool-result":return{type:"tool-result",toolCallId:r.toolCallId,toolName:r.toolName,output:r.output,providerOptions:o}}}),providerOptions:e.providerOptions};case"tool":return{role:"tool",content:e.content.map(r=>({type:"tool-result",toolCallId:r.toolCallId,toolName:r.toolName,output:r.output,providerOptions:r.providerOptions})),providerOptions:e.providerOptions};default:{const r=n;throw new Cw({role:r})}}}async function Zw(e,t,n){const r=e.filter(s=>s.role==="user").map(s=>s.content).filter(s=>Array.isArray(s)).flat().filter(s=>s.type==="image"||s.type==="file").map(s=>{var a;const i=(a=s.mediaType)!=null?a:s.type==="image"?"image/*":void 0;let l=s.type==="image"?s.image:s.data;if(typeof l=="string")try{l=new URL(l)}catch{}return{mediaType:i,data:l}}).filter(s=>s.data instanceof URL).map(s=>({url:s.data,isUrlSupportedByModel:s.mediaType!=null&&tv({url:s.data.toString(),mediaType:s.mediaType,supportedUrls:n})})),o=await t(r);return Object.fromEntries(o.map((s,a)=>s==null?null:[r[a].url.toString(),{data:s.data,mediaType:s.mediaType}]).filter(s=>s!=null))}function Lw(e,t){var n;if(e.type==="text")return{type:"text",text:e.text,providerOptions:e.providerOptions};let r;const o=e.type;switch(o){case"image":r=e.image;break;case"file":r=e.data;break;default:throw new Error(`Unsupported part type: ${o}`)}const{data:s,mediaType:a}=nc(r);let i=a??e.mediaType,l=s;if(l instanceof URL){const u=t[l.toString()];u&&(l=u.data,i??(i=u.mediaType))}switch(o){case"image":return(l instanceof Uint8Array||typeof l=="string")&&(i=(n=Pw({data:l,signatures:Ow}))!=null?n:i),{type:"file",mediaType:i??"image/*",filename:void 0,data:l,providerOptions:e.providerOptions};case"file":{if(i==null)throw new Error("Media type is missing for file part");return{type:"file",mediaType:i,filename:e.filename,data:l,providerOptions:e.providerOptions}}}}function Ss({maxOutputTokens:e,temperature:t,topP:n,topK:r,presencePenalty:o,frequencyPenalty:s,seed:a,stopSequences:i}){if(e!=null){if(!Number.isInteger(e))throw new Ct({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new Ct({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(t!=null&&typeof t!="number")throw new Ct({parameter:"temperature",value:t,message:"temperature must be a number"});if(n!=null&&typeof n!="number")throw new Ct({parameter:"topP",value:n,message:"topP must be a number"});if(r!=null&&typeof r!="number")throw new Ct({parameter:"topK",value:r,message:"topK must be a number"});if(o!=null&&typeof o!="number")throw new Ct({parameter:"presencePenalty",value:o,message:"presencePenalty must be a number"});if(s!=null&&typeof s!="number")throw new Ct({parameter:"frequencyPenalty",value:s,message:"frequencyPenalty must be a number"});if(a!=null&&!Number.isInteger(a))throw new Ct({parameter:"seed",value:a,message:"seed must be an integer"});return{maxOutputTokens:e,temperature:t,topP:n,topK:r,presencePenalty:o,frequencyPenalty:s,stopSequences:i,seed:a}}function qw(e){return e!=null&&Object.keys(e).length>0}function oc({tools:e,toolChoice:t,activeTools:n}){return qw(e)?{tools:(n!=null?Object.entries(e).filter(([o])=>n.includes(o)):Object.entries(e)).map(([o,s])=>{const a=s.type;switch(a){case void 0:case"dynamic":case"function":return{type:"function",name:o,description:s.description,inputSchema:Wr(s.inputSchema).jsonSchema,providerOptions:s.providerOptions};case"provider-defined":return{type:"provider-defined",name:o,id:s.id,args:s.args};default:{const i=a;throw new Error(`Unsupported tool type: ${i}`)}}}),toolChoice:t==null?{type:"auto"}:typeof t=="string"?{type:t}:{type:"tool",toolName:t.toolName}}:{tools:void 0,toolChoice:void 0}}var lr=el(()=>ue([Jm(),d(),I(),Ae(),Oe(d(),lr),z(lr)])),Et=Oe(d(),Oe(d(),lr)),sc=g({type:A("text"),text:d(),providerOptions:Et.optional()}),Bw=g({type:A("image"),image:ue([tc,zr(URL)]),mediaType:d().optional(),providerOptions:Et.optional()}),ac=g({type:A("file"),data:ue([tc,zr(URL)]),filename:d().optional(),mediaType:d(),providerOptions:Et.optional()}),Vw=g({type:A("reasoning"),text:d(),providerOptions:Et.optional()}),Fw=g({type:A("tool-call"),toolCallId:d(),toolName:d(),input:mt(),providerOptions:Et.optional(),providerExecuted:Ae().optional()}),Hw=et("type",[g({type:A("text"),value:d()}),g({type:A("json"),value:lr}),g({type:A("error-text"),value:d()}),g({type:A("error-json"),value:lr}),g({type:A("content"),value:z(ue([g({type:A("text"),text:d()}),g({type:A("media"),data:d(),mediaType:d()})]))})]),ic=g({type:A("tool-result"),toolCallId:d(),toolName:d(),output:Hw,providerOptions:Et.optional()}),Jw=g({role:A("system"),content:d(),providerOptions:Et.optional()}),Gw=g({role:A("user"),content:ue([d(),z(ue([sc,Bw,ac]))]),providerOptions:Et.optional()}),Ww=g({role:A("assistant"),content:ue([d(),z(ue([sc,ac,Vw,Fw,ic]))]),providerOptions:Et.optional()}),Kw=g({role:A("tool"),content:z(ic),providerOptions:Et.optional()}),Yw=ue([Jw,Gw,Ww,Kw]);async function lc(e){if(e.prompt==null&&e.messages==null)throw new tn({prompt:e,message:"prompt or messages must be defined"});if(e.prompt!=null&&e.messages!=null)throw new tn({prompt:e,message:"prompt and messages cannot be defined at the same time"});if(e.system!=null&&typeof e.system!="string")throw new tn({prompt:e,message:"system must be a string"});let t;if(e.prompt!=null&&typeof e.prompt=="string")t=[{role:"user",content:e.prompt}];else if(e.prompt!=null&&Array.isArray(e.prompt))t=e.prompt;else if(e.messages!=null)t=e.messages;else throw new tn({prompt:e,message:"prompt or messages must be defined"});if(t.length===0)throw new tn({prompt:e,message:"messages must not be empty"});const n=await gt({value:t,schema:z(Yw)});if(!n.success)throw new tn({prompt:e,message:"The messages must be a ModelMessage[]. If you have passed a UIMessage[], you can use convertToModelMessages to convert them.",cause:n.error});return{messages:t,system:e.system}}function uc(e){return ds.isInstance(e)||Wl.isInstance(e)?new W({name:"GatewayError",message:"Vercel AI Gateway access failed. If you want to use AI SDK providers directly, use the providers, e.g. @ai-sdk/openai, or register a different global default provider.",cause:e}):e}function Sn({operationId:e,telemetry:t}){return{"operation.name":`${e}${(t==null?void 0:t.functionId)!=null?` ${t.functionId}`:""}`,"resource.name":t==null?void 0:t.functionId,"ai.operationId":e,"ai.telemetry.functionId":t==null?void 0:t.functionId}}function cc({model:e,settings:t,telemetry:n,headers:r}){var o;return{"ai.model.provider":e.provider,"ai.model.id":e.modelId,...Object.entries(t).reduce((s,[a,i])=>(s[`ai.settings.${a}`]=i,s),{}),...Object.entries((o=n==null?void 0:n.metadata)!=null?o:{}).reduce((s,[a,i])=>(s[`ai.telemetry.metadata.${a}`]=i,s),{}),...Object.entries(r??{}).reduce((s,[a,i])=>(i!==void 0&&(s[`ai.request.headers.${a}`]=i),s),{})}}var Xw={startSpan(){return ro},startActiveSpan(e,t,n,r){if(typeof t=="function")return t(ro);if(typeof n=="function")return n(ro);if(typeof r=="function")return r(ro)}},ro={spanContext(){return Qw},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}},Qw={traceId:"",spanId:"",traceFlags:0};function dc({isEnabled:e=!1,tracer:t}={}){return e?t||uw.getTracer("ai"):Xw}function In({name:e,tracer:t,attributes:n,fn:r,endWhenDone:o=!0}){return t.startActiveSpan(e,{attributes:n},async s=>{try{const a=await r(s);return o&&s.end(),a}catch(a){try{Is(s,a)}finally{s.end()}throw a}})}function Is(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:eo.ERROR,message:t.message})):e.setStatus({code:eo.ERROR})}function dt({telemetry:e,attributes:t}){return(e==null?void 0:e.isEnabled)!==!0?{}:Object.entries(t).reduce((n,[r,o])=>{if(o==null)return n;if(typeof o=="object"&&"input"in o&&typeof o.input=="function"){if((e==null?void 0:e.recordInputs)===!1)return n;const s=o.input();return s==null?n:{...n,[r]:s}}if(typeof o=="object"&&"output"in o&&typeof o.output=="function"){if((e==null?void 0:e.recordOutputs)===!1)return n;const s=o.output();return s==null?n:{...n,[r]:s}}return{...n,[r]:o}},{})}function pc(e){return JSON.stringify(e.map(t=>({...t,content:typeof t.content=="string"?t.content:t.content.map(n=>n.type==="file"?{...n,data:n.data instanceof Uint8Array?Dw(n.data):n.data}:n)})))}function hc(e,t){return{inputTokens:ur(e.inputTokens,t.inputTokens),outputTokens:ur(e.outputTokens,t.outputTokens),totalTokens:ur(e.totalTokens,t.totalTokens),reasoningTokens:ur(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:ur(e.cachedInputTokens,t.cachedInputTokens)}}function ur(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}function Cs(e){return e===void 0?[]:Array.isArray(e)?e:[e]}function e0({error:e,exponentialBackoffDelay:t}){const n=e.responseHeaders;if(!n)return t;let r;const o=n["retry-after-ms"];if(o){const a=parseFloat(o);Number.isNaN(a)||(r=a)}const s=n["retry-after"];if(s&&r===void 0){const a=parseFloat(s);Number.isNaN(a)?r=Date.parse(s)-Date.now():r=a*1e3}return r!=null&&!Number.isNaN(r)&&0<=r&&(r<60*1e3||r<t)?r:t}var t0=({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:n=2,abortSignal:r}={})=>async o=>fc(o,{maxRetries:e,delayInMs:t,backoffFactor:n,abortSignal:r});async function fc(e,{maxRetries:t,delayInMs:n,backoffFactor:r,abortSignal:o},s=[]){try{return await e()}catch(a){if(un(a)||t===0)throw a;const i=ts(a),l=[...s,a],u=l.length;if(u>t)throw new ec({message:`Failed after ${u} attempts. Last error: ${i}`,reason:"maxRetriesExceeded",errors:l});if(a instanceof Error&&De.isInstance(a)&&a.isRetryable===!0&&u<=t)return await Yg(e0({error:a,exponentialBackoffDelay:n}),{abortSignal:o}),fc(e,{maxRetries:t,delayInMs:r*n,backoffFactor:r,abortSignal:o},l);throw u===1?a:new ec({message:`Failed after ${u} attempts with non-retryable error: '${i}'`,reason:"errorNotRetryable",errors:l})}}function mc({maxRetries:e,abortSignal:t}){if(e!=null){if(!Number.isInteger(e))throw new Ct({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});if(e<0)throw new Ct({parameter:"maxRetries",value:e,message:"maxRetries must be >= 0"})}const n=e??2;return{maxRetries:n,retry:t0({maxRetries:n,abortSignal:t})}}function gc(e){const t=e.filter(n=>n.type==="text");if(t.length!==0)return t.map(n=>n.text).join("")}var vc=class{constructor({data:e,mediaType:t}){const n=e instanceof Uint8Array;this.base64Data=n?void 0:e,this.uint8ArrayData=n?e:void 0,this.mediaType=t}get base64(){return this.base64Data==null&&(this.base64Data=Yr(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=Kr(this.base64Data)),this.uint8ArrayData}},n0=class extends vc{constructor(e){super(e),this.type="file"}};async function yc({toolCall:e,tools:t,repairToolCall:n,system:r,messages:o}){try{if(t==null)throw new ks({toolName:e.toolName});try{return await _c({toolCall:e,tools:t})}catch(s){if(n==null||!(ks.isInstance(s)||Ru.isInstance(s)))throw s;let a=null;try{a=await n({toolCall:e,tools:t,inputSchema:({toolName:i})=>{const{inputSchema:l}=t[i];return Wr(l).jsonSchema},system:r,messages:o,error:s})}catch(i){throw new Tw({cause:i,originalError:s})}if(a==null)throw s;return await _c({toolCall:a,tools:t})}}catch(s){const a=await cn({text:e.input}),i=a.success?a.value:e.input;return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:i,dynamic:!0,invalid:!0,error:s}}}async function _c({toolCall:e,tools:t}){const n=e.toolName,r=t[n];if(r==null)throw new ks({toolName:e.toolName,availableTools:Object.keys(t)});const o=Wr(r.inputSchema),s=e.input.trim()===""?await gt({value:{},schema:o}):await cn({text:e.input,schema:o});if(s.success===!1)throw new Ru({toolName:n,toolInput:e.input,cause:s.error});return r.type==="dynamic"?{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:s.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,dynamic:!0}:{type:"tool-call",toolCallId:e.toolCallId,toolName:n,input:s.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}}var wc=class{constructor({content:e,finishReason:t,usage:n,warnings:r,request:o,response:s,providerMetadata:a}){this.content=e,this.finishReason=t,this.usage=n,this.warnings=r,this.request=o,this.response=s,this.providerMetadata=a}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 Es(e){return({steps:t})=>t.length===e}async function bc({stopConditions:e,steps:t}){return(await Promise.all(e.map(n=>n({steps:t})))).some(n=>n)}function Rs({output:e,tool:t,errorMode:n}){return n==="text"?{type:"error-text",value:yn(e)}:n==="json"?{type:"error-json",value:xc(e)}:t!=null&&t.toModelOutput?t.toModelOutput(e):typeof e=="string"?{type:"text",value:e}:{type:"json",value:xc(e)}}function xc(e){return e===void 0?null:e}function As({content:e,tools:t}){const n=[],r=e.filter(s=>s.type!=="source").filter(s=>(s.type!=="tool-result"||s.providerExecuted)&&(s.type!=="tool-error"||s.providerExecuted)).filter(s=>s.type!=="text"||s.text.length>0).map(s=>{switch(s.type){case"text":return{type:"text",text:s.text,providerOptions:s.providerMetadata};case"reasoning":return{type:"reasoning",text:s.text,providerOptions:s.providerMetadata};case"file":return{type:"file",data:s.file.base64,mediaType:s.file.mediaType,providerOptions:s.providerMetadata};case"tool-call":return{type:"tool-call",toolCallId:s.toolCallId,toolName:s.toolName,input:s.input,providerExecuted:s.providerExecuted,providerOptions:s.providerMetadata};case"tool-result":return{type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:Rs({tool:t==null?void 0:t[s.toolName],output:s.output,errorMode:"none"}),providerExecuted:!0,providerOptions:s.providerMetadata};case"tool-error":return{type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:Rs({tool:t==null?void 0:t[s.toolName],output:s.error,errorMode:"json"}),providerOptions:s.providerMetadata}}});r.length>0&&n.push({role:"assistant",content:r});const o=e.filter(s=>s.type==="tool-result"||s.type==="tool-error").filter(s=>!s.providerExecuted).map(s=>({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:Rs({tool:t==null?void 0:t[s.toolName],output:s.type==="tool-result"?s.output:s.error,errorMode:s.type==="tool-error"?"text":"none"})}));return o.length>0&&n.push({role:"tool",content:o}),n}var r0=Kn({prefix:"aitxt",size:24});async function o0({model:e,tools:t,toolChoice:n,system:r,prompt:o,messages:s,maxRetries:a,abortSignal:i,headers:l,stopWhen:u=Es(1),experimental_output:p,experimental_telemetry:x,providerOptions:w,experimental_activeTools:h,activeTools:f=h,experimental_prepareStep:y,prepareStep:m=y,experimental_repairToolCall:c,experimental_download:b,experimental_context:v,_internal:{generateId:_=r0,currentDate:R=()=>new Date}={},onStepFinish:C,...T}){const P=to(e),D=Cs(u),{maxRetries:H,retry:K}=mc({maxRetries:a,abortSignal:i}),he=Ss(T),Y=Lt(l??{},`ai/${no}`),ne=cc({model:P,telemetry:x,headers:Y,settings:{...he,maxRetries:H}}),V=await lc({system:r,prompt:o,messages:s}),se=dc(x);try{return await In({name:"ai.generateText",attributes:dt({telemetry:x,attributes:{...Sn({operationId:"ai.generateText",telemetry:x}),...ne,"ai.model.provider":P.provider,"ai.model.id":P.modelId,"ai.prompt":{input:()=>JSON.stringify({system:r,prompt:o,messages:s})}}}),tracer:se,fn:async ae=>{var ce,Pe,oe,me,ee,Ie,k;const F=Ss(T);let ge,xe=[],Ce=[];const _r=[],wt=[];do{const Re=[...V.messages,..._r],de=await(m==null?void 0:m({model:P,steps:wt,stepNumber:wt.length,messages:Re})),ve=to((ce=de==null?void 0:de.model)!=null?ce:P),$e=await rc({prompt:{system:(Pe=de==null?void 0:de.system)!=null?Pe:V.system,messages:(oe=de==null?void 0:de.messages)!=null?oe:Re},supportedUrls:await ve.supportedUrls,download:b}),{toolChoice:ie,tools:Ye}=oc({tools:t,toolChoice:(me=de==null?void 0:de.toolChoice)!=null?me:n,activeTools:(ee=de==null?void 0:de.activeTools)!=null?ee:f});ge=await K(()=>{var we;return In({name:"ai.generateText.doGenerate",attributes:dt({telemetry:x,attributes:{...Sn({operationId:"ai.generateText.doGenerate",telemetry:x}),...ne,"ai.model.provider":ve.provider,"ai.model.id":ve.modelId,"ai.prompt.messages":{input:()=>pc($e)},"ai.prompt.tools":{input:()=>Ye==null?void 0:Ye.map(Mt=>JSON.stringify(Mt))},"ai.prompt.toolChoice":{input:()=>ie!=null?JSON.stringify(ie):void 0},"gen_ai.system":ve.provider,"gen_ai.request.model":ve.modelId,"gen_ai.request.frequency_penalty":T.frequencyPenalty,"gen_ai.request.max_tokens":T.maxOutputTokens,"gen_ai.request.presence_penalty":T.presencePenalty,"gen_ai.request.stop_sequences":T.stopSequences,"gen_ai.request.temperature":(we=T.temperature)!=null?we:void 0,"gen_ai.request.top_k":T.topK,"gen_ai.request.top_p":T.topP}}),tracer:se,fn:async Mt=>{var br,en,lt,qt,xr,Mn,Pn,Io;const Le=await ve.doGenerate({...F,tools:Ye,toolChoice:ie,responseFormat:p==null?void 0:p.responseFormat,prompt:$e,providerOptions:w,abortSignal:i,headers:Y}),Bt={id:(en=(br=Le.response)==null?void 0:br.id)!=null?en:_(),timestamp:(qt=(lt=Le.response)==null?void 0:lt.timestamp)!=null?qt:R(),modelId:(Mn=(xr=Le.response)==null?void 0:xr.modelId)!=null?Mn:ve.modelId,headers:(Pn=Le.response)==null?void 0:Pn.headers,body:(Io=Le.response)==null?void 0:Io.body};return Mt.setAttributes(dt({telemetry:x,attributes:{"ai.response.finishReason":Le.finishReason,"ai.response.text":{output:()=>gc(Le.content)},"ai.response.toolCalls":{output:()=>{const Vt=kc(Le.content);return Vt==null?void 0:JSON.stringify(Vt)}},"ai.response.id":Bt.id,"ai.response.model":Bt.modelId,"ai.response.timestamp":Bt.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(Le.providerMetadata),"ai.usage.promptTokens":Le.usage.inputTokens,"ai.usage.completionTokens":Le.usage.outputTokens,"gen_ai.response.finish_reasons":[Le.finishReason],"gen_ai.response.id":Bt.id,"gen_ai.response.model":Bt.modelId,"gen_ai.usage.input_tokens":Le.usage.inputTokens,"gen_ai.usage.output_tokens":Le.usage.outputTokens}})),{...Le,response:Bt}}})});const Nt=await Promise.all(ge.content.filter(we=>we.type==="tool-call").map(we=>yc({toolCall:we,tools:t,repairToolCall:c,system:r,messages:Re})));for(const we of Nt){if(we.invalid)continue;const Mt=t[we.toolName];(Mt==null?void 0:Mt.onInputAvailable)!=null&&await Mt.onInputAvailable({input:we.input,toolCallId:we.toolCallId,messages:Re,abortSignal:i,experimental_context:v})}const Z=Nt.filter(we=>we.invalid&&we.dynamic);Ce=[];for(const we of Z)Ce.push({type:"tool-error",toolCallId:we.toolCallId,toolName:we.toolName,input:we.input,error:ts(we.error),dynamic:!0});xe=Nt.filter(we=>!we.providerExecuted),t!=null&&Ce.push(...await s0({toolCalls:xe.filter(we=>!we.invalid),tools:t,tracer:se,telemetry:x,messages:Re,abortSignal:i,experimental_context:v}));const _e=i0({content:ge.content,toolCalls:Nt,toolOutputs:Ce});_r.push(...As({content:_e,tools:t}));const Qt=new wc({content:_e,finishReason:ge.finishReason,usage:ge.usage,warnings:ge.warnings,providerMetadata:ge.providerMetadata,request:(Ie=ge.request)!=null?Ie:{},response:{...ge.response,messages:structuredClone(_r)}});xu((k=ge.warnings)!=null?k:[]),wt.push(Qt),await(C==null?void 0:C(Qt))}while(xe.length>0&&Ce.length===xe.length&&!await bc({stopConditions:D,steps:wt}));ae.setAttributes(dt({telemetry:x,attributes:{"ai.response.finishReason":ge.finishReason,"ai.response.text":{output:()=>gc(ge.content)},"ai.response.toolCalls":{output:()=>{const Re=kc(ge.content);return Re==null?void 0:JSON.stringify(Re)}},"ai.response.providerMetadata":JSON.stringify(ge.providerMetadata),"ai.usage.promptTokens":ge.usage.inputTokens,"ai.usage.completionTokens":ge.usage.outputTokens}}));const Ke=wt[wt.length-1];let wr;return Ke.finishReason==="stop"&&(wr=await(p==null?void 0:p.parseOutput({text:Ke.text},{response:Ke.response,usage:Ke.usage,finishReason:Ke.finishReason}))),new a0({steps:wt,resolvedOutput:wr})}})}catch(ae){throw uc(ae)}}async function s0({toolCalls:e,tools:t,tracer:n,telemetry:r,messages:o,abortSignal:s,experimental_context:a}){return(await Promise.all(e.map(async({toolCallId:l,toolName:u,input:p})=>{const x=t[u];if((x==null?void 0:x.execute)!=null)return In({name:"ai.toolCall",attributes:dt({telemetry:r,attributes:{...Sn({operationId:"ai.toolCall",telemetry:r}),"ai.toolCall.name":u,"ai.toolCall.id":l,"ai.toolCall.args":{output:()=>JSON.stringify(p)}}}),tracer:n,fn:async w=>{try{const h=Il({execute:x.execute.bind(x),input:p,options:{toolCallId:l,messages:o,abortSignal:s,experimental_context:a}});let f;for await(const y of h)y.type==="final"&&(f=y.output);try{w.setAttributes(dt({telemetry:r,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(f)}}}))}catch{}return{type:"tool-result",toolCallId:l,toolName:u,input:p,output:f,dynamic:x.type==="dynamic"}}catch(h){return Is(w,h),{type:"tool-error",toolCallId:l,toolName:u,input:p,error:h,dynamic:x.type==="dynamic"}}}})}))).filter(l=>l!=null)}var a0=class{constructor(e){this.steps=e.steps,this.resolvedOutput=e.resolvedOutput}get finalStep(){return this.steps[this.steps.length-1]}get content(){return this.finalStep.content}get text(){return this.finalStep.text}get files(){return this.finalStep.files}get reasoningText(){return this.finalStep.reasoningText}get reasoning(){return this.finalStep.reasoning}get toolCalls(){return this.finalStep.toolCalls}get staticToolCalls(){return this.finalStep.staticToolCalls}get dynamicToolCalls(){return this.finalStep.dynamicToolCalls}get toolResults(){return this.finalStep.toolResults}get staticToolResults(){return this.finalStep.staticToolResults}get dynamicToolResults(){return this.finalStep.dynamicToolResults}get sources(){return this.finalStep.sources}get finishReason(){return this.finalStep.finishReason}get warnings(){return this.finalStep.warnings}get providerMetadata(){return this.finalStep.providerMetadata}get response(){return this.finalStep.response}get request(){return this.finalStep.request}get usage(){return this.finalStep.usage}get totalUsage(){return this.steps.reduce((e,t)=>hc(e,t.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0})}get experimental_output(){if(this.resolvedOutput==null)throw new wu;return this.resolvedOutput}};function kc(e){const t=e.filter(n=>n.type==="tool-call");if(t.length!==0)return t.map(n=>({toolCallId:n.toolCallId,toolName:n.toolName,input:n.input}))}function i0({content:e,toolCalls:t,toolOutputs:n}){return[...e.map(r=>{switch(r.type){case"text":case"reasoning":case"source":return r;case"file":return{type:"file",file:new vc(r)};case"tool-call":return t.find(o=>o.toolCallId===r.toolCallId);case"tool-result":{const o=t.find(s=>s.toolCallId===r.toolCallId);if(o==null)throw new Error(`Tool call ${r.toolCallId} not found.`);return r.isError?{type:"tool-error",toolCallId:r.toolCallId,toolName:r.toolName,input:o.input,error:r.result,providerExecuted:!0,dynamic:o.dynamic}:{type:"tool-result",toolCallId:r.toolCallId,toolName:r.toolName,input:o.input,output:r.result,providerExecuted:!0,dynamic:o.dynamic}}}}),...n]}function oo(e,t){const n=new Headers(e??{});for(const[r,o]of Object.entries(t))n.has(r)||n.set(r,o);return n}function l0({status:e,statusText:t,headers:n,textStream:r}){return new Response(r.pipeThrough(new TextEncoderStream),{status:e??200,statusText:t,headers:oo(n,{"content-type":"text/plain; charset=utf-8"})})}function Tc({response:e,status:t,statusText:n,headers:r,stream:o}){e.writeHead(t??200,n,r);const s=o.getReader();(async()=>{try{for(;;){const{done:i,value:l}=await s.read();if(i)break;e.write(l)||await new Promise(p=>{e.once("drain",p)})}}catch(i){throw i}finally{e.end()}})()}function u0({response:e,status:t,statusText:n,headers:r,textStream:o}){Tc({response:e,status:t,statusText:n,headers:Object.fromEntries(oo(r,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:o.pipeThrough(new TextEncoderStream)})}var Sc=class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
|
|
53
|
+
Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new Gm({message:o,statusCode:n,cause:s})}},ud="GatewayInvalidRequestError",Ib=`vercel.ai.gateway.error.${ud}`,cd=Symbol.for(Ib),dd,pd,Tb=class extends(pd=Ct,dd=cd,pd){constructor({message:t="Invalid request",statusCode:e=400,cause:r}={}){super({message:t,statusCode:e,cause:r}),this[dd]=!0,this.name=ud,this.type="invalid_request_error"}static isInstance(t){return Ct.hasMarker(t)&&cd in t}},hd="GatewayRateLimitError",kb=`vercel.ai.gateway.error.${hd}`,fd=Symbol.for(kb),md,vd,Pb=class extends(vd=Ct,md=fd,vd){constructor({message:t="Rate limit exceeded",statusCode:e=429,cause:r}={}){super({message:t,statusCode:e,cause:r}),this[md]=!0,this.name=hd,this.type="rate_limit_exceeded"}static isInstance(t){return Ct.hasMarker(t)&&fd in t}},gd="GatewayModelNotFoundError",Cb=`vercel.ai.gateway.error.${gd}`,yd=Symbol.for(Cb),Rb=Sn(()=>en(P({modelId:x()}))),_d,wd,bd=class extends(wd=Ct,_d=yd,wd){constructor({message:t="Model not found",statusCode:e=404,modelId:r,cause:a}={}){super({message:t,statusCode:e,cause:a}),this[_d]=!0,this.name=gd,this.type="model_not_found",this.modelId=r}static isInstance(t){return Ct.hasMarker(t)&&yd in t}},xd="GatewayInternalServerError",Ob=`vercel.ai.gateway.error.${xd}`,Ed=Symbol.for(Ob),Sd,Id,Td=class extends(Id=Ct,Sd=Ed,Id){constructor({message:t="Internal server error",statusCode:e=500,cause:r}={}){super({message:t,statusCode:e,cause:r}),this[Sd]=!0,this.name=xd,this.type="internal_server_error"}static isInstance(t){return Ct.hasMarker(t)&&Ed in t}},kd="GatewayResponseError",$b=`vercel.ai.gateway.error.${kd}`,Pd=Symbol.for($b),Cd,Rd,Ab=class extends(Rd=Ct,Cd=Pd,Rd){constructor({message:t="Invalid response from Gateway",statusCode:e=502,response:r,validationError:a,cause:n}={}){super({message:t,statusCode:e,cause:n}),this[Cd]=!0,this.name=kd,this.type="response_error",this.response=r,this.validationError=a}static isInstance(t){return Ct.hasMarker(t)&&Pd in t}};async function Od({response:t,statusCode:e,defaultMessage:r="Gateway request failed",cause:a,authMethod:n}){const s=await $r({value:t,schema:Nb});if(!s.success)return new Ab({message:`Invalid error response format: ${r}`,statusCode:e,response:t,validationError:s.error,cause:a});const o=s.value,i=o.error.type,l=o.error.message;switch(i){case"authentication_error":return ri.createContextualError({apiKeyProvided:n==="api-key",oidcTokenProvided:n==="oidc",statusCode:e,cause:a});case"invalid_request_error":return new Tb({message:l,statusCode:e,cause:a});case"rate_limit_exceeded":return new Pb({message:l,statusCode:e,cause:a});case"model_not_found":{const u=await $r({value:o.error.param,schema:Rb});return new bd({message:l,statusCode:e,modelId:u.success?u.value.modelId:void 0,cause:a})}case"internal_server_error":return new Td({message:l,statusCode:e,cause:a});default:return new Td({message:l,statusCode:e,cause:a})}}var Nb=Sn(()=>en(P({error:P({message:x(),type:x().nullish(),param:Cr().nullish(),code:Ae([x(),U()]).nullish()})})));function tn(t,e){var r;return Ct.isInstance(t)?t:Ue.isInstance(t)?Od({response:Mb(t),statusCode:(r=t.statusCode)!=null?r:500,defaultMessage:"Gateway request failed",cause:t,authMethod:e}):Od({response:{},statusCode:500,defaultMessage:t instanceof Error?`Gateway request failed: ${t.message}`:"Unknown Gateway error",cause:t,authMethod:e})}function Mb(t){if(t.data!==void 0)return t.data;if(t.responseBody!=null)try{return JSON.parse(t.responseBody)}catch{return t.responseBody}return{}}var $d="ai-gateway-auth-method";async function oa(t){const e=await $r({value:t[$d],schema:Db});return e.success?e.value:void 0}var Db=Sn(()=>en(Ae([H("api-key"),H("oidc")]))),Ad=class{constructor(t){this.config=t}async getAvailableModels(){try{const{value:t}=await Vc({url:`${this.config.baseURL}/config`,headers:await Ar(this.config.headers()),successfulResponseHandler:is(jb),failedResponseHandler:sa({errorSchema:Mt(),errorToMessage:e=>e}),fetch:this.config.fetch});return t}catch(t){throw await tn(t)}}async getCredits(){try{const t=new URL(this.config.baseURL),{value:e}=await Vc({url:`${t.origin}/v1/credits`,headers:await Ar(this.config.headers()),successfulResponseHandler:is(Lb),failedResponseHandler:sa({errorSchema:Mt(),errorToMessage:r=>r}),fetch:this.config.fetch});return e}catch(t){throw await tn(t)}}},jb=Sn(()=>en(P({models:Y(P({id:x(),name:x(),description:x().nullish(),pricing:P({input:x(),output:x(),input_cache_read:x().nullish(),input_cache_write:x().nullish()}).transform(({input:t,output:e,input_cache_read:r,input_cache_write:a})=>({input:t,output:e,...r?{cachedInputTokens:r}:{},...a?{cacheCreationInputTokens:a}:{}})).nullish(),specification:P({specificationVersion:H("v2"),provider:x(),modelId:x()}),modelType:vt(["language","embedding","image"]).nullish()}))}))),Lb=Sn(()=>en(P({balance:x(),total_used:x()}).transform(({balance:t,total_used:e})=>({balance:t,totalUsed:e})))),zb=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(t){const{abortSignal:e,...r}=t;return{args:this.maybeEncodeFileParts(r),warnings:[]}}async doGenerate(t){const{args:e,warnings:r}=await this.getArgs(t),{abortSignal:a}=t,n=await Ar(this.config.headers());try{const{responseHeaders:s,value:o,rawValue:i}=await Ho({url:this.getUrl(),headers:qo(n,t.headers,this.getModelConfigHeaders(this.modelId,!1),await Ar(this.config.o11yHeaders)),body:e,successfulResponseHandler:is(Mt()),failedResponseHandler:sa({errorSchema:Mt(),errorToMessage:l=>l}),...a&&{abortSignal:a},fetch:this.config.fetch});return{...o,request:{body:e},response:{headers:s,body:i},warnings:r}}catch(s){throw await tn(s,await oa(n))}}async doStream(t){const{args:e,warnings:r}=await this.getArgs(t),{abortSignal:a}=t,n=await Ar(this.config.headers());try{const{value:s,responseHeaders:o}=await Ho({url:this.getUrl(),headers:qo(n,t.headers,this.getModelConfigHeaders(this.modelId,!0),await Ar(this.config.o11yHeaders)),body:e,successfulResponseHandler:lw(Mt()),failedResponseHandler:sa({errorSchema:Mt(),errorToMessage:i=>i}),...a&&{abortSignal:a},fetch:this.config.fetch});return{stream:s.pipeThrough(new TransformStream({start(i){r.length>0&&i.enqueue({type:"stream-start",warnings:r})},transform(i,l){if(i.success){const u=i.value;if(u.type==="raw"&&!t.includeRawChunks)return;u.type==="response-metadata"&&u.timestamp&&typeof u.timestamp=="string"&&(u.timestamp=new Date(u.timestamp)),l.enqueue(u)}else l.error(i.error)}})),request:{body:e},response:{headers:o}}}catch(s){throw await tn(s,await oa(n))}}isFilePart(t){return t&&typeof t=="object"&&"type"in t&&t.type==="file"}maybeEncodeFileParts(t){for(const e of t.prompt)for(const r of e.content)if(this.isFilePart(r)){const a=r;if(a.data instanceof Uint8Array){const n=Uint8Array.from(a.data),s=Buffer.from(n).toString("base64");a.data=new URL(`data:${a.mediaType||"application/octet-stream"};base64,${s}`)}}return t}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(t,e){return{"ai-language-model-specification-version":"2","ai-language-model-id":t,"ai-language-model-streaming":String(e)}}},Ub=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:t,headers:e,abortSignal:r,providerOptions:a}){var n;const s=await Ar(this.config.headers());try{const{responseHeaders:o,value:i,rawValue:l}=await Ho({url:this.getUrl(),headers:qo(s,e??{},this.getModelConfigHeaders(),await Ar(this.config.o11yHeaders)),body:{input:t.length===1?t[0]:t,...a?{providerOptions:a}:{}},successfulResponseHandler:is(Fb),failedResponseHandler:sa({errorSchema:Mt(),errorToMessage:u=>u}),...r&&{abortSignal:r},fetch:this.config.fetch});return{embeddings:i.embeddings,usage:(n=i.usage)!=null?n:void 0,providerMetadata:i.providerMetadata,response:{headers:o,body:l}}}catch(o){throw await tn(o,await oa(s))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"2","ai-model-id":this.modelId}}},Fb=Sn(()=>en(P({embeddings:Y(Y(U())),usage:P({tokens:U()}).nullish(),providerMetadata:St(x(),St(x(),Cr())).optional()})));async function qb(){var t;return(t=rd.getContext().headers)==null?void 0:t["x-vercel-id"]}var Zb="2.0.0",Vb="0.0.1";function Bb(t={}){var e,r;let a=null,n=null;const s=(e=t.metadataCacheRefreshMillis)!=null?e:1e3*60*5;let o=0;const i=(r=rb(t.baseURL))!=null?r:"https://ai-gateway.vercel.sh/v1/ai",l=async()=>{const p=await Jb(t);if(p)return aa({Authorization:`Bearer ${p.token}`,"ai-gateway-protocol-version":Vb,[$d]:p.authMethod,...t.headers},`ai-sdk/gateway/${Zb}`);throw ri.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401})},u=()=>{const p=ss({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),f=ss({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),m=ss({settingValue:void 0,environmentVariableName:"VERCEL_REGION"});return async()=>{const v=await qb();return{...p&&{"ai-o11y-deployment-id":p},...f&&{"ai-o11y-environment":f},...m&&{"ai-o11y-region":m},...v&&{"ai-o11y-request-id":v}}}},d=p=>new zb(p,{provider:"gateway",baseURL:i,headers:l,fetch:t.fetch,o11yHeaders:u()}),h=async()=>{var p,f,m;const v=(m=(f=(p=t._internal)==null?void 0:p.currentDate)==null?void 0:f.call(p).getTime())!=null?m:Date.now();return(!a||v-o>s)&&(o=v,a=new Ad({baseURL:i,headers:l,fetch:t.fetch}).getAvailableModels().then(w=>(n=w,w)).catch(async w=>{throw await tn(w,await oa(await l()))})),n?Promise.resolve(n):a},g=async()=>new Ad({baseURL:i,headers:l,fetch:t.fetch}).getCredits().catch(async p=>{throw await tn(p,await oa(await l()))}),c=function(p){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return d(p)};return c.getAvailableModels=h,c.getCredits=g,c.imageModel=p=>{throw new go({modelId:p,modelType:"imageModel"})},c.languageModel=d,c.textEmbeddingModel=p=>new Ub(p,{provider:"gateway",baseURL:i,headers:l,fetch:t.fetch,o11yHeaders:u()}),c}var Hb=Bb();async function Jb(t){const e=ss({settingValue:t.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});if(e)return{token:e,authMethod:"api-key"};try{return{token:await rd.getVercelOidcToken(),authMethod:"oidc"}}catch{return null}}var Wb=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},rn="1.9.0",Nd=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function Gb(t){var e=new Set([t]),r=new Set,a=t.match(Nd);if(!a)return function(){return!1};var n={major:+a[1],minor:+a[2],patch:+a[3],prerelease:a[4]};if(n.prerelease!=null)return function(l){return l===t};function s(i){return r.add(i),!1}function o(i){return e.add(i),!0}return function(l){if(e.has(l))return!0;if(r.has(l))return!1;var u=l.match(Nd);if(!u)return s(l);var d={major:+u[1],minor:+u[2],patch:+u[3],prerelease:u[4]};return d.prerelease!=null||n.major!==d.major?s(l):n.major===0?n.minor===d.minor&&n.patch<=d.patch?o(l):s(l):n.minor<=d.minor?o(l):s(l)}}var Kb=Gb(rn),Qb=rn.split(".")[0],ia=Symbol.for("opentelemetry.js.api."+Qb),la=Wb;function ua(t,e,r,a){var n;a===void 0&&(a=!1);var s=la[ia]=(n=la[ia])!==null&&n!==void 0?n:{version:rn};if(!a&&s[t]){var o=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+t);return r.error(o.stack||o.message),!1}if(s.version!==rn){var o=new Error("@opentelemetry/api: Registration of version v"+s.version+" for "+t+" does not match previously registered API v"+rn);return r.error(o.stack||o.message),!1}return s[t]=e,r.debug("@opentelemetry/api: Registered a global for "+t+" v"+rn+"."),!0}function nn(t){var e,r,a=(e=la[ia])===null||e===void 0?void 0:e.version;if(!(!a||!Kb(a)))return(r=la[ia])===null||r===void 0?void 0:r[t]}function ca(t,e){e.debug("@opentelemetry/api: Unregistering a global for "+t+" v"+rn+".");var r=la[ia];r&&delete r[t]}var Yb=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var a=r.call(t),n,s=[],o;try{for(;(e===void 0||e-- >0)&&!(n=a.next()).done;)s.push(n.value)}catch(i){o={error:i}}finally{try{n&&!n.done&&(r=a.return)&&r.call(a)}finally{if(o)throw o.error}}return s},Xb=function(t,e,r){if(r||arguments.length===2)for(var a=0,n=e.length,s;a<n;a++)(s||!(a in e))&&(s||(s=Array.prototype.slice.call(e,0,a)),s[a]=e[a]);return t.concat(s||Array.prototype.slice.call(e))},e1=function(){function t(e){this._namespace=e.namespace||"DiagComponentLogger"}return t.prototype.debug=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return da("debug",this._namespace,e)},t.prototype.error=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return da("error",this._namespace,e)},t.prototype.info=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return da("info",this._namespace,e)},t.prototype.warn=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return da("warn",this._namespace,e)},t.prototype.verbose=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return da("verbose",this._namespace,e)},t}();function da(t,e,r){var a=nn("diag");if(a)return r.unshift(e),a[t].apply(a,Xb([],Yb(r),!1))}var Rt;(function(t){t[t.NONE=0]="NONE",t[t.ERROR=30]="ERROR",t[t.WARN=50]="WARN",t[t.INFO=60]="INFO",t[t.DEBUG=70]="DEBUG",t[t.VERBOSE=80]="VERBOSE",t[t.ALL=9999]="ALL"})(Rt||(Rt={}));function t1(t,e){t<Rt.NONE?t=Rt.NONE:t>Rt.ALL&&(t=Rt.ALL),e=e||{};function r(a,n){var s=e[a];return typeof s=="function"&&t>=n?s.bind(e):function(){}}return{error:r("error",Rt.ERROR),warn:r("warn",Rt.WARN),info:r("info",Rt.INFO),debug:r("debug",Rt.DEBUG),verbose:r("verbose",Rt.VERBOSE)}}var r1=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var a=r.call(t),n,s=[],o;try{for(;(e===void 0||e-- >0)&&!(n=a.next()).done;)s.push(n.value)}catch(i){o={error:i}}finally{try{n&&!n.done&&(r=a.return)&&r.call(a)}finally{if(o)throw o.error}}return s},n1=function(t,e,r){if(r||arguments.length===2)for(var a=0,n=e.length,s;a<n;a++)(s||!(a in e))&&(s||(s=Array.prototype.slice.call(e,0,a)),s[a]=e[a]);return t.concat(s||Array.prototype.slice.call(e))},a1="diag",nr=function(){function t(){function e(n){return function(){for(var s=[],o=0;o<arguments.length;o++)s[o]=arguments[o];var i=nn("diag");if(i)return i[n].apply(i,n1([],r1(s),!1))}}var r=this,a=function(n,s){var o,i,l;if(s===void 0&&(s={logLevel:Rt.INFO}),n===r){var u=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return r.error((o=u.stack)!==null&&o!==void 0?o:u.message),!1}typeof s=="number"&&(s={logLevel:s});var d=nn("diag"),h=t1((i=s.logLevel)!==null&&i!==void 0?i:Rt.INFO,n);if(d&&!s.suppressOverrideMessage){var g=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";d.warn("Current logger will be overwritten from "+g),h.warn("Current logger will overwrite one already registered from "+g)}return ua("diag",h,r,!0)};r.setLogger=a,r.disable=function(){ca(a1,r)},r.createComponentLogger=function(n){return new e1(n)},r.verbose=e("verbose"),r.debug=e("debug"),r.info=e("info"),r.warn=e("warn"),r.error=e("error")}return t.instance=function(){return this._instance||(this._instance=new t),this._instance},t}(),s1=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var a=r.call(t),n,s=[],o;try{for(;(e===void 0||e-- >0)&&!(n=a.next()).done;)s.push(n.value)}catch(i){o={error:i}}finally{try{n&&!n.done&&(r=a.return)&&r.call(a)}finally{if(o)throw o.error}}return s},o1=function(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],a=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&a>=t.length&&(t=void 0),{value:t&&t[a++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},i1=function(){function t(e){this._entries=e?new Map(e):new Map}return t.prototype.getEntry=function(e){var r=this._entries.get(e);if(r)return Object.assign({},r)},t.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(e){var r=s1(e,2),a=r[0],n=r[1];return[a,n]})},t.prototype.setEntry=function(e,r){var a=new t(this._entries);return a._entries.set(e,r),a},t.prototype.removeEntry=function(e){var r=new t(this._entries);return r._entries.delete(e),r},t.prototype.removeEntries=function(){for(var e,r,a=[],n=0;n<arguments.length;n++)a[n]=arguments[n];var s=new t(this._entries);try{for(var o=o1(a),i=o.next();!i.done;i=o.next()){var l=i.value;s._entries.delete(l)}}catch(u){e={error:u}}finally{try{i&&!i.done&&(r=o.return)&&r.call(o)}finally{if(e)throw e.error}}return s},t.prototype.clear=function(){return new t},t}();nr.instance();function l1(t){return t===void 0&&(t={}),new i1(new Map(Object.entries(t)))}function Md(t){return Symbol.for(t)}var u1=function(){function t(e){var r=this;r._currentContext=e?new Map(e):new Map,r.getValue=function(a){return r._currentContext.get(a)},r.setValue=function(a,n){var s=new t(r._currentContext);return s._currentContext.set(a,n),s},r.deleteValue=function(a){var n=new t(r._currentContext);return n._currentContext.delete(a),n}}return t}(),c1=new u1,an=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(a,n){a.__proto__=n}||function(a,n){for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(a[s]=n[s])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function a(){this.constructor=e}e.prototype=r===null?Object.create(r):(a.prototype=r.prototype,new a)}}(),d1=function(){function t(){}return t.prototype.createGauge=function(e,r){return b1},t.prototype.createHistogram=function(e,r){return x1},t.prototype.createCounter=function(e,r){return w1},t.prototype.createUpDownCounter=function(e,r){return E1},t.prototype.createObservableGauge=function(e,r){return I1},t.prototype.createObservableCounter=function(e,r){return S1},t.prototype.createObservableUpDownCounter=function(e,r){return T1},t.prototype.addBatchObservableCallback=function(e,r){},t.prototype.removeBatchObservableCallback=function(e){},t}(),cs=function(){function t(){}return t}(),p1=function(t){an(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.add=function(r,a){},e}(cs),h1=function(t){an(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.add=function(r,a){},e}(cs),f1=function(t){an(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.record=function(r,a){},e}(cs),m1=function(t){an(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.record=function(r,a){},e}(cs),ni=function(){function t(){}return t.prototype.addCallback=function(e){},t.prototype.removeCallback=function(e){},t}(),v1=function(t){an(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(ni),g1=function(t){an(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(ni),y1=function(t){an(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(ni),_1=new d1,w1=new p1,b1=new f1,x1=new m1,E1=new h1,S1=new v1,I1=new g1,T1=new y1,k1={get:function(t,e){if(t!=null)return t[e]},keys:function(t){return t==null?[]:Object.keys(t)}},P1={set:function(t,e,r){t!=null&&(t[e]=r)}},C1=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var a=r.call(t),n,s=[],o;try{for(;(e===void 0||e-- >0)&&!(n=a.next()).done;)s.push(n.value)}catch(i){o={error:i}}finally{try{n&&!n.done&&(r=a.return)&&r.call(a)}finally{if(o)throw o.error}}return s},R1=function(t,e,r){if(r||arguments.length===2)for(var a=0,n=e.length,s;a<n;a++)(s||!(a in e))&&(s||(s=Array.prototype.slice.call(e,0,a)),s[a]=e[a]);return t.concat(s||Array.prototype.slice.call(e))},O1=function(){function t(){}return t.prototype.active=function(){return c1},t.prototype.with=function(e,r,a){for(var n=[],s=3;s<arguments.length;s++)n[s-3]=arguments[s];return r.call.apply(r,R1([a],C1(n),!1))},t.prototype.bind=function(e,r){return r},t.prototype.enable=function(){return this},t.prototype.disable=function(){return this},t}(),$1=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var a=r.call(t),n,s=[],o;try{for(;(e===void 0||e-- >0)&&!(n=a.next()).done;)s.push(n.value)}catch(i){o={error:i}}finally{try{n&&!n.done&&(r=a.return)&&r.call(a)}finally{if(o)throw o.error}}return s},A1=function(t,e,r){if(r||arguments.length===2)for(var a=0,n=e.length,s;a<n;a++)(s||!(a in e))&&(s||(s=Array.prototype.slice.call(e,0,a)),s[a]=e[a]);return t.concat(s||Array.prototype.slice.call(e))},ai="context",N1=new O1,ds=function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalContextManager=function(e){return ua(ai,e,nr.instance())},t.prototype.active=function(){return this._getContextManager().active()},t.prototype.with=function(e,r,a){for(var n,s=[],o=3;o<arguments.length;o++)s[o-3]=arguments[o];return(n=this._getContextManager()).with.apply(n,A1([e,r,a],$1(s),!1))},t.prototype.bind=function(e,r){return this._getContextManager().bind(e,r)},t.prototype._getContextManager=function(){return nn(ai)||N1},t.prototype.disable=function(){this._getContextManager().disable(),ca(ai,nr.instance())},t}(),si;(function(t){t[t.NONE=0]="NONE",t[t.SAMPLED=1]="SAMPLED"})(si||(si={}));var Dd="0000000000000000",jd="00000000000000000000000000000000",M1={traceId:jd,spanId:Dd,traceFlags:si.NONE},pa=function(){function t(e){e===void 0&&(e=M1),this._spanContext=e}return t.prototype.spanContext=function(){return this._spanContext},t.prototype.setAttribute=function(e,r){return this},t.prototype.setAttributes=function(e){return this},t.prototype.addEvent=function(e,r){return this},t.prototype.addLink=function(e){return this},t.prototype.addLinks=function(e){return this},t.prototype.setStatus=function(e){return this},t.prototype.updateName=function(e){return this},t.prototype.end=function(e){},t.prototype.isRecording=function(){return!1},t.prototype.recordException=function(e,r){},t}(),oi=Md("OpenTelemetry Context Key SPAN");function ii(t){return t.getValue(oi)||void 0}function D1(){return ii(ds.getInstance().active())}function li(t,e){return t.setValue(oi,e)}function j1(t){return t.deleteValue(oi)}function L1(t,e){return li(t,new pa(e))}function Ld(t){var e;return(e=ii(t))===null||e===void 0?void 0:e.spanContext()}var z1=/^([0-9a-f]{32})$/i,U1=/^[0-9a-f]{16}$/i;function F1(t){return z1.test(t)&&t!==jd}function q1(t){return U1.test(t)&&t!==Dd}function zd(t){return F1(t.traceId)&&q1(t.spanId)}function Z1(t){return new pa(t)}var ui=ds.getInstance(),Ud=function(){function t(){}return t.prototype.startSpan=function(e,r,a){a===void 0&&(a=ui.active());var n=!!(r!=null&&r.root);if(n)return new pa;var s=a&&Ld(a);return V1(s)&&zd(s)?new pa(s):new pa},t.prototype.startActiveSpan=function(e,r,a,n){var s,o,i;if(!(arguments.length<2)){arguments.length===2?i=r:arguments.length===3?(s=r,i=a):(s=r,o=a,i=n);var l=o??ui.active(),u=this.startSpan(e,s,l),d=li(l,u);return ui.with(d,i,void 0,u)}},t}();function V1(t){return typeof t=="object"&&typeof t.spanId=="string"&&typeof t.traceId=="string"&&typeof t.traceFlags=="number"}var B1=new Ud,H1=function(){function t(e,r,a,n){this._provider=e,this.name=r,this.version=a,this.options=n}return t.prototype.startSpan=function(e,r,a){return this._getTracer().startSpan(e,r,a)},t.prototype.startActiveSpan=function(e,r,a,n){var s=this._getTracer();return Reflect.apply(s.startActiveSpan,s,arguments)},t.prototype._getTracer=function(){if(this._delegate)return this._delegate;var e=this._provider.getDelegateTracer(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):B1},t}(),J1=function(){function t(){}return t.prototype.getTracer=function(e,r,a){return new Ud},t}(),W1=new J1,Fd=function(){function t(){}return t.prototype.getTracer=function(e,r,a){var n;return(n=this.getDelegateTracer(e,r,a))!==null&&n!==void 0?n:new H1(this,e,r,a)},t.prototype.getDelegate=function(){var e;return(e=this._delegate)!==null&&e!==void 0?e:W1},t.prototype.setDelegate=function(e){this._delegate=e},t.prototype.getDelegateTracer=function(e,r,a){var n;return(n=this._delegate)===null||n===void 0?void 0:n.getTracer(e,r,a)},t}(),ps;(function(t){t[t.UNSET=0]="UNSET",t[t.OK=1]="OK",t[t.ERROR=2]="ERROR"})(ps||(ps={})),ds.getInstance(),nr.instance();var G1=function(){function t(){}return t.prototype.getMeter=function(e,r,a){return _1},t}(),K1=new G1,ci="metrics",Q1=function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalMeterProvider=function(e){return ua(ci,e,nr.instance())},t.prototype.getMeterProvider=function(){return nn(ci)||K1},t.prototype.getMeter=function(e,r,a){return this.getMeterProvider().getMeter(e,r,a)},t.prototype.disable=function(){ca(ci,nr.instance())},t}();Q1.getInstance();var Y1=function(){function t(){}return t.prototype.inject=function(e,r){},t.prototype.extract=function(e,r){return e},t.prototype.fields=function(){return[]},t}(),di=Md("OpenTelemetry Baggage Key");function qd(t){return t.getValue(di)||void 0}function X1(){return qd(ds.getInstance().active())}function ex(t,e){return t.setValue(di,e)}function tx(t){return t.deleteValue(di)}var pi="propagation",rx=new Y1,nx=function(){function t(){this.createBaggage=l1,this.getBaggage=qd,this.getActiveBaggage=X1,this.setBaggage=ex,this.deleteBaggage=tx}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalPropagator=function(e){return ua(pi,e,nr.instance())},t.prototype.inject=function(e,r,a){return a===void 0&&(a=P1),this._getGlobalPropagator().inject(e,r,a)},t.prototype.extract=function(e,r,a){return a===void 0&&(a=k1),this._getGlobalPropagator().extract(e,r,a)},t.prototype.fields=function(){return this._getGlobalPropagator().fields()},t.prototype.disable=function(){ca(pi,nr.instance())},t.prototype._getGlobalPropagator=function(){return nn(pi)||rx},t}();nx.getInstance();var hi="trace",ax=function(){function t(){this._proxyTracerProvider=new Fd,this.wrapSpanContext=Z1,this.isSpanContextValid=zd,this.deleteSpan=j1,this.getSpan=ii,this.getActiveSpan=D1,this.getSpanContext=Ld,this.setSpan=li,this.setSpanContext=L1}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalTracerProvider=function(e){var r=ua(hi,this._proxyTracerProvider,nr.instance());return r&&this._proxyTracerProvider.setDelegate(e),r},t.prototype.getTracerProvider=function(){return nn(hi)||this._proxyTracerProvider},t.prototype.getTracer=function(e,r){return this.getTracerProvider().getTracer(e,r)},t.prototype.disable=function(){ca(hi,nr.instance()),this._proxyTracerProvider=new Fd},t}(),sx=ax.getInstance(),ox=Object.defineProperty,ix=(t,e)=>{for(var r in e)ox(t,r,{get:e[r],enumerable:!0})},Zd="AI_NoOutputSpecifiedError",Vd=`vercel.ai.error.${Zd}`,lx=Symbol.for(Vd),Bd,Hd=class extends he{constructor({message:t="No output specified."}={}){super({name:Zd,message:t}),this[Bd]=!0}static isInstance(t){return he.hasMarker(t,Vd)}};Bd=lx;function ux(t){const e="AI SDK Warning:";switch(t.type){case"unsupported-setting":{let r=`${e} The "${t.setting}" setting is not supported by this model`;return t.details&&(r+=` - ${t.details}`),r}case"unsupported-tool":{const r="name"in t.tool?t.tool.name:"unknown tool";let a=`${e} The tool "${r}" is not supported by this model`;return t.details&&(a+=` - ${t.details}`),a}case"other":return`${e} ${t.message}`;default:return`${e} ${JSON.stringify(t,null,2)}`}}var cx="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",Jd=!1,Wd=t=>{if(t.length===0)return;const e=globalThis.AI_SDK_LOG_WARNINGS;if(e!==!1){if(typeof e=="function"){e(t);return}Jd||(Jd=!0,console.info(cx));for(const r of t)console.warn(ux(r))}},Gd="AI_InvalidArgumentError",Kd=`vercel.ai.error.${Gd}`,dx=Symbol.for(Kd),Qd,ar=class extends he{constructor({parameter:t,value:e,message:r}){super({name:Gd,message:`Invalid argument for parameter ${t}: ${r}`}),this[Qd]=!0,this.parameter=t,this.value=e}static isInstance(t){return he.hasMarker(t,Kd)}};Qd=dx;var Yd="AI_InvalidToolInputError",Xd=`vercel.ai.error.${Yd}`,px=Symbol.for(Xd),ep,tp=class extends he{constructor({toolInput:t,toolName:e,cause:r,message:a=`Invalid input for tool ${e}: ${yn(r)}`}){super({name:Yd,message:a,cause:r}),this[ep]=!0,this.toolInput=t,this.toolName=e}static isInstance(t){return he.hasMarker(t,Xd)}};ep=px;var rp="AI_NoObjectGeneratedError",np=`vercel.ai.error.${rp}`,hx=Symbol.for(np),ap,sp=class extends he{constructor({message:t="No object generated.",cause:e,text:r,response:a,usage:n,finishReason:s}){super({name:rp,message:t,cause:e}),this[ap]=!0,this.text=r,this.response=a,this.usage=n,this.finishReason=s}static isInstance(t){return he.hasMarker(t,np)}};ap=hx;var op="AI_NoOutputGeneratedError",ip=`vercel.ai.error.${op}`,fx=Symbol.for(ip),lp,mx=class extends he{constructor({message:t="No output generated.",cause:e}={}){super({name:op,message:t,cause:e}),this[lp]=!0}static isInstance(t){return he.hasMarker(t,ip)}};lp=fx;var up="AI_NoSuchToolError",cp=`vercel.ai.error.${up}`,vx=Symbol.for(cp),dp,fi=class extends he{constructor({toolName:t,availableTools:e=void 0,message:r=`Model tried to call unavailable tool '${t}'. ${e===void 0?"No tools are available.":`Available tools: ${e.join(", ")}.`}`}){super({name:up,message:r}),this[dp]=!0,this.toolName=t,this.availableTools=e}static isInstance(t){return he.hasMarker(t,cp)}};dp=vx;var pp="AI_ToolCallRepairError",hp=`vercel.ai.error.${pp}`,gx=Symbol.for(hp),fp,yx=class extends he{constructor({cause:t,originalError:e,message:r=`Error repairing tool call: ${yn(t)}`}){super({name:pp,message:r,cause:t}),this[fp]=!0,this.originalError=e}static isInstance(t){return he.hasMarker(t,hp)}};fp=gx;var _x=class extends he{constructor(t){super({name:"AI_UnsupportedModelVersionError",message:`Unsupported model version ${t.version} for provider "${t.provider}" and model "${t.modelId}". AI SDK 5 only supports models that implement specification version "v2".`}),this.version=t.version,this.provider=t.provider,this.modelId=t.modelId}},mp="AI_InvalidMessageRoleError",vp=`vercel.ai.error.${mp}`,wx=Symbol.for(vp),gp,bx=class extends he{constructor({role:t,message:e=`Invalid message role: '${t}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:mp,message:e}),this[gp]=!0,this.role=t}static isInstance(t){return he.hasMarker(t,vp)}};gp=wx;var yp="AI_DownloadError",_p=`vercel.ai.error.${yp}`,xx=Symbol.for(_p),wp,mi=class extends he{constructor({url:t,statusCode:e,statusText:r,cause:a,message:n=a==null?`Failed to download ${t}: ${e} ${r}`:`Failed to download ${t}: ${a}`}){super({name:yp,message:n,cause:a}),this[wp]=!0,this.url=t,this.statusCode=e,this.statusText=r}static isInstance(t){return he.hasMarker(t,_p)}};wp=xx;var bp="AI_RetryError",xp=`vercel.ai.error.${bp}`,Ex=Symbol.for(xp),Ep,Sp=class extends he{constructor({message:t,reason:e,errors:r}){super({name:bp,message:t}),this[Ep]=!0,this.reason=e,this.errors=r,this.lastError=r[r.length-1]}static isInstance(t){return he.hasMarker(t,xp)}};Ep=Ex;function hs(t){if(typeof t!="string"){if(t.specificationVersion!=="v2")throw new _x({version:t.specificationVersion,provider:t.provider,modelId:t.modelId});return t}return Sx().languageModel(t)}function Sx(){var t;return(t=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?t:Hb}var Ix=[{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]}],Tx=t=>{const e=typeof t=="string"?Qo(t):t,r=(e[6]&127)<<21|(e[7]&127)<<14|(e[8]&127)<<7|e[9]&127;return e.slice(r+10)};function kx(t){return typeof t=="string"&&t.startsWith("SUQz")||typeof t!="string"&&t.length>10&&t[0]===73&&t[1]===68&&t[2]===51?Tx(t):t}function Px({data:t,signatures:e}){const r=kx(t),a=typeof r=="string"?Qo(r.substring(0,Math.min(r.length,24))):r;for(const n of e)if(a.length>=n.bytesPrefix.length&&n.bytesPrefix.every((s,o)=>s===null||a[o]===s))return n.mediaType}var Ip="5.0.76",Cx=async({url:t})=>{var e;const r=t.toString();try{const a=await fetch(r,{headers:aa({},`ai-sdk/${Ip}`,Vo())});if(!a.ok)throw new mi({url:r,statusCode:a.status,statusText:a.statusText});return{data:new Uint8Array(await a.arrayBuffer()),mediaType:(e=a.headers.get("content-type"))!=null?e:void 0}}catch(a){throw mi.isInstance(a)?a:new mi({url:r,cause:a})}},Rx=(t=Cx)=>e=>Promise.all(e.map(async r=>r.isUrlSupportedByModel?null:t(r)));function Ox(t){try{const[e,r]=t.split(",");return{mediaType:e.split(";")[0].split(":")[1],base64Content:r}}catch{return{mediaType:void 0,base64Content:void 0}}}var Tp=Ae([x(),Wa(Uint8Array),Wa(ArrayBuffer),p0(t=>{var e,r;return(r=(e=globalThis.Buffer)==null?void 0:e.isBuffer(t))!=null?r:!1},{message:"Must be a Buffer"})]);function kp(t){if(t instanceof Uint8Array)return{data:t,mediaType:void 0};if(t instanceof ArrayBuffer)return{data:new Uint8Array(t),mediaType:void 0};if(typeof t=="string")try{t=new URL(t)}catch{}if(t instanceof URL&&t.protocol==="data:"){const{mediaType:e,base64Content:r}=Ox(t.toString());if(e==null||r==null)throw new he({name:"InvalidDataContentError",message:`Invalid data URL format in content ${t.toString()}`});return{data:r,mediaType:e}}return{data:t,mediaType:void 0}}function $x(t){return typeof t=="string"?t:t instanceof ArrayBuffer?Yo(new Uint8Array(t)):Yo(t)}async function Pp({prompt:t,supportedUrls:e,download:r=Rx()}){const a=await Nx(t.messages,r,e);return[...t.system!=null?[{role:"system",content:t.system}]:[],...t.messages.map(n=>Ax({message:n,downloadedAssets:a}))]}function Ax({message:t,downloadedAssets:e}){const r=t.role;switch(r){case"system":return{role:"system",content:t.content,providerOptions:t.providerOptions};case"user":return typeof t.content=="string"?{role:"user",content:[{type:"text",text:t.content}],providerOptions:t.providerOptions}:{role:"user",content:t.content.map(a=>Mx(a,e)).filter(a=>a.type!=="text"||a.text!==""),providerOptions:t.providerOptions};case"assistant":return typeof t.content=="string"?{role:"assistant",content:[{type:"text",text:t.content}],providerOptions:t.providerOptions}:{role:"assistant",content:t.content.filter(a=>a.type!=="text"||a.text!==""||a.providerOptions!=null).map(a=>{const n=a.providerOptions;switch(a.type){case"file":{const{data:s,mediaType:o}=kp(a.data);return{type:"file",data:s,filename:a.filename,mediaType:o??a.mediaType,providerOptions:n}}case"reasoning":return{type:"reasoning",text:a.text,providerOptions:n};case"text":return{type:"text",text:a.text,providerOptions:n};case"tool-call":return{type:"tool-call",toolCallId:a.toolCallId,toolName:a.toolName,input:a.input,providerExecuted:a.providerExecuted,providerOptions:n};case"tool-result":return{type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,output:a.output,providerOptions:n}}}),providerOptions:t.providerOptions};case"tool":return{role:"tool",content:t.content.map(a=>({type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,output:a.output,providerOptions:a.providerOptions})),providerOptions:t.providerOptions};default:{const a=r;throw new bx({role:a})}}}async function Nx(t,e,r){const a=t.filter(s=>s.role==="user").map(s=>s.content).filter(s=>Array.isArray(s)).flat().filter(s=>s.type==="image"||s.type==="file").map(s=>{var o;const i=(o=s.mediaType)!=null?o:s.type==="image"?"image/*":void 0;let l=s.type==="image"?s.image:s.data;if(typeof l=="string")try{l=new URL(l)}catch{}return{mediaType:i,data:l}}).filter(s=>s.data instanceof URL).map(s=>({url:s.data,isUrlSupportedByModel:s.mediaType!=null&&W0({url:s.data.toString(),mediaType:s.mediaType,supportedUrls:r})})),n=await e(a);return Object.fromEntries(n.map((s,o)=>s==null?null:[a[o].url.toString(),{data:s.data,mediaType:s.mediaType}]).filter(s=>s!=null))}function Mx(t,e){var r;if(t.type==="text")return{type:"text",text:t.text,providerOptions:t.providerOptions};let a;const n=t.type;switch(n){case"image":a=t.image;break;case"file":a=t.data;break;default:throw new Error(`Unsupported part type: ${n}`)}const{data:s,mediaType:o}=kp(a);let i=o??t.mediaType,l=s;if(l instanceof URL){const u=e[l.toString()];u&&(l=u.data,i??(i=u.mediaType))}switch(n){case"image":return(l instanceof Uint8Array||typeof l=="string")&&(i=(r=Px({data:l,signatures:Ix}))!=null?r:i),{type:"file",mediaType:i??"image/*",filename:void 0,data:l,providerOptions:t.providerOptions};case"file":{if(i==null)throw new Error("Media type is missing for file part");return{type:"file",mediaType:i,filename:t.filename,data:l,providerOptions:t.providerOptions}}}}function vi({maxOutputTokens:t,temperature:e,topP:r,topK:a,presencePenalty:n,frequencyPenalty:s,seed:o,stopSequences:i}){if(t!=null){if(!Number.isInteger(t))throw new ar({parameter:"maxOutputTokens",value:t,message:"maxOutputTokens must be an integer"});if(t<1)throw new ar({parameter:"maxOutputTokens",value:t,message:"maxOutputTokens must be >= 1"})}if(e!=null&&typeof e!="number")throw new ar({parameter:"temperature",value:e,message:"temperature must be a number"});if(r!=null&&typeof r!="number")throw new ar({parameter:"topP",value:r,message:"topP must be a number"});if(a!=null&&typeof a!="number")throw new ar({parameter:"topK",value:a,message:"topK must be a number"});if(n!=null&&typeof n!="number")throw new ar({parameter:"presencePenalty",value:n,message:"presencePenalty must be a number"});if(s!=null&&typeof s!="number")throw new ar({parameter:"frequencyPenalty",value:s,message:"frequencyPenalty must be a number"});if(o!=null&&!Number.isInteger(o))throw new ar({parameter:"seed",value:o,message:"seed must be an integer"});return{maxOutputTokens:t,temperature:e,topP:r,topK:a,presencePenalty:n,frequencyPenalty:s,stopSequences:i,seed:o}}function Dx(t){return t!=null&&Object.keys(t).length>0}function Cp({tools:t,toolChoice:e,activeTools:r}){return Dx(t)?{tools:(r!=null?Object.entries(t).filter(([n])=>r.includes(n)):Object.entries(t)).map(([n,s])=>{const o=s.type;switch(o){case void 0:case"dynamic":case"function":return{type:"function",name:n,description:s.description,inputSchema:us(s.inputSchema).jsonSchema,providerOptions:s.providerOptions};case"provider-defined":return{type:"provider-defined",name:n,id:s.id,args:s.args};default:{const i=o;throw new Error(`Unsupported tool type: ${i}`)}}}),toolChoice:e==null?{type:"auto"}:typeof e=="string"?{type:e}:{type:"tool",toolName:e.toolName}}:{tools:void 0,toolChoice:void 0}}var ha=Pc(()=>Ae([U_(),x(),U(),nt(),St(x(),ha),Y(ha)])),sr=St(x(),St(x(),ha)),Rp=P({type:H("text"),text:x(),providerOptions:sr.optional()}),jx=P({type:H("image"),image:Ae([Tp,Wa(URL)]),mediaType:x().optional(),providerOptions:sr.optional()}),Op=P({type:H("file"),data:Ae([Tp,Wa(URL)]),filename:x().optional(),mediaType:x(),providerOptions:sr.optional()}),Lx=P({type:H("reasoning"),text:x(),providerOptions:sr.optional()}),zx=P({type:H("tool-call"),toolCallId:x(),toolName:x(),input:Cr(),providerOptions:sr.optional(),providerExecuted:nt().optional()}),Ux=wn("type",[P({type:H("text"),value:x()}),P({type:H("json"),value:ha}),P({type:H("error-text"),value:x()}),P({type:H("error-json"),value:ha}),P({type:H("content"),value:Y(Ae([P({type:H("text"),text:x()}),P({type:H("media"),data:x(),mediaType:x()})]))})]),$p=P({type:H("tool-result"),toolCallId:x(),toolName:x(),output:Ux,providerOptions:sr.optional()}),Fx=P({role:H("system"),content:x(),providerOptions:sr.optional()}),qx=P({role:H("user"),content:Ae([x(),Y(Ae([Rp,jx,Op]))]),providerOptions:sr.optional()}),Zx=P({role:H("assistant"),content:Ae([x(),Y(Ae([Rp,Op,Lx,zx,$p]))]),providerOptions:sr.optional()}),Vx=P({role:H("tool"),content:Y($p),providerOptions:sr.optional()}),Bx=Ae([Fx,qx,Zx,Vx]);async function Ap(t){if(t.prompt==null&&t.messages==null)throw new Br({prompt:t,message:"prompt or messages must be defined"});if(t.prompt!=null&&t.messages!=null)throw new Br({prompt:t,message:"prompt and messages cannot be defined at the same time"});if(t.system!=null&&typeof t.system!="string")throw new Br({prompt:t,message:"system must be a string"});let e;if(t.prompt!=null&&typeof t.prompt=="string")e=[{role:"user",content:t.prompt}];else if(t.prompt!=null&&Array.isArray(t.prompt))e=t.prompt;else if(t.messages!=null)e=t.messages;else throw new Br({prompt:t,message:"prompt or messages must be defined"});if(e.length===0)throw new Br({prompt:t,message:"messages must not be empty"});const r=await $r({value:e,schema:Y(Bx)});if(!r.success)throw new Br({prompt:t,message:"The messages must be a ModelMessage[]. If you have passed a UIMessage[], you can use convertToModelMessages to convert them.",cause:r.error});return{messages:e,system:t.system}}function Np(t){return ri.isInstance(t)||bd.isInstance(t)?new he({name:"GatewayError",message:"Vercel AI Gateway access failed. If you want to use AI SDK providers directly, use the providers, e.g. @ai-sdk/openai, or register a different global default provider.",cause:t}):t}function In({operationId:t,telemetry:e}){return{"operation.name":`${t}${(e==null?void 0:e.functionId)!=null?` ${e.functionId}`:""}`,"resource.name":e==null?void 0:e.functionId,"ai.operationId":t,"ai.telemetry.functionId":e==null?void 0:e.functionId}}function Mp({model:t,settings:e,telemetry:r,headers:a}){var n;return{"ai.model.provider":t.provider,"ai.model.id":t.modelId,...Object.entries(e).reduce((s,[o,i])=>(s[`ai.settings.${o}`]=i,s),{}),...Object.entries((n=r==null?void 0:r.metadata)!=null?n:{}).reduce((s,[o,i])=>(s[`ai.telemetry.metadata.${o}`]=i,s),{}),...Object.entries(a??{}).reduce((s,[o,i])=>(i!==void 0&&(s[`ai.request.headers.${o}`]=i),s),{})}}var Hx={startSpan(){return fs},startActiveSpan(t,e,r,a){if(typeof e=="function")return e(fs);if(typeof r=="function")return r(fs);if(typeof a=="function")return a(fs)}},fs={spanContext(){return Jx},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}},Jx={traceId:"",spanId:"",traceFlags:0};function Dp({isEnabled:t=!1,tracer:e}={}){return t?e||sx.getTracer("ai"):Hx}function Tn({name:t,tracer:e,attributes:r,fn:a,endWhenDone:n=!0}){return e.startActiveSpan(t,{attributes:r},async s=>{try{const o=await a(s);return n&&s.end(),o}catch(o){try{gi(s,o)}finally{s.end()}throw o}})}function gi(t,e){e instanceof Error?(t.recordException({name:e.name,message:e.message,stack:e.stack}),t.setStatus({code:ps.ERROR,message:e.message})):t.setStatus({code:ps.ERROR})}function jt({telemetry:t,attributes:e}){return(t==null?void 0:t.isEnabled)!==!0?{}:Object.entries(e).reduce((r,[a,n])=>{if(n==null)return r;if(typeof n=="object"&&"input"in n&&typeof n.input=="function"){if((t==null?void 0:t.recordInputs)===!1)return r;const s=n.input();return s==null?r:{...r,[a]:s}}if(typeof n=="object"&&"output"in n&&typeof n.output=="function"){if((t==null?void 0:t.recordOutputs)===!1)return r;const s=n.output();return s==null?r:{...r,[a]:s}}return{...r,[a]:n}},{})}function jp(t){return JSON.stringify(t.map(e=>({...e,content:typeof e.content=="string"?e.content:e.content.map(r=>r.type==="file"?{...r,data:r.data instanceof Uint8Array?$x(r.data):r.data}:r)})))}function Lp(t,e){return{inputTokens:fa(t.inputTokens,e.inputTokens),outputTokens:fa(t.outputTokens,e.outputTokens),totalTokens:fa(t.totalTokens,e.totalTokens),reasoningTokens:fa(t.reasoningTokens,e.reasoningTokens),cachedInputTokens:fa(t.cachedInputTokens,e.cachedInputTokens)}}function fa(t,e){return t==null&&e==null?void 0:(t??0)+(e??0)}function yi(t){return t===void 0?[]:Array.isArray(t)?t:[t]}function Wx({error:t,exponentialBackoffDelay:e}){const r=t.responseHeaders;if(!r)return e;let a;const n=r["retry-after-ms"];if(n){const o=parseFloat(n);Number.isNaN(o)||(a=o)}const s=r["retry-after"];if(s&&a===void 0){const o=parseFloat(s);Number.isNaN(o)?a=Date.parse(s)-Date.now():a=o*1e3}return a!=null&&!Number.isNaN(a)&&0<=a&&(a<60*1e3||a<e)?a:e}var Gx=({maxRetries:t=2,initialDelayInMs:e=2e3,backoffFactor:r=2,abortSignal:a}={})=>async n=>zp(n,{maxRetries:t,delayInMs:e,backoffFactor:r,abortSignal:a});async function zp(t,{maxRetries:e,delayInMs:r,backoffFactor:a,abortSignal:n},s=[]){try{return await t()}catch(o){if(Yr(o)||e===0)throw o;const i=Zo(o),l=[...s,o],u=l.length;if(u>e)throw new Sp({message:`Failed after ${u} attempts. Last error: ${i}`,reason:"maxRetriesExceeded",errors:l});if(o instanceof Error&&Ue.isInstance(o)&&o.isRetryable===!0&&u<=e)return await Z0(Wx({error:o,exponentialBackoffDelay:r}),{abortSignal:n}),zp(t,{maxRetries:e,delayInMs:a*r,backoffFactor:a,abortSignal:n},l);throw u===1?o:new Sp({message:`Failed after ${u} attempts with non-retryable error: '${i}'`,reason:"errorNotRetryable",errors:l})}}function Up({maxRetries:t,abortSignal:e}){if(t!=null){if(!Number.isInteger(t))throw new ar({parameter:"maxRetries",value:t,message:"maxRetries must be an integer"});if(t<0)throw new ar({parameter:"maxRetries",value:t,message:"maxRetries must be >= 0"})}const r=t??2;return{maxRetries:r,retry:Gx({maxRetries:r,abortSignal:e})}}function Fp(t){const e=t.filter(r=>r.type==="text");if(e.length!==0)return e.map(r=>r.text).join("")}var qp=class{constructor({data:t,mediaType:e}){const r=t instanceof Uint8Array;this.base64Data=r?void 0:t,this.uint8ArrayData=r?t:void 0,this.mediaType=e}get base64(){return this.base64Data==null&&(this.base64Data=Yo(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=Qo(this.base64Data)),this.uint8ArrayData}},Kx=class extends qp{constructor(t){super(t),this.type="file"}};async function Zp({toolCall:t,tools:e,repairToolCall:r,system:a,messages:n}){try{if(e==null)throw new fi({toolName:t.toolName});try{return await Vp({toolCall:t,tools:e})}catch(s){if(r==null||!(fi.isInstance(s)||tp.isInstance(s)))throw s;let o=null;try{o=await r({toolCall:t,tools:e,inputSchema:({toolName:i})=>{const{inputSchema:l}=e[i];return us(l).jsonSchema},system:a,messages:n,error:s})}catch(i){throw new yx({cause:i,originalError:s})}if(o==null)throw s;return await Vp({toolCall:o,tools:e})}}catch(s){const o=await Xr({text:t.input}),i=o.success?o.value:t.input;return{type:"tool-call",toolCallId:t.toolCallId,toolName:t.toolName,input:i,dynamic:!0,invalid:!0,error:s}}}async function Vp({toolCall:t,tools:e}){const r=t.toolName,a=e[r];if(a==null)throw new fi({toolName:t.toolName,availableTools:Object.keys(e)});const n=us(a.inputSchema),s=t.input.trim()===""?await $r({value:{},schema:n}):await Xr({text:t.input,schema:n});if(s.success===!1)throw new tp({toolName:r,toolInput:t.input,cause:s.error});return a.type==="dynamic"?{type:"tool-call",toolCallId:t.toolCallId,toolName:t.toolName,input:s.value,providerExecuted:t.providerExecuted,providerMetadata:t.providerMetadata,dynamic:!0}:{type:"tool-call",toolCallId:t.toolCallId,toolName:r,input:s.value,providerExecuted:t.providerExecuted,providerMetadata:t.providerMetadata}}var Bp=class{constructor({content:t,finishReason:e,usage:r,warnings:a,request:n,response:s,providerMetadata:o}){this.content=t,this.finishReason=e,this.usage=r,this.warnings=a,this.request=n,this.response=s,this.providerMetadata=o}get text(){return this.content.filter(t=>t.type==="text").map(t=>t.text).join("")}get reasoning(){return this.content.filter(t=>t.type==="reasoning")}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map(t=>t.text).join("")}get files(){return this.content.filter(t=>t.type==="file").map(t=>t.file)}get sources(){return this.content.filter(t=>t.type==="source")}get toolCalls(){return this.content.filter(t=>t.type==="tool-call")}get staticToolCalls(){return this.toolCalls.filter(t=>t.dynamic!==!0)}get dynamicToolCalls(){return this.toolCalls.filter(t=>t.dynamic===!0)}get toolResults(){return this.content.filter(t=>t.type==="tool-result")}get staticToolResults(){return this.toolResults.filter(t=>t.dynamic!==!0)}get dynamicToolResults(){return this.toolResults.filter(t=>t.dynamic===!0)}};function _i(t){return({steps:e})=>e.length===t}async function Hp({stopConditions:t,steps:e}){return(await Promise.all(t.map(r=>r({steps:e})))).some(r=>r)}function wi({output:t,tool:e,errorMode:r}){return r==="text"?{type:"error-text",value:yn(t)}:r==="json"?{type:"error-json",value:Jp(t)}:e!=null&&e.toModelOutput?e.toModelOutput(t):typeof t=="string"?{type:"text",value:t}:{type:"json",value:Jp(t)}}function Jp(t){return t===void 0?null:t}function bi({content:t,tools:e}){const r=[],a=t.filter(s=>s.type!=="source").filter(s=>(s.type!=="tool-result"||s.providerExecuted)&&(s.type!=="tool-error"||s.providerExecuted)).filter(s=>s.type!=="text"||s.text.length>0).map(s=>{switch(s.type){case"text":return{type:"text",text:s.text,providerOptions:s.providerMetadata};case"reasoning":return{type:"reasoning",text:s.text,providerOptions:s.providerMetadata};case"file":return{type:"file",data:s.file.base64,mediaType:s.file.mediaType,providerOptions:s.providerMetadata};case"tool-call":return{type:"tool-call",toolCallId:s.toolCallId,toolName:s.toolName,input:s.input,providerExecuted:s.providerExecuted,providerOptions:s.providerMetadata};case"tool-result":return{type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:wi({tool:e==null?void 0:e[s.toolName],output:s.output,errorMode:"none"}),providerExecuted:!0,providerOptions:s.providerMetadata};case"tool-error":return{type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:wi({tool:e==null?void 0:e[s.toolName],output:s.error,errorMode:"json"}),providerOptions:s.providerMetadata}}});a.length>0&&r.push({role:"assistant",content:a});const n=t.filter(s=>s.type==="tool-result"||s.type==="tool-error").filter(s=>!s.providerExecuted).map(s=>({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:wi({tool:e==null?void 0:e[s.toolName],output:s.type==="tool-result"?s.output:s.error,errorMode:s.type==="tool-error"?"text":"none"})}));return n.length>0&&r.push({role:"tool",content:n}),r}var Qx=na({prefix:"aitxt",size:24});async function Yx({model:t,tools:e,toolChoice:r,system:a,prompt:n,messages:s,maxRetries:o,abortSignal:i,headers:l,stopWhen:u=_i(1),experimental_output:d,experimental_telemetry:h,providerOptions:g,experimental_activeTools:c,activeTools:p=c,experimental_prepareStep:f,prepareStep:m=f,experimental_repairToolCall:v,experimental_download:w,experimental_context:y,_internal:{generateId:_=Qx,currentDate:E=()=>new Date}={},onStepFinish:I,...S}){const R=hs(t),$=yi(u),{maxRetries:z,retry:L}=Up({maxRetries:o,abortSignal:i}),F=vi(S),M=aa(l??{},`ai/${Ip}`),D=Mp({model:R,telemetry:h,headers:M,settings:{...F,maxRetries:z}}),K=await Ap({system:a,prompt:n,messages:s}),oe=Dp(h);try{return await Tn({name:"ai.generateText",attributes:jt({telemetry:h,attributes:{...In({operationId:"ai.generateText",telemetry:h}),...D,"ai.model.provider":R.provider,"ai.model.id":R.modelId,"ai.prompt":{input:()=>JSON.stringify({system:a,prompt:n,messages:s})}}}),tracer:oe,fn:async ie=>{var C,re,B,de,ae,ke,_e;const Pe=vi(S);let xe,ve=[],Re=[];const pt=[],Ne=[];do{const be=[...K.messages,...pt],se=await(m==null?void 0:m({model:R,steps:Ne,stepNumber:Ne.length,messages:be})),Se=hs((C=se==null?void 0:se.model)!=null?C:R),Ie=await Pp({prompt:{system:(re=se==null?void 0:se.system)!=null?re:K.system,messages:(B=se==null?void 0:se.messages)!=null?B:be},supportedUrls:await Se.supportedUrls,download:w}),{toolChoice:ye,tools:Xe}=Cp({tools:e,toolChoice:(de=se==null?void 0:se.toolChoice)!=null?de:r,activeTools:(ae=se==null?void 0:se.activeTools)!=null?ae:p});xe=await L(()=>{var pe;return Tn({name:"ai.generateText.doGenerate",attributes:jt({telemetry:h,attributes:{...In({operationId:"ai.generateText.doGenerate",telemetry:h}),...D,"ai.model.provider":Se.provider,"ai.model.id":Se.modelId,"ai.prompt.messages":{input:()=>jp(Ie)},"ai.prompt.tools":{input:()=>Xe==null?void 0:Xe.map(Be=>JSON.stringify(Be))},"ai.prompt.toolChoice":{input:()=>ye!=null?JSON.stringify(ye):void 0},"gen_ai.system":Se.provider,"gen_ai.request.model":Se.modelId,"gen_ai.request.frequency_penalty":S.frequencyPenalty,"gen_ai.request.max_tokens":S.maxOutputTokens,"gen_ai.request.presence_penalty":S.presencePenalty,"gen_ai.request.stop_sequences":S.stopSequences,"gen_ai.request.temperature":(pe=S.temperature)!=null?pe:void 0,"gen_ai.request.top_k":S.topK,"gen_ai.request.top_p":S.topP}}),tracer:oe,fn:async Be=>{var hr,Ft,mt,Yt,xt,qt,Sr,pn;const Ge=await Se.doGenerate({...Pe,tools:Xe,toolChoice:ye,responseFormat:d==null?void 0:d.responseFormat,prompt:Ie,providerOptions:g,abortSignal:i,headers:M}),Zt={id:(Ft=(hr=Ge.response)==null?void 0:hr.id)!=null?Ft:_(),timestamp:(Yt=(mt=Ge.response)==null?void 0:mt.timestamp)!=null?Yt:E(),modelId:(qt=(xt=Ge.response)==null?void 0:xt.modelId)!=null?qt:Se.modelId,headers:(Sr=Ge.response)==null?void 0:Sr.headers,body:(pn=Ge.response)==null?void 0:pn.body};return Be.setAttributes(jt({telemetry:h,attributes:{"ai.response.finishReason":Ge.finishReason,"ai.response.text":{output:()=>Fp(Ge.content)},"ai.response.toolCalls":{output:()=>{const Xt=Wp(Ge.content);return Xt==null?void 0:JSON.stringify(Xt)}},"ai.response.id":Zt.id,"ai.response.model":Zt.modelId,"ai.response.timestamp":Zt.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(Ge.providerMetadata),"ai.usage.promptTokens":Ge.usage.inputTokens,"ai.usage.completionTokens":Ge.usage.outputTokens,"gen_ai.response.finish_reasons":[Ge.finishReason],"gen_ai.response.id":Zt.id,"gen_ai.response.model":Zt.modelId,"gen_ai.usage.input_tokens":Ge.usage.inputTokens,"gen_ai.usage.output_tokens":Ge.usage.outputTokens}})),{...Ge,response:Zt}}})});const Le=await Promise.all(xe.content.filter(pe=>pe.type==="tool-call").map(pe=>Zp({toolCall:pe,tools:e,repairToolCall:v,system:a,messages:be})));for(const pe of Le){if(pe.invalid)continue;const Be=e[pe.toolName];(Be==null?void 0:Be.onInputAvailable)!=null&&await Be.onInputAvailable({input:pe.input,toolCallId:pe.toolCallId,messages:be,abortSignal:i,experimental_context:y})}const J=Le.filter(pe=>pe.invalid&&pe.dynamic);Re=[];for(const pe of J)Re.push({type:"tool-error",toolCallId:pe.toolCallId,toolName:pe.toolName,input:pe.input,error:Zo(pe.error),dynamic:!0});ve=Le.filter(pe=>!pe.providerExecuted),e!=null&&Re.push(...await Xx({toolCalls:ve.filter(pe=>!pe.invalid),tools:e,tracer:oe,telemetry:h,messages:be,abortSignal:i,experimental_context:y}));const Me=tE({content:xe.content,toolCalls:Le,toolOutputs:Re});pt.push(...bi({content:Me,tools:e}));const ze=new Bp({content:Me,finishReason:xe.finishReason,usage:xe.usage,warnings:xe.warnings,providerMetadata:xe.providerMetadata,request:(ke=xe.request)!=null?ke:{},response:{...xe.response,messages:structuredClone(pt)}});Wd((_e=xe.warnings)!=null?_e:[]),Ne.push(ze),await(I==null?void 0:I(ze))}while(ve.length>0&&Re.length===ve.length&&!await Hp({stopConditions:$,steps:Ne}));ie.setAttributes(jt({telemetry:h,attributes:{"ai.response.finishReason":xe.finishReason,"ai.response.text":{output:()=>Fp(xe.content)},"ai.response.toolCalls":{output:()=>{const be=Wp(xe.content);return be==null?void 0:JSON.stringify(be)}},"ai.response.providerMetadata":JSON.stringify(xe.providerMetadata),"ai.usage.promptTokens":xe.usage.inputTokens,"ai.usage.completionTokens":xe.usage.outputTokens}}));const we=Ne[Ne.length-1];let bt;return we.finishReason==="stop"&&(bt=await(d==null?void 0:d.parseOutput({text:we.text},{response:we.response,usage:we.usage,finishReason:we.finishReason}))),new eE({steps:Ne,resolvedOutput:bt})}})}catch(ie){throw Np(ie)}}async function Xx({toolCalls:t,tools:e,tracer:r,telemetry:a,messages:n,abortSignal:s,experimental_context:o}){return(await Promise.all(t.map(async({toolCallId:l,toolName:u,input:d})=>{const h=e[u];if((h==null?void 0:h.execute)!=null)return Tn({name:"ai.toolCall",attributes:jt({telemetry:a,attributes:{...In({operationId:"ai.toolCall",telemetry:a}),"ai.toolCall.name":u,"ai.toolCall.id":l,"ai.toolCall.args":{output:()=>JSON.stringify(d)}}}),tracer:r,fn:async g=>{try{const c=Yc({execute:h.execute.bind(h),input:d,options:{toolCallId:l,messages:n,abortSignal:s,experimental_context:o}});let p;for await(const f of c)f.type==="final"&&(p=f.output);try{g.setAttributes(jt({telemetry:a,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(p)}}}))}catch{}return{type:"tool-result",toolCallId:l,toolName:u,input:d,output:p,dynamic:h.type==="dynamic"}}catch(c){return gi(g,c),{type:"tool-error",toolCallId:l,toolName:u,input:d,error:c,dynamic:h.type==="dynamic"}}}})}))).filter(l=>l!=null)}var eE=class{constructor(t){this.steps=t.steps,this.resolvedOutput=t.resolvedOutput}get finalStep(){return this.steps[this.steps.length-1]}get content(){return this.finalStep.content}get text(){return this.finalStep.text}get files(){return this.finalStep.files}get reasoningText(){return this.finalStep.reasoningText}get reasoning(){return this.finalStep.reasoning}get toolCalls(){return this.finalStep.toolCalls}get staticToolCalls(){return this.finalStep.staticToolCalls}get dynamicToolCalls(){return this.finalStep.dynamicToolCalls}get toolResults(){return this.finalStep.toolResults}get staticToolResults(){return this.finalStep.staticToolResults}get dynamicToolResults(){return this.finalStep.dynamicToolResults}get sources(){return this.finalStep.sources}get finishReason(){return this.finalStep.finishReason}get warnings(){return this.finalStep.warnings}get providerMetadata(){return this.finalStep.providerMetadata}get response(){return this.finalStep.response}get request(){return this.finalStep.request}get usage(){return this.finalStep.usage}get totalUsage(){return this.steps.reduce((t,e)=>Lp(t,e.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0})}get experimental_output(){if(this.resolvedOutput==null)throw new Hd;return this.resolvedOutput}};function Wp(t){const e=t.filter(r=>r.type==="tool-call");if(e.length!==0)return e.map(r=>({toolCallId:r.toolCallId,toolName:r.toolName,input:r.input}))}function tE({content:t,toolCalls:e,toolOutputs:r}){return[...t.map(a=>{switch(a.type){case"text":case"reasoning":case"source":return a;case"file":return{type:"file",file:new qp(a)};case"tool-call":return e.find(n=>n.toolCallId===a.toolCallId);case"tool-result":{const n=e.find(s=>s.toolCallId===a.toolCallId);if(n==null)throw new Error(`Tool call ${a.toolCallId} not found.`);return a.isError?{type:"tool-error",toolCallId:a.toolCallId,toolName:a.toolName,input:n.input,error:a.result,providerExecuted:!0,dynamic:n.dynamic}:{type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,input:n.input,output:a.result,providerExecuted:!0,dynamic:n.dynamic}}}}),...r]}function ms(t,e){const r=new Headers(t??{});for(const[a,n]of Object.entries(e))r.has(a)||r.set(a,n);return r}function rE({status:t,statusText:e,headers:r,textStream:a}){return new Response(a.pipeThrough(new TextEncoderStream),{status:t??200,statusText:e,headers:ms(r,{"content-type":"text/plain; charset=utf-8"})})}function Gp({response:t,status:e,statusText:r,headers:a,stream:n}){t.writeHead(e??200,r,a);const s=n.getReader();(async()=>{try{for(;;){const{done:i,value:l}=await s.read();if(i)break;t.write(l)||await new Promise(d=>{t.once("drain",d)})}}catch(i){throw i}finally{t.end()}})()}function nE({response:t,status:e,statusText:r,headers:a,textStream:n}){Gp({response:t,status:e,statusText:r,headers:Object.fromEntries(ms(a,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:n.pipeThrough(new TextEncoderStream)})}var Kp=class extends TransformStream{constructor(){super({transform(t,e){e.enqueue(`data: ${JSON.stringify(t)}
|
|
54
54
|
|
|
55
|
-
`)},flush(
|
|
55
|
+
`)},flush(t){t.enqueue(`data: [DONE]
|
|
56
56
|
|
|
57
|
-
`)}})}},Ic={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function c0({status:e,statusText:t,headers:n,stream:r,consumeSseStream:o}){let s=r.pipeThrough(new Sc);if(o){const[a,i]=s.tee();s=a,o({stream:i})}return new Response(s.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:oo(n,Ic)})}function d0({originalMessages:e,responseMessageId:t}){if(e==null)return;const n=e[e.length-1];return(n==null?void 0:n.role)==="assistant"?n.id:typeof t=="function"?t():t}function p0(e){return e.type.startsWith("data-")}function Cc(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;const n={...e};for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const o=t[r];if(o===void 0)continue;const s=r in e?e[r]:void 0,a=o!==null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp),i=s!=null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp);a&&i?n[r]=Cc(s,o):n[r]=o}return n}function h0(e){const t=["ROOT"];let n=-1,r=null;function o(l,u,p){switch(l){case'"':{n=u,t.pop(),t.push(p),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{n=u,r=u,t.pop(),t.push(p),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(p),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=u,t.pop(),t.push(p),t.push("INSIDE_NUMBER");break}case"{":{n=u,t.pop(),t.push(p),t.push("INSIDE_OBJECT_START");break}case"[":{n=u,t.pop(),t.push(p),t.push("INSIDE_ARRAY_START");break}}}function s(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=u,t.pop();break}}}function a(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=u,t.pop();break}}}for(let l=0;l<e.length;l++){const u=e[l];switch(t[t.length-1]){case"ROOT":o(u,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=l,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(u){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{o(u,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{s(u,l);break}case"INSIDE_STRING":{switch(u){case'"':{t.pop(),n=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=l}break}case"INSIDE_ARRAY_START":{switch(u){case"]":{n=l,t.pop();break}default:{n=l,o(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(u){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=l,t.pop();break}default:{n=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{o(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=l;break}case"INSIDE_NUMBER":{switch(u){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=l;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(u,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(u,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(u,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(u,l);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const x=e.substring(r,l+1);!"false".startsWith(x)&&!"true".startsWith(x)&&!"null".startsWith(x)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?s(u,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(u,l)):n=l;break}}}let i=e.slice(0,n+1);for(let l=t.length-1;l>=0;l--)switch(t[l]){case"INSIDE_STRING":{i+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{i+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{i+="]";break}case"INSIDE_LITERAL":{const p=e.substring(r,e.length);"true".startsWith(p)?i+="true".slice(p.length):"false".startsWith(p)?i+="false".slice(p.length):"null".startsWith(p)&&(i+="null".slice(p.length))}}return i}async function Ec(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await cn({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await cn({text:h0(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function Os(e){return e.type.startsWith("tool-")}function Rc(e){return e.type.split("-").slice(1).join("-")}function f0({lastMessage:e,messageId:t}){return{message:(e==null?void 0:e.role)==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function m0({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:o,onToolCall:s,onData:a}){return e.pipeThrough(new TransformStream({async transform(i,l){await r(async({state:u,write:p})=>{var x,w,h,f;function y(_){const C=u.message.parts.filter(Os).find(T=>T.toolCallId===_);if(C==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return C}function m(_){const C=u.message.parts.filter(T=>T.type==="dynamic-tool").find(T=>T.toolCallId===_);if(C==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return C}function c(_){var R;const C=u.message.parts.find(D=>Os(D)&&D.toolCallId===_.toolCallId),T=_,P=C;C!=null?(C.state=_.state,P.input=T.input,P.output=T.output,P.errorText=T.errorText,P.rawInput=T.rawInput,P.preliminary=T.preliminary,P.providerExecuted=(R=T.providerExecuted)!=null?R:C.providerExecuted,T.providerMetadata!=null&&C.state==="input-available"&&(C.callProviderMetadata=T.providerMetadata)):u.message.parts.push({type:`tool-${_.toolName}`,toolCallId:_.toolCallId,state:_.state,input:T.input,output:T.output,rawInput:T.rawInput,errorText:T.errorText,providerExecuted:T.providerExecuted,preliminary:T.preliminary,...T.providerMetadata!=null?{callProviderMetadata:T.providerMetadata}:{}})}function b(_){var R;const C=u.message.parts.find(D=>D.type==="dynamic-tool"&&D.toolCallId===_.toolCallId),T=_,P=C;C!=null?(C.state=_.state,P.toolName=_.toolName,P.input=T.input,P.output=T.output,P.errorText=T.errorText,P.rawInput=(R=T.rawInput)!=null?R:P.rawInput,P.preliminary=T.preliminary,T.providerMetadata!=null&&C.state==="input-available"&&(C.callProviderMetadata=T.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:_.toolName,toolCallId:_.toolCallId,state:_.state,input:T.input,output:T.output,errorText:T.errorText,preliminary:T.preliminary,...T.providerMetadata!=null?{callProviderMetadata:T.providerMetadata}:{}})}async function v(_){if(_!=null){const R=u.message.metadata!=null?Cc(u.message.metadata,_):_;t!=null&&await Tt({value:R,schema:t}),u.message.metadata=R}}switch(i.type){case"text-start":{const _={type:"text",text:"",providerMetadata:i.providerMetadata,state:"streaming"};u.activeTextParts[i.id]=_,u.message.parts.push(_),p();break}case"text-delta":{const _=u.activeTextParts[i.id];_.text+=i.delta,_.providerMetadata=(x=i.providerMetadata)!=null?x:_.providerMetadata,p();break}case"text-end":{const _=u.activeTextParts[i.id];_.state="done",_.providerMetadata=(w=i.providerMetadata)!=null?w:_.providerMetadata,delete u.activeTextParts[i.id],p();break}case"reasoning-start":{const _={type:"reasoning",text:"",providerMetadata:i.providerMetadata,state:"streaming"};u.activeReasoningParts[i.id]=_,u.message.parts.push(_),p();break}case"reasoning-delta":{const _=u.activeReasoningParts[i.id];_.text+=i.delta,_.providerMetadata=(h=i.providerMetadata)!=null?h:_.providerMetadata,p();break}case"reasoning-end":{const _=u.activeReasoningParts[i.id];_.providerMetadata=(f=i.providerMetadata)!=null?f:_.providerMetadata,_.state="done",delete u.activeReasoningParts[i.id],p();break}case"file":{u.message.parts.push({type:"file",mediaType:i.mediaType,url:i.url}),p();break}case"source-url":{u.message.parts.push({type:"source-url",sourceId:i.sourceId,url:i.url,title:i.title,providerMetadata:i.providerMetadata}),p();break}case"source-document":{u.message.parts.push({type:"source-document",sourceId:i.sourceId,mediaType:i.mediaType,title:i.title,filename:i.filename,providerMetadata:i.providerMetadata}),p();break}case"tool-input-start":{const _=u.message.parts.filter(Os);u.partialToolCalls[i.toolCallId]={text:"",toolName:i.toolName,index:_.length,dynamic:i.dynamic},i.dynamic?b({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0}):c({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0,providerExecuted:i.providerExecuted}),p();break}case"tool-input-delta":{const _=u.partialToolCalls[i.toolCallId];_.text+=i.inputTextDelta;const{value:R}=await Ec(_.text);_.dynamic?b({toolCallId:i.toolCallId,toolName:_.toolName,state:"input-streaming",input:R}):c({toolCallId:i.toolCallId,toolName:_.toolName,state:"input-streaming",input:R}),p();break}case"tool-input-available":{i.dynamic?b({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerMetadata:i.providerMetadata}):c({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}),p(),s&&!i.providerExecuted&&await s({toolCall:i});break}case"tool-input-error":{i.dynamic?b({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:i.input,errorText:i.errorText,providerMetadata:i.providerMetadata}):c({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:void 0,rawInput:i.input,errorText:i.errorText,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}),p();break}case"tool-output-available":{if(i.dynamic){const _=m(i.toolCallId);b({toolCallId:i.toolCallId,toolName:_.toolName,state:"output-available",input:_.input,output:i.output,preliminary:i.preliminary})}else{const _=y(i.toolCallId);c({toolCallId:i.toolCallId,toolName:Rc(_),state:"output-available",input:_.input,output:i.output,providerExecuted:i.providerExecuted,preliminary:i.preliminary})}p();break}case"tool-output-error":{if(i.dynamic){const _=m(i.toolCallId);b({toolCallId:i.toolCallId,toolName:_.toolName,state:"output-error",input:_.input,errorText:i.errorText})}else{const _=y(i.toolCallId);c({toolCallId:i.toolCallId,toolName:Rc(_),state:"output-error",input:_.input,rawInput:_.rawInput,errorText:i.errorText})}p();break}case"start-step":{u.message.parts.push({type:"step-start"});break}case"finish-step":{u.activeTextParts={},u.activeReasoningParts={};break}case"start":{i.messageId!=null&&(u.message.id=i.messageId),await v(i.messageMetadata),(i.messageId!=null||i.messageMetadata!=null)&&p();break}case"finish":{await v(i.messageMetadata),i.messageMetadata!=null&&p();break}case"message-metadata":{await v(i.messageMetadata),i.messageMetadata!=null&&p();break}case"error":{o==null||o(new Error(i.errorText));break}default:if(p0(i)){(n==null?void 0:n[i.type])!=null&&await Tt({value:i.data,schema:n[i.type]});const _=i;if(_.transient){a==null||a(_);break}const R=_.id!=null?u.message.parts.find(C=>_.type===C.type&&_.id===C.id):void 0;R!=null?R.data=_.data:u.message.parts.push(_),a==null||a(_),p()}}l.enqueue(i)})}}))}function g0({messageId:e,originalMessages:t=[],onFinish:n,onError:r,stream:o}){let s=t==null?void 0:t[t.length-1];(s==null?void 0:s.role)!=="assistant"?s=void 0:e=s.id;let a=!1;const i=o.pipeThrough(new TransformStream({transform(w,h){if(w.type==="start"){const f=w;f.messageId==null&&e!=null&&(f.messageId=e)}w.type==="abort"&&(a=!0),h.enqueue(w)}}));if(n==null)return i;const l=f0({lastMessage:s?structuredClone(s):void 0,messageId:e??""}),u=async w=>{await w({state:l,write:()=>{}})};let p=!1;const x=async()=>{if(p||!n)return;p=!0;const w=l.message.id===(s==null?void 0:s.id);await n({isAborted:a,isContinuation:w,responseMessage:l.message,messages:[...w?t.slice(0,-1):t,l.message]})};return m0({stream:i,runUpdateMessageJob:u,onError:r}).pipeThrough(new TransformStream({transform(w,h){h.enqueue(w)},async cancel(){await x()},async flush(){await x()}}))}function v0({response:e,status:t,statusText:n,headers:r,stream:o,consumeSseStream:s}){let a=o.pipeThrough(new Sc);if(s){const[i,l]=a.tee();a=i,s({stream:l})}Tc({response:e,status:t,statusText:n,headers:Object.fromEntries(oo(r,Ic).entries()),stream:a.pipeThrough(new TextEncoderStream)})}function so(e){const t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=function(){const n=this.getReader();let r=!1;async function o(s){var a;r=!0;try{s&&await((a=n.cancel)==null?void 0:a.call(n))}finally{try{n.releaseLock()}catch{}}}return{async next(){if(r)return{done:!0,value:void 0};const{done:s,value:a}=await n.read();return s?(await o(!0),{done:!0,value:void 0}):{done:!1,value:a}},async return(){return await o(!0),{done:!0,value:void 0}},async throw(s){throw await o(!0),s}}},t}async function y0({stream:e,onError:t}){const n=e.getReader();try{for(;;){const{done:r}=await n.read();if(r)break}}catch(r){t==null||t(r)}finally{n.releaseLock()}}function Ac(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}function _0(){let e=[],t=null,n=!1,r=Ac();const o=()=>{n=!0,r.resolve(),e.forEach(a=>a.cancel()),e=[],t==null||t.close()},s=async()=>{if(n&&e.length===0){t==null||t.close();return}if(e.length===0)return r=Ac(),await r.promise,s();try{const{value:a,done:i}=await e[0].read();i?(e.shift(),e.length>0?await s():n&&(t==null||t.close())):t==null||t.enqueue(a)}catch(a){t==null||t.error(a),e.shift(),o()}};return{stream:new ReadableStream({start(a){t=a},pull:s,async cancel(){for(const a of e)await a.cancel();e=[],n=!0}}),addStream:a=>{if(n)throw new Error("Cannot add inner stream: outer stream is closed");e.push(a.getReader()),r.resolve()},close:()=>{n=!0,r.resolve(),e.length===0&&(t==null||t.close())},terminate:o}}var ao=class{constructor(){this.status={type:"pending"},this._resolve=void 0,this._reject=void 0}get promise(){return this._promise?this._promise:(this._promise=new Promise((e,t)=>{this.status.type==="resolved"?e(this.status.value):this.status.type==="rejected"&&t(this.status.error),this._resolve=e,this._reject=t}),this._promise)}resolve(e){var t;this.status={type:"resolved",value:e},this._promise&&((t=this._resolve)==null||t.call(this,e))}reject(e){var t;this.status={type:"rejected",error:e},this._promise&&((t=this._reject)==null||t.call(this,e))}};function w0(){var e,t;return(t=(e=globalThis==null?void 0:globalThis.performance)==null?void 0:e.now())!=null?t:Date.now()}function b0({tools:e,generatorStream:t,tracer:n,telemetry:r,system:o,messages:s,abortSignal:a,repairToolCall:i,experimental_context:l}){let u=null;const p=new ReadableStream({start(c){u=c}}),x=new Set,w=new Map;let h=!1,f;function y(){h&&x.size===0&&(f!=null&&u.enqueue(f),u.close())}const m=new TransformStream({async transform(c,b){const v=c.type;switch(v){case"stream-start":case"text-start":case"text-delta":case"text-end":case"reasoning-start":case"reasoning-delta":case"reasoning-end":case"tool-input-start":case"tool-input-delta":case"tool-input-end":case"source":case"response-metadata":case"error":case"raw":{b.enqueue(c);break}case"file":{b.enqueue({type:"file",file:new n0({data:c.data,mediaType:c.mediaType})});break}case"finish":{f={type:"finish",finishReason:c.finishReason,usage:c.usage,providerMetadata:c.providerMetadata};break}case"tool-call":{try{const _=await yc({toolCall:c,tools:e,repairToolCall:i,system:o,messages:s});if(b.enqueue(_),_.invalid){u.enqueue({type:"tool-error",toolCallId:_.toolCallId,toolName:_.toolName,input:_.input,error:ts(_.error),dynamic:!0});break}const R=e[_.toolName];if(w.set(_.toolCallId,_.input),R.onInputAvailable!=null&&await R.onInputAvailable({input:_.input,toolCallId:_.toolCallId,messages:s,abortSignal:a,experimental_context:l}),R.execute!=null&&_.providerExecuted!==!0){const C=tt();x.add(C),In({name:"ai.toolCall",attributes:dt({telemetry:r,attributes:{...Sn({operationId:"ai.toolCall",telemetry:r}),"ai.toolCall.name":_.toolName,"ai.toolCall.id":_.toolCallId,"ai.toolCall.args":{output:()=>JSON.stringify(_.input)}}}),tracer:n,fn:async T=>{let P;try{const D=Il({execute:R.execute.bind(R),input:_.input,options:{toolCallId:_.toolCallId,messages:s,abortSignal:a,experimental_context:l}});for await(const H of D)u.enqueue({..._,type:"tool-result",output:H.output,...H.type==="preliminary"&&{preliminary:!0}}),H.type==="final"&&(P=H.output)}catch(D){Is(T,D),u.enqueue({..._,type:"tool-error",error:D}),x.delete(C),y();return}x.delete(C),y();try{T.setAttributes(dt({telemetry:r,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(P)}}}))}catch{}}})}}catch(_){u.enqueue({type:"error",error:_})}break}case"tool-result":{const _=c.toolName;c.isError?u.enqueue({type:"tool-error",toolCallId:c.toolCallId,toolName:_,input:w.get(c.toolCallId),providerExecuted:c.providerExecuted,error:c.result}):b.enqueue({type:"tool-result",toolCallId:c.toolCallId,toolName:_,input:w.get(c.toolCallId),output:c.result,providerExecuted:c.providerExecuted});break}default:{const _=v;throw new Error(`Unhandled chunk type: ${_}`)}}},flush(){h=!0,y()}});return new ReadableStream({async start(c){return Promise.all([t.pipeThrough(m).pipeTo(new WritableStream({write(b){c.enqueue(b)},close(){}})),p.pipeTo(new WritableStream({write(b){c.enqueue(b)},close(){c.close()}}))])}})}var x0=Kn({prefix:"aitxt",size:24});function k0({model:e,tools:t,toolChoice:n,system:r,prompt:o,messages:s,maxRetries:a,abortSignal:i,headers:l,stopWhen:u=Es(1),experimental_output:p,experimental_telemetry:x,prepareStep:w,providerOptions:h,experimental_activeTools:f,activeTools:y=f,experimental_repairToolCall:m,experimental_transform:c,experimental_download:b,includeRawChunks:v=!1,onChunk:_,onError:R=({error:ne})=>{console.error(ne)},onFinish:C,onAbort:T,onStepFinish:P,experimental_context:D,_internal:{now:H=w0,generateId:K=x0,currentDate:he=()=>new Date}={},...Y}){return new S0({model:to(e),telemetry:x,headers:l,settings:Y,maxRetries:a,abortSignal:i,system:r,prompt:o,messages:s,tools:t,toolChoice:n,transforms:Cs(c),activeTools:y,repairToolCall:m,stopConditions:Cs(u),output:p,providerOptions:h,prepareStep:w,includeRawChunks:v,onChunk:_,onError:R,onFinish:C,onAbort:T,onStepFinish:P,now:H,currentDate:he,generateId:K,experimental_context:D,download:b})}function T0(e){if(!e)return new TransformStream({transform(a,i){i.enqueue({part:a,partialOutput:void 0})}});let t,n="",r="",o="";function s({controller:a,partialOutput:i=void 0}){a.enqueue({part:{type:"text-delta",id:t,text:r},partialOutput:i}),r=""}return new TransformStream({async transform(a,i){if(a.type==="finish-step"&&r.length>0&&s({controller:i}),a.type!=="text-delta"&&a.type!=="text-start"&&a.type!=="text-end"){i.enqueue({part:a,partialOutput:void 0});return}if(t==null)t=a.id;else if(a.id!==t){i.enqueue({part:a,partialOutput:void 0});return}if(a.type==="text-start"){i.enqueue({part:a,partialOutput:void 0});return}if(a.type==="text-end"){r.length>0&&s({controller:i}),i.enqueue({part:a,partialOutput:void 0});return}n+=a.text,r+=a.text;const l=await e.parsePartial({text:n});if(l!=null){const u=JSON.stringify(l.partial);u!==o&&(s({controller:i,partialOutput:l.partial}),o=u)}}})}var S0=class{constructor({model:e,telemetry:t,headers:n,settings:r,maxRetries:o,abortSignal:s,system:a,prompt:i,messages:l,tools:u,toolChoice:p,transforms:x,activeTools:w,repairToolCall:h,stopConditions:f,output:y,providerOptions:m,prepareStep:c,includeRawChunks:b,now:v,currentDate:_,generateId:R,onChunk:C,onError:T,onFinish:P,onAbort:D,onStepFinish:H,experimental_context:K,download:he}){this._totalUsage=new ao,this._finishReason=new ao,this._steps=new ao,this.output=y,this.includeRawChunks=b,this.tools=u;let Y,ne=[];const V=[];let se,ae,ce={},Pe=[];const oe=[];let me,ee={},Ie={};const k=new TransformStream({async transform(de,ve){var $e,ie,Ye,Nt;ve.enqueue(de);const{part:Z}=de;if((Z.type==="text-delta"||Z.type==="reasoning-delta"||Z.type==="source"||Z.type==="tool-call"||Z.type==="tool-result"||Z.type==="tool-input-start"||Z.type==="tool-input-delta"||Z.type==="raw")&&await(C==null?void 0:C({chunk:Z})),Z.type==="error"&&await T({error:uc(Z.error)}),Z.type==="text-start"&&(ee[Z.id]={type:"text",text:"",providerMetadata:Z.providerMetadata},ne.push(ee[Z.id])),Z.type==="text-delta"){const _e=ee[Z.id];if(_e==null){ve.enqueue({part:{type:"error",error:`text part ${Z.id} not found`},partialOutput:void 0});return}_e.text+=Z.text,_e.providerMetadata=($e=Z.providerMetadata)!=null?$e:_e.providerMetadata}if(Z.type==="text-end"){const _e=ee[Z.id];if(_e==null){ve.enqueue({part:{type:"error",error:`text part ${Z.id} not found`},partialOutput:void 0});return}_e.providerMetadata=(ie=Z.providerMetadata)!=null?ie:_e.providerMetadata,delete ee[Z.id]}if(Z.type==="reasoning-start"&&(Ie[Z.id]={type:"reasoning",text:"",providerMetadata:Z.providerMetadata},ne.push(Ie[Z.id])),Z.type==="reasoning-delta"){const _e=Ie[Z.id];if(_e==null){ve.enqueue({part:{type:"error",error:`reasoning part ${Z.id} not found`},partialOutput:void 0});return}_e.text+=Z.text,_e.providerMetadata=(Ye=Z.providerMetadata)!=null?Ye:_e.providerMetadata}if(Z.type==="reasoning-end"){const _e=Ie[Z.id];if(_e==null){ve.enqueue({part:{type:"error",error:`reasoning part ${Z.id} not found`},partialOutput:void 0});return}_e.providerMetadata=(Nt=Z.providerMetadata)!=null?Nt:_e.providerMetadata,delete Ie[Z.id]}if(Z.type==="file"&&ne.push({type:"file",file:Z.file}),Z.type==="source"&&ne.push(Z),Z.type==="tool-call"&&ne.push(Z),Z.type==="tool-result"&&!Z.preliminary&&ne.push(Z),Z.type==="tool-error"&&ne.push(Z),Z.type==="start-step"&&(ce=Z.request,Pe=Z.warnings),Z.type==="finish-step"){const _e=As({content:ne,tools:u}),Qt=new wc({content:ne,finishReason:Z.finishReason,usage:Z.usage,warnings:Pe,request:ce,response:{...Z.response,messages:[...V,..._e]},providerMetadata:Z.providerMetadata});await(H==null?void 0:H(Qt)),xu(Pe),oe.push(Qt),ne=[],Ie={},ee={},V.push(..._e),Y.resolve()}Z.type==="finish"&&(ae=Z.totalUsage,se=Z.finishReason)},async flush(de){try{if(oe.length===0){const Ye=new bw({message:"No output generated. Check the stream for errors."});Re._finishReason.reject(Ye),Re._totalUsage.reject(Ye),Re._steps.reject(Ye);return}const ve=se??"unknown",$e=ae??{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};Re._finishReason.resolve(ve),Re._totalUsage.resolve($e),Re._steps.resolve(oe);const ie=oe[oe.length-1];await(P==null?void 0:P({finishReason:ve,totalUsage:$e,usage:ie.usage,content:ie.content,text:ie.text,reasoningText:ie.reasoningText,reasoning:ie.reasoning,files:ie.files,sources:ie.sources,toolCalls:ie.toolCalls,staticToolCalls:ie.staticToolCalls,dynamicToolCalls:ie.dynamicToolCalls,toolResults:ie.toolResults,staticToolResults:ie.staticToolResults,dynamicToolResults:ie.dynamicToolResults,request:ie.request,response:ie.response,warnings:ie.warnings,providerMetadata:ie.providerMetadata,steps:oe})),me.setAttributes(dt({telemetry:t,attributes:{"ai.response.finishReason":ve,"ai.response.text":{output:()=>ie.text},"ai.response.toolCalls":{output:()=>{var Ye;return(Ye=ie.toolCalls)!=null&&Ye.length?JSON.stringify(ie.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(ie.providerMetadata),"ai.usage.inputTokens":$e.inputTokens,"ai.usage.outputTokens":$e.outputTokens,"ai.usage.totalTokens":$e.totalTokens,"ai.usage.reasoningTokens":$e.reasoningTokens,"ai.usage.cachedInputTokens":$e.cachedInputTokens}}))}catch(ve){de.error(ve)}finally{me.end()}}}),F=_0();this.addStream=F.addStream,this.closeStream=F.close;const ge=F.stream.getReader();let xe=new ReadableStream({async start(de){de.enqueue({type:"start"})},async pull(de){function ve(){D==null||D({steps:oe}),de.enqueue({type:"abort"}),de.close()}try{const{done:$e,value:ie}=await ge.read();if($e){de.close();return}if(s!=null&&s.aborted){ve();return}de.enqueue(ie)}catch($e){un($e)&&(s!=null&&s.aborted)?ve():de.error($e)}},cancel(de){return F.stream.cancel(de)}});for(const de of x)xe=xe.pipeThrough(de({tools:u,stopStream(){F.terminate()}}));this.baseStream=xe.pipeThrough(T0(y)).pipeThrough(k);const{maxRetries:Ce,retry:_r}=mc({maxRetries:o,abortSignal:s}),wt=dc(t),Ke=Ss(r),wr=cc({model:e,telemetry:t,headers:n,settings:{...Ke,maxRetries:Ce}}),Re=this;In({name:"ai.streamText",attributes:dt({telemetry:t,attributes:{...Sn({operationId:"ai.streamText",telemetry:t}),...wr,"ai.prompt":{input:()=>JSON.stringify({system:a,prompt:i,messages:l})}}}),tracer:wt,endWhenDone:!1,fn:async de=>{me=de;async function ve({currentStep:$e,responseMessages:ie,usage:Ye}){var Nt,Z,_e,Qt,we;const Mt=Re.includeRawChunks;Y=new ao;const br=await lc({system:a,prompt:i,messages:l}),en=[...br.messages,...ie],lt=await(c==null?void 0:c({model:e,steps:oe,stepNumber:oe.length,messages:en})),qt=to((Nt=lt==null?void 0:lt.model)!=null?Nt:e),xr=await rc({prompt:{system:(Z=lt==null?void 0:lt.system)!=null?Z:br.system,messages:(_e=lt==null?void 0:lt.messages)!=null?_e:en},supportedUrls:await qt.supportedUrls,download:he}),{toolChoice:Mn,tools:Pn}=oc({tools:u,toolChoice:(Qt=lt==null?void 0:lt.toolChoice)!=null?Qt:p,activeTools:(we=lt==null?void 0:lt.activeTools)!=null?we:w}),{result:{stream:Io,response:Le,request:Bt},doStreamSpan:Vt,startTimestampMs:Wd}=await _r(()=>In({name:"ai.streamText.doStream",attributes:dt({telemetry:t,attributes:{...Sn({operationId:"ai.streamText.doStream",telemetry:t}),...wr,"ai.model.provider":qt.provider,"ai.model.id":qt.modelId,"ai.prompt.messages":{input:()=>pc(xr)},"ai.prompt.tools":{input:()=>Pn==null?void 0:Pn.map(J=>JSON.stringify(J))},"ai.prompt.toolChoice":{input:()=>Mn!=null?JSON.stringify(Mn):void 0},"gen_ai.system":qt.provider,"gen_ai.request.model":qt.modelId,"gen_ai.request.frequency_penalty":Ke.frequencyPenalty,"gen_ai.request.max_tokens":Ke.maxOutputTokens,"gen_ai.request.presence_penalty":Ke.presencePenalty,"gen_ai.request.stop_sequences":Ke.stopSequences,"gen_ai.request.temperature":Ke.temperature,"gen_ai.request.top_k":Ke.topK,"gen_ai.request.top_p":Ke.topP}}),tracer:wt,endWhenDone:!1,fn:async J=>({startTimestampMs:v(),doStreamSpan:J,result:await qt.doStream({...Ke,tools:Pn,toolChoice:Mn,responseFormat:y==null?void 0:y.responseFormat,prompt:xr,providerOptions:m,abortSignal:s,headers:n,includeRawChunks:Mt})})})),aS=b0({tools:u,generatorStream:Io,tracer:wt,telemetry:t,system:a,messages:en,repairToolCall:h,abortSignal:s,experimental_context:K}),iS=Bt??{},Co=[],ya=[];let _a;const wa={};let $n="unknown",bt={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},ba,Kd=!0,Pt={id:R(),timestamp:_(),modelId:e.modelId},Yd="";Re.addStream(aS.pipeThrough(new TransformStream({async transform(J,Ve){var kr,Tr,Eo,Ft;if(J.type==="stream-start"){_a=J.warnings;return}if(Kd){const Xe=v()-Wd;Kd=!1,Vt.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":Xe}),Vt.setAttributes({"ai.response.msToFirstChunk":Xe}),Ve.enqueue({type:"start-step",request:iS,warnings:_a??[]})}const Xd=J.type;switch(Xd){case"text-start":case"text-end":{Ve.enqueue(J);break}case"text-delta":{J.delta.length>0&&(Ve.enqueue({type:"text-delta",id:J.id,text:J.delta,providerMetadata:J.providerMetadata}),Yd+=J.delta);break}case"reasoning-start":case"reasoning-end":{Ve.enqueue(J);break}case"reasoning-delta":{Ve.enqueue({type:"reasoning-delta",id:J.id,text:J.delta,providerMetadata:J.providerMetadata});break}case"tool-call":{Ve.enqueue(J),Co.push(J);break}case"tool-result":{Ve.enqueue(J),J.preliminary||ya.push(J);break}case"tool-error":{Ve.enqueue(J),ya.push(J);break}case"response-metadata":{Pt={id:(kr=J.id)!=null?kr:Pt.id,timestamp:(Tr=J.timestamp)!=null?Tr:Pt.timestamp,modelId:(Eo=J.modelId)!=null?Eo:Pt.modelId};break}case"finish":{bt=J.usage,$n=J.finishReason,ba=J.providerMetadata;const Xe=v()-Wd;Vt.addEvent("ai.stream.finish"),Vt.setAttributes({"ai.response.msToFinish":Xe,"ai.response.avgOutputTokensPerSecond":1e3*((Ft=bt.outputTokens)!=null?Ft:0)/Xe});break}case"file":{Ve.enqueue(J);break}case"source":{Ve.enqueue(J);break}case"tool-input-start":{wa[J.id]=J.toolName;const Xe=u==null?void 0:u[J.toolName];(Xe==null?void 0:Xe.onInputStart)!=null&&await Xe.onInputStart({toolCallId:J.id,messages:en,abortSignal:s,experimental_context:K}),Ve.enqueue({...J,dynamic:(Xe==null?void 0:Xe.type)==="dynamic"});break}case"tool-input-end":{delete wa[J.id],Ve.enqueue(J);break}case"tool-input-delta":{const Xe=wa[J.id],xa=u==null?void 0:u[Xe];(xa==null?void 0:xa.onInputDelta)!=null&&await xa.onInputDelta({inputTextDelta:J.delta,toolCallId:J.id,messages:en,abortSignal:s,experimental_context:K}),Ve.enqueue(J);break}case"error":{Ve.enqueue(J),$n="error";break}case"raw":{Mt&&Ve.enqueue(J);break}default:{const Xe=Xd;throw new Error(`Unknown chunk type: ${Xe}`)}}},async flush(J){const Ve=Co.length>0?JSON.stringify(Co):void 0;try{Vt.setAttributes(dt({telemetry:t,attributes:{"ai.response.finishReason":$n,"ai.response.text":{output:()=>Yd},"ai.response.toolCalls":{output:()=>Ve},"ai.response.id":Pt.id,"ai.response.model":Pt.modelId,"ai.response.timestamp":Pt.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(ba),"ai.usage.inputTokens":bt.inputTokens,"ai.usage.outputTokens":bt.outputTokens,"ai.usage.totalTokens":bt.totalTokens,"ai.usage.reasoningTokens":bt.reasoningTokens,"ai.usage.cachedInputTokens":bt.cachedInputTokens,"gen_ai.response.finish_reasons":[$n],"gen_ai.response.id":Pt.id,"gen_ai.response.model":Pt.modelId,"gen_ai.usage.input_tokens":bt.inputTokens,"gen_ai.usage.output_tokens":bt.outputTokens}}))}catch{}finally{Vt.end()}J.enqueue({type:"finish-step",finishReason:$n,usage:bt,providerMetadata:ba,response:{...Pt,headers:Le==null?void 0:Le.headers}});const kr=hc(Ye,bt);await Y.promise;const Tr=Co.filter(Ft=>Ft.providerExecuted!==!0),Eo=ya.filter(Ft=>Ft.providerExecuted!==!0);if(Tr.length>0&&Eo.length===Tr.length&&!await bc({stopConditions:f,steps:oe})){ie.push(...As({content:oe[oe.length-1].content,tools:u}));try{await ve({currentStep:$e+1,responseMessages:ie,usage:kr})}catch(Ft){J.enqueue({type:"error",error:Ft}),Re.closeStream()}}else J.enqueue({type:"finish",finishReason:$n,totalUsage:kr}),Re.closeStream()}})))}await ve({currentStep:0,responseMessages:[],usage:{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0}})}}).catch(de=>{Re.addStream(new ReadableStream({start(ve){ve.enqueue({type:"error",error:de}),ve.close()}})),Re.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then(e=>e[e.length-1])}get content(){return this.finalStep.then(e=>e.content)}get warnings(){return this.finalStep.then(e=>e.warnings)}get providerMetadata(){return this.finalStep.then(e=>e.providerMetadata)}get text(){return this.finalStep.then(e=>e.text)}get reasoningText(){return this.finalStep.then(e=>e.reasoningText)}get reasoning(){return this.finalStep.then(e=>e.reasoning)}get sources(){return this.finalStep.then(e=>e.sources)}get files(){return this.finalStep.then(e=>e.files)}get toolCalls(){return this.finalStep.then(e=>e.toolCalls)}get staticToolCalls(){return this.finalStep.then(e=>e.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then(e=>e.dynamicToolCalls)}get toolResults(){return this.finalStep.then(e=>e.toolResults)}get staticToolResults(){return this.finalStep.then(e=>e.staticToolResults)}get dynamicToolResults(){return this.finalStep.then(e=>e.dynamicToolResults)}get usage(){return this.finalStep.then(e=>e.usage)}get request(){return this.finalStep.then(e=>e.request)}get response(){return this.finalStep.then(e=>e.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}teeStream(){const[e,t]=this.baseStream.tee();return this.baseStream=t,e}get textStream(){return so(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){e.type==="text-delta"&&t.enqueue(e.text)}})))}get fullStream(){return so(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){t.enqueue(e)}})))}async consumeStream(e){var t;try{await y0({stream:this.fullStream,onError:e==null?void 0:e.onError})}catch(n){(t=e==null?void 0:e.onError)==null||t.call(e,n)}}get experimental_partialOutputStream(){if(this.output==null)throw new wu;return so(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:e},t){e!=null&&t.enqueue(e)}})))}toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:n,messageMetadata:r,sendReasoning:o=!0,sendSources:s=!1,sendStart:a=!0,sendFinish:i=!0,onError:l=yn}={}){const u=t!=null?d0({originalMessages:e,responseMessageId:t}):void 0,p={},x=h=>{var f,y;const m=p[h];return((y=(f=this.tools)==null?void 0:f[m])==null?void 0:y.type)==="dynamic"?!0:void 0},w=this.fullStream.pipeThrough(new TransformStream({transform:async(h,f)=>{const y=r==null?void 0:r({part:h}),m=h.type;switch(m){case"text-start":{f.enqueue({type:"text-start",id:h.id,...h.providerMetadata!=null?{providerMetadata:h.providerMetadata}:{}});break}case"text-delta":{f.enqueue({type:"text-delta",id:h.id,delta:h.text,...h.providerMetadata!=null?{providerMetadata:h.providerMetadata}:{}});break}case"text-end":{f.enqueue({type:"text-end",id:h.id,...h.providerMetadata!=null?{providerMetadata:h.providerMetadata}:{}});break}case"reasoning-start":{f.enqueue({type:"reasoning-start",id:h.id,...h.providerMetadata!=null?{providerMetadata:h.providerMetadata}:{}});break}case"reasoning-delta":{o&&f.enqueue({type:"reasoning-delta",id:h.id,delta:h.text,...h.providerMetadata!=null?{providerMetadata:h.providerMetadata}:{}});break}case"reasoning-end":{f.enqueue({type:"reasoning-end",id:h.id,...h.providerMetadata!=null?{providerMetadata:h.providerMetadata}:{}});break}case"file":{f.enqueue({type:"file",mediaType:h.file.mediaType,url:`data:${h.file.mediaType};base64,${h.file.base64}`});break}case"source":{s&&h.sourceType==="url"&&f.enqueue({type:"source-url",sourceId:h.id,url:h.url,title:h.title,...h.providerMetadata!=null?{providerMetadata:h.providerMetadata}:{}}),s&&h.sourceType==="document"&&f.enqueue({type:"source-document",sourceId:h.id,mediaType:h.mediaType,title:h.title,filename:h.filename,...h.providerMetadata!=null?{providerMetadata:h.providerMetadata}:{}});break}case"tool-input-start":{p[h.id]=h.toolName;const c=x(h.id);f.enqueue({type:"tool-input-start",toolCallId:h.id,toolName:h.toolName,...h.providerExecuted!=null?{providerExecuted:h.providerExecuted}:{},...c!=null?{dynamic:c}:{}});break}case"tool-input-delta":{f.enqueue({type:"tool-input-delta",toolCallId:h.id,inputTextDelta:h.delta});break}case"tool-call":{p[h.toolCallId]=h.toolName;const c=x(h.toolCallId);h.invalid?f.enqueue({type:"tool-input-error",toolCallId:h.toolCallId,toolName:h.toolName,input:h.input,...h.providerExecuted!=null?{providerExecuted:h.providerExecuted}:{},...h.providerMetadata!=null?{providerMetadata:h.providerMetadata}:{},...c!=null?{dynamic:c}:{},errorText:l(h.error)}):f.enqueue({type:"tool-input-available",toolCallId:h.toolCallId,toolName:h.toolName,input:h.input,...h.providerExecuted!=null?{providerExecuted:h.providerExecuted}:{},...h.providerMetadata!=null?{providerMetadata:h.providerMetadata}:{},...c!=null?{dynamic:c}:{}});break}case"tool-result":{const c=x(h.toolCallId);f.enqueue({type:"tool-output-available",toolCallId:h.toolCallId,output:h.output,...h.providerExecuted!=null?{providerExecuted:h.providerExecuted}:{},...h.preliminary!=null?{preliminary:h.preliminary}:{},...c!=null?{dynamic:c}:{}});break}case"tool-error":{const c=x(h.toolCallId);f.enqueue({type:"tool-output-error",toolCallId:h.toolCallId,errorText:l(h.error),...h.providerExecuted!=null?{providerExecuted:h.providerExecuted}:{},...c!=null?{dynamic:c}:{}});break}case"error":{f.enqueue({type:"error",errorText:l(h.error)});break}case"start-step":{f.enqueue({type:"start-step"});break}case"finish-step":{f.enqueue({type:"finish-step"});break}case"start":{a&&f.enqueue({type:"start",...y!=null?{messageMetadata:y}:{},...u!=null?{messageId:u}:{}});break}case"finish":{i&&f.enqueue({type:"finish",...y!=null?{messageMetadata:y}:{}});break}case"abort":{f.enqueue(h);break}case"tool-input-end":break;case"raw":break;default:{const c=m;throw new Error(`Unknown chunk type: ${c}`)}}y!=null&&m!=="start"&&m!=="finish"&&f.enqueue({type:"message-metadata",messageMetadata:y})}}));return so(g0({stream:w,messageId:u??(t==null?void 0:t()),originalMessages:e,onFinish:n,onError:l}))}pipeUIMessageStreamToResponse(e,{originalMessages:t,generateMessageId:n,onFinish:r,messageMetadata:o,sendReasoning:s,sendSources:a,sendFinish:i,sendStart:l,onError:u,...p}={}){v0({response:e,stream:this.toUIMessageStream({originalMessages:t,generateMessageId:n,onFinish:r,messageMetadata:o,sendReasoning:s,sendSources:a,sendFinish:i,sendStart:l,onError:u}),...p})}pipeTextStreamToResponse(e,t){u0({response:e,textStream:this.textStream,...t})}toUIMessageStreamResponse({originalMessages:e,generateMessageId:t,onFinish:n,messageMetadata:r,sendReasoning:o,sendSources:s,sendFinish:a,sendStart:i,onError:l,...u}={}){return c0({stream:this.toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:n,messageMetadata:r,sendReasoning:o,sendSources:s,sendFinish:a,sendStart:i,onError:l}),...u})}toTextStreamResponse(e){return l0({textStream:this.textStream,...e})}};Kn({prefix:"aiobj",size:24}),Kn({prefix:"aiobj",size:24});var I0={};dw(I0,{object:()=>E0,text:()=>C0});var C0=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),E0=({schema:e})=>{const t=Wr(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await Ec(n);switch(r.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:r.value};default:{const o=r.state;throw new Error(`Unsupported parse state: ${o}`)}}},async parseOutput({text:n},r){const o=await cn({text:n});if(!o.success)throw new $u({message:"No object generated: could not parse the response.",cause:o.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});const s=await gt({value:o.value,schema:t});if(!s.success)throw new $u({message:"No object generated: response did not match schema.",cause:s.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});return s.value}}},Oc="2025-06-18",R0=[Oc,"2025-03-26","2024-11-05"],A0=_n({name:d(),version:d()}),Ns=_n({_meta:Ne(g({}).loose())}),cr=Ns,O0=g({method:d(),params:Ne(Ns)}),N0=_n({experimental:Ne(g({}).loose()),logging:Ne(g({}).loose()),prompts:Ne(_n({listChanged:Ne(Ae())})),resources:Ne(_n({subscribe:Ne(Ae()),listChanged:Ne(Ae())})),tools:Ne(_n({listChanged:Ne(Ae())}))}),M0=cr.extend({protocolVersion:d(),capabilities:N0,serverInfo:A0,instructions:Ne(d())}),P0=cr.extend({nextCursor:Ne(d())}),$0=g({name:d(),description:Ne(d()),inputSchema:g({type:A("object"),properties:Ne(g({}).loose())}).loose()}).loose(),z0=P0.extend({tools:z($0)}),j0=g({type:A("text"),text:d()}).loose(),D0=g({type:A("image"),data:Hi(),mimeType:d()}).loose(),Nc=g({uri:d(),mimeType:Ne(d())}).loose(),U0=Nc.extend({text:d()}),Z0=Nc.extend({blob:Hi()}),L0=g({type:A("resource"),resource:ue([U0,Z0])}).loose(),q0=cr.extend({content:z(ue([j0,D0,L0])),isError:Ae().default(!1).optional()}).or(cr.extend({toolResult:mt()})),io="2.0",B0=g({jsonrpc:A(io),id:ue([d(),I().int()])}).merge(O0).strict(),V0=g({jsonrpc:A(io),id:ue([d(),I().int()]),result:cr}).strict(),F0=g({jsonrpc:A(io),id:ue([d(),I().int()]),error:g({code:I().int(),message:d(),data:Ne(mt())})}).strict(),H0=g({jsonrpc:A(io)}).merge(g({method:d(),params:Ne(Ns)})).strict(),J0=ue([B0,H0,V0,F0]),G0=class{constructor({url:e,headers:t}){this.connected=!1,this.url=new URL(e),this.headers=t}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController,(async()=>{var r,o,s;try{const a=Lt({...this.headers,Accept:"text/event-stream"},`ai-sdk/${no}`,Yn()),i=await fetch(this.url.href,{headers:a,signal:(r=this.abortController)==null?void 0:r.signal});if(!i.ok||!i.body){const x=new Ze({message:`MCP SSE Transport Error: ${i.status} ${i.statusText}`});return(o=this.onerror)==null||o.call(this,x),t(x)}const u=i.body.pipeThrough(new TextDecoderStream).pipeThrough(new Oo).getReader(),p=async()=>{var x,w,h;try{for(;;){const{done:f,value:y}=await u.read();if(f){if(this.connected)throw this.connected=!1,new Ze({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 Ze({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=J0.parse(JSON.parse(c));(x=this.onmessage)==null||x.call(this,b)}catch(b){const v=new Ze({message:"MCP SSE Transport Error: Failed to parse message",cause:b});(w=this.onerror)==null||w.call(this,v)}}}catch(f){if(f instanceof Error&&f.name==="AbortError")return;(h=this.onerror)==null||h.call(this,f),t(f)}};this.sseConnection={close:()=>u.cancel()},p()}catch(a){if(a instanceof Error&&a.name==="AbortError")return;(s=this.onerror)==null||s.call(this,a),t(a)}})()})}async close(){var e,t,n;this.connected=!1,(e=this.sseConnection)==null||e.close(),(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e){var t,n,r;if(!this.endpoint||!this.connected)throw new Ze({message:"MCP SSE Transport Error: Not connected"});try{const s={method:"POST",headers:Lt({...this.headers,"Content-Type":"application/json"},`ai-sdk/${no}`,Yn()),body:JSON.stringify(e),signal:(t=this.abortController)==null?void 0:t.signal},a=await fetch(this.endpoint,s);if(!a.ok){const i=await a.text().catch(()=>null),l=new Ze({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${a.status}): ${i}`});(n=this.onerror)==null||n.call(this,l);return}}catch(o){(r=this.onerror)==null||r.call(this,o);return}}};function W0(e){if(e.type!=="sse")throw new Ze({message:"Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface."});return new G0(e)}function K0(e){return"start"in e&&typeof e.start=="function"&&"send"in e&&typeof e.send=="function"&&"close"in e&&typeof e.close=="function"}var Y0="1.0.0";async function X0(e){const t=new Q0(e);return await t.init(),t}var Q0=class{constructor({transport:e,name:t="ai-sdk-mcp-client",onUncaughtError:n}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this.isClosed=!0,this.onUncaughtError=n,K0(e)?this.transport=e:this.transport=W0(e),this.transport.onclose=()=>this.onClose(),this.transport.onerror=r=>this.onError(r),this.transport.onmessage=r=>{if("method"in r){this.onError(new Ze({message:"Unsupported message type"}));return}this.onResponse(r)},this.clientInfo={name:t,version:Y0}}async init(){try{await this.transport.start(),this.isClosed=!1;const e=await this.request({request:{method:"initialize",params:{protocolVersion:Oc,capabilities:{},clientInfo:this.clientInfo}},resultSchema:M0});if(e===void 0)throw new Ze({message:"Server sent invalid initialize result"});if(!R0.includes(e.protocolVersion))throw new Ze({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 Ze({message:"Server does not support tools"});break;default:throw new Ze({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:n}){return new Promise((r,o)=>{if(this.isClosed)return o(new Ze({message:"Attempted to send a request from a closed client"}));this.assertCapability(e.method);const s=n==null?void 0:n.signal;s==null||s.throwIfAborted();const a=this.requestMessageId++,i={...e,jsonrpc:"2.0",id:a},l=()=>{this.responseHandlers.delete(a)};this.responseHandlers.set(a,u=>{if(s!=null&&s.aborted)return o(new Ze({message:"Request was aborted",cause:s.reason}));if(u instanceof Error)return o(u);try{const p=t.parse(u.result);r(p)}catch(p){const x=new Ze({message:"Failed to parse server response",cause:p});o(x)}}),this.transport.send(i).catch(u=>{l(),o(u)})})}async listTools({params:e,options:t}={}){try{return this.request({request:{method:"tools/list",params:e},resultSchema:z0,options:t})}catch(n){throw n}}async callTool({name:e,args:t,options:n}){try{return this.request({request:{method:"tools/call",params:{name:e,arguments:t}},resultSchema:q0,options:{signal:n==null?void 0:n.abortSignal}})}catch(r){throw r}}async notification(e){const t={...e,jsonrpc:"2.0"};await this.transport.send(t)}async tools({schemas:e="automatic"}={}){var t;const n={};try{const r=await this.listTools();for(const{name:o,description:s,inputSchema:a}of r.tools){if(e!=="automatic"&&!(o in e))continue;const i=this,l=async(p,x)=>{var w;return(w=x==null?void 0:x.abortSignal)==null||w.throwIfAborted(),i.callTool({name:o,args:p,options:x})},u=e==="automatic"?_l({description:s,inputSchema:er({...a,properties:(t=a.properties)!=null?t:{},additionalProperties:!1}),execute:l}):{description:s,inputSchema:e[o].inputSchema,execute:l};n[o]=u}return n}catch(r){throw r}}onClose(){if(this.isClosed)return;this.isClosed=!0;const e=new Ze({message:"Connection closed"});for(const t of this.responseHandlers.values())t(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){const t=Number(e.id),n=this.responseHandlers.get(t);if(n===void 0)throw new Ze({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),n("result"in e?e:new Ze({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}};const Mc="2025-06-18",lo="2.0",Pc=Je([S(),Ue().int()]),$c=S(),eb=$({progressToken:O(Pc)}).passthrough(),pt=$({_meta:O(eb)}).passthrough(),rt=$({method:S(),params:O(pt)}),dr=$({_meta:O($({}).passthrough())}).passthrough(),Rt=$({method:S(),params:O(dr)}),ht=$({_meta:O($({}).passthrough())}).passthrough(),uo=Je([S(),Ue().int()]),zc=$({jsonrpc:X(lo),id:uo}).merge(rt).strict(),tb=e=>zc.safeParse(e).success,nb=$({jsonrpc:X(lo)}).merge(Rt).strict(),jc=$({jsonrpc:X(lo),id:uo,result:ht}).strict(),rb=e=>jc.safeParse(e).success;var Dc;(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"})(Dc||(Dc={}));const ob=$({jsonrpc:X(lo),id:uo,error:$({code:Ue().int(),message:S(),data:O(Gn())})}).strict(),co=Je([zc,nb,jc,ob]),Uc=ht.strict(),Zc=Rt.extend({method:X("notifications/cancelled"),params:dr.extend({requestId:uo,reason:S().optional()})}),sb=$({src:S(),mimeType:O(S()),sizes:O(L(S()))}).passthrough(),pr=$({icons:L(sb).optional()}).passthrough(),hr=$({name:S(),title:O(S())}).passthrough(),Lc=hr.extend({version:S(),websiteUrl:O(S())}).merge(pr),ab=$({experimental:O($({}).passthrough()),sampling:O($({}).passthrough()),elicitation:O($({}).passthrough()),roots:O($({listChanged:O(je())}).passthrough())}).passthrough(),ib=rt.extend({method:X("initialize"),params:pt.extend({protocolVersion:S(),capabilities:ab,clientInfo:Lc})}),lb=$({experimental:O($({}).passthrough()),logging:O($({}).passthrough()),completions:O($({}).passthrough()),prompts:O($({listChanged:O(je())}).passthrough()),resources:O($({subscribe:O(je()),listChanged:O(je())}).passthrough()),tools:O($({listChanged:O(je())}).passthrough())}).passthrough(),ub=ht.extend({protocolVersion:S(),capabilities:lb,serverInfo:Lc,instructions:O(S())}),qc=Rt.extend({method:X("notifications/initialized")}),cb=e=>qc.safeParse(e).success,Bc=rt.extend({method:X("ping")}),db=$({progress:Ue(),total:O(Ue()),message:O(S())}).passthrough(),Vc=Rt.extend({method:X("notifications/progress"),params:dr.merge(db).extend({progressToken:Pc})}),po=rt.extend({params:pt.extend({cursor:O($c)}).optional()}),ho=ht.extend({nextCursor:O($c)}),Fc=$({uri:S(),mimeType:O(S()),_meta:O($({}).passthrough())}).passthrough(),Hc=Fc.extend({text:S()}),Ms=S().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Jc=Fc.extend({blob:Ms}),Gc=hr.extend({uri:S(),description:O(S()),mimeType:O(S()),_meta:O($({}).passthrough())}).merge(pr),pb=hr.extend({uriTemplate:S(),description:O(S()),mimeType:O(S()),_meta:O($({}).passthrough())}).merge(pr),hb=po.extend({method:X("resources/list")}),fb=ho.extend({resources:L(Gc)}),mb=po.extend({method:X("resources/templates/list")}),gb=ho.extend({resourceTemplates:L(pb)}),vb=rt.extend({method:X("resources/read"),params:pt.extend({uri:S()})}),yb=ht.extend({contents:L(Je([Hc,Jc]))}),_b=Rt.extend({method:X("notifications/resources/list_changed")}),wb=rt.extend({method:X("resources/subscribe"),params:pt.extend({uri:S()})}),bb=rt.extend({method:X("resources/unsubscribe"),params:pt.extend({uri:S()})}),xb=Rt.extend({method:X("notifications/resources/updated"),params:dr.extend({uri:S()})}),kb=$({name:S(),description:O(S()),required:O(je())}).passthrough(),Tb=hr.extend({description:O(S()),arguments:O(L(kb)),_meta:O($({}).passthrough())}).merge(pr),Sb=po.extend({method:X("prompts/list")}),Ib=ho.extend({prompts:L(Tb)}),Cb=rt.extend({method:X("prompts/get"),params:pt.extend({name:S(),arguments:O(Wn(S()))})}),Ps=$({type:X("text"),text:S(),_meta:O($({}).passthrough())}).passthrough(),$s=$({type:X("image"),data:Ms,mimeType:S(),_meta:O($({}).passthrough())}).passthrough(),zs=$({type:X("audio"),data:Ms,mimeType:S(),_meta:O($({}).passthrough())}).passthrough(),Eb=$({type:X("resource"),resource:Je([Hc,Jc]),_meta:O($({}).passthrough())}).passthrough(),Rb=Gc.extend({type:X("resource_link")}),Wc=Je([Ps,$s,zs,Rb,Eb]),Ab=$({role:Zt(["user","assistant"]),content:Wc}).passthrough(),Ob=ht.extend({description:O(S()),messages:L(Ab)}),Nb=Rt.extend({method:X("notifications/prompts/list_changed")}),Mb=$({title:O(S()),readOnlyHint:O(je()),destructiveHint:O(je()),idempotentHint:O(je()),openWorldHint:O(je())}).passthrough(),Pb=hr.extend({description:O(S()),inputSchema:$({type:X("object"),properties:O($({}).passthrough()),required:O(L(S()))}).passthrough(),outputSchema:O($({type:X("object"),properties:O($({}).passthrough()),required:O(L(S()))}).passthrough()),annotations:O(Mb),_meta:O($({}).passthrough())}).merge(pr),$b=po.extend({method:X("tools/list")}),zb=ho.extend({tools:L(Pb)}),Kc=ht.extend({content:L(Wc).default([]),structuredContent:$({}).passthrough().optional(),isError:O(je())});Kc.or(ht.extend({toolResult:Gn()}));const jb=rt.extend({method:X("tools/call"),params:pt.extend({name:S(),arguments:O(Wn(Gn()))})}),Db=Rt.extend({method:X("notifications/tools/list_changed")}),Yc=Zt(["debug","info","notice","warning","error","critical","alert","emergency"]),Ub=rt.extend({method:X("logging/setLevel"),params:pt.extend({level:Yc})}),Zb=Rt.extend({method:X("notifications/message"),params:dr.extend({level:Yc,logger:O(S()),data:Gn()})}),Lb=$({name:S().optional()}).passthrough(),qb=$({hints:O(L(Lb)),costPriority:O(Ue().min(0).max(1)),speedPriority:O(Ue().min(0).max(1)),intelligencePriority:O(Ue().min(0).max(1))}).passthrough(),Bb=$({role:Zt(["user","assistant"]),content:Je([Ps,$s,zs])}).passthrough(),Vb=rt.extend({method:X("sampling/createMessage"),params:pt.extend({messages:L(Bb),systemPrompt:O(S()),includeContext:O(Zt(["none","thisServer","allServers"])),temperature:O(Ue()),maxTokens:Ue().int(),stopSequences:O(L(S())),metadata:O($({}).passthrough()),modelPreferences:O(qb)})}),Fb=ht.extend({model:S(),stopReason:O(Zt(["endTurn","stopSequence","maxTokens"]).or(S())),role:Zt(["user","assistant"]),content:Wg("type",[Ps,$s,zs])}),Hb=$({type:X("boolean"),title:O(S()),description:O(S()),default:O(je())}).passthrough(),Jb=$({type:X("string"),title:O(S()),description:O(S()),minLength:O(Ue()),maxLength:O(Ue()),format:O(Zt(["email","uri","date","date-time"]))}).passthrough(),Gb=$({type:Zt(["number","integer"]),title:O(S()),description:O(S()),minimum:O(Ue()),maximum:O(Ue())}).passthrough(),Wb=$({type:X("string"),title:O(S()),description:O(S()),enum:L(S()),enumNames:O(L(S()))}).passthrough(),Kb=Je([Hb,Jb,Gb,Wb]),Yb=rt.extend({method:X("elicitation/create"),params:pt.extend({message:S(),requestedSchema:$({type:X("object"),properties:Wn(S(),Kb),required:O(L(S()))}).passthrough()})}),Xb=ht.extend({action:Zt(["accept","decline","cancel"]),content:O(Wn(S(),Gn()))}),Qb=$({type:X("ref/resource"),uri:S()}).passthrough(),ex=$({type:X("ref/prompt"),name:S()}).passthrough(),tx=rt.extend({method:X("completion/complete"),params:pt.extend({ref:Je([ex,Qb]),argument:$({name:S(),value:S()}).passthrough(),context:O($({arguments:O(Wn(S(),S()))}))})}),nx=ht.extend({completion:$({values:L(S()).max(100),total:O(Ue().int()),hasMore:O(je())}).passthrough()}),rx=$({uri:S().startsWith("file://"),name:O(S()),_meta:O($({}).passthrough())}).passthrough(),ox=rt.extend({method:X("roots/list")}),sx=ht.extend({roots:L(rx)}),ax=Rt.extend({method:X("notifications/roots/list_changed")});Je([Bc,ib,tx,Ub,Cb,Sb,hb,mb,vb,wb,bb,jb,$b]),Je([Zc,Vc,qc,ax]),Je([Uc,Fb,Xb,sx]),Je([Bc,Vb,Yb,ox]),Je([Zc,Vc,Zb,xb,_b,Db,Nb]),Je([Uc,ub,nx,Ob,Ib,fb,gb,yb,Kc,zb]);let js;js=globalThis.crypto;async function ix(e){return(await js).getRandomValues(new Uint8Array(e))}async function lx(e){const t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";let n="";const r=await ix(e);for(let o=0;o<e;o++){const s=r[o]%t.length;n+=t[s]}return n}async function ux(e){return await lx(e)}async function cx(e){const t=await(await js).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function dx(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;const t=await ux(e),n=await cx(t);return{code_verifier:t,code_challenge:n}}const qe=S().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:N.custom,message:"URL must be parseable",fatal:!0}),Kg}).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"}),px=$({resource:S().url(),authorization_servers:L(qe).optional(),jwks_uri:S().url().optional(),scopes_supported:L(S()).optional(),bearer_methods_supported:L(S()).optional(),resource_signing_alg_values_supported:L(S()).optional(),resource_name:S().optional(),resource_documentation:S().optional(),resource_policy_uri:S().url().optional(),resource_tos_uri:S().url().optional(),tls_client_certificate_bound_access_tokens:je().optional(),authorization_details_types_supported:L(S()).optional(),dpop_signing_alg_values_supported:L(S()).optional(),dpop_bound_access_tokens_required:je().optional()}).passthrough(),Xc=$({issuer:S(),authorization_endpoint:qe,token_endpoint:qe,registration_endpoint:qe.optional(),scopes_supported:L(S()).optional(),response_types_supported:L(S()),response_modes_supported:L(S()).optional(),grant_types_supported:L(S()).optional(),token_endpoint_auth_methods_supported:L(S()).optional(),token_endpoint_auth_signing_alg_values_supported:L(S()).optional(),service_documentation:qe.optional(),revocation_endpoint:qe.optional(),revocation_endpoint_auth_methods_supported:L(S()).optional(),revocation_endpoint_auth_signing_alg_values_supported:L(S()).optional(),introspection_endpoint:S().optional(),introspection_endpoint_auth_methods_supported:L(S()).optional(),introspection_endpoint_auth_signing_alg_values_supported:L(S()).optional(),code_challenge_methods_supported:L(S()).optional()}).passthrough(),hx=$({issuer:S(),authorization_endpoint:qe,token_endpoint:qe,userinfo_endpoint:qe.optional(),jwks_uri:qe,registration_endpoint:qe.optional(),scopes_supported:L(S()).optional(),response_types_supported:L(S()),response_modes_supported:L(S()).optional(),grant_types_supported:L(S()).optional(),acr_values_supported:L(S()).optional(),subject_types_supported:L(S()),id_token_signing_alg_values_supported:L(S()),id_token_encryption_alg_values_supported:L(S()).optional(),id_token_encryption_enc_values_supported:L(S()).optional(),userinfo_signing_alg_values_supported:L(S()).optional(),userinfo_encryption_alg_values_supported:L(S()).optional(),userinfo_encryption_enc_values_supported:L(S()).optional(),request_object_signing_alg_values_supported:L(S()).optional(),request_object_encryption_alg_values_supported:L(S()).optional(),request_object_encryption_enc_values_supported:L(S()).optional(),token_endpoint_auth_methods_supported:L(S()).optional(),token_endpoint_auth_signing_alg_values_supported:L(S()).optional(),display_values_supported:L(S()).optional(),claim_types_supported:L(S()).optional(),claims_supported:L(S()).optional(),service_documentation:S().optional(),claims_locales_supported:L(S()).optional(),ui_locales_supported:L(S()).optional(),claims_parameter_supported:je().optional(),request_parameter_supported:je().optional(),request_uri_parameter_supported:je().optional(),require_request_uri_registration:je().optional(),op_policy_uri:qe.optional(),op_tos_uri:qe.optional()}).passthrough().merge(Xc.pick({code_challenge_methods_supported:!0})),Qc=$({access_token:S(),id_token:S().optional(),token_type:S(),expires_in:Ue().optional(),scope:S().optional(),refresh_token:S().optional()}).strip(),fx=$({error:S(),error_description:S().optional(),error_uri:S().optional()}),ed=qe.optional().or(X("").transform(()=>{})),mx=$({redirect_uris:L(qe),token_endpoint_auth_method:S().optional(),grant_types:L(S()).optional(),response_types:L(S()).optional(),client_name:S().optional(),client_uri:qe.optional(),logo_uri:ed,scope:S().optional(),contacts:L(S()).optional(),tos_uri:ed,policy_uri:S().optional(),jwks_uri:qe.optional(),jwks:Gg().optional(),software_id:S().optional(),software_version:S().optional(),software_statement:S().optional()}).strip(),gx=$({client_id:S(),client_secret:S().optional(),client_id_issued_at:Ue().optional(),client_secret_expires_at:Ue().optional()}).strip(),vx=mx.merge(gx);$({error:S(),error_description:S().optional()}).strip(),$({token:S(),token_type_hint:S().optional()}).strip();function yx(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function _x({requestedResource:e,configuredResource:t}){const n=typeof e=="string"?new URL(e):new URL(e.href),r=typeof t=="string"?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length<r.pathname.length)return!1;const o=n.pathname.endsWith("/")?n.pathname:n.pathname+"/",s=r.pathname.endsWith("/")?r.pathname:r.pathname+"/";return o.startsWith(s)}class Be extends Error{constructor(t,n){super(t),this.errorUri=n,this.name=this.constructor.name}toResponseObject(){const t={error:this.errorCode,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}get errorCode(){return this.constructor.errorCode}}class Ds extends Be{}Ds.errorCode="invalid_request";class fo extends Be{}fo.errorCode="invalid_client";class mo extends Be{}mo.errorCode="invalid_grant";class go extends Be{}go.errorCode="unauthorized_client";class Us extends Be{}Us.errorCode="unsupported_grant_type";class Zs extends Be{}Zs.errorCode="invalid_scope";class Ls extends Be{}Ls.errorCode="access_denied";class Cn extends Be{}Cn.errorCode="server_error";class qs extends Be{}qs.errorCode="temporarily_unavailable";class Bs extends Be{}Bs.errorCode="unsupported_response_type";class Vs extends Be{}Vs.errorCode="unsupported_token_type";class Fs extends Be{}Fs.errorCode="invalid_token";class Hs extends Be{}Hs.errorCode="method_not_allowed";class Js extends Be{}Js.errorCode="too_many_requests";class Gs extends Be{}Gs.errorCode="invalid_client_metadata";class Ws extends Be{}Ws.errorCode="insufficient_scope";const wx={[Ds.errorCode]:Ds,[fo.errorCode]:fo,[mo.errorCode]:mo,[go.errorCode]:go,[Us.errorCode]:Us,[Zs.errorCode]:Zs,[Ls.errorCode]:Ls,[Cn.errorCode]:Cn,[qs.errorCode]:qs,[Bs.errorCode]:Bs,[Vs.errorCode]:Vs,[Fs.errorCode]:Fs,[Hs.errorCode]:Hs,[Js.errorCode]:Js,[Gs.errorCode]:Gs,[Ws.errorCode]:Ws};class fr extends Error{constructor(t){super(t??"Unauthorized")}}const Ks="code",Ys="S256";function td(e,t){const n=e.client_secret!==void 0;return t.length===0?n?"client_secret_post":"none":n&&t.includes("client_secret_basic")?"client_secret_basic":n&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":n?"client_secret_post":"none"}function nd(e,t,n,r){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":bx(o,s,n);return;case"client_secret_post":xx(o,s,r);return;case"none":kx(o,r);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function bx(e,t,n){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const r=btoa(`${e}:${t}`);n.set("Authorization",`Basic ${r}`)}function xx(e,t,n){n.set("client_id",e),t&&n.set("client_secret",t)}function kx(e,t){t.set("client_id",e)}async function Xs(e){const t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{const r=fx.parse(JSON.parse(n)),{error:o,error_description:s,error_uri:a}=r,i=wx[o]||Cn;return new i(s||"",a)}catch(r){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${r}. Raw body: ${n}`;return new Cn(o)}}async function Qs(e,t){var n,r;try{return await ea(e,t)}catch(o){if(o instanceof fo||o instanceof go)return await((n=e.invalidateCredentials)===null||n===void 0?void 0:n.call(e,"all")),await ea(e,t);if(o instanceof mo)return await((r=e.invalidateCredentials)===null||r===void 0?void 0:r.call(e,"tokens")),await ea(e,t);throw o}}async function ea(e,{serverUrl:t,authorizationCode:n,scope:r,resourceMetadataUrl:o,fetchFn:s}){let a,i;try{a=await Ix(t,{resourceMetadataUrl:o},s),a.authorization_servers&&a.authorization_servers.length>0&&(i=a.authorization_servers[0])}catch{}i||(i=t);const l=await Tx(t,e,a),u=await Ox(i,{fetchFn:s});let p=await Promise.resolve(e.clientInformation());if(!p){if(n!==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 y=await $x(i,{metadata:u,clientMetadata:e.clientMetadata,fetchFn:s});await e.saveClientInformation(y),p=y}if(n!==void 0){const y=await e.codeVerifier(),m=await Mx(i,{metadata:u,clientInformation:p,authorizationCode:n,codeVerifier:y,redirectUri:e.redirectUrl,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(m),"AUTHORIZED"}const x=await e.tokens();if(x!=null&&x.refresh_token)try{const y=await Px(i,{metadata:u,clientInformation:p,refreshToken:x.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(y),"AUTHORIZED"}catch(y){if(!(!(y instanceof Be)||y instanceof Cn))throw y}const w=e.state?await e.state():void 0,{authorizationUrl:h,codeVerifier:f}=await Nx(i,{metadata:u,clientInformation:p,state:w,redirectUrl:e.redirectUrl,scope:r||e.clientMetadata.scope,resource:l});return await e.saveCodeVerifier(f),await e.redirectToAuthorization(h),"REDIRECT"}async function Tx(e,t,n){const r=yx(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n==null?void 0:n.resource);if(n){if(!_x({requestedResource:r,configuredResource:n.resource}))throw new Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}function Sx(e){const t=e.headers.get("WWW-Authenticate");if(!t)return;const[n,r]=t.split(" ");if(n.toLowerCase()!=="bearer"||!r)return;const s=/resource_metadata="([^"]*)"/.exec(t);if(s)try{return new URL(s[1])}catch{return}}async function Ix(e,t,n=fetch){const r=await Rx(e,"oauth-protected-resource",n,{protocolVersion:t==null?void 0:t.protocolVersion,metadataUrl:t==null?void 0:t.resourceMetadataUrl});if(!r||r.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!r.ok)throw new Error(`HTTP ${r.status} trying to load well-known OAuth protected resource metadata.`);return px.parse(await r.json())}async function ta(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?ta(e,void 0,n):void 0;throw r}}function Cx(e,t="",n={}){return t.endsWith("/")&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function rd(e,t,n=fetch){return await ta(e,{"MCP-Protocol-Version":t},n)}function Ex(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function Rx(e,t,n,r){var o,s;const a=new URL(e),i=(o=r==null?void 0:r.protocolVersion)!==null&&o!==void 0?o:Mc;let l;if(r!=null&&r.metadataUrl)l=new URL(r.metadataUrl);else{const p=Cx(t,a.pathname);l=new URL(p,(s=r==null?void 0:r.metadataServerUrl)!==null&&s!==void 0?s:a),l.search=a.search}let u=await rd(l,i,n);if(!(r!=null&&r.metadataUrl)&&Ex(u,a.pathname)){const p=new URL(`/.well-known/${t}`,a);u=await rd(p,i,n)}return u}function Ax(e){const t=typeof e=="string"?new URL(e):e,n=t.pathname!=="/",r=[];if(!n)return r.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),r.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),r;let o=t.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),r.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,t.origin),type:"oauth"}),r.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),r.push({url:new URL(`/.well-known/openid-configuration${o}`,t.origin),type:"oidc"}),r.push({url:new URL(`${o}/.well-known/openid-configuration`,t.origin),type:"oidc"}),r}async function Ox(e,{fetchFn:t=fetch,protocolVersion:n=Mc}={}){const r={"MCP-Protocol-Version":n,Accept:"application/json"},o=Ax(e);for(const{url:s,type:a}of o){const i=await ta(s,r,t);if(i){if(!i.ok){if(i.status>=400&&i.status<500)continue;throw new Error(`HTTP ${i.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${s}`)}return a==="oauth"?Xc.parse(await i.json()):hx.parse(await i.json())}}}async function Nx(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:o,state:s,resource:a}){let i;if(t){if(i=new URL(t.authorization_endpoint),!t.response_types_supported.includes(Ks))throw new Error(`Incompatible auth server: does not support response type ${Ks}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Ys))throw new Error(`Incompatible auth server: does not support code challenge method ${Ys}`)}else i=new URL("/authorize",e);const l=await dx(),u=l.code_verifier,p=l.code_challenge;return i.searchParams.set("response_type",Ks),i.searchParams.set("client_id",n.client_id),i.searchParams.set("code_challenge",p),i.searchParams.set("code_challenge_method",Ys),i.searchParams.set("redirect_uri",String(r)),s&&i.searchParams.set("state",s),o&&i.searchParams.set("scope",o),o!=null&&o.includes("offline_access")&&i.searchParams.append("prompt","consent"),a&&i.searchParams.set("resource",a.href),{authorizationUrl:i,codeVerifier:u}}async function Mx(e,{metadata:t,clientInformation:n,authorizationCode:r,codeVerifier:o,redirectUri:s,resource:a,addClientAuthentication:i,fetchFn:l}){var u;const p="authorization_code",x=t!=null&&t.token_endpoint?new URL(t.token_endpoint):new URL("/token",e);if(t!=null&&t.grant_types_supported&&!t.grant_types_supported.includes(p))throw new Error(`Incompatible auth server: does not support grant type ${p}`);const w=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),h=new URLSearchParams({grant_type:p,code:r,code_verifier:o,redirect_uri:String(s)});if(i)i(w,h,e,t);else{const y=(u=t==null?void 0:t.token_endpoint_auth_methods_supported)!==null&&u!==void 0?u:[],m=td(n,y);nd(m,n,w,h)}a&&h.set("resource",a.href);const f=await(l??fetch)(x,{method:"POST",headers:w,body:h});if(!f.ok)throw await Xs(f);return Qc.parse(await f.json())}async function Px(e,{metadata:t,clientInformation:n,refreshToken:r,resource:o,addClientAuthentication:s,fetchFn:a}){var i;const l="refresh_token";let u;if(t){if(u=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 u=new URL("/token",e);const p=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),x=new URLSearchParams({grant_type:l,refresh_token:r});if(s)s(p,x,e,t);else{const h=(i=t==null?void 0:t.token_endpoint_auth_methods_supported)!==null&&i!==void 0?i:[],f=td(n,h);nd(f,n,p,x)}o&&x.set("resource",o.href);const w=await(a??fetch)(u,{method:"POST",headers:p,body:x});if(!w.ok)throw await Xs(w);return Qc.parse({refresh_token:r,...await w.json()})}async function $x(e,{metadata:t,clientMetadata:n,fetchFn:r}){let o;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");o=new URL(t.registration_endpoint)}else o=new URL("/register",e);const s=await(r??fetch)(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!s.ok)throw await Xs(s);return vx.parse(await s.json())}const zx={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class vo extends Error{constructor(t,n){super(`Streamable HTTP error: ${n}`),this.code=t}}class jx{constructor(t,n){var r;this._hasCompletedAuthFlow=!1,this._url=t,this._resourceMetadataUrl=void 0,this._requestInit=n==null?void 0:n.requestInit,this._authProvider=n==null?void 0:n.authProvider,this._fetch=n==null?void 0:n.fetch,this._sessionId=n==null?void 0:n.sessionId,this._reconnectionOptions=(r=n==null?void 0:n.reconnectionOptions)!==null&&r!==void 0?r:zx}async _authThenStart(){var t;if(!this._authProvider)throw new fr("No auth provider");let n;try{n=await Qs(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(r){throw(t=this.onerror)===null||t===void 0||t.call(this,r),r}if(n!=="AUTHORIZED")throw new fr;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var t;const n={};if(this._authProvider){const o=await this._authProvider.tokens();o&&(n.Authorization=`Bearer ${o.access_token}`)}this._sessionId&&(n["mcp-session-id"]=this._sessionId),this._protocolVersion&&(n["mcp-protocol-version"]=this._protocolVersion);const r=this._normalizeHeaders((t=this._requestInit)===null||t===void 0?void 0:t.headers);return new Headers({...n,...r})}async _startOrAuthSse(t){var n,r,o;const{resumptionToken:s}=t;try{const a=await this._commonHeaders();a.set("Accept","text/event-stream"),s&&a.set("last-event-id",s);const i=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._url,{method:"GET",headers:a,signal:(r=this._abortController)===null||r===void 0?void 0:r.signal});if(!i.ok){if(i.status===401&&this._authProvider)return await this._authThenStart();if(i.status===405)return;throw new vo(i.status,`Failed to open SSE stream: ${i.statusText}`)}this._handleSseStream(i.body,t,!0)}catch(a){throw(o=this.onerror)===null||o===void 0||o.call(this,a),a}}_getNextReconnectionDelay(t){const n=this._reconnectionOptions.initialReconnectionDelay,r=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(n*Math.pow(r,t),o)}_normalizeHeaders(t){return t?t instanceof Headers?Object.fromEntries(t.entries()):Array.isArray(t)?Object.fromEntries(t):{...t}:{}}_scheduleReconnection(t,n=0){var r;const o=this._reconnectionOptions.maxRetries;if(o>0&&n>=o){(r=this.onerror)===null||r===void 0||r.call(this,new Error(`Maximum reconnection attempts (${o}) exceeded.`));return}const s=this._getNextReconnectionDelay(n);setTimeout(()=>{this._startOrAuthSse(t).catch(a=>{var i;(i=this.onerror)===null||i===void 0||i.call(this,new Error(`Failed to reconnect SSE stream: ${a instanceof Error?a.message:String(a)}`)),this._scheduleReconnection(t,n+1)})},s)}_handleSseStream(t,n,r){if(!t)return;const{onresumptiontoken:o,replayMessageId:s}=n;let a;(async()=>{var l,u,p,x;try{const w=t.pipeThrough(new TextDecoderStream).pipeThrough(new Oo).getReader();for(;;){const{value:h,done:f}=await w.read();if(f)break;if(h.id&&(a=h.id,o==null||o(h.id)),!h.event||h.event==="message")try{const y=co.parse(JSON.parse(h.data));s!==void 0&&rb(y)&&(y.id=s),(l=this.onmessage)===null||l===void 0||l.call(this,y)}catch(y){(u=this.onerror)===null||u===void 0||u.call(this,y)}}}catch(w){if((p=this.onerror)===null||p===void 0||p.call(this,new Error(`SSE stream disconnected: ${w}`)),r&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:o,replayMessageId:s},0)}catch(h){(x=this.onerror)===null||x===void 0||x.call(this,new Error(`Failed to reconnect: ${h instanceof Error?h.message:String(h)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(t){if(!this._authProvider)throw new fr("No auth provider");if(await Qs(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new fr("Failed to authorize")}async close(){var t,n;(t=this._abortController)===null||t===void 0||t.abort(),(n=this.onclose)===null||n===void 0||n.call(this)}async send(t,n){var r,o,s,a;try{const{resumptionToken:i,onresumptiontoken:l}=n||{};if(i){this._startOrAuthSse({resumptionToken:i,replayMessageId:tb(t)?t.id:void 0}).catch(m=>{var c;return(c=this.onerror)===null||c===void 0?void 0:c.call(this,m)});return}const u=await this._commonHeaders();u.set("content-type","application/json"),u.set("accept","application/json, text/event-stream");const p={...this._requestInit,method:"POST",headers:u,body:JSON.stringify(t),signal:(r=this._abortController)===null||r===void 0?void 0:r.signal},x=await((o=this._fetch)!==null&&o!==void 0?o:fetch)(this._url,p),w=x.headers.get("mcp-session-id");if(w&&(this._sessionId=w),!x.ok){if(x.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new vo(401,"Server returned 401 after successful authentication");if(this._resourceMetadataUrl=Sx(x),await Qs(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new fr;return this._hasCompletedAuthFlow=!0,this.send(t)}const m=await x.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${x.status}): ${m}`)}if(this._hasCompletedAuthFlow=!1,x.status===202){cb(t)&&this._startOrAuthSse({resumptionToken:void 0}).catch(m=>{var c;return(c=this.onerror)===null||c===void 0?void 0:c.call(this,m)});return}const f=(Array.isArray(t)?t:[t]).filter(m=>"method"in m&&"id"in m&&m.id!==void 0).length>0,y=x.headers.get("content-type");if(f)if(y!=null&&y.includes("text/event-stream"))this._handleSseStream(x.body,{onresumptiontoken:l},!1);else if(y!=null&&y.includes("application/json")){const m=await x.json(),c=Array.isArray(m)?m.map(b=>co.parse(b)):[co.parse(m)];for(const b of c)(s=this.onmessage)===null||s===void 0||s.call(this,b)}else throw new vo(-1,`Unexpected content type: ${y}`)}catch(i){throw(a=this.onerror)===null||a===void 0||a.call(this,i),i}}get sessionId(){return this._sessionId}async terminateSession(){var t,n,r;if(this._sessionId)try{const o=await this._commonHeaders(),s={...this._requestInit,method:"DELETE",headers:o,signal:(t=this._abortController)===null||t===void 0?void 0:t.signal},a=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._url,s);if(!a.ok&&a.status!==405)throw new vo(a.status,`Failed to terminate session: ${a.statusText}`);this._sessionId=void 0}catch(o){throw(r=this.onerror)===null||r===void 0||r.call(this,o),o}}setProtocolVersion(t){this._protocolVersion=t}get protocolVersion(){return this._protocolVersion}}var na=g({error:g({message:d(),type:d().nullish(),param:ut().nullish(),code:ue([d(),I()]).nullish()})}),At=dn({errorSchema:na,errorToMessage:e=>e.error.message});function Dx({prompt:e,systemMessageMode:t="system"}){const n=[],r=[];for(const{role:o,content:s}of e)switch(o){case"system":{switch(t){case"system":{n.push({role:"system",content:s});break}case"developer":{n.push({role:"developer",content:s});break}case"remove":{r.push({type:"other",message:"system messages are removed for this model"});break}default:{const a=t;throw new Error(`Unsupported system message mode: ${a}`)}}break}case"user":{if(s.length===1&&s[0].type==="text"){n.push({role:"user",content:s[0].text});break}n.push({role:"user",content:s.map((a,i)=>{var l,u,p;switch(a.type){case"text":return{type:"text",text:a.text};case"file":if(a.mediaType.startsWith("image/")){const x=a.mediaType==="image/*"?"image/jpeg":a.mediaType;return{type:"image_url",image_url:{url:a.data instanceof URL?a.data.toString():`data:${x};base64,${pn(a.data)}`,detail:(u=(l=a.providerOptions)==null?void 0:l.openai)==null?void 0:u.imageDetail}}}else if(a.mediaType.startsWith("audio/")){if(a.data instanceof URL)throw new ft({functionality:"audio file parts with URLs"});switch(a.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:pn(a.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:pn(a.data),format:"mp3"}};default:throw new ft({functionality:`audio content parts with media type ${a.mediaType}`})}}else if(a.mediaType==="application/pdf"){if(a.data instanceof URL)throw new ft({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof a.data=="string"&&a.data.startsWith("file-")?{file_id:a.data}:{filename:(p=a.filename)!=null?p:`part-${i}.pdf`,file_data:`data:application/pdf;base64,${pn(a.data)}`}}}else throw new ft({functionality:`file part media type ${a.mediaType}`})}})});break}case"assistant":{let a="";const i=[];for(const l of s)switch(l.type){case"text":{a+=l.text;break}case"tool-call":{i.push({id:l.toolCallId,type:"function",function:{name:l.toolName,arguments:JSON.stringify(l.input)}});break}}n.push({role:"assistant",content:a,tool_calls:i.length>0?i:void 0});break}case"tool":{for(const a of s){const i=a.output;let l;switch(i.type){case"text":case"error-text":l=i.value;break;case"content":case"json":case"error-json":l=JSON.stringify(i.value);break}n.push({role:"tool",tool_call_id:a.toolCallId,content:l})}break}default:{const a=o;throw new Error(`Unsupported role: ${a}`)}}return{messages:n,warnings:r}}function od({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n!=null?new Date(n*1e3):void 0}}function sd(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 Ux=Ee(()=>te(g({id:d().nullish(),created:I().nullish(),model:d().nullish(),choices:z(g({message:g({role:A("assistant").nullish(),content:d().nullish(),tool_calls:z(g({id:d().nullish(),type:A("function"),function:g({name:d(),arguments:d()})})).nullish(),annotations:z(g({type:A("url_citation"),start_index:I(),end_index:I(),url:d(),title:d()})).nullish()}),index:I(),logprobs:g({content:z(g({token:d(),logprob:I(),top_logprobs:z(g({token:d(),logprob:I()}))})).nullish()}).nullish(),finish_reason:d().nullish()})),usage:g({prompt_tokens:I().nullish(),completion_tokens:I().nullish(),total_tokens:I().nullish(),prompt_tokens_details:g({cached_tokens:I().nullish()}).nullish(),completion_tokens_details:g({reasoning_tokens:I().nullish(),accepted_prediction_tokens:I().nullish(),rejected_prediction_tokens:I().nullish()}).nullish()}).nullish()}))),Zx=Ee(()=>te(ue([g({id:d().nullish(),created:I().nullish(),model:d().nullish(),choices:z(g({delta:g({role:Se(["assistant"]).nullish(),content:d().nullish(),tool_calls:z(g({index:I(),id:d().nullish(),type:A("function").nullish(),function:g({name:d().nullish(),arguments:d().nullish()})})).nullish(),annotations:z(g({type:A("url_citation"),start_index:I(),end_index:I(),url:d(),title:d()})).nullish()}).nullish(),logprobs:g({content:z(g({token:d(),logprob:I(),top_logprobs:z(g({token:d(),logprob:I()}))})).nullish()}).nullish(),finish_reason:d().nullish(),index:I()})),usage:g({prompt_tokens:I().nullish(),completion_tokens:I().nullish(),total_tokens:I().nullish(),prompt_tokens_details:g({cached_tokens:I().nullish()}).nullish(),completion_tokens_details:g({reasoning_tokens:I().nullish(),accepted_prediction_tokens:I().nullish(),rejected_prediction_tokens:I().nullish()}).nullish()}).nullish()}),na]))),Lx=Ee(()=>te(g({logitBias:Oe(xg(),I()).optional(),logprobs:ue([Ae(),I()]).optional(),parallelToolCalls:Ae().optional(),user:d().optional(),reasoningEffort:Se(["minimal","low","medium","high"]).optional(),maxCompletionTokens:I().optional(),store:Ae().optional(),metadata:Oe(d().max(64),d().max(512)).optional(),prediction:Oe(d(),ut()).optional(),structuredOutputs:Ae().optional(),serviceTier:Se(["auto","flex","priority","default"]).optional(),strictJsonSchema:Ae().optional(),textVerbosity:Se(["low","medium","high"]).optional(),promptCacheKey:d().optional(),safetyIdentifier:d().optional()})));function qx({tools:e,toolChoice:t,structuredOutputs:n,strictJsonSchema:r}){e=e!=null&&e.length?e:void 0;const o=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:o};const s=[];for(const i of e)switch(i.type){case"function":s.push({type:"function",function:{name:i.name,description:i.description,parameters:i.inputSchema,strict:n?r:void 0}});break;default:o.push({type:"unsupported-tool",tool:i});break}if(t==null)return{tools:s,toolChoice:void 0,toolWarnings:o};const a=t.type;switch(a){case"auto":case"none":case"required":return{tools:s,toolChoice:a,toolWarnings:o};case"tool":return{tools:s,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:o};default:{const i=a;throw new ft({functionality:`tool choice type: ${i}`})}}}var Bx=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:o,frequencyPenalty:s,presencePenalty:a,stopSequences:i,responseFormat:l,seed:u,tools:p,toolChoice:x,providerOptions:w}){var h,f,y,m;const c=[],b=(h=await St({provider:"openai",providerOptions:w,schema:Lx}))!=null?h:{},v=(f=b.structuredOutputs)!=null?f:!0;o!=null&&c.push({type:"unsupported-setting",setting:"topK"}),(l==null?void 0:l.type)==="json"&&l.schema!=null&&!v&&c.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{messages:_,warnings:R}=Dx({prompt:e,systemMessageMode:Hx(this.modelId)});c.push(...R);const C=(y=b.strictJsonSchema)!=null?y:!1,T={model:this.modelId,logit_bias:b.logitBias,logprobs:b.logprobs===!0||typeof b.logprobs=="number"?!0:void 0,top_logprobs:typeof b.logprobs=="number"?b.logprobs:typeof b.logprobs=="boolean"&&b.logprobs?0:void 0,user:b.user,parallel_tool_calls:b.parallelToolCalls,max_tokens:t,temperature:n,top_p:r,frequency_penalty:s,presence_penalty:a,response_format:(l==null?void 0:l.type)==="json"?v&&l.schema!=null?{type:"json_schema",json_schema:{schema:l.schema,strict:C,name:(m=l.name)!=null?m:"response",description:l.description}}:{type:"json_object"}:void 0,stop:i,seed:u,verbosity:b.textVerbosity,max_completion_tokens:b.maxCompletionTokens,store:b.store,metadata:b.metadata,prediction:b.prediction,reasoning_effort:b.reasoningEffort,service_tier:b.serviceTier,prompt_cache_key:b.promptCacheKey,safety_identifier:b.safetyIdentifier,messages:_};ad(this.modelId)?(T.temperature!=null&&(T.temperature=void 0,c.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),T.top_p!=null&&(T.top_p=void 0,c.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"})),T.frequency_penalty!=null&&(T.frequency_penalty=void 0,c.push({type:"unsupported-setting",setting:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),T.presence_penalty!=null&&(T.presence_penalty=void 0,c.push({type:"unsupported-setting",setting:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),T.logit_bias!=null&&(T.logit_bias=void 0,c.push({type:"other",message:"logitBias is not supported for reasoning models"})),T.logprobs!=null&&(T.logprobs=void 0,c.push({type:"other",message:"logprobs is not supported for reasoning models"})),T.top_logprobs!=null&&(T.top_logprobs=void 0,c.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),T.max_tokens!=null&&(T.max_completion_tokens==null&&(T.max_completion_tokens=T.max_tokens),T.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&T.temperature!=null&&(T.temperature=void 0,c.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),b.serviceTier==="flex"&&!Vx(this.modelId)&&(c.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),T.service_tier=void 0),b.serviceTier==="priority"&&!Fx(this.modelId)&&(c.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),T.service_tier=void 0);const{tools:P,toolChoice:D,toolWarnings:H}=qx({tools:p,toolChoice:x,structuredOutputs:v,strictJsonSchema:C});return{args:{...T,tools:P,tool_choice:D},warnings:[...c,...H]}}async doGenerate(e){var t,n,r,o,s,a,i,l,u,p,x,w,h,f;const{args:y,warnings:m}=await this.getArgs(e),{responseHeaders:c,value:b,rawValue:v}=await nt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Ge(this.config.headers(),e.headers),body:y,failedResponseHandler:At,successfulResponseHandler:vt(Ux),abortSignal:e.abortSignal,fetch:this.config.fetch}),_=b.choices[0],R=[],C=_.message.content;C!=null&&C.length>0&&R.push({type:"text",text:C});for(const H of(t=_.message.tool_calls)!=null?t:[])R.push({type:"tool-call",toolCallId:(n=H.id)!=null?n:tt(),toolName:H.function.name,input:H.function.arguments});for(const H of(r=_.message.annotations)!=null?r:[])R.push({type:"source",sourceType:"url",id:tt(),url:H.url,title:H.title});const T=(o=b.usage)==null?void 0:o.completion_tokens_details,P=(s=b.usage)==null?void 0:s.prompt_tokens_details,D={openai:{}};return(T==null?void 0:T.accepted_prediction_tokens)!=null&&(D.openai.acceptedPredictionTokens=T==null?void 0:T.accepted_prediction_tokens),(T==null?void 0:T.rejected_prediction_tokens)!=null&&(D.openai.rejectedPredictionTokens=T==null?void 0:T.rejected_prediction_tokens),((a=_.logprobs)==null?void 0:a.content)!=null&&(D.openai.logprobs=_.logprobs.content),{content:R,finishReason:sd(_.finish_reason),usage:{inputTokens:(l=(i=b.usage)==null?void 0:i.prompt_tokens)!=null?l:void 0,outputTokens:(p=(u=b.usage)==null?void 0:u.completion_tokens)!=null?p:void 0,totalTokens:(w=(x=b.usage)==null?void 0:x.total_tokens)!=null?w:void 0,reasoningTokens:(h=T==null?void 0:T.reasoning_tokens)!=null?h:void 0,cachedInputTokens:(f=P==null?void 0:P.cached_tokens)!=null?f:void 0},request:{body:y},response:{...od(b),headers:c,body:v},warnings:m,providerMetadata:D}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:o,value:s}=await nt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Ge(this.config.headers(),e.headers),body:r,failedResponseHandler:At,successfulResponseHandler:Qn(Zx),abortSignal:e.abortSignal,fetch:this.config.fetch}),a=[];let i="unknown";const l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let u=!0,p=!1;const x={openai:{}};return{stream:s.pipeThrough(new TransformStream({start(w){w.enqueue({type:"stream-start",warnings:n})},transform(w,h){var f,y,m,c,b,v,_,R,C,T,P,D,H,K,he,Y,ne,V,se,ae,ce,Pe,oe,me;if(e.includeRawChunks&&h.enqueue({type:"raw",rawValue:w.rawValue}),!w.success){i="error",h.enqueue({type:"error",error:w.error});return}const ee=w.value;if("error"in ee){i="error",h.enqueue({type:"error",error:ee.error});return}u&&(u=!1,h.enqueue({type:"response-metadata",...od(ee)})),ee.usage!=null&&(l.inputTokens=(f=ee.usage.prompt_tokens)!=null?f:void 0,l.outputTokens=(y=ee.usage.completion_tokens)!=null?y:void 0,l.totalTokens=(m=ee.usage.total_tokens)!=null?m:void 0,l.reasoningTokens=(b=(c=ee.usage.completion_tokens_details)==null?void 0:c.reasoning_tokens)!=null?b:void 0,l.cachedInputTokens=(_=(v=ee.usage.prompt_tokens_details)==null?void 0:v.cached_tokens)!=null?_:void 0,((R=ee.usage.completion_tokens_details)==null?void 0:R.accepted_prediction_tokens)!=null&&(x.openai.acceptedPredictionTokens=(C=ee.usage.completion_tokens_details)==null?void 0:C.accepted_prediction_tokens),((T=ee.usage.completion_tokens_details)==null?void 0:T.rejected_prediction_tokens)!=null&&(x.openai.rejectedPredictionTokens=(P=ee.usage.completion_tokens_details)==null?void 0:P.rejected_prediction_tokens));const Ie=ee.choices[0];if((Ie==null?void 0:Ie.finish_reason)!=null&&(i=sd(Ie.finish_reason)),((D=Ie==null?void 0:Ie.logprobs)==null?void 0:D.content)!=null&&(x.openai.logprobs=Ie.logprobs.content),(Ie==null?void 0:Ie.delta)==null)return;const k=Ie.delta;if(k.content!=null&&(p||(h.enqueue({type:"text-start",id:"0"}),p=!0),h.enqueue({type:"text-delta",id:"0",delta:k.content})),k.tool_calls!=null)for(const F of k.tool_calls){const ge=F.index;if(a[ge]==null){if(F.type!=="function")throw new zn({data:F,message:"Expected 'function' type."});if(F.id==null)throw new zn({data:F,message:"Expected 'id' to be a string."});if(((H=F.function)==null?void 0:H.name)==null)throw new zn({data:F,message:"Expected 'function.name' to be a string."});h.enqueue({type:"tool-input-start",id:F.id,toolName:F.function.name}),a[ge]={id:F.id,type:"function",function:{name:F.function.name,arguments:(K=F.function.arguments)!=null?K:""},hasFinished:!1};const Ce=a[ge];((he=Ce.function)==null?void 0:he.name)!=null&&((Y=Ce.function)==null?void 0:Y.arguments)!=null&&(Ce.function.arguments.length>0&&h.enqueue({type:"tool-input-delta",id:Ce.id,delta:Ce.function.arguments}),Gr(Ce.function.arguments)&&(h.enqueue({type:"tool-input-end",id:Ce.id}),h.enqueue({type:"tool-call",toolCallId:(ne=Ce.id)!=null?ne:tt(),toolName:Ce.function.name,input:Ce.function.arguments}),Ce.hasFinished=!0));continue}const xe=a[ge];xe.hasFinished||(((V=F.function)==null?void 0:V.arguments)!=null&&(xe.function.arguments+=(ae=(se=F.function)==null?void 0:se.arguments)!=null?ae:""),h.enqueue({type:"tool-input-delta",id:xe.id,delta:(ce=F.function.arguments)!=null?ce:""}),((Pe=xe.function)==null?void 0:Pe.name)!=null&&((oe=xe.function)==null?void 0:oe.arguments)!=null&&Gr(xe.function.arguments)&&(h.enqueue({type:"tool-input-end",id:xe.id}),h.enqueue({type:"tool-call",toolCallId:(me=xe.id)!=null?me:tt(),toolName:xe.function.name,input:xe.function.arguments}),xe.hasFinished=!0))}if(k.annotations!=null)for(const F of k.annotations)h.enqueue({type:"source",sourceType:"url",id:tt(),url:F.url,title:F.title})},flush(w){p&&w.enqueue({type:"text-end",id:"0"}),w.enqueue({type:"finish",finishReason:i,usage:l,...x!=null?{providerMetadata:x}:{}})}})),request:{body:r},response:{headers:o}}}};function ad(e){return(e.startsWith("o")||e.startsWith("gpt-5"))&&!e.startsWith("gpt-5-chat")}function Vx(e){return e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat")}function Fx(e){return e.startsWith("gpt-4")||e.startsWith("gpt-5-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-nano")&&!e.startsWith("gpt-5-chat")||e.startsWith("o3")||e.startsWith("o4-mini")}function Hx(e){var t,n;return ad(e)?(n=(t=Jx[e])==null?void 0:t.systemMessageMode)!=null?n:"developer":"system"}var Jx={"o1-mini":{systemMessageMode:"remove"},"o1-mini-2024-09-12":{systemMessageMode:"remove"},"o1-preview":{systemMessageMode:"remove"},"o1-preview-2024-09-12":{systemMessageMode:"remove"},o3:{systemMessageMode:"developer"},"o3-2025-04-16":{systemMessageMode:"developer"},"o3-mini":{systemMessageMode:"developer"},"o3-mini-2025-01-31":{systemMessageMode:"developer"},"o4-mini":{systemMessageMode:"developer"},"o4-mini-2025-04-16":{systemMessageMode:"developer"}};function Gx({prompt:e,user:t="user",assistant:n="assistant"}){let r="";e[0].role==="system"&&(r+=`${e[0].content}
|
|
57
|
+
`)}})}},Qp={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function aE({status:t,statusText:e,headers:r,stream:a,consumeSseStream:n}){let s=a.pipeThrough(new Kp);if(n){const[o,i]=s.tee();s=o,n({stream:i})}return new Response(s.pipeThrough(new TextEncoderStream),{status:t,statusText:e,headers:ms(r,Qp)})}function sE({originalMessages:t,responseMessageId:e}){if(t==null)return;const r=t[t.length-1];return(r==null?void 0:r.role)==="assistant"?r.id:typeof e=="function"?e():e}function oE(t){return t.type.startsWith("data-")}function Yp(t,e){if(t===void 0&&e===void 0)return;if(t===void 0)return e;if(e===void 0)return t;const r={...t};for(const a in e)if(Object.prototype.hasOwnProperty.call(e,a)){const n=e[a];if(n===void 0)continue;const s=a in t?t[a]:void 0,o=n!==null&&typeof n=="object"&&!Array.isArray(n)&&!(n instanceof Date)&&!(n instanceof RegExp),i=s!=null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp);o&&i?r[a]=Yp(s,n):r[a]=n}return r}function iE(t){const e=["ROOT"];let r=-1,a=null;function n(l,u,d){switch(l){case'"':{r=u,e.pop(),e.push(d),e.push("INSIDE_STRING");break}case"f":case"t":case"n":{r=u,a=u,e.pop(),e.push(d),e.push("INSIDE_LITERAL");break}case"-":{e.pop(),e.push(d),e.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=u,e.pop(),e.push(d),e.push("INSIDE_NUMBER");break}case"{":{r=u,e.pop(),e.push(d),e.push("INSIDE_OBJECT_START");break}case"[":{r=u,e.pop(),e.push(d),e.push("INSIDE_ARRAY_START");break}}}function s(l,u){switch(l){case",":{e.pop(),e.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{r=u,e.pop();break}}}function o(l,u){switch(l){case",":{e.pop(),e.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=u,e.pop();break}}}for(let l=0;l<t.length;l++){const u=t[l];switch(e[e.length-1]){case"ROOT":n(u,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(u){case'"':{e.pop(),e.push("INSIDE_OBJECT_KEY");break}case"}":{r=l,e.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(u){case'"':{e.pop(),e.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(u){case'"':{e.pop(),e.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(u){case":":{e.pop(),e.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{n(u,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{s(u,l);break}case"INSIDE_STRING":{switch(u){case'"':{e.pop(),r=l;break}case"\\":{e.push("INSIDE_STRING_ESCAPE");break}default:r=l}break}case"INSIDE_ARRAY_START":{switch(u){case"]":{r=l,e.pop();break}default:{r=l,n(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(u){case",":{e.pop(),e.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=l,e.pop();break}default:{r=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{n(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{e.pop(),r=l;break}case"INSIDE_NUMBER":{switch(u){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=l;break}case"e":case"E":case"-":case".":break;case",":{e.pop(),e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&o(u,l),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(u,l);break}case"}":{e.pop(),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(u,l);break}case"]":{e.pop(),e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&o(u,l);break}default:{e.pop();break}}break}case"INSIDE_LITERAL":{const h=t.substring(a,l+1);!"false".startsWith(h)&&!"true".startsWith(h)&&!"null".startsWith(h)?(e.pop(),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?s(u,l):e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&o(u,l)):r=l;break}}}let i=t.slice(0,r+1);for(let l=e.length-1;l>=0;l--)switch(e[l]){case"INSIDE_STRING":{i+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{i+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{i+="]";break}case"INSIDE_LITERAL":{const d=t.substring(a,t.length);"true".startsWith(d)?i+="true".slice(d.length):"false".startsWith(d)?i+="false".slice(d.length):"null".startsWith(d)&&(i+="null".slice(d.length))}}return i}async function Xp(t){if(t===void 0)return{value:void 0,state:"undefined-input"};let e=await Xr({text:t});return e.success?{value:e.value,state:"successful-parse"}:(e=await Xr({text:iE(t)}),e.success?{value:e.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function xi(t){return t.type.startsWith("tool-")}function eh(t){return t.type.split("-").slice(1).join("-")}function lE({lastMessage:t,messageId:e}){return{message:(t==null?void 0:t.role)==="assistant"?t:{id:e,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function uE({stream:t,messageMetadataSchema:e,dataPartSchemas:r,runUpdateMessageJob:a,onError:n,onToolCall:s,onData:o}){return t.pipeThrough(new TransformStream({async transform(i,l){await a(async({state:u,write:d})=>{var h,g,c,p;function f(_){const I=u.message.parts.filter(xi).find(S=>S.toolCallId===_);if(I==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return I}function m(_){const I=u.message.parts.filter(S=>S.type==="dynamic-tool").find(S=>S.toolCallId===_);if(I==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return I}function v(_){var E;const I=u.message.parts.find($=>xi($)&&$.toolCallId===_.toolCallId),S=_,R=I;I!=null?(I.state=_.state,R.input=S.input,R.output=S.output,R.errorText=S.errorText,R.rawInput=S.rawInput,R.preliminary=S.preliminary,R.providerExecuted=(E=S.providerExecuted)!=null?E:I.providerExecuted,S.providerMetadata!=null&&I.state==="input-available"&&(I.callProviderMetadata=S.providerMetadata)):u.message.parts.push({type:`tool-${_.toolName}`,toolCallId:_.toolCallId,state:_.state,input:S.input,output:S.output,rawInput:S.rawInput,errorText:S.errorText,providerExecuted:S.providerExecuted,preliminary:S.preliminary,...S.providerMetadata!=null?{callProviderMetadata:S.providerMetadata}:{}})}function w(_){var E;const I=u.message.parts.find($=>$.type==="dynamic-tool"&&$.toolCallId===_.toolCallId),S=_,R=I;I!=null?(I.state=_.state,R.toolName=_.toolName,R.input=S.input,R.output=S.output,R.errorText=S.errorText,R.rawInput=(E=S.rawInput)!=null?E:R.rawInput,R.preliminary=S.preliminary,S.providerMetadata!=null&&I.state==="input-available"&&(I.callProviderMetadata=S.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:_.toolName,toolCallId:_.toolCallId,state:_.state,input:S.input,output:S.output,errorText:S.errorText,preliminary:S.preliminary,...S.providerMetadata!=null?{callProviderMetadata:S.providerMetadata}:{}})}async function y(_){if(_!=null){const E=u.message.metadata!=null?Yp(u.message.metadata,_):_;e!=null&&await Bo({value:E,schema:e}),u.message.metadata=E}}switch(i.type){case"text-start":{const _={type:"text",text:"",providerMetadata:i.providerMetadata,state:"streaming"};u.activeTextParts[i.id]=_,u.message.parts.push(_),d();break}case"text-delta":{const _=u.activeTextParts[i.id];_.text+=i.delta,_.providerMetadata=(h=i.providerMetadata)!=null?h:_.providerMetadata,d();break}case"text-end":{const _=u.activeTextParts[i.id];_.state="done",_.providerMetadata=(g=i.providerMetadata)!=null?g:_.providerMetadata,delete u.activeTextParts[i.id],d();break}case"reasoning-start":{const _={type:"reasoning",text:"",providerMetadata:i.providerMetadata,state:"streaming"};u.activeReasoningParts[i.id]=_,u.message.parts.push(_),d();break}case"reasoning-delta":{const _=u.activeReasoningParts[i.id];_.text+=i.delta,_.providerMetadata=(c=i.providerMetadata)!=null?c:_.providerMetadata,d();break}case"reasoning-end":{const _=u.activeReasoningParts[i.id];_.providerMetadata=(p=i.providerMetadata)!=null?p:_.providerMetadata,_.state="done",delete u.activeReasoningParts[i.id],d();break}case"file":{u.message.parts.push({type:"file",mediaType:i.mediaType,url:i.url}),d();break}case"source-url":{u.message.parts.push({type:"source-url",sourceId:i.sourceId,url:i.url,title:i.title,providerMetadata:i.providerMetadata}),d();break}case"source-document":{u.message.parts.push({type:"source-document",sourceId:i.sourceId,mediaType:i.mediaType,title:i.title,filename:i.filename,providerMetadata:i.providerMetadata}),d();break}case"tool-input-start":{const _=u.message.parts.filter(xi);u.partialToolCalls[i.toolCallId]={text:"",toolName:i.toolName,index:_.length,dynamic:i.dynamic},i.dynamic?w({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0}):v({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0,providerExecuted:i.providerExecuted}),d();break}case"tool-input-delta":{const _=u.partialToolCalls[i.toolCallId];_.text+=i.inputTextDelta;const{value:E}=await Xp(_.text);_.dynamic?w({toolCallId:i.toolCallId,toolName:_.toolName,state:"input-streaming",input:E}):v({toolCallId:i.toolCallId,toolName:_.toolName,state:"input-streaming",input:E}),d();break}case"tool-input-available":{i.dynamic?w({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerMetadata:i.providerMetadata}):v({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}),d(),s&&!i.providerExecuted&&await s({toolCall:i});break}case"tool-input-error":{i.dynamic?w({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:i.input,errorText:i.errorText,providerMetadata:i.providerMetadata}):v({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:void 0,rawInput:i.input,errorText:i.errorText,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}),d();break}case"tool-output-available":{if(i.dynamic){const _=m(i.toolCallId);w({toolCallId:i.toolCallId,toolName:_.toolName,state:"output-available",input:_.input,output:i.output,preliminary:i.preliminary})}else{const _=f(i.toolCallId);v({toolCallId:i.toolCallId,toolName:eh(_),state:"output-available",input:_.input,output:i.output,providerExecuted:i.providerExecuted,preliminary:i.preliminary})}d();break}case"tool-output-error":{if(i.dynamic){const _=m(i.toolCallId);w({toolCallId:i.toolCallId,toolName:_.toolName,state:"output-error",input:_.input,errorText:i.errorText})}else{const _=f(i.toolCallId);v({toolCallId:i.toolCallId,toolName:eh(_),state:"output-error",input:_.input,rawInput:_.rawInput,errorText:i.errorText})}d();break}case"start-step":{u.message.parts.push({type:"step-start"});break}case"finish-step":{u.activeTextParts={},u.activeReasoningParts={};break}case"start":{i.messageId!=null&&(u.message.id=i.messageId),await y(i.messageMetadata),(i.messageId!=null||i.messageMetadata!=null)&&d();break}case"finish":{await y(i.messageMetadata),i.messageMetadata!=null&&d();break}case"message-metadata":{await y(i.messageMetadata),i.messageMetadata!=null&&d();break}case"error":{n==null||n(new Error(i.errorText));break}default:if(oE(i)){(r==null?void 0:r[i.type])!=null&&await Bo({value:i.data,schema:r[i.type]});const _=i;if(_.transient){o==null||o(_);break}const E=_.id!=null?u.message.parts.find(I=>_.type===I.type&&_.id===I.id):void 0;E!=null?E.data=_.data:u.message.parts.push(_),o==null||o(_),d()}}l.enqueue(i)})}}))}function cE({messageId:t,originalMessages:e=[],onFinish:r,onError:a,stream:n}){let s=e==null?void 0:e[e.length-1];(s==null?void 0:s.role)!=="assistant"?s=void 0:t=s.id;let o=!1;const i=n.pipeThrough(new TransformStream({transform(g,c){if(g.type==="start"){const p=g;p.messageId==null&&t!=null&&(p.messageId=t)}g.type==="abort"&&(o=!0),c.enqueue(g)}}));if(r==null)return i;const l=lE({lastMessage:s?structuredClone(s):void 0,messageId:t??""}),u=async g=>{await g({state:l,write:()=>{}})};let d=!1;const h=async()=>{if(d||!r)return;d=!0;const g=l.message.id===(s==null?void 0:s.id);await r({isAborted:o,isContinuation:g,responseMessage:l.message,messages:[...g?e.slice(0,-1):e,l.message]})};return uE({stream:i,runUpdateMessageJob:u,onError:a}).pipeThrough(new TransformStream({transform(g,c){c.enqueue(g)},async cancel(){await h()},async flush(){await h()}}))}function dE({response:t,status:e,statusText:r,headers:a,stream:n,consumeSseStream:s}){let o=n.pipeThrough(new Kp);if(s){const[i,l]=o.tee();o=i,s({stream:l})}Gp({response:t,status:e,statusText:r,headers:Object.fromEntries(ms(a,Qp).entries()),stream:o.pipeThrough(new TextEncoderStream)})}function vs(t){const e=t.pipeThrough(new TransformStream);return e[Symbol.asyncIterator]=function(){const r=this.getReader();let a=!1;async function n(s){var o;a=!0;try{s&&await((o=r.cancel)==null?void 0:o.call(r))}finally{try{r.releaseLock()}catch{}}}return{async next(){if(a)return{done:!0,value:void 0};const{done:s,value:o}=await r.read();return s?(await n(!0),{done:!0,value:void 0}):{done:!1,value:o}},async return(){return await n(!0),{done:!0,value:void 0}},async throw(s){throw await n(!0),s}}},e}async function pE({stream:t,onError:e}){const r=t.getReader();try{for(;;){const{done:a}=await r.read();if(a)break}}catch(a){e==null||e(a)}finally{r.releaseLock()}}function th(){let t,e;return{promise:new Promise((a,n)=>{t=a,e=n}),resolve:t,reject:e}}function hE(){let t=[],e=null,r=!1,a=th();const n=()=>{r=!0,a.resolve(),t.forEach(o=>o.cancel()),t=[],e==null||e.close()},s=async()=>{if(r&&t.length===0){e==null||e.close();return}if(t.length===0)return a=th(),await a.promise,s();try{const{value:o,done:i}=await t[0].read();i?(t.shift(),t.length>0?await s():r&&(e==null||e.close())):e==null||e.enqueue(o)}catch(o){e==null||e.error(o),t.shift(),n()}};return{stream:new ReadableStream({start(o){e=o},pull:s,async cancel(){for(const o of t)await o.cancel();t=[],r=!0}}),addStream:o=>{if(r)throw new Error("Cannot add inner stream: outer stream is closed");t.push(o.getReader()),a.resolve()},close:()=>{r=!0,a.resolve(),t.length===0&&(e==null||e.close())},terminate:n}}var gs=class{constructor(){this.status={type:"pending"},this._resolve=void 0,this._reject=void 0}get promise(){return this._promise?this._promise:(this._promise=new Promise((t,e)=>{this.status.type==="resolved"?t(this.status.value):this.status.type==="rejected"&&e(this.status.error),this._resolve=t,this._reject=e}),this._promise)}resolve(t){var e;this.status={type:"resolved",value:t},this._promise&&((e=this._resolve)==null||e.call(this,t))}reject(t){var e;this.status={type:"rejected",error:t},this._promise&&((e=this._reject)==null||e.call(this,t))}};function fE(){var t,e;return(e=(t=globalThis==null?void 0:globalThis.performance)==null?void 0:t.now())!=null?e:Date.now()}function mE({tools:t,generatorStream:e,tracer:r,telemetry:a,system:n,messages:s,abortSignal:o,repairToolCall:i,experimental_context:l}){let u=null;const d=new ReadableStream({start(v){u=v}}),h=new Set,g=new Map;let c=!1,p;function f(){c&&h.size===0&&(p!=null&&u.enqueue(p),u.close())}const m=new TransformStream({async transform(v,w){const y=v.type;switch(y){case"stream-start":case"text-start":case"text-delta":case"text-end":case"reasoning-start":case"reasoning-delta":case"reasoning-end":case"tool-input-start":case"tool-input-delta":case"tool-input-end":case"source":case"response-metadata":case"error":case"raw":{w.enqueue(v);break}case"file":{w.enqueue({type:"file",file:new Kx({data:v.data,mediaType:v.mediaType})});break}case"finish":{p={type:"finish",finishReason:v.finishReason,usage:v.usage,providerMetadata:v.providerMetadata};break}case"tool-call":{try{const _=await Zp({toolCall:v,tools:t,repairToolCall:i,system:n,messages:s});if(w.enqueue(_),_.invalid){u.enqueue({type:"tool-error",toolCallId:_.toolCallId,toolName:_.toolName,input:_.input,error:Zo(_.error),dynamic:!0});break}const E=t[_.toolName];if(g.set(_.toolCallId,_.input),E.onInputAvailable!=null&&await E.onInputAvailable({input:_.input,toolCallId:_.toolCallId,messages:s,abortSignal:o,experimental_context:l}),E.execute!=null&&_.providerExecuted!==!0){const I=V0();h.add(I),Tn({name:"ai.toolCall",attributes:jt({telemetry:a,attributes:{...In({operationId:"ai.toolCall",telemetry:a}),"ai.toolCall.name":_.toolName,"ai.toolCall.id":_.toolCallId,"ai.toolCall.args":{output:()=>JSON.stringify(_.input)}}}),tracer:r,fn:async S=>{let R;try{const $=Yc({execute:E.execute.bind(E),input:_.input,options:{toolCallId:_.toolCallId,messages:s,abortSignal:o,experimental_context:l}});for await(const z of $)u.enqueue({..._,type:"tool-result",output:z.output,...z.type==="preliminary"&&{preliminary:!0}}),z.type==="final"&&(R=z.output)}catch($){gi(S,$),u.enqueue({..._,type:"tool-error",error:$}),h.delete(I),f();return}h.delete(I),f();try{S.setAttributes(jt({telemetry:a,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(R)}}}))}catch{}}})}}catch(_){u.enqueue({type:"error",error:_})}break}case"tool-result":{const _=v.toolName;v.isError?u.enqueue({type:"tool-error",toolCallId:v.toolCallId,toolName:_,input:g.get(v.toolCallId),providerExecuted:v.providerExecuted,error:v.result}):w.enqueue({type:"tool-result",toolCallId:v.toolCallId,toolName:_,input:g.get(v.toolCallId),output:v.result,providerExecuted:v.providerExecuted});break}default:{const _=y;throw new Error(`Unhandled chunk type: ${_}`)}}},flush(){c=!0,f()}});return new ReadableStream({async start(v){return Promise.all([e.pipeThrough(m).pipeTo(new WritableStream({write(w){v.enqueue(w)},close(){}})),d.pipeTo(new WritableStream({write(w){v.enqueue(w)},close(){v.close()}}))])}})}var vE=na({prefix:"aitxt",size:24});function gE({model:t,tools:e,toolChoice:r,system:a,prompt:n,messages:s,maxRetries:o,abortSignal:i,headers:l,stopWhen:u=_i(1),experimental_output:d,experimental_telemetry:h,prepareStep:g,providerOptions:c,experimental_activeTools:p,activeTools:f=p,experimental_repairToolCall:m,experimental_transform:v,experimental_download:w,includeRawChunks:y=!1,onChunk:_,onError:E=({error:D})=>{console.error(D)},onFinish:I,onAbort:S,onStepFinish:R,experimental_context:$,_internal:{now:z=fE,generateId:L=vE,currentDate:F=()=>new Date}={},...M}){return new _E({model:hs(t),telemetry:h,headers:l,settings:M,maxRetries:o,abortSignal:i,system:a,prompt:n,messages:s,tools:e,toolChoice:r,transforms:yi(v),activeTools:f,repairToolCall:m,stopConditions:yi(u),output:d,providerOptions:c,prepareStep:g,includeRawChunks:y,onChunk:_,onError:E,onFinish:I,onAbort:S,onStepFinish:R,now:z,currentDate:F,generateId:L,experimental_context:$,download:w})}function yE(t){if(!t)return new TransformStream({transform(o,i){i.enqueue({part:o,partialOutput:void 0})}});let e,r="",a="",n="";function s({controller:o,partialOutput:i=void 0}){o.enqueue({part:{type:"text-delta",id:e,text:a},partialOutput:i}),a=""}return new TransformStream({async transform(o,i){if(o.type==="finish-step"&&a.length>0&&s({controller:i}),o.type!=="text-delta"&&o.type!=="text-start"&&o.type!=="text-end"){i.enqueue({part:o,partialOutput:void 0});return}if(e==null)e=o.id;else if(o.id!==e){i.enqueue({part:o,partialOutput:void 0});return}if(o.type==="text-start"){i.enqueue({part:o,partialOutput:void 0});return}if(o.type==="text-end"){a.length>0&&s({controller:i}),i.enqueue({part:o,partialOutput:void 0});return}r+=o.text,a+=o.text;const l=await t.parsePartial({text:r});if(l!=null){const u=JSON.stringify(l.partial);u!==n&&(s({controller:i,partialOutput:l.partial}),n=u)}}})}var _E=class{constructor({model:t,telemetry:e,headers:r,settings:a,maxRetries:n,abortSignal:s,system:o,prompt:i,messages:l,tools:u,toolChoice:d,transforms:h,activeTools:g,repairToolCall:c,stopConditions:p,output:f,providerOptions:m,prepareStep:v,includeRawChunks:w,now:y,currentDate:_,generateId:E,onChunk:I,onError:S,onFinish:R,onAbort:$,onStepFinish:z,experimental_context:L,download:F}){this._totalUsage=new gs,this._finishReason=new gs,this._steps=new gs,this.output=f,this.includeRawChunks=w,this.tools=u;let M,D=[];const K=[];let oe,ie,C={},re=[];const B=[];let de,ae={},ke={};const _e=new TransformStream({async transform(se,Se){var Ie,ye,Xe,Le;Se.enqueue(se);const{part:J}=se;if((J.type==="text-delta"||J.type==="reasoning-delta"||J.type==="source"||J.type==="tool-call"||J.type==="tool-result"||J.type==="tool-input-start"||J.type==="tool-input-delta"||J.type==="raw")&&await(I==null?void 0:I({chunk:J})),J.type==="error"&&await S({error:Np(J.error)}),J.type==="text-start"&&(ae[J.id]={type:"text",text:"",providerMetadata:J.providerMetadata},D.push(ae[J.id])),J.type==="text-delta"){const Me=ae[J.id];if(Me==null){Se.enqueue({part:{type:"error",error:`text part ${J.id} not found`},partialOutput:void 0});return}Me.text+=J.text,Me.providerMetadata=(Ie=J.providerMetadata)!=null?Ie:Me.providerMetadata}if(J.type==="text-end"){const Me=ae[J.id];if(Me==null){Se.enqueue({part:{type:"error",error:`text part ${J.id} not found`},partialOutput:void 0});return}Me.providerMetadata=(ye=J.providerMetadata)!=null?ye:Me.providerMetadata,delete ae[J.id]}if(J.type==="reasoning-start"&&(ke[J.id]={type:"reasoning",text:"",providerMetadata:J.providerMetadata},D.push(ke[J.id])),J.type==="reasoning-delta"){const Me=ke[J.id];if(Me==null){Se.enqueue({part:{type:"error",error:`reasoning part ${J.id} not found`},partialOutput:void 0});return}Me.text+=J.text,Me.providerMetadata=(Xe=J.providerMetadata)!=null?Xe:Me.providerMetadata}if(J.type==="reasoning-end"){const Me=ke[J.id];if(Me==null){Se.enqueue({part:{type:"error",error:`reasoning part ${J.id} not found`},partialOutput:void 0});return}Me.providerMetadata=(Le=J.providerMetadata)!=null?Le:Me.providerMetadata,delete ke[J.id]}if(J.type==="file"&&D.push({type:"file",file:J.file}),J.type==="source"&&D.push(J),J.type==="tool-call"&&D.push(J),J.type==="tool-result"&&!J.preliminary&&D.push(J),J.type==="tool-error"&&D.push(J),J.type==="start-step"&&(C=J.request,re=J.warnings),J.type==="finish-step"){const Me=bi({content:D,tools:u}),ze=new Bp({content:D,finishReason:J.finishReason,usage:J.usage,warnings:re,request:C,response:{...J.response,messages:[...K,...Me]},providerMetadata:J.providerMetadata});await(z==null?void 0:z(ze)),Wd(re),B.push(ze),D=[],ke={},ae={},K.push(...Me),M.resolve()}J.type==="finish"&&(ie=J.totalUsage,oe=J.finishReason)},async flush(se){try{if(B.length===0){const Xe=new mx({message:"No output generated. Check the stream for errors."});be._finishReason.reject(Xe),be._totalUsage.reject(Xe),be._steps.reject(Xe);return}const Se=oe??"unknown",Ie=ie??{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};be._finishReason.resolve(Se),be._totalUsage.resolve(Ie),be._steps.resolve(B);const ye=B[B.length-1];await(R==null?void 0:R({finishReason:Se,totalUsage:Ie,usage:ye.usage,content:ye.content,text:ye.text,reasoningText:ye.reasoningText,reasoning:ye.reasoning,files:ye.files,sources:ye.sources,toolCalls:ye.toolCalls,staticToolCalls:ye.staticToolCalls,dynamicToolCalls:ye.dynamicToolCalls,toolResults:ye.toolResults,staticToolResults:ye.staticToolResults,dynamicToolResults:ye.dynamicToolResults,request:ye.request,response:ye.response,warnings:ye.warnings,providerMetadata:ye.providerMetadata,steps:B})),de.setAttributes(jt({telemetry:e,attributes:{"ai.response.finishReason":Se,"ai.response.text":{output:()=>ye.text},"ai.response.toolCalls":{output:()=>{var Xe;return(Xe=ye.toolCalls)!=null&&Xe.length?JSON.stringify(ye.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(ye.providerMetadata),"ai.usage.inputTokens":Ie.inputTokens,"ai.usage.outputTokens":Ie.outputTokens,"ai.usage.totalTokens":Ie.totalTokens,"ai.usage.reasoningTokens":Ie.reasoningTokens,"ai.usage.cachedInputTokens":Ie.cachedInputTokens}}))}catch(Se){se.error(Se)}finally{de.end()}}}),Pe=hE();this.addStream=Pe.addStream,this.closeStream=Pe.close;const xe=Pe.stream.getReader();let ve=new ReadableStream({async start(se){se.enqueue({type:"start"})},async pull(se){function Se(){$==null||$({steps:B}),se.enqueue({type:"abort"}),se.close()}try{const{done:Ie,value:ye}=await xe.read();if(Ie){se.close();return}if(s!=null&&s.aborted){Se();return}se.enqueue(ye)}catch(Ie){Yr(Ie)&&(s!=null&&s.aborted)?Se():se.error(Ie)}},cancel(se){return Pe.stream.cancel(se)}});for(const se of h)ve=ve.pipeThrough(se({tools:u,stopStream(){Pe.terminate()}}));this.baseStream=ve.pipeThrough(yE(f)).pipeThrough(_e);const{maxRetries:Re,retry:pt}=Up({maxRetries:n,abortSignal:s}),Ne=Dp(e),we=vi(a),bt=Mp({model:t,telemetry:e,headers:r,settings:{...we,maxRetries:Re}}),be=this;Tn({name:"ai.streamText",attributes:jt({telemetry:e,attributes:{...In({operationId:"ai.streamText",telemetry:e}),...bt,"ai.prompt":{input:()=>JSON.stringify({system:o,prompt:i,messages:l})}}}),tracer:Ne,endWhenDone:!1,fn:async se=>{de=se;async function Se({currentStep:Ie,responseMessages:ye,usage:Xe}){var Le,J,Me,ze,pe;const Be=be.includeRawChunks;M=new gs;const hr=await Ap({system:o,prompt:i,messages:l}),Ft=[...hr.messages,...ye],mt=await(v==null?void 0:v({model:t,steps:B,stepNumber:B.length,messages:Ft})),Yt=hs((Le=mt==null?void 0:mt.model)!=null?Le:t),xt=await Pp({prompt:{system:(J=mt==null?void 0:mt.system)!=null?J:hr.system,messages:(Me=mt==null?void 0:mt.messages)!=null?Me:Ft},supportedUrls:await Yt.supportedUrls,download:F}),{toolChoice:qt,tools:Sr}=Cp({tools:u,toolChoice:(ze=mt==null?void 0:mt.toolChoice)!=null?ze:d,activeTools:(pe=mt==null?void 0:mt.activeTools)!=null?pe:g}),{result:{stream:pn,response:Ge,request:Zt},doStreamSpan:Xt,startTimestampMs:Ra}=await pt(()=>Tn({name:"ai.streamText.doStream",attributes:jt({telemetry:e,attributes:{...In({operationId:"ai.streamText.doStream",telemetry:e}),...bt,"ai.model.provider":Yt.provider,"ai.model.id":Yt.modelId,"ai.prompt.messages":{input:()=>jp(xt)},"ai.prompt.tools":{input:()=>Sr==null?void 0:Sr.map(ue=>JSON.stringify(ue))},"ai.prompt.toolChoice":{input:()=>qt!=null?JSON.stringify(qt):void 0},"gen_ai.system":Yt.provider,"gen_ai.request.model":Yt.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:Ne,endWhenDone:!1,fn:async ue=>({startTimestampMs:y(),doStreamSpan:ue,result:await Yt.doStream({...we,tools:Sr,toolChoice:qt,responseFormat:f==null?void 0:f.responseFormat,prompt:xt,providerOptions:m,abortSignal:s,headers:r,includeRawChunks:Be})})})),Vt=mE({tools:u,generatorStream:pn,tracer:Ne,telemetry:e,system:o,messages:Ft,repairToolCall:c,abortSignal:s,experimental_context:L}),Kl=Zt??{},Un=[],Oa=[];let $a;const Aa={};let qr="unknown",ht={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},Na,Ma=!0,Bt={id:E(),timestamp:_(),modelId:t.modelId},Fn="";be.addStream(Vt.pipeThrough(new TransformStream({async transform(ue,ct){var Zr,hn,fn,T;if(ue.type==="stream-start"){$a=ue.warnings;return}if(Ma){const k=y()-Ra;Ma=!1,Xt.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":k}),Xt.setAttributes({"ai.response.msToFirstChunk":k}),ct.enqueue({type:"start-step",request:Kl,warnings:$a??[]})}const b=ue.type;switch(b){case"text-start":case"text-end":{ct.enqueue(ue);break}case"text-delta":{ue.delta.length>0&&(ct.enqueue({type:"text-delta",id:ue.id,text:ue.delta,providerMetadata:ue.providerMetadata}),Fn+=ue.delta);break}case"reasoning-start":case"reasoning-end":{ct.enqueue(ue);break}case"reasoning-delta":{ct.enqueue({type:"reasoning-delta",id:ue.id,text:ue.delta,providerMetadata:ue.providerMetadata});break}case"tool-call":{ct.enqueue(ue),Un.push(ue);break}case"tool-result":{ct.enqueue(ue),ue.preliminary||Oa.push(ue);break}case"tool-error":{ct.enqueue(ue),Oa.push(ue);break}case"response-metadata":{Bt={id:(Zr=ue.id)!=null?Zr:Bt.id,timestamp:(hn=ue.timestamp)!=null?hn:Bt.timestamp,modelId:(fn=ue.modelId)!=null?fn:Bt.modelId};break}case"finish":{ht=ue.usage,qr=ue.finishReason,Na=ue.providerMetadata;const k=y()-Ra;Xt.addEvent("ai.stream.finish"),Xt.setAttributes({"ai.response.msToFinish":k,"ai.response.avgOutputTokensPerSecond":1e3*((T=ht.outputTokens)!=null?T:0)/k});break}case"file":{ct.enqueue(ue);break}case"source":{ct.enqueue(ue);break}case"tool-input-start":{Aa[ue.id]=ue.toolName;const k=u==null?void 0:u[ue.toolName];(k==null?void 0:k.onInputStart)!=null&&await k.onInputStart({toolCallId:ue.id,messages:Ft,abortSignal:s,experimental_context:L}),ct.enqueue({...ue,dynamic:(k==null?void 0:k.type)==="dynamic"});break}case"tool-input-end":{delete Aa[ue.id],ct.enqueue(ue);break}case"tool-input-delta":{const k=Aa[ue.id],A=u==null?void 0:u[k];(A==null?void 0:A.onInputDelta)!=null&&await A.onInputDelta({inputTextDelta:ue.delta,toolCallId:ue.id,messages:Ft,abortSignal:s,experimental_context:L}),ct.enqueue(ue);break}case"error":{ct.enqueue(ue),qr="error";break}case"raw":{Be&&ct.enqueue(ue);break}default:{const k=b;throw new Error(`Unknown chunk type: ${k}`)}}},async flush(ue){const ct=Un.length>0?JSON.stringify(Un):void 0;try{Xt.setAttributes(jt({telemetry:e,attributes:{"ai.response.finishReason":qr,"ai.response.text":{output:()=>Fn},"ai.response.toolCalls":{output:()=>ct},"ai.response.id":Bt.id,"ai.response.model":Bt.modelId,"ai.response.timestamp":Bt.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(Na),"ai.usage.inputTokens":ht.inputTokens,"ai.usage.outputTokens":ht.outputTokens,"ai.usage.totalTokens":ht.totalTokens,"ai.usage.reasoningTokens":ht.reasoningTokens,"ai.usage.cachedInputTokens":ht.cachedInputTokens,"gen_ai.response.finish_reasons":[qr],"gen_ai.response.id":Bt.id,"gen_ai.response.model":Bt.modelId,"gen_ai.usage.input_tokens":ht.inputTokens,"gen_ai.usage.output_tokens":ht.outputTokens}}))}catch{}finally{Xt.end()}ue.enqueue({type:"finish-step",finishReason:qr,usage:ht,providerMetadata:Na,response:{...Bt,headers:Ge==null?void 0:Ge.headers}});const Zr=Lp(Xe,ht);await M.promise;const hn=Un.filter(T=>T.providerExecuted!==!0),fn=Oa.filter(T=>T.providerExecuted!==!0);if(hn.length>0&&fn.length===hn.length&&!await Hp({stopConditions:p,steps:B})){ye.push(...bi({content:B[B.length-1].content,tools:u}));try{await Se({currentStep:Ie+1,responseMessages:ye,usage:Zr})}catch(T){ue.enqueue({type:"error",error:T}),be.closeStream()}}else ue.enqueue({type:"finish",finishReason:qr,totalUsage:Zr}),be.closeStream()}})))}await Se({currentStep:0,responseMessages:[],usage:{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0}})}}).catch(se=>{be.addStream(new ReadableStream({start(Se){Se.enqueue({type:"error",error:se}),Se.close()}})),be.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then(t=>t[t.length-1])}get content(){return this.finalStep.then(t=>t.content)}get warnings(){return this.finalStep.then(t=>t.warnings)}get providerMetadata(){return this.finalStep.then(t=>t.providerMetadata)}get text(){return this.finalStep.then(t=>t.text)}get reasoningText(){return this.finalStep.then(t=>t.reasoningText)}get reasoning(){return this.finalStep.then(t=>t.reasoning)}get sources(){return this.finalStep.then(t=>t.sources)}get files(){return this.finalStep.then(t=>t.files)}get toolCalls(){return this.finalStep.then(t=>t.toolCalls)}get staticToolCalls(){return this.finalStep.then(t=>t.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then(t=>t.dynamicToolCalls)}get toolResults(){return this.finalStep.then(t=>t.toolResults)}get staticToolResults(){return this.finalStep.then(t=>t.staticToolResults)}get dynamicToolResults(){return this.finalStep.then(t=>t.dynamicToolResults)}get usage(){return this.finalStep.then(t=>t.usage)}get request(){return this.finalStep.then(t=>t.request)}get response(){return this.finalStep.then(t=>t.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}teeStream(){const[t,e]=this.baseStream.tee();return this.baseStream=e,t}get textStream(){return vs(this.teeStream().pipeThrough(new TransformStream({transform({part:t},e){t.type==="text-delta"&&e.enqueue(t.text)}})))}get fullStream(){return vs(this.teeStream().pipeThrough(new TransformStream({transform({part:t},e){e.enqueue(t)}})))}async consumeStream(t){var e;try{await pE({stream:this.fullStream,onError:t==null?void 0:t.onError})}catch(r){(e=t==null?void 0:t.onError)==null||e.call(t,r)}}get experimental_partialOutputStream(){if(this.output==null)throw new Hd;return vs(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:t},e){t!=null&&e.enqueue(t)}})))}toUIMessageStream({originalMessages:t,generateMessageId:e,onFinish:r,messageMetadata:a,sendReasoning:n=!0,sendSources:s=!1,sendStart:o=!0,sendFinish:i=!0,onError:l=yn}={}){const u=e!=null?sE({originalMessages:t,responseMessageId:e}):void 0,d={},h=c=>{var p,f;const m=d[c];return((f=(p=this.tools)==null?void 0:p[m])==null?void 0:f.type)==="dynamic"?!0:void 0},g=this.fullStream.pipeThrough(new TransformStream({transform:async(c,p)=>{const f=a==null?void 0:a({part:c}),m=c.type;switch(m){case"text-start":{p.enqueue({type:"text-start",id:c.id,...c.providerMetadata!=null?{providerMetadata:c.providerMetadata}:{}});break}case"text-delta":{p.enqueue({type:"text-delta",id:c.id,delta:c.text,...c.providerMetadata!=null?{providerMetadata:c.providerMetadata}:{}});break}case"text-end":{p.enqueue({type:"text-end",id:c.id,...c.providerMetadata!=null?{providerMetadata:c.providerMetadata}:{}});break}case"reasoning-start":{p.enqueue({type:"reasoning-start",id:c.id,...c.providerMetadata!=null?{providerMetadata:c.providerMetadata}:{}});break}case"reasoning-delta":{n&&p.enqueue({type:"reasoning-delta",id:c.id,delta:c.text,...c.providerMetadata!=null?{providerMetadata:c.providerMetadata}:{}});break}case"reasoning-end":{p.enqueue({type:"reasoning-end",id:c.id,...c.providerMetadata!=null?{providerMetadata:c.providerMetadata}:{}});break}case"file":{p.enqueue({type:"file",mediaType:c.file.mediaType,url:`data:${c.file.mediaType};base64,${c.file.base64}`});break}case"source":{s&&c.sourceType==="url"&&p.enqueue({type:"source-url",sourceId:c.id,url:c.url,title:c.title,...c.providerMetadata!=null?{providerMetadata:c.providerMetadata}:{}}),s&&c.sourceType==="document"&&p.enqueue({type:"source-document",sourceId:c.id,mediaType:c.mediaType,title:c.title,filename:c.filename,...c.providerMetadata!=null?{providerMetadata:c.providerMetadata}:{}});break}case"tool-input-start":{d[c.id]=c.toolName;const v=h(c.id);p.enqueue({type:"tool-input-start",toolCallId:c.id,toolName:c.toolName,...c.providerExecuted!=null?{providerExecuted:c.providerExecuted}:{},...v!=null?{dynamic:v}:{}});break}case"tool-input-delta":{p.enqueue({type:"tool-input-delta",toolCallId:c.id,inputTextDelta:c.delta});break}case"tool-call":{d[c.toolCallId]=c.toolName;const v=h(c.toolCallId);c.invalid?p.enqueue({type:"tool-input-error",toolCallId:c.toolCallId,toolName:c.toolName,input:c.input,...c.providerExecuted!=null?{providerExecuted:c.providerExecuted}:{},...c.providerMetadata!=null?{providerMetadata:c.providerMetadata}:{},...v!=null?{dynamic:v}:{},errorText:l(c.error)}):p.enqueue({type:"tool-input-available",toolCallId:c.toolCallId,toolName:c.toolName,input:c.input,...c.providerExecuted!=null?{providerExecuted:c.providerExecuted}:{},...c.providerMetadata!=null?{providerMetadata:c.providerMetadata}:{},...v!=null?{dynamic:v}:{}});break}case"tool-result":{const v=h(c.toolCallId);p.enqueue({type:"tool-output-available",toolCallId:c.toolCallId,output:c.output,...c.providerExecuted!=null?{providerExecuted:c.providerExecuted}:{},...c.preliminary!=null?{preliminary:c.preliminary}:{},...v!=null?{dynamic:v}:{}});break}case"tool-error":{const v=h(c.toolCallId);p.enqueue({type:"tool-output-error",toolCallId:c.toolCallId,errorText:l(c.error),...c.providerExecuted!=null?{providerExecuted:c.providerExecuted}:{},...v!=null?{dynamic:v}:{}});break}case"error":{p.enqueue({type:"error",errorText:l(c.error)});break}case"start-step":{p.enqueue({type:"start-step"});break}case"finish-step":{p.enqueue({type:"finish-step"});break}case"start":{o&&p.enqueue({type:"start",...f!=null?{messageMetadata:f}:{},...u!=null?{messageId:u}:{}});break}case"finish":{i&&p.enqueue({type:"finish",...f!=null?{messageMetadata:f}:{}});break}case"abort":{p.enqueue(c);break}case"tool-input-end":break;case"raw":break;default:{const v=m;throw new Error(`Unknown chunk type: ${v}`)}}f!=null&&m!=="start"&&m!=="finish"&&p.enqueue({type:"message-metadata",messageMetadata:f})}}));return vs(cE({stream:g,messageId:u??(e==null?void 0:e()),originalMessages:t,onFinish:r,onError:l}))}pipeUIMessageStreamToResponse(t,{originalMessages:e,generateMessageId:r,onFinish:a,messageMetadata:n,sendReasoning:s,sendSources:o,sendFinish:i,sendStart:l,onError:u,...d}={}){dE({response:t,stream:this.toUIMessageStream({originalMessages:e,generateMessageId:r,onFinish:a,messageMetadata:n,sendReasoning:s,sendSources:o,sendFinish:i,sendStart:l,onError:u}),...d})}pipeTextStreamToResponse(t,e){nE({response:t,textStream:this.textStream,...e})}toUIMessageStreamResponse({originalMessages:t,generateMessageId:e,onFinish:r,messageMetadata:a,sendReasoning:n,sendSources:s,sendFinish:o,sendStart:i,onError:l,...u}={}){return aE({stream:this.toUIMessageStream({originalMessages:t,generateMessageId:e,onFinish:r,messageMetadata:a,sendReasoning:n,sendSources:s,sendFinish:o,sendStart:i,onError:l}),...u})}toTextStreamResponse(t){return rE({textStream:this.textStream,...t})}};na({prefix:"aiobj",size:24}),na({prefix:"aiobj",size:24});var wE={};ix(wE,{object:()=>xE,text:()=>bE});var bE=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:t}){return{partial:t}},async parseOutput({text:t}){return t}}),xE=({schema:t})=>{const e=us(t);return{type:"object",responseFormat:{type:"json",schema:e.jsonSchema},async parsePartial({text:r}){const a=await Xp(r);switch(a.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:a.value};default:{const n=a.state;throw new Error(`Unsupported parse state: ${n}`)}}},async parseOutput({text:r},a){const n=await Xr({text:r});if(!n.success)throw new sp({message:"No object generated: could not parse the response.",cause:n.error,text:r,response:a.response,usage:a.usage,finishReason:a.finishReason});const s=await $r({value:n.value,schema:e});if(!s.success)throw new sp({message:"No object generated: response did not match schema.",cause:s.error,text:r,response:a.response,usage:a.usage,finishReason:a.finishReason});return s.value}}},EE=_n({name:x(),version:x()}),Ei=_n({_meta:at(P({}).loose())}),ma=Ei,SE=P({method:x(),params:at(Ei)}),IE=_n({experimental:at(P({}).loose()),logging:at(P({}).loose()),prompts:at(_n({listChanged:at(nt())})),resources:at(_n({subscribe:at(nt()),listChanged:at(nt())})),tools:at(_n({listChanged:at(nt())}))});ma.extend({protocolVersion:x(),capabilities:IE,serverInfo:EE,instructions:at(x())});var TE=ma.extend({nextCursor:at(x())}),kE=P({name:x(),description:at(x()),inputSchema:P({type:H("object"),properties:at(P({}).loose())}).loose()}).loose();TE.extend({tools:Y(kE)});var PE=P({type:H("text"),text:x()}).loose(),CE=P({type:H("image"),data:wc(),mimeType:x()}).loose(),rh=P({uri:x(),mimeType:at(x())}).loose(),RE=rh.extend({text:x()}),OE=rh.extend({blob:wc()}),$E=P({type:H("resource"),resource:Ae([RE,OE])}).loose();ma.extend({content:Y(Ae([PE,CE,$E])),isError:nt().default(!1).optional()}).or(ma.extend({toolResult:Cr()}));var ys="2.0",AE=P({jsonrpc:H(ys),id:Ae([x(),U().int()])}).merge(SE).strict(),NE=P({jsonrpc:H(ys),id:Ae([x(),U().int()]),result:ma}).strict(),ME=P({jsonrpc:H(ys),id:Ae([x(),U().int()]),error:P({code:U().int(),message:x(),data:at(Cr())})}).strict(),DE=P({jsonrpc:H(ys)}).merge(P({method:x(),params:at(Ei)})).strict();Ae([AE,DE,NE,ME]);const _s="2025-06-18",jE=[_s,"2025-03-26","2024-11-05","2024-10-07"],ws="2.0",nh=_t([O(),dt().int()]),ah=O(),LE=W({progressToken:q(nh)}).passthrough(),Lt=W({_meta:q(LE)}).passthrough(),It=W({method:O(),params:q(Lt)}),va=W({_meta:q(W({}).passthrough())}).passthrough(),or=W({method:O(),params:q(va)}),zt=W({_meta:q(W({}).passthrough())}).passthrough(),bs=_t([O(),dt().int()]),sh=W({jsonrpc:me(ws),id:bs}).merge(It).strict(),oh=t=>sh.safeParse(t).success,ih=W({jsonrpc:me(ws)}).merge(or).strict(),zE=t=>ih.safeParse(t).success,lh=W({jsonrpc:me(ws),id:bs,result:zt}).strict(),Si=t=>lh.safeParse(t).success;var ir;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError"})(ir||(ir={}));const uh=W({jsonrpc:me(ws),id:bs,error:W({code:dt().int(),message:O(),data:q(ea())})}).strict(),UE=t=>uh.safeParse(t).success,sn=_t([sh,ih,lh,uh]),on=zt.strict(),Ii=or.extend({method:me("notifications/cancelled"),params:va.extend({requestId:bs,reason:O().optional()})}),ga=W({name:O(),title:q(O())}).passthrough(),ch=ga.extend({version:O()}),FE=W({experimental:q(W({}).passthrough()),sampling:q(W({}).passthrough()),elicitation:q(W({}).passthrough()),roots:q(W({listChanged:q(lt())}).passthrough())}).passthrough(),qE=It.extend({method:me("initialize"),params:Lt.extend({protocolVersion:O(),capabilities:FE,clientInfo:ch})}),ZE=W({experimental:q(W({}).passthrough()),logging:q(W({}).passthrough()),completions:q(W({}).passthrough()),prompts:q(W({listChanged:q(lt())}).passthrough()),resources:q(W({subscribe:q(lt()),listChanged:q(lt())}).passthrough()),tools:q(W({listChanged:q(lt())}).passthrough())}).passthrough(),dh=zt.extend({protocolVersion:O(),capabilities:ZE,serverInfo:ch,instructions:q(O())}),ph=or.extend({method:me("notifications/initialized")}),VE=t=>ph.safeParse(t).success,Ti=It.extend({method:me("ping")}),BE=W({progress:dt(),total:q(dt()),message:q(O())}).passthrough(),ki=or.extend({method:me("notifications/progress"),params:va.merge(BE).extend({progressToken:nh})}),xs=It.extend({params:Lt.extend({cursor:q(ah)}).optional()}),Es=zt.extend({nextCursor:q(ah)}),hh=W({uri:O(),mimeType:q(O()),_meta:q(W({}).passthrough())}).passthrough(),fh=hh.extend({text:O()}),Pi=O().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),mh=hh.extend({blob:Pi}),vh=ga.extend({uri:O(),description:q(O()),mimeType:q(O()),_meta:q(W({}).passthrough())}),HE=ga.extend({uriTemplate:O(),description:q(O()),mimeType:q(O()),_meta:q(W({}).passthrough())}),JE=xs.extend({method:me("resources/list")}),gh=Es.extend({resources:ee(vh)}),WE=xs.extend({method:me("resources/templates/list")}),yh=Es.extend({resourceTemplates:ee(HE)}),GE=It.extend({method:me("resources/read"),params:Lt.extend({uri:O()})}),_h=zt.extend({contents:ee(_t([fh,mh]))}),wh=or.extend({method:me("notifications/resources/list_changed")}),KE=It.extend({method:me("resources/subscribe"),params:Lt.extend({uri:O()})}),QE=It.extend({method:me("resources/unsubscribe"),params:Lt.extend({uri:O()})}),bh=or.extend({method:me("notifications/resources/updated"),params:va.extend({uri:O()})}),YE=W({name:O(),description:q(O()),required:q(lt())}).passthrough(),XE=ga.extend({description:q(O()),arguments:q(ee(YE)),_meta:q(W({}).passthrough())}),eS=xs.extend({method:me("prompts/list")}),xh=Es.extend({prompts:ee(XE)}),tS=It.extend({method:me("prompts/get"),params:Lt.extend({name:O(),arguments:q(ta(O()))})}),Ci=W({type:me("text"),text:O(),_meta:q(W({}).passthrough())}).passthrough(),Ri=W({type:me("image"),data:Pi,mimeType:O(),_meta:q(W({}).passthrough())}).passthrough(),Oi=W({type:me("audio"),data:Pi,mimeType:O(),_meta:q(W({}).passthrough())}).passthrough(),rS=W({type:me("resource"),resource:_t([fh,mh]),_meta:q(W({}).passthrough())}).passthrough(),nS=vh.extend({type:me("resource_link")}),Eh=_t([Ci,Ri,Oi,nS,rS]),aS=W({role:xr(["user","assistant"]),content:Eh}).passthrough(),Sh=zt.extend({description:q(O()),messages:ee(aS)}),Ih=or.extend({method:me("notifications/prompts/list_changed")}),sS=W({title:q(O()),readOnlyHint:q(lt()),destructiveHint:q(lt()),idempotentHint:q(lt()),openWorldHint:q(lt())}).passthrough(),oS=ga.extend({description:q(O()),inputSchema:W({type:me("object"),properties:q(W({}).passthrough()),required:q(ee(O()))}).passthrough(),outputSchema:q(W({type:me("object"),properties:q(W({}).passthrough()),required:q(ee(O()))}).passthrough()),annotations:q(sS),_meta:q(W({}).passthrough())}),iS=xs.extend({method:me("tools/list")}),Th=Es.extend({tools:ee(oS)}),Ss=zt.extend({content:ee(Eh).default([]),structuredContent:W({}).passthrough().optional(),isError:q(lt())});Ss.or(zt.extend({toolResult:ea()}));const lS=It.extend({method:me("tools/call"),params:Lt.extend({name:O(),arguments:q(ta(ea()))})}),kh=or.extend({method:me("notifications/tools/list_changed")}),Ph=xr(["debug","info","notice","warning","error","critical","alert","emergency"]),uS=It.extend({method:me("logging/setLevel"),params:Lt.extend({level:Ph})}),Ch=or.extend({method:me("notifications/message"),params:va.extend({level:Ph,logger:q(O()),data:ea()})}),cS=W({name:O().optional()}).passthrough(),dS=W({hints:q(ee(cS)),costPriority:q(dt().min(0).max(1)),speedPriority:q(dt().min(0).max(1)),intelligencePriority:q(dt().min(0).max(1))}).passthrough(),pS=W({role:xr(["user","assistant"]),content:_t([Ci,Ri,Oi])}).passthrough(),Rh=It.extend({method:me("sampling/createMessage"),params:Lt.extend({messages:ee(pS),systemPrompt:q(O()),includeContext:q(xr(["none","thisServer","allServers"])),temperature:q(dt()),maxTokens:dt().int(),stopSequences:q(ee(O())),metadata:q(W({}).passthrough()),modelPreferences:q(dS)})}),Oh=zt.extend({model:O(),stopReason:q(xr(["endTurn","stopSequence","maxTokens"]).or(O())),role:xr(["user","assistant"]),content:q0("type",[Ci,Ri,Oi])}),hS=W({type:me("boolean"),title:q(O()),description:q(O()),default:q(lt())}).passthrough(),fS=W({type:me("string"),title:q(O()),description:q(O()),minLength:q(dt()),maxLength:q(dt()),format:q(xr(["email","uri","date","date-time"]))}).passthrough(),mS=W({type:xr(["number","integer"]),title:q(O()),description:q(O()),minimum:q(dt()),maximum:q(dt())}).passthrough(),vS=W({type:me("string"),title:q(O()),description:q(O()),enum:ee(O()),enumNames:q(ee(O()))}).passthrough(),gS=_t([hS,fS,mS,vS]),$h=It.extend({method:me("elicitation/create"),params:Lt.extend({message:O(),requestedSchema:W({type:me("object"),properties:ta(O(),gS),required:q(ee(O()))}).passthrough()})}),Ah=zt.extend({action:xr(["accept","decline","cancel"]),content:q(ta(O(),ea()))}),yS=W({type:me("ref/resource"),uri:O()}).passthrough(),_S=W({type:me("ref/prompt"),name:O()}).passthrough(),wS=It.extend({method:me("completion/complete"),params:Lt.extend({ref:_t([_S,yS]),argument:W({name:O(),value:O()}).passthrough(),context:q(W({arguments:q(ta(O(),O()))}))})}),Nh=zt.extend({completion:W({values:ee(O()).max(100),total:q(dt().int()),hasMore:q(lt())}).passthrough()}),bS=W({uri:O().startsWith("file://"),name:q(O()),_meta:q(W({}).passthrough())}).passthrough(),Mh=It.extend({method:me("roots/list")}),Dh=zt.extend({roots:ee(bS)}),xS=or.extend({method:me("notifications/roots/list_changed")});_t([Ti,qE,wS,uS,tS,eS,JE,WE,GE,KE,QE,lS,iS]),_t([Ii,ki,ph,xS]),_t([on,Oh,Ah,Dh]),_t([Ti,Rh,$h,Mh]),_t([Ii,ki,Ch,bh,wh,kh,Ih]),_t([on,dh,Nh,Sh,xh,gh,yh,_h,Ss,Th]);class Nr extends Error{constructor(e,r,a){super(`MCP error ${e}: ${r}`),this.code=e,this.data=a,this.name="McpError"}}let $i;$i=globalThis.crypto;async function ES(t){return(await $i).getRandomValues(new Uint8Array(t))}async function SS(t){const e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";let r="";const a=await ES(t);for(let n=0;n<t;n++){const s=a[n]%e.length;r+=e[s]}return r}async function IS(t){return await SS(t)}async function TS(t){const e=await(await $i).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function kS(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;const e=await IS(t),r=await TS(e);return{code_verifier:e,code_challenge:r}}const PS=W({resource:O().url(),authorization_servers:ee(O().url()).optional(),jwks_uri:O().url().optional(),scopes_supported:ee(O()).optional(),bearer_methods_supported:ee(O()).optional(),resource_signing_alg_values_supported:ee(O()).optional(),resource_name:O().optional(),resource_documentation:O().optional(),resource_policy_uri:O().url().optional(),resource_tos_uri:O().url().optional(),tls_client_certificate_bound_access_tokens:lt().optional(),authorization_details_types_supported:ee(O()).optional(),dpop_signing_alg_values_supported:ee(O()).optional(),dpop_bound_access_tokens_required:lt().optional()}).passthrough(),jh=W({issuer:O(),authorization_endpoint:O(),token_endpoint:O(),registration_endpoint:O().optional(),scopes_supported:ee(O()).optional(),response_types_supported:ee(O()),response_modes_supported:ee(O()).optional(),grant_types_supported:ee(O()).optional(),token_endpoint_auth_methods_supported:ee(O()).optional(),token_endpoint_auth_signing_alg_values_supported:ee(O()).optional(),service_documentation:O().optional(),revocation_endpoint:O().optional(),revocation_endpoint_auth_methods_supported:ee(O()).optional(),revocation_endpoint_auth_signing_alg_values_supported:ee(O()).optional(),introspection_endpoint:O().optional(),introspection_endpoint_auth_methods_supported:ee(O()).optional(),introspection_endpoint_auth_signing_alg_values_supported:ee(O()).optional(),code_challenge_methods_supported:ee(O()).optional()}).passthrough(),CS=W({issuer:O(),authorization_endpoint:O(),token_endpoint:O(),userinfo_endpoint:O().optional(),jwks_uri:O(),registration_endpoint:O().optional(),scopes_supported:ee(O()).optional(),response_types_supported:ee(O()),response_modes_supported:ee(O()).optional(),grant_types_supported:ee(O()).optional(),acr_values_supported:ee(O()).optional(),subject_types_supported:ee(O()),id_token_signing_alg_values_supported:ee(O()),id_token_encryption_alg_values_supported:ee(O()).optional(),id_token_encryption_enc_values_supported:ee(O()).optional(),userinfo_signing_alg_values_supported:ee(O()).optional(),userinfo_encryption_alg_values_supported:ee(O()).optional(),userinfo_encryption_enc_values_supported:ee(O()).optional(),request_object_signing_alg_values_supported:ee(O()).optional(),request_object_encryption_alg_values_supported:ee(O()).optional(),request_object_encryption_enc_values_supported:ee(O()).optional(),token_endpoint_auth_methods_supported:ee(O()).optional(),token_endpoint_auth_signing_alg_values_supported:ee(O()).optional(),display_values_supported:ee(O()).optional(),claim_types_supported:ee(O()).optional(),claims_supported:ee(O()).optional(),service_documentation:O().optional(),claims_locales_supported:ee(O()).optional(),ui_locales_supported:ee(O()).optional(),claims_parameter_supported:lt().optional(),request_parameter_supported:lt().optional(),request_uri_parameter_supported:lt().optional(),require_request_uri_registration:lt().optional(),op_policy_uri:O().optional(),op_tos_uri:O().optional()}).passthrough().merge(jh.pick({code_challenge_methods_supported:!0})),Lh=W({access_token:O(),id_token:O().optional(),token_type:O(),expires_in:dt().optional(),scope:O().optional(),refresh_token:O().optional()}).strip(),RS=W({error:O(),error_description:O().optional(),error_uri:O().optional()}),OS=W({redirect_uris:ee(O()).refine(t=>t.every(e=>URL.canParse(e)),{message:"redirect_uris must contain valid URLs"}),token_endpoint_auth_method:O().optional(),grant_types:ee(O()).optional(),response_types:ee(O()).optional(),client_name:O().optional(),client_uri:O().optional(),logo_uri:O().optional(),scope:O().optional(),contacts:ee(O()).optional(),tos_uri:O().optional(),policy_uri:O().optional(),jwks_uri:O().optional(),jwks:F0().optional(),software_id:O().optional(),software_version:O().optional(),software_statement:O().optional()}).strip(),$S=W({client_id:O(),client_secret:O().optional(),client_id_issued_at:dt().optional(),client_secret_expires_at:dt().optional()}).strip(),AS=OS.merge($S);W({error:O(),error_description:O().optional()}).strip(),W({token:O(),token_type_hint:O().optional()}).strip();function NS(t){const e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function MS({requestedResource:t,configuredResource:e}){const r=typeof t=="string"?new URL(t):new URL(t.href),a=typeof e=="string"?new URL(e):new URL(e.href);if(r.origin!==a.origin||r.pathname.length<a.pathname.length)return!1;const n=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=a.pathname.endsWith("/")?a.pathname:a.pathname+"/";return n.startsWith(s)}class ft extends Error{constructor(e,r){super(e),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){const e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}}class Ai extends ft{}Ai.errorCode="invalid_request";class Is extends ft{}Is.errorCode="invalid_client";class Ts extends ft{}Ts.errorCode="invalid_grant";class ks extends ft{}ks.errorCode="unauthorized_client";class Ni extends ft{}Ni.errorCode="unsupported_grant_type";class Mi extends ft{}Mi.errorCode="invalid_scope";class Di extends ft{}Di.errorCode="access_denied";class kn extends ft{}kn.errorCode="server_error";class ji extends ft{}ji.errorCode="temporarily_unavailable";class Li extends ft{}Li.errorCode="unsupported_response_type";class zi extends ft{}zi.errorCode="unsupported_token_type";class Ui extends ft{}Ui.errorCode="invalid_token";class Fi extends ft{}Fi.errorCode="method_not_allowed";class qi extends ft{}qi.errorCode="too_many_requests";class Zi extends ft{}Zi.errorCode="invalid_client_metadata";class Vi extends ft{}Vi.errorCode="insufficient_scope";const DS={[Ai.errorCode]:Ai,[Is.errorCode]:Is,[Ts.errorCode]:Ts,[ks.errorCode]:ks,[Ni.errorCode]:Ni,[Mi.errorCode]:Mi,[Di.errorCode]:Di,[kn.errorCode]:kn,[ji.errorCode]:ji,[Li.errorCode]:Li,[zi.errorCode]:zi,[Ui.errorCode]:Ui,[Fi.errorCode]:Fi,[qi.errorCode]:qi,[Zi.errorCode]:Zi,[Vi.errorCode]:Vi};class Gt extends Error{constructor(e){super(e??"Unauthorized")}}function zh(t,e){const r=t.client_secret!==void 0;return e.length===0?r?"client_secret_post":"none":r&&e.includes("client_secret_basic")?"client_secret_basic":r&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":r?"client_secret_post":"none"}function Uh(t,e,r,a){const{client_id:n,client_secret:s}=e;switch(t){case"client_secret_basic":jS(n,s,r);return;case"client_secret_post":LS(n,s,a);return;case"none":zS(n,a);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function jS(t,e,r){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");const a=btoa(`${t}:${e}`);r.set("Authorization",`Basic ${a}`)}function LS(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function zS(t,e){e.set("client_id",t)}async function Bi(t){const e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{const a=RS.parse(JSON.parse(r)),{error:n,error_description:s,error_uri:o}=a,i=DS[n]||kn;return new i(s||"",o)}catch(a){const n=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${a}. Raw body: ${r}`;return new kn(n)}}async function Pn(t,e){var r,a;try{return await Hi(t,e)}catch(n){if(n instanceof Is||n instanceof ks)return await((r=t.invalidateCredentials)===null||r===void 0?void 0:r.call(t,"all")),await Hi(t,e);if(n instanceof Ts)return await((a=t.invalidateCredentials)===null||a===void 0?void 0:a.call(t,"tokens")),await Hi(t,e);throw n}}async function Hi(t,{serverUrl:e,authorizationCode:r,scope:a,resourceMetadataUrl:n,fetchFn:s}){let o,i;try{o=await FS(e,{resourceMetadataUrl:n},s),o.authorization_servers&&o.authorization_servers.length>0&&(i=o.authorization_servers[0])}catch{}i||(i=e);const l=await US(e,t,o),u=await HS(i,{fetchFn:s});let d=await Promise.resolve(t.clientInformation());if(!d){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const f=await KS(i,{metadata:u,clientMetadata:t.clientMetadata});await t.saveClientInformation(f),d=f}if(r!==void 0){const f=await t.codeVerifier(),m=await WS(i,{metadata:u,clientInformation:d,authorizationCode:r,codeVerifier:f,redirectUri:t.redirectUrl,resource:l,addClientAuthentication:t.addClientAuthentication,fetchFn:s});return await t.saveTokens(m),"AUTHORIZED"}const h=await t.tokens();if(h!=null&&h.refresh_token)try{const f=await GS(i,{metadata:u,clientInformation:d,refreshToken:h.refresh_token,resource:l,addClientAuthentication:t.addClientAuthentication});return await t.saveTokens(f),"AUTHORIZED"}catch(f){if(!(!(f instanceof ft)||f instanceof kn))throw f}const g=t.state?await t.state():void 0,{authorizationUrl:c,codeVerifier:p}=await JS(i,{metadata:u,clientInformation:d,state:g,redirectUrl:t.redirectUrl,scope:a||t.clientMetadata.scope,resource:l});return await t.saveCodeVerifier(p),await t.redirectToAuthorization(c),"REDIRECT"}async function US(t,e,r){const a=NS(t);if(e.validateResourceURL)return await e.validateResourceURL(a,r==null?void 0:r.resource);if(r){if(!MS({requestedResource:a,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${a} (or origin)`);return new URL(r.resource)}}function Ji(t){const e=t.headers.get("WWW-Authenticate");if(!e)return;const[r,a]=e.split(" ");if(r.toLowerCase()!=="bearer"||!a)return;const s=/resource_metadata="([^"]*)"/.exec(e);if(s)try{return new URL(s[1])}catch{return}}async function FS(t,e,r=fetch){const a=await VS(t,"oauth-protected-resource",r,{protocolVersion:e==null?void 0:e.protocolVersion,metadataUrl:e==null?void 0:e.resourceMetadataUrl});if(!a||a.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!a.ok)throw new Error(`HTTP ${a.status} trying to load well-known OAuth protected resource metadata.`);return PS.parse(await a.json())}async function Wi(t,e,r=fetch){try{return await r(t,{headers:e})}catch(a){if(a instanceof TypeError)return e?Wi(t,void 0,r):void 0;throw a}}function qS(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function Fh(t,e,r=fetch){return await Wi(t,{"MCP-Protocol-Version":e},r)}function ZS(t,e){return!t||t.status===404&&e!=="/"}async function VS(t,e,r,a){var n,s;const o=new URL(t),i=(n=a==null?void 0:a.protocolVersion)!==null&&n!==void 0?n:_s;let l;if(a!=null&&a.metadataUrl)l=new URL(a.metadataUrl);else{const d=qS(e,o.pathname);l=new URL(d,(s=a==null?void 0:a.metadataServerUrl)!==null&&s!==void 0?s:o),l.search=o.search}let u=await Fh(l,i,r);if(!(a!=null&&a.metadataUrl)&&ZS(u,o.pathname)){const d=new URL(`/.well-known/${e}`,o);u=await Fh(d,i,r)}return u}function BS(t){const e=typeof t=="string"?new URL(t):t,r=e.pathname!=="/",a=[];if(!r)return a.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),a.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),a;let n=e.pathname;return n.endsWith("/")&&(n=n.slice(0,-1)),a.push({url:new URL(`/.well-known/oauth-authorization-server${n}`,e.origin),type:"oauth"}),a.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),a.push({url:new URL(`/.well-known/openid-configuration${n}`,e.origin),type:"oidc"}),a.push({url:new URL(`${n}/.well-known/openid-configuration`,e.origin),type:"oidc"}),a}async function HS(t,{fetchFn:e=fetch,protocolVersion:r=_s}={}){var a;const n={"MCP-Protocol-Version":r},s=BS(t);for(const{url:o,type:i}of s){const l=await Wi(o,n,e);if(!l)throw new Error(`CORS error trying to load ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${o}`);if(!l.ok){if(l.status>=400&&l.status<500)continue;throw new Error(`HTTP ${l.status} trying to load ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${o}`)}if(i==="oauth")return jh.parse(await l.json());{const u=CS.parse(await l.json());if(!(!((a=u.code_challenge_methods_supported)===null||a===void 0)&&a.includes("S256")))throw new Error(`Incompatible OIDC provider at ${o}: does not support S256 code challenge method required by MCP specification`);return u}}}async function JS(t,{metadata:e,clientInformation:r,redirectUrl:a,scope:n,state:s,resource:o}){const i="code",l="S256";let u;if(e){if(u=new URL(e.authorization_endpoint),!e.response_types_supported.includes(i))throw new Error(`Incompatible auth server: does not support response type ${i}`);if(!e.code_challenge_methods_supported||!e.code_challenge_methods_supported.includes(l))throw new Error(`Incompatible auth server: does not support code challenge method ${l}`)}else u=new URL("/authorize",t);const d=await kS(),h=d.code_verifier,g=d.code_challenge;return u.searchParams.set("response_type",i),u.searchParams.set("client_id",r.client_id),u.searchParams.set("code_challenge",g),u.searchParams.set("code_challenge_method",l),u.searchParams.set("redirect_uri",String(a)),s&&u.searchParams.set("state",s),n&&u.searchParams.set("scope",n),n!=null&&n.includes("offline_access")&&u.searchParams.append("prompt","consent"),o&&u.searchParams.set("resource",o.href),{authorizationUrl:u,codeVerifier:h}}async function WS(t,{metadata:e,clientInformation:r,authorizationCode:a,codeVerifier:n,redirectUri:s,resource:o,addClientAuthentication:i,fetchFn:l}){var u;const d="authorization_code",h=e!=null&&e.token_endpoint?new URL(e.token_endpoint):new URL("/token",t);if(e!=null&&e.grant_types_supported&&!e.grant_types_supported.includes(d))throw new Error(`Incompatible auth server: does not support grant type ${d}`);const g=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),c=new URLSearchParams({grant_type:d,code:a,code_verifier:n,redirect_uri:String(s)});if(i)i(g,c,t,e);else{const f=(u=e==null?void 0:e.token_endpoint_auth_methods_supported)!==null&&u!==void 0?u:[],m=zh(r,f);Uh(m,r,g,c)}o&&c.set("resource",o.href);const p=await(l??fetch)(h,{method:"POST",headers:g,body:c});if(!p.ok)throw await Bi(p);return Lh.parse(await p.json())}async function GS(t,{metadata:e,clientInformation:r,refreshToken:a,resource:n,addClientAuthentication:s,fetchFn:o}){var i;const l="refresh_token";let u;if(e){if(u=new URL(e.token_endpoint),e.grant_types_supported&&!e.grant_types_supported.includes(l))throw new Error(`Incompatible auth server: does not support grant type ${l}`)}else u=new URL("/token",t);const d=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),h=new URLSearchParams({grant_type:l,refresh_token:a});if(s)s(d,h,t,e);else{const c=(i=e==null?void 0:e.token_endpoint_auth_methods_supported)!==null&&i!==void 0?i:[],p=zh(r,c);Uh(p,r,d,h)}n&&h.set("resource",n.href);const g=await(o??fetch)(u,{method:"POST",headers:d,body:h});if(!g.ok)throw await Bi(g);return Lh.parse({refresh_token:a,...await g.json()})}async function KS(t,{metadata:e,clientMetadata:r,fetchFn:a}){let n;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");n=new URL(e.registration_endpoint)}else n=new URL("/register",t);const s=await(a??fetch)(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok)throw await Bi(s);return AS.parse(await s.json())}class qh extends Error{constructor(e,r){super(e),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}}function Gi(t){}function Zh(t){if(typeof t=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:e=Gi,onError:r=Gi,onRetry:a=Gi,onComment:n}=t;let s="",o=!0,i,l="",u="";function d(f){const m=o?f.replace(/^\xEF\xBB\xBF/,""):f,[v,w]=QS(`${s}${m}`);for(const y of v)h(y);s=w,o=!1}function h(f){if(f===""){c();return}if(f.startsWith(":")){n&&n(f.slice(f.startsWith(": ")?2:1));return}const m=f.indexOf(":");if(m!==-1){const v=f.slice(0,m),w=f[m+1]===" "?2:1,y=f.slice(m+w);g(v,y,f);return}g(f,"",f)}function g(f,m,v){switch(f){case"event":u=m;break;case"data":l=`${l}${m}
|
|
58
|
+
`;break;case"id":i=m.includes("\0")?void 0:m;break;case"retry":/^\d+$/.test(m)?a(parseInt(m,10)):r(new qh(`Invalid \`retry\` value: "${m}"`,{type:"invalid-retry",value:m,line:v}));break;default:r(new qh(`Unknown field "${f.length>20?`${f.slice(0,20)}…`:f}"`,{type:"unknown-field",field:f,value:m,line:v}));break}}function c(){l.length>0&&e({id:i,event:u||void 0,data:l.endsWith(`
|
|
59
|
+
`)?l.slice(0,-1):l}),i=void 0,l="",u=""}function p(f={}){s&&f.consume&&h(s),o=!0,i=void 0,l="",u="",s=""}return{feed:d,reset:p}}function QS(t){const e=[];let r="",a=0;for(;a<t.length;){const n=t.indexOf("\r",a),s=t.indexOf(`
|
|
60
|
+
`,a);let o=-1;if(n!==-1&&s!==-1?o=Math.min(n,s):n!==-1?o=n:s!==-1&&(o=s),o===-1){r=t.slice(a);break}else{const i=t.slice(a,o);e.push(i),a=o+1,t[a-1]==="\r"&&t[a]===`
|
|
61
|
+
`&&a++}}return[e,r]}class Vh extends TransformStream{constructor({onError:e,onRetry:r,onComment:a}={}){let n;super({start(s){n=Zh({onEvent:o=>{s.enqueue(o)},onError(o){e==="terminate"?s.error(o):typeof e=="function"&&e(o)},onRetry:r,onComment:a})},transform(s){n.feed(s)}})}}const YS={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class Ki extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}}class Ps{constructor(e,r){var a;this._url=e,this._resourceMetadataUrl=void 0,this._requestInit=r==null?void 0:r.requestInit,this._authProvider=r==null?void 0:r.authProvider,this._fetch=r==null?void 0:r.fetch,this._sessionId=r==null?void 0:r.sessionId,this._reconnectionOptions=(a=r==null?void 0:r.reconnectionOptions)!==null&&a!==void 0?a:YS}async _authThenStart(){var e;if(!this._authProvider)throw new Gt("No auth provider");let r;try{r=await Pn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(a){throw(e=this.onerror)===null||e===void 0||e.call(this,a),a}if(r!=="AUTHORIZED")throw new Gt;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;const r={};if(this._authProvider){const n=await this._authProvider.tokens();n&&(r.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(r["mcp-session-id"]=this._sessionId),this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);const a=this._normalizeHeaders((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...r,...a})}async _startOrAuthSse(e){var r,a,n;const{resumptionToken:s}=e;try{const o=await this._commonHeaders();o.set("Accept","text/event-stream"),s&&o.set("last-event-id",s);const i=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,{method:"GET",headers:o,signal:(a=this._abortController)===null||a===void 0?void 0:a.signal});if(!i.ok){if(i.status===401&&this._authProvider)return await this._authThenStart();if(i.status===405)return;throw new Ki(i.status,`Failed to open SSE stream: ${i.statusText}`)}this._handleSseStream(i.body,e,!0)}catch(o){throw(n=this.onerror)===null||n===void 0||n.call(this,o),o}}_getNextReconnectionDelay(e){const r=this._reconnectionOptions.initialReconnectionDelay,a=this._reconnectionOptions.reconnectionDelayGrowFactor,n=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(a,e),n)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,r=0){var a;const n=this._reconnectionOptions.maxRetries;if(n>0&&r>=n){(a=this.onerror)===null||a===void 0||a.call(this,new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}const s=this._getNextReconnectionDelay(r);setTimeout(()=>{this._startOrAuthSse(e).catch(o=>{var i;(i=this.onerror)===null||i===void 0||i.call(this,new Error(`Failed to reconnect SSE stream: ${o instanceof Error?o.message:String(o)}`)),this._scheduleReconnection(e,r+1)})},s)}_handleSseStream(e,r,a){if(!e)return;const{onresumptiontoken:n,replayMessageId:s}=r;let o;(async()=>{var l,u,d,h;try{const g=e.pipeThrough(new TextDecoderStream).pipeThrough(new Vh).getReader();for(;;){const{value:c,done:p}=await g.read();if(p)break;if(c.id&&(o=c.id,n==null||n(c.id)),!c.event||c.event==="message")try{const f=sn.parse(JSON.parse(c.data));s!==void 0&&Si(f)&&(f.id=s),(l=this.onmessage)===null||l===void 0||l.call(this,f)}catch(f){(u=this.onerror)===null||u===void 0||u.call(this,f)}}}catch(g){if((d=this.onerror)===null||d===void 0||d.call(this,new Error(`SSE stream disconnected: ${g}`)),a&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:o,onresumptiontoken:n,replayMessageId:s},0)}catch(c){(h=this.onerror)===null||h===void 0||h.call(this,new Error(`Failed to reconnect: ${c instanceof Error?c.message:String(c)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new Gt("No auth provider");if(await Pn(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new Gt("Failed to authorize")}async close(){var e,r;(e=this._abortController)===null||e===void 0||e.abort(),(r=this.onclose)===null||r===void 0||r.call(this)}async send(e,r){var a,n,s,o;try{const{resumptionToken:i,onresumptiontoken:l}=r||{};if(i){this._startOrAuthSse({resumptionToken:i,replayMessageId:oh(e)?e.id:void 0}).catch(m=>{var v;return(v=this.onerror)===null||v===void 0?void 0:v.call(this,m)});return}const u=await this._commonHeaders();u.set("content-type","application/json"),u.set("accept","application/json, text/event-stream");const d={...this._requestInit,method:"POST",headers:u,body:JSON.stringify(e),signal:(a=this._abortController)===null||a===void 0?void 0:a.signal},h=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._url,d),g=h.headers.get("mcp-session-id");if(g&&(this._sessionId=g),!h.ok){if(h.status===401&&this._authProvider){if(this._resourceMetadataUrl=Ji(h),await Pn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new Gt;return this.send(e)}const m=await h.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${h.status}): ${m}`)}if(h.status===202){VE(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(m=>{var v;return(v=this.onerror)===null||v===void 0?void 0:v.call(this,m)});return}const p=(Array.isArray(e)?e:[e]).filter(m=>"method"in m&&"id"in m&&m.id!==void 0).length>0,f=h.headers.get("content-type");if(p)if(f!=null&&f.includes("text/event-stream"))this._handleSseStream(h.body,{onresumptiontoken:l},!1);else if(f!=null&&f.includes("application/json")){const m=await h.json(),v=Array.isArray(m)?m.map(w=>sn.parse(w)):[sn.parse(m)];for(const w of v)(s=this.onmessage)===null||s===void 0||s.call(this,w)}else throw new Ki(-1,`Unexpected content type: ${f}`)}catch(i){throw(o=this.onerror)===null||o===void 0||o.call(this,i),i}}get sessionId(){return this._sessionId}async terminateSession(){var e,r,a;if(this._sessionId)try{const n=await this._commonHeaders(),s={...this._requestInit,method:"DELETE",headers:n,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},o=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,s);if(!o.ok&&o.status!==405)throw new Ki(o.status,`Failed to terminate session: ${o.statusText}`);this._sessionId=void 0}catch(n){throw(a=this.onerror)===null||a===void 0||a.call(this,n),n}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}}class Cs{constructor(){this._messageQueue=[]}static createLinkedPair(){const e=new Cs,r=new Cs;return e._otherTransport=r,r._otherTransport=e,[e,r]}async start(){for(var e;this._messageQueue.length>0;){const r=this._messageQueue.shift();(e=this.onmessage)===null||e===void 0||e.call(this,r.message,r.extra)}}async close(){var e;const r=this._otherTransport;this._otherTransport=void 0,await(r==null?void 0:r.close()),(e=this.onclose)===null||e===void 0||e.call(this)}async send(e,r){if(!this._otherTransport)throw new Error("Not connected");this._otherTransport.onmessage?this._otherTransport.onmessage(e,{authInfo:r==null?void 0:r.authInfo}):this._otherTransport._messageQueue.push({message:e,extra:{authInfo:r==null?void 0:r.authInfo}})}}new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Ut(...t){return t.reduce((e,r)=>({...e,...r??{}}),{})}function ya(t){return Object.fromEntries([...t.headers])}var XS=({prefix:t,size:e=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:a="-"}={})=>{const n=()=>{const s=r.length,o=new Array(e);for(let i=0;i<e;i++)o[i]=r[Math.random()*s|0];return o.join("")};if(t==null)return n;if(r.includes(a))throw new vo({argument:"separator",message:`The separator "${a}" must not be part of the alphabet "${r}".`});return()=>`${t}${a}${n()}`},Ot=XS();function Qi(t){return(t instanceof Error||t instanceof DOMException)&&(t.name==="AbortError"||t.name==="ResponseAborted"||t.name==="TimeoutError")}var eI=["fetch failed","failed to fetch"];function tI({error:t,url:e,requestBodyValues:r}){if(Qi(t))return t;if(t instanceof TypeError&&eI.includes(t.message.toLowerCase())){const a=t.cause;if(a!=null)return new Ue({message:`Cannot connect to API: ${a.message}`,cause:a,url:e,requestBodyValues:r,isRetryable:!0})}return t}function rI(t){return Object.fromEntries(Object.entries(t).filter(([e,r])=>r!=null))}function Bh({apiKey:t,environmentVariableName:e,apiKeyParameterName:r="apiKey",description:a}){if(typeof t=="string")return t;if(t!=null)throw new La({message:`${a} API key must be a string.`});if(typeof process>"u")throw new La({message:`${a} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(t=process.env[e],t==null)throw new La({message:`${a} API key is missing. Pass it using the '${r}' parameter or the ${e} environment variable.`});if(typeof t!="string")throw new La({message:`${a} API key must be a string. The value of the ${e} environment variable is not a string.`});return t}var nI=/"__proto__"\s*:/,aI=/"constructor"\s*:/;function sI(t){const e=JSON.parse(t);return e===null||typeof e!="object"||nI.test(t)===!1&&aI.test(t)===!1?e:oI(e)}function oI(t){let e=[t];for(;e.length;){const r=e;e=[];for(const a of r){if(Object.prototype.hasOwnProperty.call(a,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(a,"constructor")&&Object.prototype.hasOwnProperty.call(a.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const n in a){const s=a[n];s&&typeof s=="object"&&e.push(s)}}}return t}function Yi(t){const{stackTraceLimit:e}=Error;Error.stackTraceLimit=0;try{return sI(t)}finally{Error.stackTraceLimit=e}}var Xi=Symbol.for("vercel.ai.validator");function iI(t){return{[Xi]:!0,validate:t}}function lI(t){return typeof t=="object"&&t!==null&&Xi in t&&t[Xi]===!0&&"validate"in t}function uI(t){return lI(t)?t:cI(t)}function cI(t){return iI(async e=>{const r=await t["~standard"].validate(e);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new er({value:e,cause:r.issues})}})}async function dI({value:t,schema:e}){const r=await _a({value:t,schema:e});if(!r.success)throw er.wrap({value:t,cause:r.error});return r.value}async function _a({value:t,schema:e}){const r=uI(e);try{if(r.validate==null)return{success:!0,value:t,rawValue:t};const a=await r.validate(t);return a.success?{success:!0,value:a.value,rawValue:t}:{success:!1,error:er.wrap({value:t,cause:a.error}),rawValue:t}}catch(a){return{success:!1,error:er.wrap({value:t,cause:a}),rawValue:t}}}async function pI({text:t,schema:e}){try{const r=Yi(t);return e==null?r:dI({value:r,schema:e})}catch(r){throw Tr.isInstance(r)||er.isInstance(r)?r:new Tr({text:t,cause:r})}}async function Hh({text:t,schema:e}){try{const r=Yi(t);return e==null?{success:!0,value:r,rawValue:r}:await _a({value:r,schema:e})}catch(r){return{success:!1,error:Tr.isInstance(r)?r:new Tr({text:t,cause:r}),rawValue:void 0}}}function Rs(t){try{return Yi(t),!0}catch{return!1}}function hI({stream:t,schema:e}){return t.pipeThrough(new TextDecoderStream).pipeThrough(new Vh).pipeThrough(new TransformStream({async transform({data:r},a){r!=="[DONE]"&&a.enqueue(await Hh({text:r,schema:e}))}}))}async function lr({provider:t,providerOptions:e,schema:r}){if((e==null?void 0:e[t])==null)return;const a=await _a({value:e[t],schema:r});if(!a.success)throw new vo({argument:"providerOptions",message:`invalid ${t} provider options`,cause:a.error});return a.value}var fI=()=>globalThis.fetch,Kt=async({url:t,headers:e,body:r,failedResponseHandler:a,successfulResponseHandler:n,abortSignal:s,fetch:o})=>Jh({url:t,headers:{"Content-Type":"application/json",...e},body:{content:JSON.stringify(r),values:r},failedResponseHandler:a,successfulResponseHandler:n,abortSignal:s,fetch:o}),mI=async({url:t,headers:e,formData:r,failedResponseHandler:a,successfulResponseHandler:n,abortSignal:s,fetch:o})=>Jh({url:t,headers:e,body:{content:r,values:Object.fromEntries(r.entries())},failedResponseHandler:a,successfulResponseHandler:n,abortSignal:s,fetch:o}),Jh=async({url:t,headers:e={},body:r,successfulResponseHandler:a,failedResponseHandler:n,abortSignal:s,fetch:o=fI()})=>{try{const i=await o(t,{method:"POST",headers:rI(e),body:r.content,signal:s}),l=ya(i);if(!i.ok){let u;try{u=await n({response:i,url:t,requestBodyValues:r.values})}catch(d){throw Qi(d)||Ue.isInstance(d)?d:new Ue({message:"Failed to process error response",cause:d,statusCode:i.status,url:t,responseHeaders:l,requestBodyValues:r.values})}throw u.value}try{return await a({response:i,url:t,requestBodyValues:r.values})}catch(u){throw u instanceof Error&&(Qi(u)||Ue.isInstance(u))?u:new Ue({message:"Failed to process successful response",cause:u,statusCode:i.status,url:t,responseHeaders:l,requestBodyValues:r.values})}}catch(i){throw tI({error:i,url:t,requestBodyValues:r.values})}};function b2(t){return t}function el({id:t,name:e,inputSchema:r}){return({execute:a,outputSchema:n,toModelOutput:s,onInputStart:o,onInputDelta:i,onInputAvailable:l,...u})=>({type:"provider-defined",id:t,name:e,args:u,inputSchema:r,outputSchema:n,execute:a,toModelOutput:s,onInputStart:o,onInputDelta:i,onInputAvailable:l})}var Wh=({errorSchema:t,errorToMessage:e,isRetryable:r})=>async({response:a,url:n,requestBodyValues:s})=>{const o=await a.text(),i=ya(a);if(o.trim()==="")return{responseHeaders:i,value:new Ue({message:a.statusText,url:n,requestBodyValues:s,statusCode:a.status,responseHeaders:i,responseBody:o,isRetryable:r==null?void 0:r(a)})};try{const l=await pI({text:o,schema:t});return{responseHeaders:i,value:new Ue({message:e(l),url:n,requestBodyValues:s,statusCode:a.status,responseHeaders:i,responseBody:o,data:l,isRetryable:r==null?void 0:r(a,l)})}}catch{return{responseHeaders:i,value:new Ue({message:a.statusText,url:n,requestBodyValues:s,statusCode:a.status,responseHeaders:i,responseBody:o,isRetryable:r==null?void 0:r(a)})}}},Os=t=>async({response:e})=>{const r=ya(e);if(e.body==null)throw new su({});return{responseHeaders:r,value:hI({stream:e.body,schema:t})}},ln=t=>async({response:e,url:r,requestBodyValues:a})=>{const n=await e.text(),s=await Hh({text:n,schema:t}),o=ya(e);if(!s.success)throw new Ue({message:"Invalid JSON response",cause:s.error,statusCode:e.status,responseHeaders:o,responseBody:n,url:r,requestBodyValues:a});return{responseHeaders:o,value:s.value,rawValue:s.rawValue}},vI=()=>async({response:t,url:e,requestBodyValues:r})=>{const a=ya(t);if(!t.body)throw new Ue({message:"Response body is empty",url:e,requestBodyValues:r,statusCode:t.status,responseHeaders:a,responseBody:void 0});try{const n=await t.arrayBuffer();return{responseHeaders:a,value:new Uint8Array(n)}}catch(n){throw new Ue({message:"Failed to read response as array buffer",url:e,requestBodyValues:r,statusCode:t.status,responseHeaders:a,responseBody:void 0,cause:n})}},{btoa:gI,atob:yI}=globalThis;function _I(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=yI(e);return Uint8Array.from(r,a=>a.codePointAt(0))}function wI(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCodePoint(t[r]);return gI(e)}function un(t){return t instanceof Uint8Array?wI(t):t}function Gh(t){return t==null?void 0:t.replace(/\/$/,"")}var tl=P({error:P({message:x(),type:x().nullish(),param:Mt().nullish(),code:Ae([x(),U()]).nullish()})}),ur=Wh({errorSchema:tl,errorToMessage:t=>t.error.message});function bI({prompt:t,systemMessageMode:e="system"}){const r=[],a=[];for(const{role:n,content:s}of t)switch(n){case"system":{switch(e){case"system":{r.push({role:"system",content:s});break}case"developer":{r.push({role:"developer",content:s});break}case"remove":{a.push({type:"other",message:"system messages are removed for this model"});break}default:{const o=e;throw new Error(`Unsupported system message mode: ${o}`)}}break}case"user":{if(s.length===1&&s[0].type==="text"){r.push({role:"user",content:s[0].text});break}r.push({role:"user",content:s.map((o,i)=>{var l,u,d;switch(o.type){case"text":return{type:"text",text:o.text};case"file":if(o.mediaType.startsWith("image/")){const h=o.mediaType==="image/*"?"image/jpeg":o.mediaType;return{type:"image_url",image_url:{url:o.data instanceof URL?o.data.toString():`data:${h};base64,${un(o.data)}`,detail:(u=(l=o.providerOptions)==null?void 0:l.openai)==null?void 0:u.imageDetail}}}else if(o.mediaType.startsWith("audio/")){if(o.data instanceof URL)throw new Nt({functionality:"audio file parts with URLs"});switch(o.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:un(o.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:un(o.data),format:"mp3"}};default:throw new Nt({functionality:`audio content parts with media type ${o.mediaType}`})}}else if(o.mediaType==="application/pdf"){if(o.data instanceof URL)throw new Nt({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof o.data=="string"&&o.data.startsWith("file-")?{file_id:o.data}:{filename:(d=o.filename)!=null?d:`part-${i}.pdf`,file_data:`data:application/pdf;base64,${un(o.data)}`}}}else throw new Nt({functionality:`file part media type ${o.mediaType}`})}})});break}case"assistant":{let o="";const i=[];for(const l of s)switch(l.type){case"text":{o+=l.text;break}case"tool-call":{i.push({id:l.toolCallId,type:"function",function:{name:l.toolName,arguments:JSON.stringify(l.input)}});break}}r.push({role:"assistant",content:o,tool_calls:i.length>0?i:void 0});break}case"tool":{for(const o of s){const i=o.output;let l;switch(i.type){case"text":case"error-text":l=i.value;break;case"content":case"json":case"error-json":l=JSON.stringify(i.value);break}r.push({role:"tool",tool_call_id:o.toolCallId,content:l})}break}default:{const o=n;throw new Error(`Unsupported role: ${o}`)}}return{messages:r,warnings:a}}function Kh({id:t,model:e,created:r}){return{id:t??void 0,modelId:e??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function Qh(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var xI=P({logitBias:St(m0(),U()).optional(),logprobs:Ae([nt(),U()]).optional(),parallelToolCalls:nt().optional(),user:x().optional(),reasoningEffort:vt(["minimal","low","medium","high"]).optional(),maxCompletionTokens:U().optional(),store:nt().optional(),metadata:St(x().max(64),x().max(512)).optional(),prediction:St(x(),Mt()).optional(),structuredOutputs:nt().optional(),serviceTier:vt(["auto","flex","priority"]).optional(),strictJsonSchema:nt().optional(),textVerbosity:vt(["low","medium","high"]).optional(),promptCacheKey:x().optional(),safetyIdentifier:x().optional()}),Yh=P({key:x(),type:vt(["eq","ne","gt","gte","lt","lte"]),value:Ae([x(),U(),nt()])}),Xh=P({type:vt(["and","or"]),filters:Y(Ae([Yh,Pc(()=>Xh)]))}),EI=Ae([Yh,Xh]),ef=P({vectorStoreIds:Y(x()).optional(),maxNumResults:U().optional(),ranking:P({ranker:vt(["auto","default-2024-08-21"]).optional()}).optional(),filters:EI.optional()}),SI=el({id:"openai.file_search",name:"file_search",inputSchema:P({query:x()})}),tf=P({searchContextSize:vt(["low","medium","high"]).optional(),userLocation:P({type:H("approximate"),country:x().optional(),city:x().optional(),region:x().optional(),timezone:x().optional()}).optional()}),II=el({id:"openai.web_search_preview",name:"web_search_preview",inputSchema:P({})});function TI({tools:t,toolChoice:e,structuredOutputs:r,strictJsonSchema:a}){t=t!=null&&t.length?t:void 0;const n=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};const s=[];for(const i of t)switch(i.type){case"function":s.push({type:"function",function:{name:i.name,description:i.description,parameters:i.inputSchema,strict:r?a:void 0}});break;case"provider-defined":switch(i.id){case"openai.file_search":{const l=ef.parse(i.args);s.push({type:"file_search",vector_store_ids:l.vectorStoreIds,max_num_results:l.maxNumResults,ranking_options:l.ranking?{ranker:l.ranking.ranker}:void 0,filters:l.filters});break}case"openai.web_search_preview":{const l=tf.parse(i.args);s.push({type:"web_search_preview",search_context_size:l.searchContextSize,user_location:l.userLocation});break}default:n.push({type:"unsupported-tool",tool:i});break}break;default:n.push({type:"unsupported-tool",tool:i});break}if(e==null)return{tools:s,toolChoice:void 0,toolWarnings:n};const o=e.type;switch(o){case"auto":case"none":case"required":return{tools:s,toolChoice:o,toolWarnings:n};case"tool":return{tools:s,toolChoice:{type:"function",function:{name:e.toolName}},toolWarnings:n};default:{const i=o;throw new Nt({functionality:`tool choice type: ${i}`})}}}var kI=class{constructor(t,e){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=t,this.config=e}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:e,temperature:r,topP:a,topK:n,frequencyPenalty:s,presencePenalty:o,stopSequences:i,responseFormat:l,seed:u,tools:d,toolChoice:h,providerOptions:g}){var c,p,f,m;const v=[],w=(c=await lr({provider:"openai",providerOptions:g,schema:xI}))!=null?c:{},y=(p=w.structuredOutputs)!=null?p:!0;n!=null&&v.push({type:"unsupported-setting",setting:"topK"}),(l==null?void 0:l.type)==="json"&&l.schema!=null&&!y&&v.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{messages:_,warnings:E}=bI({prompt:t,systemMessageMode:$I(this.modelId)});v.push(...E);const I=(f=w.strictJsonSchema)!=null?f:!1,S={model:this.modelId,logit_bias:w.logitBias,logprobs:w.logprobs===!0||typeof w.logprobs=="number"?!0:void 0,top_logprobs:typeof w.logprobs=="number"?w.logprobs:typeof w.logprobs=="boolean"&&w.logprobs?0:void 0,user:w.user,parallel_tool_calls:w.parallelToolCalls,max_tokens:e,temperature:r,top_p:a,frequency_penalty:s,presence_penalty:o,response_format:(l==null?void 0:l.type)==="json"?y&&l.schema!=null?{type:"json_schema",json_schema:{schema:l.schema,strict:I,name:(m=l.name)!=null?m:"response",description:l.description}}:{type:"json_object"}:void 0,stop:i,seed:u,verbosity:w.textVerbosity,max_completion_tokens:w.maxCompletionTokens,store:w.store,metadata:w.metadata,prediction:w.prediction,reasoning_effort:w.reasoningEffort,service_tier:w.serviceTier,prompt_cache_key:w.promptCacheKey,safety_identifier:w.safetyIdentifier,messages:_};nf(this.modelId)?(S.temperature!=null&&(S.temperature=void 0,v.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),S.top_p!=null&&(S.top_p=void 0,v.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"})),S.frequency_penalty!=null&&(S.frequency_penalty=void 0,v.push({type:"unsupported-setting",setting:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),S.presence_penalty!=null&&(S.presence_penalty=void 0,v.push({type:"unsupported-setting",setting:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),S.logit_bias!=null&&(S.logit_bias=void 0,v.push({type:"other",message:"logitBias is not supported for reasoning models"})),S.logprobs!=null&&(S.logprobs=void 0,v.push({type:"other",message:"logprobs is not supported for reasoning models"})),S.top_logprobs!=null&&(S.top_logprobs=void 0,v.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,v.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),w.serviceTier==="flex"&&!RI(this.modelId)&&(v.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),S.service_tier=void 0),w.serviceTier==="priority"&&!OI(this.modelId)&&(v.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),S.service_tier=void 0);const{tools:R,toolChoice:$,toolWarnings:z}=TI({tools:d,toolChoice:h,structuredOutputs:y,strictJsonSchema:I});return{args:{...S,tools:R,tool_choice:$},warnings:[...v,...z]}}async doGenerate(t){var e,r,a,n,s,o,i,l,u,d,h,g,c,p;const{args:f,warnings:m}=await this.getArgs(t),{responseHeaders:v,value:w,rawValue:y}=await Kt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Ut(this.config.headers(),t.headers),body:f,failedResponseHandler:ur,successfulResponseHandler:ln(PI),abortSignal:t.abortSignal,fetch:this.config.fetch}),_=w.choices[0],E=[],I=_.message.content;I!=null&&I.length>0&&E.push({type:"text",text:I});for(const z of(e=_.message.tool_calls)!=null?e:[])E.push({type:"tool-call",toolCallId:(r=z.id)!=null?r:Ot(),toolName:z.function.name,input:z.function.arguments});for(const z of(a=_.message.annotations)!=null?a:[])E.push({type:"source",sourceType:"url",id:Ot(),url:z.url,title:z.title});const S=(n=w.usage)==null?void 0:n.completion_tokens_details,R=(s=w.usage)==null?void 0:s.prompt_tokens_details,$={openai:{}};return(S==null?void 0:S.accepted_prediction_tokens)!=null&&($.openai.acceptedPredictionTokens=S==null?void 0:S.accepted_prediction_tokens),(S==null?void 0:S.rejected_prediction_tokens)!=null&&($.openai.rejectedPredictionTokens=S==null?void 0:S.rejected_prediction_tokens),((o=_.logprobs)==null?void 0:o.content)!=null&&($.openai.logprobs=_.logprobs.content),{content:E,finishReason:Qh(_.finish_reason),usage:{inputTokens:(l=(i=w.usage)==null?void 0:i.prompt_tokens)!=null?l:void 0,outputTokens:(d=(u=w.usage)==null?void 0:u.completion_tokens)!=null?d:void 0,totalTokens:(g=(h=w.usage)==null?void 0:h.total_tokens)!=null?g:void 0,reasoningTokens:(c=S==null?void 0:S.reasoning_tokens)!=null?c:void 0,cachedInputTokens:(p=R==null?void 0:R.cached_tokens)!=null?p:void 0},request:{body:f},response:{...Kh(w),headers:v,body:y},warnings:m,providerMetadata:$}}async doStream(t){const{args:e,warnings:r}=await this.getArgs(t),a={...e,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:n,value:s}=await Kt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Ut(this.config.headers(),t.headers),body:a,failedResponseHandler:ur,successfulResponseHandler:Os(CI),abortSignal:t.abortSignal,fetch:this.config.fetch}),o=[];let i="unknown";const l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let u=!0,d=!1;const h={openai:{}};return{stream:s.pipeThrough(new TransformStream({start(g){g.enqueue({type:"stream-start",warnings:r})},transform(g,c){var p,f,m,v,w,y,_,E,I,S,R,$,z,L,F,M,D,K,oe,ie,C,re,B,de;if(t.includeRawChunks&&c.enqueue({type:"raw",rawValue:g.rawValue}),!g.success){i="error",c.enqueue({type:"error",error:g.error});return}const ae=g.value;if("error"in ae){i="error",c.enqueue({type:"error",error:ae.error});return}u&&(u=!1,c.enqueue({type:"response-metadata",...Kh(ae)})),ae.usage!=null&&(l.inputTokens=(p=ae.usage.prompt_tokens)!=null?p:void 0,l.outputTokens=(f=ae.usage.completion_tokens)!=null?f:void 0,l.totalTokens=(m=ae.usage.total_tokens)!=null?m:void 0,l.reasoningTokens=(w=(v=ae.usage.completion_tokens_details)==null?void 0:v.reasoning_tokens)!=null?w:void 0,l.cachedInputTokens=(_=(y=ae.usage.prompt_tokens_details)==null?void 0:y.cached_tokens)!=null?_:void 0,((E=ae.usage.completion_tokens_details)==null?void 0:E.accepted_prediction_tokens)!=null&&(h.openai.acceptedPredictionTokens=(I=ae.usage.completion_tokens_details)==null?void 0:I.accepted_prediction_tokens),((S=ae.usage.completion_tokens_details)==null?void 0:S.rejected_prediction_tokens)!=null&&(h.openai.rejectedPredictionTokens=(R=ae.usage.completion_tokens_details)==null?void 0:R.rejected_prediction_tokens));const ke=ae.choices[0];if((ke==null?void 0:ke.finish_reason)!=null&&(i=Qh(ke.finish_reason)),(($=ke==null?void 0:ke.logprobs)==null?void 0:$.content)!=null&&(h.openai.logprobs=ke.logprobs.content),(ke==null?void 0:ke.delta)==null)return;const _e=ke.delta;if(_e.content!=null&&(d||(c.enqueue({type:"text-start",id:"0"}),d=!0),c.enqueue({type:"text-delta",id:"0",delta:_e.content})),_e.tool_calls!=null)for(const Pe of _e.tool_calls){const xe=Pe.index;if(o[xe]==null){if(Pe.type!=="function")throw new Zn({data:Pe,message:"Expected 'function' type."});if(Pe.id==null)throw new Zn({data:Pe,message:"Expected 'id' to be a string."});if(((z=Pe.function)==null?void 0:z.name)==null)throw new Zn({data:Pe,message:"Expected 'function.name' to be a string."});c.enqueue({type:"tool-input-start",id:Pe.id,toolName:Pe.function.name}),o[xe]={id:Pe.id,type:"function",function:{name:Pe.function.name,arguments:(L=Pe.function.arguments)!=null?L:""},hasFinished:!1};const Re=o[xe];((F=Re.function)==null?void 0:F.name)!=null&&((M=Re.function)==null?void 0:M.arguments)!=null&&(Re.function.arguments.length>0&&c.enqueue({type:"tool-input-delta",id:Re.id,delta:Re.function.arguments}),Rs(Re.function.arguments)&&(c.enqueue({type:"tool-input-end",id:Re.id}),c.enqueue({type:"tool-call",toolCallId:(D=Re.id)!=null?D:Ot(),toolName:Re.function.name,input:Re.function.arguments}),Re.hasFinished=!0));continue}const ve=o[xe];ve.hasFinished||(((K=Pe.function)==null?void 0:K.arguments)!=null&&(ve.function.arguments+=(ie=(oe=Pe.function)==null?void 0:oe.arguments)!=null?ie:""),c.enqueue({type:"tool-input-delta",id:ve.id,delta:(C=Pe.function.arguments)!=null?C:""}),((re=ve.function)==null?void 0:re.name)!=null&&((B=ve.function)==null?void 0:B.arguments)!=null&&Rs(ve.function.arguments)&&(c.enqueue({type:"tool-input-end",id:ve.id}),c.enqueue({type:"tool-call",toolCallId:(de=ve.id)!=null?de:Ot(),toolName:ve.function.name,input:ve.function.arguments}),ve.hasFinished=!0))}if(_e.annotations!=null)for(const Pe of _e.annotations)c.enqueue({type:"source",sourceType:"url",id:Ot(),url:Pe.url,title:Pe.title})},flush(g){d&&g.enqueue({type:"text-end",id:"0"}),g.enqueue({type:"finish",finishReason:i,usage:l,...h!=null?{providerMetadata:h}:{}})}})),request:{body:a},response:{headers:n}}}},rf=P({prompt_tokens:U().nullish(),completion_tokens:U().nullish(),total_tokens:U().nullish(),prompt_tokens_details:P({cached_tokens:U().nullish()}).nullish(),completion_tokens_details:P({reasoning_tokens:U().nullish(),accepted_prediction_tokens:U().nullish(),rejected_prediction_tokens:U().nullish()}).nullish()}).nullish(),PI=P({id:x().nullish(),created:U().nullish(),model:x().nullish(),choices:Y(P({message:P({role:H("assistant").nullish(),content:x().nullish(),tool_calls:Y(P({id:x().nullish(),type:H("function"),function:P({name:x(),arguments:x()})})).nullish(),annotations:Y(P({type:H("url_citation"),start_index:U(),end_index:U(),url:x(),title:x()})).nullish()}),index:U(),logprobs:P({content:Y(P({token:x(),logprob:U(),top_logprobs:Y(P({token:x(),logprob:U()}))})).nullish()}).nullish(),finish_reason:x().nullish()})),usage:rf}),CI=Ae([P({id:x().nullish(),created:U().nullish(),model:x().nullish(),choices:Y(P({delta:P({role:vt(["assistant"]).nullish(),content:x().nullish(),tool_calls:Y(P({index:U(),id:x().nullish(),type:H("function").nullish(),function:P({name:x().nullish(),arguments:x().nullish()})})).nullish(),annotations:Y(P({type:H("url_citation"),start_index:U(),end_index:U(),url:x(),title:x()})).nullish()}).nullish(),logprobs:P({content:Y(P({token:x(),logprob:U(),top_logprobs:Y(P({token:x(),logprob:U()}))})).nullish()}).nullish(),finish_reason:x().nullish(),index:U()})),usage:rf}),tl]);function nf(t){return(t.startsWith("o")||t.startsWith("gpt-5"))&&!t.startsWith("gpt-5-chat")}function RI(t){return t.startsWith("o3")||t.startsWith("o4-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat")}function OI(t){return t.startsWith("gpt-4")||t.startsWith("gpt-5-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-nano")&&!t.startsWith("gpt-5-chat")||t.startsWith("o3")||t.startsWith("o4-mini")}function $I(t){var e,r;return nf(t)?(r=(e=AI[t])==null?void 0:e.systemMessageMode)!=null?r:"developer":"system"}var AI={"o1-mini":{systemMessageMode:"remove"},"o1-mini-2024-09-12":{systemMessageMode:"remove"},"o1-preview":{systemMessageMode:"remove"},"o1-preview-2024-09-12":{systemMessageMode:"remove"},o3:{systemMessageMode:"developer"},"o3-2025-04-16":{systemMessageMode:"developer"},"o3-mini":{systemMessageMode:"developer"},"o3-mini-2025-01-31":{systemMessageMode:"developer"},"o4-mini":{systemMessageMode:"developer"},"o4-mini-2025-04-16":{systemMessageMode:"developer"}};function NI({prompt:t,user:e="user",assistant:r="assistant"}){let a="";t[0].role==="system"&&(a+=`${t[0].content}
|
|
58
62
|
|
|
59
|
-
`,
|
|
60
|
-
${
|
|
63
|
+
`,t=t.slice(1));for(const{role:n,content:s}of t)switch(n){case"system":throw new Br({message:"Unexpected system message in prompt: ${content}",prompt:t});case"user":{const o=s.map(i=>{switch(i.type){case"text":return i.text}}).filter(Boolean).join("");a+=`${e}:
|
|
64
|
+
${o}
|
|
61
65
|
|
|
62
|
-
`;break}case"assistant":{const
|
|
63
|
-
${
|
|
66
|
+
`;break}case"assistant":{const o=s.map(i=>{switch(i.type){case"text":return i.text;case"tool-call":throw new Nt({functionality:"tool-call messages"})}}).join("");a+=`${r}:
|
|
67
|
+
${o}
|
|
64
68
|
|
|
65
|
-
`;break}case"tool":throw new
|
|
66
|
-
`,{prompt:
|
|
67
|
-
${t}:`]}}function id({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n!=null?new Date(n*1e3):void 0}}function ld(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 Wx=Ee(()=>te(g({id:d().nullish(),created:I().nullish(),model:d().nullish(),choices:z(g({text:d(),finish_reason:d(),logprobs:g({tokens:z(d()),token_logprobs:z(I()),top_logprobs:z(Oe(d(),I())).nullish()}).nullish()})),usage:g({prompt_tokens:I(),completion_tokens:I(),total_tokens:I()}).nullish()}))),Kx=Ee(()=>te(ue([g({id:d().nullish(),created:I().nullish(),model:d().nullish(),choices:z(g({text:d(),finish_reason:d().nullish(),index:I(),logprobs:g({tokens:z(d()),token_logprobs:z(I()),top_logprobs:z(Oe(d(),I())).nullish()}).nullish()})),usage:g({prompt_tokens:I(),completion_tokens:I(),total_tokens:I()}).nullish()}),na]))),ud=Ee(()=>te(g({echo:Ae().optional(),logitBias:Oe(d(),I()).optional(),suffix:d().optional(),user:d().optional(),logprobs:ue([Ae(),I()]).optional()}))),Yx=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={},this.modelId=e,this.config=t}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:o,frequencyPenalty:s,presencePenalty:a,stopSequences:i,responseFormat:l,tools:u,toolChoice:p,seed:x,providerOptions:w}){const h=[],f={...await St({provider:"openai",providerOptions:w,schema:ud}),...await St({provider:this.providerOptionsName,providerOptions:w,schema:ud})};o!=null&&h.push({type:"unsupported-setting",setting:"topK"}),u!=null&&u.length&&h.push({type:"unsupported-setting",setting:"tools"}),p!=null&&h.push({type:"unsupported-setting",setting:"toolChoice"}),l!=null&&l.type!=="text"&&h.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});const{prompt:y,stopSequences:m}=Gx({prompt:e}),c=[...m??[],...i??[]];return{args:{model:this.modelId,echo:f.echo,logit_bias:f.logitBias,logprobs:(f==null?void 0:f.logprobs)===!0?0:(f==null?void 0:f.logprobs)===!1||f==null?void 0:f.logprobs,suffix:f.suffix,user:f.user,max_tokens:t,temperature:n,top_p:r,frequency_penalty:s,presence_penalty:a,seed:x,prompt:y,stop:c.length>0?c:void 0},warnings:h}}async doGenerate(e){var t,n,r;const{args:o,warnings:s}=await this.getArgs(e),{responseHeaders:a,value:i,rawValue:l}=await nt({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Ge(this.config.headers(),e.headers),body:o,failedResponseHandler:At,successfulResponseHandler:vt(Wx),abortSignal:e.abortSignal,fetch:this.config.fetch}),u=i.choices[0],p={openai:{}};return u.logprobs!=null&&(p.openai.logprobs=u.logprobs),{content:[{type:"text",text:u.text}],usage:{inputTokens:(t=i.usage)==null?void 0:t.prompt_tokens,outputTokens:(n=i.usage)==null?void 0:n.completion_tokens,totalTokens:(r=i.usage)==null?void 0:r.total_tokens},finishReason:ld(u.finish_reason),request:{body:o},response:{...id(i),headers:a,body:l},providerMetadata:p,warnings:s}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:o,value:s}=await nt({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Ge(this.config.headers(),e.headers),body:r,failedResponseHandler:At,successfulResponseHandler:Qn(Kx),abortSignal:e.abortSignal,fetch:this.config.fetch});let a="unknown";const i={openai:{}},l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let u=!0;return{stream:s.pipeThrough(new TransformStream({start(p){p.enqueue({type:"stream-start",warnings:n})},transform(p,x){if(e.includeRawChunks&&x.enqueue({type:"raw",rawValue:p.rawValue}),!p.success){a="error",x.enqueue({type:"error",error:p.error});return}const w=p.value;if("error"in w){a="error",x.enqueue({type:"error",error:w.error});return}u&&(u=!1,x.enqueue({type:"response-metadata",...id(w)}),x.enqueue({type:"text-start",id:"0"})),w.usage!=null&&(l.inputTokens=w.usage.prompt_tokens,l.outputTokens=w.usage.completion_tokens,l.totalTokens=w.usage.total_tokens);const h=w.choices[0];(h==null?void 0:h.finish_reason)!=null&&(a=ld(h.finish_reason)),(h==null?void 0:h.logprobs)!=null&&(i.openai.logprobs=h.logprobs),(h==null?void 0:h.text)!=null&&h.text.length>0&&x.enqueue({type:"text-delta",id:"0",delta:h.text})},flush(p){u||p.enqueue({type:"text-end",id:"0"}),p.enqueue({type:"finish",finishReason:a,providerMetadata:i,usage:l})}})),request:{body:r},response:{headers:o}}}},Xx=Ee(()=>te(g({dimensions:I().optional(),user:d().optional()}))),Qx=Ee(()=>te(g({data:z(g({embedding:z(I())})),usage:g({prompt_tokens:I()}).nullish()}))),ek=class{constructor(e,t){this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){var o;if(e.length>this.maxEmbeddingsPerCall)throw new fp({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const s=(o=await St({provider:"openai",providerOptions:r,schema:Xx}))!=null?o:{},{responseHeaders:a,value:i,rawValue:l}=await nt({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:Ge(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:"float",dimensions:s.dimensions,user:s.user},failedResponseHandler:At,successfulResponseHandler:vt(Qx),abortSignal:n,fetch:this.config.fetch});return{embeddings:i.data.map(u=>u.embedding),usage:i.usage?{tokens:i.usage.prompt_tokens}:void 0,response:{headers:a,body:l}}}},tk=Ee(()=>te(g({data:z(g({b64_json:d(),revised_prompt:d().optional()}))}))),nk={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10},rk=new Set(["gpt-image-1","gpt-image-1-mini"]),ok=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get maxImagesPerCall(){var e;return(e=nk[this.modelId])!=null?e:1}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:r,seed:o,providerOptions:s,headers:a,abortSignal:i}){var l,u,p,x;const w=[];r!=null&&w.push({type:"unsupported-setting",setting:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),o!=null&&w.push({type:"unsupported-setting",setting:"seed"});const h=(p=(u=(l=this.config._internal)==null?void 0:l.currentDate)==null?void 0:u.call(l))!=null?p:new Date,{value:f,responseHeaders:y}=await nt({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:Ge(this.config.headers(),a),body:{model:this.modelId,prompt:e,n:t,size:n,...(x=s.openai)!=null?x:{},...rk.has(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:At,successfulResponseHandler:vt(tk),abortSignal:i,fetch:this.config.fetch});return{images:f.data.map(m=>m.b64_json),warnings:w,response:{timestamp:h,modelId:this.modelId,headers:y},providerMetadata:{openai:{images:f.data.map(m=>m.revised_prompt?{revisedPrompt:m.revised_prompt}:null)}}}}},sk=Fe(()=>te(g({code:d().nullish(),containerId:d()}))),ak=Fe(()=>te(g({outputs:z(et("type",[g({type:A("logs"),logs:d()}),g({type:A("image"),url:d()})])).nullish()}))),ik=Fe(()=>te(g({container:ue([d(),g({fileIds:z(d()).optional()})]).optional()}))),lk=Tn({id:"openai.code_interpreter",name:"code_interpreter",inputSchema:sk,outputSchema:ak}),uk=(e={})=>lk(e),cd=g({key:d(),type:Se(["eq","ne","gt","gte","lt","lte"]),value:ue([d(),I(),Ae()])}),dd=g({type:Se(["and","or"]),filters:z(ue([cd,el(()=>dd)]))}),ck=Fe(()=>te(g({vectorStoreIds:z(d()),maxNumResults:I().optional(),ranking:g({ranker:d().optional(),scoreThreshold:I().optional()}).optional(),filters:ue([cd,dd]).optional()}))),dk=Fe(()=>te(g({queries:z(d()),results:z(g({attributes:Oe(d(),mt()),fileId:d(),filename:d(),score:I(),text:d()})).nullable()}))),pk=Tn({id:"openai.file_search",name:"file_search",inputSchema:g({}),outputSchema:dk}),hk=Fe(()=>te(g({background:Se(["auto","opaque","transparent"]).optional(),inputFidelity:Se(["low","high"]).optional(),inputImageMask:g({fileId:d().optional(),imageUrl:d().optional()}).optional(),model:d().optional(),moderation:Se(["auto"]).optional(),outputCompression:I().int().min(0).max(100).optional(),outputFormat:Se(["png","jpeg","webp"]).optional(),partialImages:I().int().min(0).max(3).optional(),quality:Se(["auto","low","medium","high"]).optional(),size:Se(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),fk=Fe(()=>te(g({}))),mk=Fe(()=>te(g({result:d()}))),gk=Tn({id:"openai.image_generation",name:"image_generation",inputSchema:fk,outputSchema:mk}),vk=(e={})=>gk(e),pd=Fe(()=>te(g({action:g({type:A("exec"),command:z(d()),timeoutMs:I().optional(),user:d().optional(),workingDirectory:d().optional(),env:Oe(d(),d()).optional()})}))),hd=Fe(()=>te(g({output:d()}))),yk=Tn({id:"openai.local_shell",name:"local_shell",inputSchema:pd,outputSchema:hd}),_k=Fe(()=>te(g({filters:g({allowedDomains:z(d()).optional()}).optional(),searchContextSize:Se(["low","medium","high"]).optional(),userLocation:g({type:A("approximate"),country:d().optional(),city:d().optional(),region:d().optional(),timezone:d().optional()}).optional()}))),wk=Fe(()=>te(g({}))),bk=Fe(()=>te(g({action:et("type",[g({type:A("search"),query:d().optional()}),g({type:A("openPage"),url:d()}),g({type:A("find"),url:d(),pattern:d()})])}))),xk=Tn({id:"openai.web_search",name:"web_search",inputSchema:wk,outputSchema:bk}),kk=(e={})=>xk(e),Tk=Fe(()=>te(g({searchContextSize:Se(["low","medium","high"]).optional(),userLocation:g({type:A("approximate"),country:d().optional(),city:d().optional(),region:d().optional(),timezone:d().optional()}).optional()}))),Sk=Fe(()=>te(g({}))),Ik=Fe(()=>te(g({action:et("type",[g({type:A("search"),query:d().optional()}),g({type:A("openPage"),url:d()}),g({type:A("find"),url:d(),pattern:d()})])}))),Ck=Tn({id:"openai.web_search_preview",name:"web_search_preview",inputSchema:Sk,outputSchema:Ik}),Ek={codeInterpreter:uk,fileSearch:pk,imageGeneration:vk,localShell:yk,webSearchPreview:Ck,webSearch:kk};function fd(e,t){return t?t.some(n=>e.startsWith(n)):!1}async function Rk({prompt:e,systemMessageMode:t,fileIdPrefixes:n,store:r,hasLocalShellTool:o=!1}){var s,a,i,l;const u=[],p=[];for(const{role:x,content:w}of e)switch(x){case"system":{switch(t){case"system":{u.push({role:"system",content:w});break}case"developer":{u.push({role:"developer",content:w});break}case"remove":{p.push({type:"other",message:"system messages are removed for this model"});break}default:{const h=t;throw new Error(`Unsupported system message mode: ${h}`)}}break}case"user":{u.push({role:"user",content:w.map((h,f)=>{var y,m,c;switch(h.type){case"text":return{type:"input_text",text:h.text};case"file":if(h.mediaType.startsWith("image/")){const b=h.mediaType==="image/*"?"image/jpeg":h.mediaType;return{type:"input_image",...h.data instanceof URL?{image_url:h.data.toString()}:typeof h.data=="string"&&fd(h.data,n)?{file_id:h.data}:{image_url:`data:${b};base64,${pn(h.data)}`},detail:(m=(y=h.providerOptions)==null?void 0:y.openai)==null?void 0:m.imageDetail}}else{if(h.mediaType==="application/pdf")return h.data instanceof URL?{type:"input_file",file_url:h.data.toString()}:{type:"input_file",...typeof h.data=="string"&&fd(h.data,n)?{file_id:h.data}:{filename:(c=h.filename)!=null?c:`part-${f}.pdf`,file_data:`data:application/pdf;base64,${pn(h.data)}`}};throw new ft({functionality:`file part media type ${h.mediaType}`})}}})});break}case"assistant":{const h={},f={};for(const y of w)switch(y.type){case"text":{const m=(a=(s=y.providerOptions)==null?void 0:s.openai)==null?void 0:a.itemId;if(r&&m!=null){u.push({type:"item_reference",id:m});break}u.push({role:"assistant",content:[{type:"output_text",text:y.text}],id:m});break}case"tool-call":{if(f[y.toolCallId]=y,y.providerExecuted)break;const m=(l=(i=y.providerOptions)==null?void 0:i.openai)==null?void 0:l.itemId;if(r&&m!=null){u.push({type:"item_reference",id:m});break}if(o&&y.toolName==="local_shell"){const c=await Tt({value:y.input,schema:pd});u.push({type:"local_shell_call",call_id:y.toolCallId,id:m,action:{type:"exec",command:c.action.command,timeout_ms:c.action.timeoutMs,user:c.action.user,working_directory:c.action.workingDirectory,env:c.action.env}});break}u.push({type:"function_call",call_id:y.toolCallId,name:y.toolName,arguments:JSON.stringify(y.input),id:m});break}case"tool-result":{r?u.push({type:"item_reference",id:y.toolCallId}):p.push({type:"other",message:`Results for OpenAI tool ${y.toolName} are not sent to the API when store is false`});break}case"reasoning":{const m=await St({provider:"openai",providerOptions:y.providerOptions,schema:Ak}),c=m==null?void 0:m.itemId;if(c!=null){const b=h[c];if(r)b===void 0&&(u.push({type:"item_reference",id:c}),h[c]={type:"reasoning",id:c,summary:[]});else{const v=[];y.text.length>0?v.push({type:"summary_text",text:y.text}):b!==void 0&&p.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(y)}.`}),b===void 0?(h[c]={type:"reasoning",id:c,encrypted_content:m==null?void 0:m.reasoningEncryptedContent,summary:v},u.push(h[c])):(b.summary.push(...v),(m==null?void 0:m.reasoningEncryptedContent)!=null&&(b.encrypted_content=m.reasoningEncryptedContent))}}else p.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(y)}.`});break}}break}case"tool":{for(const h of w){const f=h.output;if(o&&h.toolName==="local_shell"&&f.type==="json"){const m=await Tt({value:f.value,schema:hd});u.push({type:"local_shell_call_output",call_id:h.toolCallId,output:m.output});break}let y;switch(f.type){case"text":case"error-text":y=f.value;break;case"json":case"error-json":y=JSON.stringify(f.value);break;case"content":y=f.value.map(m=>{switch(m.type){case"text":return{type:"input_text",text:m.text};case"media":return m.mediaType.startsWith("image/")?{type:"input_image",image_url:`data:${m.mediaType};base64,${m.data}`}:{type:"input_file",filename:"data",file_data:`data:${m.mediaType};base64,${m.data}`}}});break}u.push({type:"function_call_output",call_id:h.toolCallId,output:y})}break}default:{const h=x;throw new Error(`Unsupported role: ${h}`)}}return{input:u,warnings:p}}var Ak=g({itemId:d().nullish(),reasoningEncryptedContent:d().nullish()});function md({finishReason:e,hasFunctionCall:t}){switch(e){case void 0:case null:return t?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return t?"tool-calls":"unknown"}}var Ok=Ee(()=>te(ue([g({type:A("response.output_text.delta"),item_id:d(),delta:d(),logprobs:z(g({token:d(),logprob:I(),top_logprobs:z(g({token:d(),logprob:I()}))})).nullish()}),g({type:Se(["response.completed","response.incomplete"]),response:g({incomplete_details:g({reason:d()}).nullish(),usage:g({input_tokens:I(),input_tokens_details:g({cached_tokens:I().nullish()}).nullish(),output_tokens:I(),output_tokens_details:g({reasoning_tokens:I().nullish()}).nullish()}),service_tier:d().nullish()})}),g({type:A("response.created"),response:g({id:d(),created_at:I(),model:d(),service_tier:d().nullish()})}),g({type:A("response.output_item.added"),output_index:I(),item:et("type",[g({type:A("message"),id:d()}),g({type:A("reasoning"),id:d(),encrypted_content:d().nullish()}),g({type:A("function_call"),id:d(),call_id:d(),name:d(),arguments:d()}),g({type:A("web_search_call"),id:d(),status:d()}),g({type:A("computer_call"),id:d(),status:d()}),g({type:A("file_search_call"),id:d()}),g({type:A("image_generation_call"),id:d()}),g({type:A("code_interpreter_call"),id:d(),container_id:d(),code:d().nullable(),outputs:z(et("type",[g({type:A("logs"),logs:d()}),g({type:A("image"),url:d()})])).nullable(),status:d()})])}),g({type:A("response.output_item.done"),output_index:I(),item:et("type",[g({type:A("message"),id:d()}),g({type:A("reasoning"),id:d(),encrypted_content:d().nullish()}),g({type:A("function_call"),id:d(),call_id:d(),name:d(),arguments:d(),status:A("completed")}),g({type:A("code_interpreter_call"),id:d(),code:d().nullable(),container_id:d(),outputs:z(et("type",[g({type:A("logs"),logs:d()}),g({type:A("image"),url:d()})])).nullable()}),g({type:A("image_generation_call"),id:d(),result:d()}),g({type:A("web_search_call"),id:d(),status:d(),action:et("type",[g({type:A("search"),query:d().nullish()}),g({type:A("open_page"),url:d()}),g({type:A("find"),url:d(),pattern:d()})])}),g({type:A("file_search_call"),id:d(),queries:z(d()),results:z(g({attributes:Oe(d(),mt()),file_id:d(),filename:d(),score:I(),text:d()})).nullish()}),g({type:A("local_shell_call"),id:d(),call_id:d(),action:g({type:A("exec"),command:z(d()),timeout_ms:I().optional(),user:d().optional(),working_directory:d().optional(),env:Oe(d(),d()).optional()})}),g({type:A("computer_call"),id:d(),status:A("completed")})])}),g({type:A("response.function_call_arguments.delta"),item_id:d(),output_index:I(),delta:d()}),g({type:A("response.image_generation_call.partial_image"),item_id:d(),output_index:I(),partial_image_b64:d()}),g({type:A("response.code_interpreter_call_code.delta"),item_id:d(),output_index:I(),delta:d()}),g({type:A("response.code_interpreter_call_code.done"),item_id:d(),output_index:I(),code:d()}),g({type:A("response.output_text.annotation.added"),annotation:et("type",[g({type:A("url_citation"),url:d(),title:d()}),g({type:A("file_citation"),file_id:d(),filename:d().nullish(),index:I().nullish(),start_index:I().nullish(),end_index:I().nullish(),quote:d().nullish()})])}),g({type:A("response.reasoning_summary_part.added"),item_id:d(),summary_index:I()}),g({type:A("response.reasoning_summary_text.delta"),item_id:d(),summary_index:I(),delta:d()}),g({type:A("response.reasoning_summary_part.done"),item_id:d(),summary_index:I()}),g({type:A("error"),code:d(),message:d(),param:d().nullish(),sequence_number:I()}),g({type:d()}).loose().transform(e=>({type:"unknown_chunk",message:e.type}))]))),Nk=Ee(()=>te(g({id:d(),created_at:I(),error:g({code:d(),message:d()}).nullish(),model:d(),output:z(et("type",[g({type:A("message"),role:A("assistant"),id:d(),content:z(g({type:A("output_text"),text:d(),logprobs:z(g({token:d(),logprob:I(),top_logprobs:z(g({token:d(),logprob:I()}))})).nullish(),annotations:z(et("type",[g({type:A("url_citation"),start_index:I(),end_index:I(),url:d(),title:d()}),g({type:A("file_citation"),file_id:d(),filename:d().nullish(),index:I().nullish(),start_index:I().nullish(),end_index:I().nullish(),quote:d().nullish()}),g({type:A("container_file_citation")})]))}))}),g({type:A("web_search_call"),id:d(),status:d(),action:et("type",[g({type:A("search"),query:d().nullish()}),g({type:A("open_page"),url:d()}),g({type:A("find"),url:d(),pattern:d()})])}),g({type:A("file_search_call"),id:d(),queries:z(d()),results:z(g({attributes:Oe(d(),mt()),file_id:d(),filename:d(),score:I(),text:d()})).nullish()}),g({type:A("code_interpreter_call"),id:d(),code:d().nullable(),container_id:d(),outputs:z(et("type",[g({type:A("logs"),logs:d()}),g({type:A("image"),url:d()})])).nullable()}),g({type:A("image_generation_call"),id:d(),result:d()}),g({type:A("local_shell_call"),id:d(),call_id:d(),action:g({type:A("exec"),command:z(d()),timeout_ms:I().optional(),user:d().optional(),working_directory:d().optional(),env:Oe(d(),d()).optional()})}),g({type:A("function_call"),call_id:d(),name:d(),arguments:d(),id:d()}),g({type:A("computer_call"),id:d(),status:d().optional()}),g({type:A("reasoning"),id:d(),encrypted_content:d().nullish(),summary:z(g({type:A("summary_text"),text:d()}))})])),service_tier:d().nullish(),incomplete_details:g({reason:d()}).nullish(),usage:g({input_tokens:I(),input_tokens_details:g({cached_tokens:I().nullish()}).nullish(),output_tokens:I(),output_tokens_details:g({reasoning_tokens:I().nullish()}).nullish()})}))),gd=20,Mk=Ee(()=>te(g({include:z(Se(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:d().nullish(),logprobs:ue([Ae(),I().min(1).max(gd)]).optional(),maxToolCalls:I().nullish(),metadata:ut().nullish(),parallelToolCalls:Ae().nullish(),previousResponseId:d().nullish(),promptCacheKey:d().nullish(),reasoningEffort:d().nullish(),reasoningSummary:d().nullish(),safetyIdentifier:d().nullish(),serviceTier:Se(["auto","flex","priority","default"]).nullish(),store:Ae().nullish(),strictJsonSchema:Ae().nullish(),textVerbosity:Se(["low","medium","high"]).nullish(),truncation:Se(["auto","disabled"]).nullish(),user:d().nullish()})));async function Pk({tools:e,toolChoice:t,strictJsonSchema:n}){e=e!=null&&e.length?e:void 0;const r=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};const o=[];for(const a of e)switch(a.type){case"function":o.push({type:"function",name:a.name,description:a.description,parameters:a.inputSchema,strict:n});break;case"provider-defined":{switch(a.id){case"openai.file_search":{const i=await Tt({value:a.args,schema:ck});o.push({type:"file_search",vector_store_ids:i.vectorStoreIds,max_num_results:i.maxNumResults,ranking_options:i.ranking?{ranker:i.ranking.ranker,score_threshold:i.ranking.scoreThreshold}:void 0,filters:i.filters});break}case"openai.local_shell":{o.push({type:"local_shell"});break}case"openai.web_search_preview":{const i=await Tt({value:a.args,schema:Tk});o.push({type:"web_search_preview",search_context_size:i.searchContextSize,user_location:i.userLocation});break}case"openai.web_search":{const i=await Tt({value:a.args,schema:_k});o.push({type:"web_search",filters:i.filters!=null?{allowed_domains:i.filters.allowedDomains}:void 0,search_context_size:i.searchContextSize,user_location:i.userLocation});break}case"openai.code_interpreter":{const i=await Tt({value:a.args,schema:ik});o.push({type:"code_interpreter",container:i.container==null?{type:"auto",file_ids:void 0}:typeof i.container=="string"?i.container:{type:"auto",file_ids:i.container.fileIds}});break}case"openai.image_generation":{const i=await Tt({value:a.args,schema:hk});o.push({type:"image_generation",background:i.background,input_fidelity:i.inputFidelity,input_image_mask:i.inputImageMask?{file_id:i.inputImageMask.fileId,image_url:i.inputImageMask.imageUrl}:void 0,model:i.model,size:i.size,quality:i.quality,moderation:i.moderation,output_format:i.outputFormat,output_compression:i.outputCompression});break}}break}default:r.push({type:"unsupported-tool",tool:a});break}if(t==null)return{tools:o,toolChoice:void 0,toolWarnings:r};const s=t.type;switch(s){case"auto":case"none":case"required":return{tools:o,toolChoice:s,toolWarnings:r};case"tool":return{tools:o,toolChoice:t.toolName==="code_interpreter"||t.toolName==="file_search"||t.toolName==="image_generation"||t.toolName==="web_search_preview"||t.toolName==="web_search"?{type:t.toolName}:{type:"function",name:t.toolName},toolWarnings:r};default:{const a=s;throw new ft({functionality:`tool choice type: ${a}`})}}}var $k=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({maxOutputTokens:e,temperature:t,stopSequences:n,topP:r,topK:o,presencePenalty:s,frequencyPenalty:a,seed:i,prompt:l,providerOptions:u,tools:p,toolChoice:x,responseFormat:w}){var h,f,y,m;const c=[],b=Fk(this.modelId);o!=null&&c.push({type:"unsupported-setting",setting:"topK"}),i!=null&&c.push({type:"unsupported-setting",setting:"seed"}),s!=null&&c.push({type:"unsupported-setting",setting:"presencePenalty"}),a!=null&&c.push({type:"unsupported-setting",setting:"frequencyPenalty"}),n!=null&&c.push({type:"unsupported-setting",setting:"stopSequences"});const v=await St({provider:"openai",providerOptions:u,schema:Mk}),{input:_,warnings:R}=await Rk({prompt:l,systemMessageMode:b.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes,store:(h=v==null?void 0:v.store)!=null?h:!0,hasLocalShellTool:D("openai.local_shell")});c.push(...R);const C=(f=v==null?void 0:v.strictJsonSchema)!=null?f:!1;let T=v==null?void 0:v.include;function P(ae){T==null?T=[ae]:T.includes(ae)||(T=[...T,ae])}function D(ae){return(p==null?void 0:p.find(ce=>ce.type==="provider-defined"&&ce.id===ae))!=null}const H=typeof(v==null?void 0:v.logprobs)=="number"?v==null?void 0:v.logprobs:(v==null?void 0:v.logprobs)===!0?gd:void 0;H&&P("message.output_text.logprobs");const K=(y=p==null?void 0:p.find(ae=>ae.type==="provider-defined"&&(ae.id==="openai.web_search"||ae.id==="openai.web_search_preview")))==null?void 0:y.name;K&&P("web_search_call.action.sources"),D("openai.code_interpreter")&&P("code_interpreter_call.outputs");const he=v==null?void 0:v.store;he===!1&&b.isReasoningModel&&P("reasoning.encrypted_content");const Y={model:this.modelId,input:_,temperature:t,top_p:r,max_output_tokens:e,...((w==null?void 0:w.type)==="json"||(v==null?void 0:v.textVerbosity))&&{text:{...(w==null?void 0:w.type)==="json"&&{format:w.schema!=null?{type:"json_schema",strict:C,name:(m=w.name)!=null?m:"response",description:w.description,schema:w.schema}:{type:"json_object"}},...(v==null?void 0:v.textVerbosity)&&{verbosity:v.textVerbosity}}},max_tool_calls:v==null?void 0:v.maxToolCalls,metadata:v==null?void 0:v.metadata,parallel_tool_calls:v==null?void 0:v.parallelToolCalls,previous_response_id:v==null?void 0:v.previousResponseId,store:he,user:v==null?void 0:v.user,instructions:v==null?void 0:v.instructions,service_tier:v==null?void 0:v.serviceTier,include:T,prompt_cache_key:v==null?void 0:v.promptCacheKey,safety_identifier:v==null?void 0:v.safetyIdentifier,top_logprobs:H,truncation:v==null?void 0:v.truncation,...b.isReasoningModel&&((v==null?void 0:v.reasoningEffort)!=null||(v==null?void 0:v.reasoningSummary)!=null)&&{reasoning:{...(v==null?void 0:v.reasoningEffort)!=null&&{effort:v.reasoningEffort},...(v==null?void 0:v.reasoningSummary)!=null&&{summary:v.reasoningSummary}}}};b.isReasoningModel?(Y.temperature!=null&&(Y.temperature=void 0,c.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),Y.top_p!=null&&(Y.top_p=void 0,c.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"}))):((v==null?void 0:v.reasoningEffort)!=null&&c.push({type:"unsupported-setting",setting:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),(v==null?void 0:v.reasoningSummary)!=null&&c.push({type:"unsupported-setting",setting:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),(v==null?void 0:v.serviceTier)==="flex"&&!b.supportsFlexProcessing&&(c.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete Y.service_tier),(v==null?void 0:v.serviceTier)==="priority"&&!b.supportsPriorityProcessing&&(c.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete Y.service_tier);const{tools:ne,toolChoice:V,toolWarnings:se}=await Pk({tools:p,toolChoice:x,strictJsonSchema:C});return{webSearchToolName:K,args:{...Y,tools:ne,tool_choice:V},warnings:[...c,...se],store:he}}async doGenerate(e){var t,n,r,o,s,a,i,l,u,p,x,w,h,f,y,m,c,b,v;const{args:_,warnings:R,webSearchToolName:C}=await this.getArgs(e),T=this.config.url({path:"/responses",modelId:this.modelId}),{responseHeaders:P,value:D,rawValue:H}=await nt({url:T,headers:Ge(this.config.headers(),e.headers),body:_,failedResponseHandler:At,successfulResponseHandler:vt(Nk),abortSignal:e.abortSignal,fetch:this.config.fetch});if(D.error)throw new De({message:D.error.message,url:T,requestBodyValues:_,statusCode:400,responseHeaders:P,responseBody:H,isRetryable:!1});const K=[],he=[];let Y=!1;for(const V of D.output)switch(V.type){case"reasoning":{V.summary.length===0&&V.summary.push({type:"summary_text",text:""});for(const se of V.summary)K.push({type:"reasoning",text:se.text,providerMetadata:{openai:{itemId:V.id,reasoningEncryptedContent:(t=V.encrypted_content)!=null?t:null}}});break}case"image_generation_call":{K.push({type:"tool-call",toolCallId:V.id,toolName:"image_generation",input:"{}",providerExecuted:!0}),K.push({type:"tool-result",toolCallId:V.id,toolName:"image_generation",result:{result:V.result},providerExecuted:!0});break}case"local_shell_call":{K.push({type:"tool-call",toolCallId:V.call_id,toolName:"local_shell",input:JSON.stringify({action:V.action}),providerMetadata:{openai:{itemId:V.id}}});break}case"message":{for(const se of V.content){(r=(n=e.providerOptions)==null?void 0:n.openai)!=null&&r.logprobs&&se.logprobs&&he.push(se.logprobs),K.push({type:"text",text:se.text,providerMetadata:{openai:{itemId:V.id}}});for(const ae of se.annotations)ae.type==="url_citation"?K.push({type:"source",sourceType:"url",id:(a=(s=(o=this.config).generateId)==null?void 0:s.call(o))!=null?a:tt(),url:ae.url,title:ae.title}):ae.type==="file_citation"&&K.push({type:"source",sourceType:"document",id:(u=(l=(i=this.config).generateId)==null?void 0:l.call(i))!=null?u:tt(),mediaType:"text/plain",title:(x=(p=ae.quote)!=null?p:ae.filename)!=null?x:"Document",filename:(w=ae.filename)!=null?w:ae.file_id})}break}case"function_call":{Y=!0,K.push({type:"tool-call",toolCallId:V.call_id,toolName:V.name,input:V.arguments,providerMetadata:{openai:{itemId:V.id}}});break}case"web_search_call":{K.push({type:"tool-call",toolCallId:V.id,toolName:C??"web_search",input:JSON.stringify({}),providerExecuted:!0}),K.push({type:"tool-result",toolCallId:V.id,toolName:C??"web_search",result:yd(V.action),providerExecuted:!0});break}case"computer_call":{K.push({type:"tool-call",toolCallId:V.id,toolName:"computer_use",input:"",providerExecuted:!0}),K.push({type:"tool-result",toolCallId:V.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:V.status||"completed"},providerExecuted:!0});break}case"file_search_call":{K.push({type:"tool-call",toolCallId:V.id,toolName:"file_search",input:"{}",providerExecuted:!0}),K.push({type:"tool-result",toolCallId:V.id,toolName:"file_search",result:{queries:V.queries,results:(f=(h=V.results)==null?void 0:h.map(se=>({attributes:se.attributes,fileId:se.file_id,filename:se.filename,score:se.score,text:se.text})))!=null?f:null},providerExecuted:!0});break}case"code_interpreter_call":{K.push({type:"tool-call",toolCallId:V.id,toolName:"code_interpreter",input:JSON.stringify({code:V.code,containerId:V.container_id}),providerExecuted:!0}),K.push({type:"tool-result",toolCallId:V.id,toolName:"code_interpreter",result:{outputs:V.outputs},providerExecuted:!0});break}}const ne={openai:{responseId:D.id}};return he.length>0&&(ne.openai.logprobs=he),typeof D.service_tier=="string"&&(ne.openai.serviceTier=D.service_tier),{content:K,finishReason:md({finishReason:(y=D.incomplete_details)==null?void 0:y.reason,hasFunctionCall:Y}),usage:{inputTokens:D.usage.input_tokens,outputTokens:D.usage.output_tokens,totalTokens:D.usage.input_tokens+D.usage.output_tokens,reasoningTokens:(c=(m=D.usage.output_tokens_details)==null?void 0:m.reasoning_tokens)!=null?c:void 0,cachedInputTokens:(v=(b=D.usage.input_tokens_details)==null?void 0:b.cached_tokens)!=null?v:void 0},request:{body:_},response:{id:D.id,timestamp:new Date(D.created_at*1e3),modelId:D.model,headers:P,body:H},providerMetadata:ne,warnings:R}}async doStream(e){const{args:t,warnings:n,webSearchToolName:r,store:o}=await this.getArgs(e),{responseHeaders:s,value:a}=await nt({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:Ge(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:At,successfulResponseHandler:Qn(Ok),abortSignal:e.abortSignal,fetch:this.config.fetch}),i=this;let l="unknown";const u={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},p=[];let x=null;const w={};let h=!1;const f={};let y;return{stream:a.pipeThrough(new TransformStream({start(m){m.enqueue({type:"stream-start",warnings:n})},transform(m,c){var b,v,_,R,C,T,P,D,H,K,he,Y,ne,V,se,ae,ce,Pe,oe,me,ee,Ie;if(e.includeRawChunks&&c.enqueue({type:"raw",rawValue:m.rawValue}),!m.success){l="error",c.enqueue({type:"error",error:m.error});return}const k=m.value;if(vd(k))k.item.type==="function_call"?(w[k.output_index]={toolName:k.item.name,toolCallId:k.item.call_id},c.enqueue({type:"tool-input-start",id:k.item.call_id,toolName:k.item.name})):k.item.type==="web_search_call"?(w[k.output_index]={toolName:r??"web_search",toolCallId:k.item.id},c.enqueue({type:"tool-input-start",id:k.item.id,toolName:r??"web_search",providerExecuted:!0}),c.enqueue({type:"tool-input-end",id:k.item.id}),c.enqueue({type:"tool-call",toolCallId:k.item.id,toolName:"web_search",input:JSON.stringify({}),providerExecuted:!0})):k.item.type==="computer_call"?(w[k.output_index]={toolName:"computer_use",toolCallId:k.item.id},c.enqueue({type:"tool-input-start",id:k.item.id,toolName:"computer_use",providerExecuted:!0})):k.item.type==="code_interpreter_call"?(w[k.output_index]={toolName:"code_interpreter",toolCallId:k.item.id,codeInterpreter:{containerId:k.item.container_id}},c.enqueue({type:"tool-input-start",id:k.item.id,toolName:"code_interpreter",providerExecuted:!0}),c.enqueue({type:"tool-input-delta",id:k.item.id,delta:`{"containerId":"${k.item.container_id}","code":"`})):k.item.type==="file_search_call"?c.enqueue({type:"tool-call",toolCallId:k.item.id,toolName:"file_search",input:"{}",providerExecuted:!0}):k.item.type==="image_generation_call"?c.enqueue({type:"tool-call",toolCallId:k.item.id,toolName:"image_generation",input:"{}",providerExecuted:!0}):k.item.type==="message"?c.enqueue({type:"text-start",id:k.item.id,providerMetadata:{openai:{itemId:k.item.id}}}):vd(k)&&k.item.type==="reasoning"&&(f[k.item.id]={encryptedContent:k.item.encrypted_content,summaryParts:{0:"active"}},c.enqueue({type:"reasoning-start",id:`${k.item.id}:0`,providerMetadata:{openai:{itemId:k.item.id,reasoningEncryptedContent:(b=k.item.encrypted_content)!=null?b:null}}}));else if(jk(k)){if(k.item.type==="function_call")w[k.output_index]=void 0,h=!0,c.enqueue({type:"tool-input-end",id:k.item.call_id}),c.enqueue({type:"tool-call",toolCallId:k.item.call_id,toolName:k.item.name,input:k.item.arguments,providerMetadata:{openai:{itemId:k.item.id}}});else if(k.item.type==="web_search_call")w[k.output_index]=void 0,c.enqueue({type:"tool-result",toolCallId:k.item.id,toolName:"web_search",result:yd(k.item.action),providerExecuted:!0});else if(k.item.type==="computer_call")w[k.output_index]=void 0,c.enqueue({type:"tool-input-end",id:k.item.id}),c.enqueue({type:"tool-call",toolCallId:k.item.id,toolName:"computer_use",input:"",providerExecuted:!0}),c.enqueue({type:"tool-result",toolCallId:k.item.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:k.item.status||"completed"},providerExecuted:!0});else if(k.item.type==="file_search_call")w[k.output_index]=void 0,c.enqueue({type:"tool-result",toolCallId:k.item.id,toolName:"file_search",result:{queries:k.item.queries,results:(_=(v=k.item.results)==null?void 0:v.map(F=>({attributes:F.attributes,fileId:F.file_id,filename:F.filename,score:F.score,text:F.text})))!=null?_:null},providerExecuted:!0});else if(k.item.type==="code_interpreter_call")w[k.output_index]=void 0,c.enqueue({type:"tool-result",toolCallId:k.item.id,toolName:"code_interpreter",result:{outputs:k.item.outputs},providerExecuted:!0});else if(k.item.type==="image_generation_call")c.enqueue({type:"tool-result",toolCallId:k.item.id,toolName:"image_generation",result:{result:k.item.result},providerExecuted:!0});else if(k.item.type==="local_shell_call")w[k.output_index]=void 0,c.enqueue({type:"tool-call",toolCallId:k.item.call_id,toolName:"local_shell",input:JSON.stringify({action:{type:"exec",command:k.item.action.command,timeoutMs:k.item.action.timeout_ms,user:k.item.action.user,workingDirectory:k.item.action.working_directory,env:k.item.action.env}}),providerMetadata:{openai:{itemId:k.item.id}}});else if(k.item.type==="message")c.enqueue({type:"text-end",id:k.item.id});else if(k.item.type==="reasoning"){const F=f[k.item.id],ge=Object.entries(F.summaryParts).filter(([xe,Ce])=>Ce==="active"||Ce==="can-conclude").map(([xe])=>xe);for(const xe of ge)c.enqueue({type:"reasoning-end",id:`${k.item.id}:${xe}`,providerMetadata:{openai:{itemId:k.item.id,reasoningEncryptedContent:(R=k.item.encrypted_content)!=null?R:null}}});delete f[k.item.id]}}else if(Zk(k)){const F=w[k.output_index];F!=null&&c.enqueue({type:"tool-input-delta",id:F.toolCallId,delta:k.delta})}else if(Lk(k)){const F=w[k.output_index];F!=null&&c.enqueue({type:"tool-input-delta",id:F.toolCallId,delta:JSON.stringify(k.delta).slice(1,-1)})}else if(qk(k)){const F=w[k.output_index];F!=null&&(c.enqueue({type:"tool-input-delta",id:F.toolCallId,delta:'"}'}),c.enqueue({type:"tool-input-end",id:F.toolCallId}),c.enqueue({type:"tool-call",toolCallId:F.toolCallId,toolName:"code_interpreter",input:JSON.stringify({code:k.code,containerId:F.codeInterpreter.containerId}),providerExecuted:!0}))}else if(Uk(k))x=k.response.id,c.enqueue({type:"response-metadata",id:k.response.id,timestamp:new Date(k.response.created_at*1e3),modelId:k.response.model});else if(zk(k))c.enqueue({type:"text-delta",id:k.item_id,delta:k.delta}),(T=(C=e.providerOptions)==null?void 0:C.openai)!=null&&T.logprobs&&k.logprobs&&p.push(k.logprobs);else if(k.type==="response.reasoning_summary_part.added"){if(k.summary_index>0){const F=f[k.item_id];F.summaryParts[k.summary_index]="active";for(const ge of Object.keys(F.summaryParts))F.summaryParts[ge]==="can-conclude"&&(c.enqueue({type:"reasoning-end",id:`${k.item_id}:${ge}`,providerMetadata:{openai:{itemId:k.item_id}}}),F.summaryParts[ge]="concluded");c.enqueue({type:"reasoning-start",id:`${k.item_id}:${k.summary_index}`,providerMetadata:{openai:{itemId:k.item_id,reasoningEncryptedContent:(D=(P=f[k.item_id])==null?void 0:P.encryptedContent)!=null?D:null}}})}}else k.type==="response.reasoning_summary_text.delta"?c.enqueue({type:"reasoning-delta",id:`${k.item_id}:${k.summary_index}`,delta:k.delta,providerMetadata:{openai:{itemId:k.item_id}}}):k.type==="response.reasoning_summary_part.done"?o?(c.enqueue({type:"reasoning-end",id:`${k.item_id}:${k.summary_index}`,providerMetadata:{openai:{itemId:k.item_id}}}),f[k.item_id].summaryParts[k.summary_index]="concluded"):f[k.item_id].summaryParts[k.summary_index]="can-conclude":Dk(k)?(l=md({finishReason:(H=k.response.incomplete_details)==null?void 0:H.reason,hasFunctionCall:h}),u.inputTokens=k.response.usage.input_tokens,u.outputTokens=k.response.usage.output_tokens,u.totalTokens=k.response.usage.input_tokens+k.response.usage.output_tokens,u.reasoningTokens=(he=(K=k.response.usage.output_tokens_details)==null?void 0:K.reasoning_tokens)!=null?he:void 0,u.cachedInputTokens=(ne=(Y=k.response.usage.input_tokens_details)==null?void 0:Y.cached_tokens)!=null?ne:void 0,typeof k.response.service_tier=="string"&&(y=k.response.service_tier)):Bk(k)?k.annotation.type==="url_citation"?c.enqueue({type:"source",sourceType:"url",id:(ae=(se=(V=i.config).generateId)==null?void 0:se.call(V))!=null?ae:tt(),url:k.annotation.url,title:k.annotation.title}):k.annotation.type==="file_citation"&&c.enqueue({type:"source",sourceType:"document",id:(oe=(Pe=(ce=i.config).generateId)==null?void 0:Pe.call(ce))!=null?oe:tt(),mediaType:"text/plain",title:(ee=(me=k.annotation.quote)!=null?me:k.annotation.filename)!=null?ee:"Document",filename:(Ie=k.annotation.filename)!=null?Ie:k.annotation.file_id}):Vk(k)&&c.enqueue({type:"error",error:k})},flush(m){const c={openai:{responseId:x}};p.length>0&&(c.openai.logprobs=p),y!==void 0&&(c.openai.serviceTier=y),m.enqueue({type:"finish",finishReason:l,usage:u,providerMetadata:c})}})),request:{body:t},response:{headers:s}}}};function zk(e){return e.type==="response.output_text.delta"}function jk(e){return e.type==="response.output_item.done"}function Dk(e){return e.type==="response.completed"||e.type==="response.incomplete"}function Uk(e){return e.type==="response.created"}function Zk(e){return e.type==="response.function_call_arguments.delta"}function Lk(e){return e.type==="response.code_interpreter_call_code.delta"}function qk(e){return e.type==="response.code_interpreter_call_code.done"}function vd(e){return e.type==="response.output_item.added"}function Bk(e){return e.type==="response.output_text.annotation.added"}function Vk(e){return e.type==="error"}function Fk(e){const t=e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat"),n=e.startsWith("gpt-4")||e.startsWith("gpt-5-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-nano")&&!e.startsWith("gpt-5-chat")||e.startsWith("o3")||e.startsWith("o4-mini"),r={systemMessageMode:"system",supportsFlexProcessing:t,supportsPriorityProcessing:n};return e.startsWith("gpt-5-chat")?{...r,isReasoningModel:!1}:e.startsWith("o")||e.startsWith("gpt-5")||e.startsWith("codex-")||e.startsWith("computer-use")?e.startsWith("o1-mini")||e.startsWith("o1-preview")?{...r,isReasoningModel:!0,systemMessageMode:"remove"}:{...r,isReasoningModel:!0,systemMessageMode:"developer"}:{...r,isReasoningModel:!1}}function yd(e){var t;switch(e.type){case"search":return{action:{type:"search",query:(t=e.query)!=null?t:void 0}};case"open_page":return{action:{type:"openPage",url:e.url}};case"find":return{action:{type:"find",url:e.url,pattern:e.pattern}}}}var Hk=Ee(()=>te(g({instructions:d().nullish(),speed:I().min(.25).max(4).default(1).nullish()}))),Jk=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({text:e,voice:t="alloy",outputFormat:n="mp3",speed:r,instructions:o,language:s,providerOptions:a}){const i=[],l=await St({provider:"openai",providerOptions:a,schema:Hk}),u={model:this.modelId,input:e,voice:t,response_format:"mp3",speed:r,instructions:o};if(n&&(["mp3","opus","aac","flac","wav","pcm"].includes(n)?u.response_format=n:i.push({type:"unsupported-setting",setting:"outputFormat",details:`Unsupported output format: ${n}. Using mp3 instead.`})),l){const p={};for(const x in p){const w=p[x];w!==void 0&&(u[x]=w)}}return s&&i.push({type:"unsupported-setting",setting:"language",details:`OpenAI speech models do not support language selection. Language parameter "${s}" was ignored.`}),{requestBody:u,warnings:i}}async doGenerate(e){var t,n,r;const o=(r=(n=(t=this.config._internal)==null?void 0:t.currentDate)==null?void 0:n.call(t))!=null?r:new Date,{requestBody:s,warnings:a}=await this.getArgs(e),{value:i,responseHeaders:l,rawValue:u}=await nt({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:Ge(this.config.headers(),e.headers),body:s,failedResponseHandler:At,successfulResponseHandler:mv(),abortSignal:e.abortSignal,fetch:this.config.fetch});return{audio:i,warnings:a,request:{body:JSON.stringify(s)},response:{timestamp:o,modelId:this.modelId,headers:l,body:u}}}},Gk=Ee(()=>te(g({text:d(),language:d().nullish(),duration:I().nullish(),words:z(g({word:d(),start:I(),end:I()})).nullish(),segments:z(g({id:I(),seek:I(),start:I(),end:I(),text:d(),tokens:z(I()),temperature:I(),avg_logprob:I(),compression_ratio:I(),no_speech_prob:I()})).nullish()}))),Wk=Ee(()=>te(g({include:z(d()).optional(),language:d().optional(),prompt:d().optional(),temperature:I().min(0).max(1).default(0).optional(),timestampGranularities:z(Se(["word","segment"])).default(["segment"]).optional()}))),_d={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"},Kk=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({audio:e,mediaType:t,providerOptions:n}){const r=[],o=await St({provider:"openai",providerOptions:n,schema:Wk}),s=new FormData,a=e instanceof Uint8Array?new Blob([e]):new Blob([Kr(e)]);s.append("model",this.modelId);const i=nv(t);if(s.append("file",new File([a],"audio",{type:t}),`audio.${i}`),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[u,p]of Object.entries(l))if(p!=null)if(Array.isArray(p))for(const x of p)s.append(`${u}[]`,String(x));else s.append(u,String(p))}return{formData:s,warnings:r}}async doGenerate(e){var t,n,r,o,s,a,i,l;const u=(r=(n=(t=this.config._internal)==null?void 0:t.currentDate)==null?void 0:n.call(t))!=null?r:new Date,{formData:p,warnings:x}=await this.getArgs(e),{value:w,responseHeaders:h,rawValue:f}=await fv({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:Ge(this.config.headers(),e.headers),formData:p,failedResponseHandler:At,successfulResponseHandler:vt(Gk),abortSignal:e.abortSignal,fetch:this.config.fetch}),y=w.language!=null&&w.language in _d?_d[w.language]:void 0;return{text:w.text,segments:(i=(a=(o=w.segments)==null?void 0:o.map(m=>({text:m.text,startSecond:m.start,endSecond:m.end})))!=null?a:(s=w.words)==null?void 0:s.map(m=>({text:m.word,startSecond:m.start,endSecond:m.end})))!=null?i:[],language:y,durationInSeconds:(l=w.duration)!=null?l:void 0,warnings:x,response:{timestamp:u,modelId:this.modelId,headers:h,body:f}}}},Yk="2.0.53";function wd(e={}){var t,n;const r=(t=is(Xn({settingValue:e.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?t:"https://api.openai.com/v1",o=(n=e.name)!=null?n:"openai",s=()=>Lt({Authorization:`Bearer ${vl({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${Yk}`),a=y=>new Bx(y,{provider:`${o}.chat`,url:({path:m})=>`${r}${m}`,headers:s,fetch:e.fetch}),i=y=>new Yx(y,{provider:`${o}.completion`,url:({path:m})=>`${r}${m}`,headers:s,fetch:e.fetch}),l=y=>new ek(y,{provider:`${o}.embedding`,url:({path:m})=>`${r}${m}`,headers:s,fetch:e.fetch}),u=y=>new ok(y,{provider:`${o}.image`,url:({path:m})=>`${r}${m}`,headers:s,fetch:e.fetch}),p=y=>new Kk(y,{provider:`${o}.transcription`,url:({path:m})=>`${r}${m}`,headers:s,fetch:e.fetch}),x=y=>new Jk(y,{provider:`${o}.speech`,url:({path:m})=>`${r}${m}`,headers:s,fetch:e.fetch}),w=y=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return h(y)},h=y=>new $k(y,{provider:`${o}.responses`,url:({path:m})=>`${r}${m}`,headers:s,fetch:e.fetch,fileIdPrefixes:["file-"]}),f=function(y){return w(y)};return f.languageModel=w,f.chat=a,f.completion=i,f.responses=h,f.embedding=l,f.textEmbedding=l,f.textEmbeddingModel=l,f.image=u,f.imageModel=u,f.transcription=p,f.transcriptionModel=p,f.speech=x,f.speechModel=x,f.tools=Ek,f}wd();function mr(e){var t,n;return(n=(t=e==null?void 0:e.providerOptions)==null?void 0:t.openaiCompatible)!=null?n:{}}function Xk(e){const t=[];for(const{role:n,content:r,...o}of e){const s=mr({...o});switch(n){case"system":{t.push({role:"system",content:r,...s});break}case"user":{if(r.length===1&&r[0].type==="text"){t.push({role:"user",content:r[0].text,...mr(r[0])});break}t.push({role:"user",content:r.map(a=>{const i=mr(a);switch(a.type){case"text":return{type:"text",text:a.text,...i};case"file":if(a.mediaType.startsWith("image/")){const l=a.mediaType==="image/*"?"image/jpeg":a.mediaType;return{type:"image_url",image_url:{url:a.data instanceof URL?a.data.toString():`data:${l};base64,${pn(a.data)}`},...i}}else throw new ft({functionality:`file part media type ${a.mediaType}`})}}),...s});break}case"assistant":{let a="";const i=[];for(const l of r){const u=mr(l);switch(l.type){case"text":{a+=l.text;break}case"tool-call":{i.push({id:l.toolCallId,type:"function",function:{name:l.toolName,arguments:JSON.stringify(l.input)},...u});break}}}t.push({role:"assistant",content:a,tool_calls:i.length>0?i:void 0,...s});break}case"tool":{for(const a of r){const i=a.output;let l;switch(i.type){case"text":case"error-text":l=i.value;break;case"content":case"json":case"error-json":l=JSON.stringify(i.value);break}const u=mr(a);t.push({role:"tool",tool_call_id:a.toolCallId,content:l,...u})}break}default:{const a=n;throw new Error(`Unsupported role: ${a}`)}}}return t}function bd({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n!=null?new Date(n*1e3):void 0}}function xd(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 ra=g({user:d().optional(),reasoningEffort:d().optional(),textVerbosity:d().optional()}),Qk=g({error:g({message:d(),type:d().nullish(),param:ut().nullish(),code:ue([d(),I()]).nullish()})}),eT={errorSchema:Qk,errorToMessage:e=>e.error.message};function tT({tools:e,toolChoice:t}){e=e!=null&&e.length?e:void 0;const n=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};const r=[];for(const s of e)s.type==="provider-defined"?n.push({type:"unsupported-tool",tool:s}):r.push({type:"function",function:{name:s.name,description:s.description,parameters:s.inputSchema}});if(t==null)return{tools:r,toolChoice:void 0,toolWarnings:n};const o=t.type;switch(o){case"auto":case"none":case"required":return{tools:r,toolChoice:o,toolWarnings:n};case"tool":return{tools:r,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:n};default:{const s=o;throw new ft({functionality:`tool choice type: ${s}`})}}}var nT=class{constructor(e,t){this.specificationVersion="v2";var n,r;this.modelId=e,this.config=t;const o=(n=t.errorStructure)!=null?n:eT;this.chunkSchema=oT(o.errorSchema),this.failedResponseHandler=dn(o),this.supportsStructuredOutputs=(r=t.supportsStructuredOutputs)!=null?r:!1}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var e,t,n;return(n=(t=(e=this.config).supportedUrls)==null?void 0:t.call(e))!=null?n:{}}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:o,frequencyPenalty:s,presencePenalty:a,providerOptions:i,stopSequences:l,responseFormat:u,seed:p,toolChoice:x,tools:w}){var h,f,y,m;const c=[],b=Object.assign((h=await St({provider:"openai-compatible",providerOptions:i,schema:ra}))!=null?h:{},(f=await St({provider:this.providerOptionsName,providerOptions:i,schema:ra}))!=null?f:{});o!=null&&c.push({type:"unsupported-setting",setting:"topK"}),(u==null?void 0:u.type)==="json"&&u.schema!=null&&!this.supportsStructuredOutputs&&c.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:v,toolChoice:_,toolWarnings:R}=tT({tools:w,toolChoice:x});return{args:{model:this.modelId,user:b.user,max_tokens:t,temperature:n,top_p:r,frequency_penalty:s,presence_penalty:a,response_format:(u==null?void 0:u.type)==="json"?this.supportsStructuredOutputs===!0&&u.schema!=null?{type:"json_schema",json_schema:{schema:u.schema,name:(y=u.name)!=null?y:"response",description:u.description}}:{type:"json_object"}:void 0,stop:l,seed:p,...Object.fromEntries(Object.entries((m=i==null?void 0:i[this.providerOptionsName])!=null?m:{}).filter(([C])=>!Object.keys(ra.shape).includes(C))),reasoning_effort:b.reasoningEffort,verbosity:b.textVerbosity,messages:Xk(e),tools:v,tool_choice:_},warnings:[...c,...R]}}async doGenerate(e){var t,n,r,o,s,a,i,l,u,p,x,w,h,f,y,m,c;const{args:b,warnings:v}=await this.getArgs({...e}),_=JSON.stringify(b),{responseHeaders:R,value:C,rawValue:T}=await nt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Ge(this.config.headers(),e.headers),body:b,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:vt(rT),abortSignal:e.abortSignal,fetch:this.config.fetch}),P=C.choices[0],D=[],H=P.message.content;H!=null&&H.length>0&&D.push({type:"text",text:H});const K=(t=P.message.reasoning_content)!=null?t:P.message.reasoning;if(K!=null&&K.length>0&&D.push({type:"reasoning",text:K}),P.message.tool_calls!=null)for(const ne of P.message.tool_calls)D.push({type:"tool-call",toolCallId:(n=ne.id)!=null?n:tt(),toolName:ne.function.name,input:ne.function.arguments});const he={[this.providerOptionsName]:{},...await((o=(r=this.config.metadataExtractor)==null?void 0:r.extractMetadata)==null?void 0:o.call(r,{parsedBody:T}))},Y=(s=C.usage)==null?void 0:s.completion_tokens_details;return(Y==null?void 0:Y.accepted_prediction_tokens)!=null&&(he[this.providerOptionsName].acceptedPredictionTokens=Y==null?void 0:Y.accepted_prediction_tokens),(Y==null?void 0:Y.rejected_prediction_tokens)!=null&&(he[this.providerOptionsName].rejectedPredictionTokens=Y==null?void 0:Y.rejected_prediction_tokens),{content:D,finishReason:xd(P.finish_reason),usage:{inputTokens:(i=(a=C.usage)==null?void 0:a.prompt_tokens)!=null?i:void 0,outputTokens:(u=(l=C.usage)==null?void 0:l.completion_tokens)!=null?u:void 0,totalTokens:(x=(p=C.usage)==null?void 0:p.total_tokens)!=null?x:void 0,reasoningTokens:(f=(h=(w=C.usage)==null?void 0:w.completion_tokens_details)==null?void 0:h.reasoning_tokens)!=null?f:void 0,cachedInputTokens:(c=(m=(y=C.usage)==null?void 0:y.prompt_tokens_details)==null?void 0:m.cached_tokens)!=null?c:void 0},providerMetadata:he,request:{body:_},response:{...bd(C),headers:R,body:T},warnings:v}}async doStream(e){var t;const{args:n,warnings:r}=await this.getArgs({...e}),o={...n,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},s=(t=this.config.metadataExtractor)==null?void 0:t.createStreamExtractor(),{responseHeaders:a,value:i}=await nt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Ge(this.config.headers(),e.headers),body:o,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:Qn(this.chunkSchema),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=[];let u="unknown";const p={completionTokens:void 0,completionTokensDetails:{reasoningTokens:void 0,acceptedPredictionTokens:void 0,rejectedPredictionTokens:void 0},promptTokens:void 0,promptTokensDetails:{cachedTokens:void 0},totalTokens:void 0};let x=!0;const w=this.providerOptionsName;let h=!1,f=!1;return{stream:i.pipeThrough(new TransformStream({start(y){y.enqueue({type:"stream-start",warnings:r})},transform(y,m){var c,b,v,_,R,C,T,P,D,H,K,he,Y;if(e.includeRawChunks&&m.enqueue({type:"raw",rawValue:y.rawValue}),!y.success){u="error",m.enqueue({type:"error",error:y.error});return}const ne=y.value;if(s==null||s.processChunk(y.rawValue),"error"in ne){u="error",m.enqueue({type:"error",error:ne.error.message});return}if(x&&(x=!1,m.enqueue({type:"response-metadata",...bd(ne)})),ne.usage!=null){const{prompt_tokens:ce,completion_tokens:Pe,total_tokens:oe,prompt_tokens_details:me,completion_tokens_details:ee}=ne.usage;p.promptTokens=ce??void 0,p.completionTokens=Pe??void 0,p.totalTokens=oe??void 0,(ee==null?void 0:ee.reasoning_tokens)!=null&&(p.completionTokensDetails.reasoningTokens=ee==null?void 0:ee.reasoning_tokens),(ee==null?void 0:ee.accepted_prediction_tokens)!=null&&(p.completionTokensDetails.acceptedPredictionTokens=ee==null?void 0:ee.accepted_prediction_tokens),(ee==null?void 0:ee.rejected_prediction_tokens)!=null&&(p.completionTokensDetails.rejectedPredictionTokens=ee==null?void 0:ee.rejected_prediction_tokens),(me==null?void 0:me.cached_tokens)!=null&&(p.promptTokensDetails.cachedTokens=me==null?void 0:me.cached_tokens)}const V=ne.choices[0];if((V==null?void 0:V.finish_reason)!=null&&(u=xd(V.finish_reason)),(V==null?void 0:V.delta)==null)return;const se=V.delta,ae=(c=se.reasoning_content)!=null?c:se.reasoning;if(ae&&(h||(m.enqueue({type:"reasoning-start",id:"reasoning-0"}),h=!0),m.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:ae})),se.content&&(f||(m.enqueue({type:"text-start",id:"txt-0"}),f=!0),m.enqueue({type:"text-delta",id:"txt-0",delta:se.content})),se.tool_calls!=null)for(const ce of se.tool_calls){const Pe=ce.index;if(l[Pe]==null){if(ce.id==null)throw new zn({data:ce,message:"Expected 'id' to be a string."});if(((b=ce.function)==null?void 0:b.name)==null)throw new zn({data:ce,message:"Expected 'function.name' to be a string."});m.enqueue({type:"tool-input-start",id:ce.id,toolName:ce.function.name}),l[Pe]={id:ce.id,type:"function",function:{name:ce.function.name,arguments:(v=ce.function.arguments)!=null?v:""},hasFinished:!1};const me=l[Pe];((_=me.function)==null?void 0:_.name)!=null&&((R=me.function)==null?void 0:R.arguments)!=null&&(me.function.arguments.length>0&&m.enqueue({type:"tool-input-delta",id:me.id,delta:me.function.arguments}),Gr(me.function.arguments)&&(m.enqueue({type:"tool-input-end",id:me.id}),m.enqueue({type:"tool-call",toolCallId:(C=me.id)!=null?C:tt(),toolName:me.function.name,input:me.function.arguments}),me.hasFinished=!0));continue}const oe=l[Pe];oe.hasFinished||(((T=ce.function)==null?void 0:T.arguments)!=null&&(oe.function.arguments+=(D=(P=ce.function)==null?void 0:P.arguments)!=null?D:""),m.enqueue({type:"tool-input-delta",id:oe.id,delta:(H=ce.function.arguments)!=null?H:""}),((K=oe.function)==null?void 0:K.name)!=null&&((he=oe.function)==null?void 0:he.arguments)!=null&&Gr(oe.function.arguments)&&(m.enqueue({type:"tool-input-end",id:oe.id}),m.enqueue({type:"tool-call",toolCallId:(Y=oe.id)!=null?Y:tt(),toolName:oe.function.name,input:oe.function.arguments}),oe.hasFinished=!0))}},flush(y){var m,c,b,v,_,R;h&&y.enqueue({type:"reasoning-end",id:"reasoning-0"}),f&&y.enqueue({type:"text-end",id:"txt-0"});for(const T of l.filter(P=>!P.hasFinished))y.enqueue({type:"tool-input-end",id:T.id}),y.enqueue({type:"tool-call",toolCallId:(m=T.id)!=null?m:tt(),toolName:T.function.name,input:T.function.arguments});const C={[w]:{},...s==null?void 0:s.buildMetadata()};p.completionTokensDetails.acceptedPredictionTokens!=null&&(C[w].acceptedPredictionTokens=p.completionTokensDetails.acceptedPredictionTokens),p.completionTokensDetails.rejectedPredictionTokens!=null&&(C[w].rejectedPredictionTokens=p.completionTokensDetails.rejectedPredictionTokens),y.enqueue({type:"finish",finishReason:u,usage:{inputTokens:(c=p.promptTokens)!=null?c:void 0,outputTokens:(b=p.completionTokens)!=null?b:void 0,totalTokens:(v=p.totalTokens)!=null?v:void 0,reasoningTokens:(_=p.completionTokensDetails.reasoningTokens)!=null?_:void 0,cachedInputTokens:(R=p.promptTokensDetails.cachedTokens)!=null?R:void 0},providerMetadata:C})}})),request:{body:o},response:{headers:a}}}},kd=g({prompt_tokens:I().nullish(),completion_tokens:I().nullish(),total_tokens:I().nullish(),prompt_tokens_details:g({cached_tokens:I().nullish()}).nullish(),completion_tokens_details:g({reasoning_tokens:I().nullish(),accepted_prediction_tokens:I().nullish(),rejected_prediction_tokens:I().nullish()}).nullish()}).nullish(),rT=g({id:d().nullish(),created:I().nullish(),model:d().nullish(),choices:z(g({message:g({role:A("assistant").nullish(),content:d().nullish(),reasoning_content:d().nullish(),reasoning:d().nullish(),tool_calls:z(g({id:d().nullish(),function:g({name:d(),arguments:d()})})).nullish()}),finish_reason:d().nullish()})),usage:kd}),oT=e=>ue([g({id:d().nullish(),created:I().nullish(),model:d().nullish(),choices:z(g({delta:g({role:Se(["assistant"]).nullish(),content:d().nullish(),reasoning_content:d().nullish(),reasoning:d().nullish(),tool_calls:z(g({index:I(),id:d().nullish(),function:g({name:d().nullish(),arguments:d().nullish()})})).nullish()}).nullish(),finish_reason:d().nullish()})),usage:kd}),e]);g({echo:Ae().optional(),logitBias:Oe(d(),I()).optional(),suffix:d().optional(),user:d().optional()});var sT=g({prompt_tokens:I(),completion_tokens:I(),total_tokens:I()});g({id:d().nullish(),created:I().nullish(),model:d().nullish(),choices:z(g({text:d(),finish_reason:d()})),usage:sT.nullish()}),g({dimensions:I().optional(),user:d().optional()}),g({data:z(g({embedding:z(I())})),usage:g({prompt_tokens:I()}).nullish(),providerMetadata:Oe(d(),Oe(d(),ut())).optional()}),g({data:z(g({b64_json:d()}))});var Td=e=>{var t,n;return e==null?void 0:{deepseek:{promptCacheHitTokens:(t=e.prompt_cache_hit_tokens)!=null?t:NaN,promptCacheMissTokens:(n=e.prompt_cache_miss_tokens)!=null?n:NaN}}},aT={extractMetadata:async({parsedBody:e})=>{const t=await gt({value:e,schema:iT});return!t.success||t.value.usage==null?void 0:Td(t.value.usage)},createStreamExtractor:()=>{let e;return{processChunk:async t=>{var n,r;const o=await gt({value:t,schema:lT});o.success&&((r=(n=o.value.choices)==null?void 0:n[0])==null?void 0:r.finish_reason)==="stop"&&o.value.usage&&(e=o.value.usage)},buildMetadata:()=>Td(e)}}},Sd=g({prompt_cache_hit_tokens:I().nullish(),prompt_cache_miss_tokens:I().nullish()}),iT=g({usage:Sd.nullish()}),lT=g({choices:z(g({finish_reason:d().nullish()})).nullish(),usage:Sd.nullish()}),uT="1.0.23";function Id(e={}){var t;const n=is((t=e.baseURL)!=null?t:"https://api.deepseek.com/v1"),r=()=>Lt({Authorization:`Bearer ${vl({apiKey:e.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...e.headers},`ai-sdk/deepseek/${uT}`),o=a=>new nT(a,{provider:"deepseek.chat",url:({path:i})=>`${n}${i}`,headers:r,fetch:e.fetch,metadataExtractor:aT}),s=a=>o(a);return s.languageModel=o,s.chat=o,s.textEmbeddingModel=a=>{throw new Ro({modelId:a,modelType:"textEmbeddingModel"})},s.imageModel=a=>{throw new Ro({modelId:a,modelType:"imageModel"})},s}Id();const cT=(e,t,n)=>{if(n.endsWith("content"))chrome.tabs.query({},r=>{r.forEach(o=>{chrome.tabs.sendMessage(o.id,{type:e,data:t,direction:n,tabId:o.id})})});else return chrome.runtime.sendMessage({direction:n,type:e,data:t})},dT=(e,t,n,r)=>{const o=(s,a,i)=>{if(s.type===e&&s.direction===n){const{data:l}=s;t(l,a,i),i(a)}};return chrome.runtime.onMessage.addListener(o),()=>chrome.runtime.onMessage.removeListener(o)};class pT{constructor(t){this._isStarted=!1,this._isClosed=!1,this.targetSessionId=t,this._messageListener=dT("mcp-server-to-client",n=>{var r;try{if(n.sessionId!==this.targetSessionId)return;const o=co.parse(n.mcpMessage);(r=this.onmessage)==null||r.call(this,o)}catch(o){console.log("【Client Transport】处理server消息错误:",o)}},"content->side")}_throwError(t,n){if(t()){const r=new Error(n);throw console.log(n,r),this.onerror&&this.onerror(r),r}}async start(){this._throwError(()=>this._isClosed,"【Client Transport】 未启动,无法重新启动"),this._isStarted=!0}async send(t,n){this._throwError(()=>!this._isStarted,"【Client Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Client Transport】 已关闭,无法发送消息");const r=chrome.sessionRegistry.get(this.targetSessionId);this._throwError(()=>!r,`【Client Transport】sessionRegistry中未找到${this.targetSessionId}`);const o=r.tabIds[r.tabIds.length-1];cT("mcp-client-to-server",{sessionId:this.targetSessionId,tabId:o,mcpMessage:t},"side->content")}async close(){if(!this._isClosed)try{this._isClosed=!0,this._isStarted=!1,this._messageListener&&this._messageListener(),this.onclose&&this.onclose()}catch{this._throwError(()=>!0,"【Client Transport】 关闭时发生错误")}}}const hT={openai:wd,deepseek:Id};class fT{constructor({llmConfig:t,mcpServers:n,llm:r}){if(this.mcpServers={},this.mcpClients={},this.mcpTools={},this.ignoreToolnames=[],this.messages=[],this.mcpServers=n||{},this.mcpClients={},this.mcpTools={},r)this.llm=r;else if(t){let o;typeof t.providerType=="string"?o=hT[t.providerType]:o=t.providerType,this.llm=o({apiKey:t.apiKey,baseURL:t.baseURL})}else throw new Error("Either llmConfig or llm must be provided")}async _createOneClient(t){try{let n;"type"in t&&t.type.toLocaleLowerCase()==="streamablehttp"?n=new jx(new URL(t.url)):"type"in t&&t.type==="extension"?n=new pT(t.sessionId):n=t;const r=await X0({transport:n});return r.__transport__=n,r}catch(n){return this.onError&&this.onError((n==null?void 0:n.message)||"Failed to create MCP client",n),console.error("Failed to create MCP client",t,n),null}}async _closeOneClient(t){var n,r,o,s,a;try{await((r=(n=t.__transport__)==null?void 0:n.terminateSession)==null?void 0:r.call(n)),await((s=(o=t.__transport__)==null?void 0:o.close)==null?void 0:s.call(o)),await((a=t==null?void 0:t.close)==null?void 0:a.call(t))}catch{}}async _createMpcClients(){const t=Object.entries(this.mcpServers),n=await Promise.all(t.map(async([r,o])=>{const s=await this._createOneClient(o);return{serverName:r,client:s}}));this.mcpClients={},n.forEach(({serverName:r,client:o})=>{this.mcpClients[r]=o})}async _createMpcTools(){const t=Object.entries(this.mcpClients),n=await Promise.all(t.map(async([r,o])=>{var s;try{const a=o?await((s=o==null?void 0:o.tools)==null?void 0:s.call(o)):null;return{serverName:r,tools:a}}catch(a){return this.onError&&this.onError((a==null?void 0:a.message)||"Failed to query tools",a),console.error("Failed to query tools",a),{serverName:r,tools:null}}}));this.mcpTools={},n.forEach(({serverName:r,tools:o})=>{this.mcpTools[r]=o})}async closeAll(){await Promise.all(Object.values(this.mcpClients).map(async t=>{try{await this._closeOneClient(t)}catch(n){this.onError&&this.onError((n==null?void 0:n.message)||"Failed to close client",n),console.error("Failed to close client",n)}}))}async initClientsAndTools(){var t;await this._createMpcClients(),await this._createMpcTools(),(t=this.onUpdatedTools)==null||t.call(this)}async updateMcpServers(t){await this.closeAll(),this.mcpServers=t||this.mcpServers,await this.initClientsAndTools()}async insertMcpServer(t,n){var o,s;if(this.mcpServers[t])return!1;const r=await this._createOneClient(n);return this.mcpClients[t]=r,this.mcpTools[t]=await((o=r==null?void 0:r.tools)==null?void 0:o.call(r)),this.mcpServers[t]=n,(s=this.onUpdatedTools)==null||s.call(this),!0}async removeMcpServer(t){var o;if(!this.mcpServers[t])return;delete this.mcpServers[t];const n=this.mcpClients[t];delete this.mcpClients[t];try{await this._closeOneClient(n)}catch{}const r=this.mcpTools[t];delete this.mcpTools[t],r&&Object.keys(r).forEach(s=>{this.ignoreToolnames=this.ignoreToolnames.filter(a=>a!==s)}),(o=this.onUpdatedTools)==null||o.call(this)}_tempMergeTools(t={}){const n=Object.values(this.mcpTools).reduce((r,o)=>({...r,...o}),{});return Object.assign(n,t),this.ignoreToolnames.forEach(r=>{delete n[r]}),n}async _chat(t,{model:n,maxSteps:r=5,...o}){var i;if(!this.llm)throw new Error("LLM is not initialized");await this.initClientsAndTools();const s={model:this.llm(n),stopWhen:Es(r),...o,tools:this._tempMergeTools(o.tools)};o.message&&!o.messages&&(this.messages.push({role:"user",content:o.message}),s.messages=[...this.messages]);const a=t(s);return(i=a==null?void 0:a.response)==null||i.then(l=>{this.messages.push(...l.messages)}),a}async chat(t){return this._chat(o0,t)}async chatStream(t){return this._chat(k0,t)}}var En={},mT=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then},Cd={},it={};let oa;const gT=[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];it.getSymbolSize=function(t){if(!t)throw new Error('"version" cannot be null or undefined');if(t<1||t>40)throw new Error('"version" should be in range from 1 to 40');return t*4+17},it.getSymbolTotalCodewords=function(t){return gT[t]},it.getBCHDigit=function(e){let t=0;for(;e!==0;)t++,e>>>=1;return t},it.setToSJISFunction=function(t){if(typeof t!="function")throw new Error('"toSJISFunc" is not a valid function.');oa=t},it.isKanjiModeEnabled=function(){return typeof oa<"u"},it.toSJIS=function(t){return oa(t)};var yo={};(function(e){e.L={bit:1},e.M={bit:0},e.Q={bit:3},e.H={bit:2};function t(n){if(typeof n!="string")throw new Error("Param is not a string");switch(n.toLowerCase()){case"l":case"low":return e.L;case"m":case"medium":return e.M;case"q":case"quartile":return e.Q;case"h":case"high":return e.H;default:throw new Error("Unknown EC Level: "+n)}}e.isValid=function(r){return r&&typeof r.bit<"u"&&r.bit>=0&&r.bit<4},e.from=function(r,o){if(e.isValid(r))return r;try{return t(r)}catch{return o}}})(yo);function Ed(){this.buffer=[],this.length=0}Ed.prototype={get:function(e){const t=Math.floor(e/8);return(this.buffer[t]>>>7-e%8&1)===1},put:function(e,t){for(let n=0;n<t;n++)this.putBit((e>>>t-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(e){const t=Math.floor(this.length/8);this.buffer.length<=t&&this.buffer.push(0),e&&(this.buffer[t]|=128>>>this.length%8),this.length++}};var vT=Ed;function gr(e){if(!e||e<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=e,this.data=new Uint8Array(e*e),this.reservedBit=new Uint8Array(e*e)}gr.prototype.set=function(e,t,n,r){const o=e*this.size+t;this.data[o]=n,r&&(this.reservedBit[o]=!0)},gr.prototype.get=function(e,t){return this.data[e*this.size+t]},gr.prototype.xor=function(e,t,n){this.data[e*this.size+t]^=n},gr.prototype.isReserved=function(e,t){return this.reservedBit[e*this.size+t]};var yT=gr,Rd={};(function(e){const t=it.getSymbolSize;e.getRowColCoords=function(r){if(r===1)return[];const o=Math.floor(r/7)+2,s=t(r),a=s===145?26:Math.ceil((s-13)/(2*o-2))*2,i=[s-7];for(let l=1;l<o-1;l++)i[l]=i[l-1]-a;return i.push(6),i.reverse()},e.getPositions=function(r){const o=[],s=e.getRowColCoords(r),a=s.length;for(let i=0;i<a;i++)for(let l=0;l<a;l++)i===0&&l===0||i===0&&l===a-1||i===a-1&&l===0||o.push([s[i],s[l]]);return o}})(Rd);var Ad={};const _T=it.getSymbolSize,Od=7;Ad.getPositions=function(t){const n=_T(t);return[[0,0],[n-Od,0],[0,n-Od]]};var Nd={};(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 a=0,i=0,l=0,u=null,p=null;for(let x=0;x<s;x++){i=l=0,u=p=null;for(let w=0;w<s;w++){let h=o.get(x,w);h===u?i++:(i>=5&&(a+=t.N1+(i-5)),u=h,i=1),h=o.get(w,x),h===p?l++:(l>=5&&(a+=t.N1+(l-5)),p=h,l=1)}i>=5&&(a+=t.N1+(i-5)),l>=5&&(a+=t.N1+(l-5))}return a},e.getPenaltyN2=function(o){const s=o.size;let a=0;for(let i=0;i<s-1;i++)for(let l=0;l<s-1;l++){const u=o.get(i,l)+o.get(i,l+1)+o.get(i+1,l)+o.get(i+1,l+1);(u===4||u===0)&&a++}return a*t.N2},e.getPenaltyN3=function(o){const s=o.size;let a=0,i=0,l=0;for(let u=0;u<s;u++){i=l=0;for(let p=0;p<s;p++)i=i<<1&2047|o.get(u,p),p>=10&&(i===1488||i===93)&&a++,l=l<<1&2047|o.get(p,u),p>=10&&(l===1488||l===93)&&a++}return a*t.N3},e.getPenaltyN4=function(o){let s=0;const a=o.data.length;for(let l=0;l<a;l++)s+=o.data[l];return Math.abs(Math.ceil(s*100/a/5)-10)*t.N4};function n(r,o,s){switch(r){case e.Patterns.PATTERN000:return(o+s)%2===0;case e.Patterns.PATTERN001:return o%2===0;case e.Patterns.PATTERN010:return s%3===0;case e.Patterns.PATTERN011:return(o+s)%3===0;case e.Patterns.PATTERN100:return(Math.floor(o/2)+Math.floor(s/3))%2===0;case e.Patterns.PATTERN101:return o*s%2+o*s%3===0;case e.Patterns.PATTERN110:return(o*s%2+o*s%3)%2===0;case e.Patterns.PATTERN111:return(o*s%3+(o+s)%2)%2===0;default:throw new Error("bad maskPattern:"+r)}}e.applyMask=function(o,s){const a=s.size;for(let i=0;i<a;i++)for(let l=0;l<a;l++)s.isReserved(l,i)||s.xor(l,i,n(o,l,i))},e.getBestMask=function(o,s){const a=Object.keys(e.Patterns).length;let i=0,l=1/0;for(let u=0;u<a;u++){s(u),e.applyMask(u,o);const p=e.getPenaltyN1(o)+e.getPenaltyN2(o)+e.getPenaltyN3(o)+e.getPenaltyN4(o);e.applyMask(u,o),p<l&&(l=p,i=u)}return i}})(Nd);var _o={};const Yt=yo,wo=[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],bo=[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];_o.getBlocksCount=function(t,n){switch(n){case Yt.L:return wo[(t-1)*4+0];case Yt.M:return wo[(t-1)*4+1];case Yt.Q:return wo[(t-1)*4+2];case Yt.H:return wo[(t-1)*4+3];default:return}},_o.getTotalCodewordsCount=function(t,n){switch(n){case Yt.L:return bo[(t-1)*4+0];case Yt.M:return bo[(t-1)*4+1];case Yt.Q:return bo[(t-1)*4+2];case Yt.H:return bo[(t-1)*4+3];default:return}};var Md={},xo={};const vr=new Uint8Array(512),ko=new Uint8Array(256);(function(){let t=1;for(let n=0;n<255;n++)vr[n]=t,ko[t]=n,t<<=1,t&256&&(t^=285);for(let n=255;n<512;n++)vr[n]=vr[n-255]})(),xo.log=function(t){if(t<1)throw new Error("log("+t+")");return ko[t]},xo.exp=function(t){return vr[t]},xo.mul=function(t,n){return t===0||n===0?0:vr[ko[t]+ko[n]]},function(e){const t=xo;e.mul=function(r,o){const s=new Uint8Array(r.length+o.length-1);for(let a=0;a<r.length;a++)for(let i=0;i<o.length;i++)s[a+i]^=t.mul(r[a],o[i]);return s},e.mod=function(r,o){let s=new Uint8Array(r);for(;s.length-o.length>=0;){const a=s[0];for(let l=0;l<o.length;l++)s[l]^=t.mul(o[l],a);let i=0;for(;i<s.length&&s[i]===0;)i++;s=s.slice(i)}return s},e.generateECPolynomial=function(r){let o=new Uint8Array([1]);for(let s=0;s<r;s++)o=e.mul(o,new Uint8Array([1,t.exp(s)]));return o}}(Md);const Pd=Md;function sa(e){this.genPoly=void 0,this.degree=e,this.degree&&this.initialize(this.degree)}sa.prototype.initialize=function(t){this.degree=t,this.genPoly=Pd.generateECPolynomial(this.degree)},sa.prototype.encode=function(t){if(!this.genPoly)throw new Error("Encoder not initialized");const n=new Uint8Array(t.length+this.degree);n.set(t);const r=Pd.mod(n,this.genPoly),o=this.degree-r.length;if(o>0){const s=new Uint8Array(this.degree);return s.set(r,o),s}return r};var wT=sa,$d={},Xt={},aa={};aa.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40};var Ot={};const zd="[0-9]+",bT="[A-Z $%*+\\-./:]+";let yr="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";yr=yr.replace(/u/g,"\\u");const xT="(?:(?![A-Z0-9 $%*+\\-./:]|"+yr+`)(?:.|[\r
|
|
68
|
-
]))+`;
|
|
69
|
-
Make sure your charset is UTF-8`);
|
|
70
|
-
Suggested mode is: `+
|
|
69
|
+
`;break}case"tool":throw new Nt({functionality:"tool messages"});default:{const o=n;throw new Error(`Unsupported role: ${o}`)}}return a+=`${r}:
|
|
70
|
+
`,{prompt:a,stopSequences:[`
|
|
71
|
+
${e}:`]}}function af({id:t,model:e,created:r}){return{id:t??void 0,modelId:e??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function sf(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var of=P({echo:nt().optional(),logitBias:St(x(),U()).optional(),suffix:x().optional(),user:x().optional(),logprobs:Ae([nt(),U()]).optional()}),MI=class{constructor(t,e){this.specificationVersion="v2",this.supportedUrls={},this.modelId=t,this.config=e}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:e,temperature:r,topP:a,topK:n,frequencyPenalty:s,presencePenalty:o,stopSequences:i,responseFormat:l,tools:u,toolChoice:d,seed:h,providerOptions:g}){const c=[],p={...await lr({provider:"openai",providerOptions:g,schema:of}),...await lr({provider:this.providerOptionsName,providerOptions:g,schema:of})};n!=null&&c.push({type:"unsupported-setting",setting:"topK"}),u!=null&&u.length&&c.push({type:"unsupported-setting",setting:"tools"}),d!=null&&c.push({type:"unsupported-setting",setting:"toolChoice"}),l!=null&&l.type!=="text"&&c.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});const{prompt:f,stopSequences:m}=NI({prompt:t}),v=[...m??[],...i??[]];return{args:{model:this.modelId,echo:p.echo,logit_bias:p.logitBias,logprobs:(p==null?void 0:p.logprobs)===!0?0:(p==null?void 0:p.logprobs)===!1||p==null?void 0:p.logprobs,suffix:p.suffix,user:p.user,max_tokens:e,temperature:r,top_p:a,frequency_penalty:s,presence_penalty:o,seed:h,prompt:f,stop:v.length>0?v:void 0},warnings:c}}async doGenerate(t){var e,r,a;const{args:n,warnings:s}=await this.getArgs(t),{responseHeaders:o,value:i,rawValue:l}=await Kt({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Ut(this.config.headers(),t.headers),body:n,failedResponseHandler:ur,successfulResponseHandler:ln(DI),abortSignal:t.abortSignal,fetch:this.config.fetch}),u=i.choices[0],d={openai:{}};return u.logprobs!=null&&(d.openai.logprobs=u.logprobs),{content:[{type:"text",text:u.text}],usage:{inputTokens:(e=i.usage)==null?void 0:e.prompt_tokens,outputTokens:(r=i.usage)==null?void 0:r.completion_tokens,totalTokens:(a=i.usage)==null?void 0:a.total_tokens},finishReason:sf(u.finish_reason),request:{body:n},response:{...af(i),headers:o,body:l},providerMetadata:d,warnings:s}}async doStream(t){const{args:e,warnings:r}=await this.getArgs(t),a={...e,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:n,value:s}=await Kt({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Ut(this.config.headers(),t.headers),body:a,failedResponseHandler:ur,successfulResponseHandler:Os(jI),abortSignal:t.abortSignal,fetch:this.config.fetch});let o="unknown";const i={openai:{}},l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let u=!0;return{stream:s.pipeThrough(new TransformStream({start(d){d.enqueue({type:"stream-start",warnings:r})},transform(d,h){if(t.includeRawChunks&&h.enqueue({type:"raw",rawValue:d.rawValue}),!d.success){o="error",h.enqueue({type:"error",error:d.error});return}const g=d.value;if("error"in g){o="error",h.enqueue({type:"error",error:g.error});return}u&&(u=!1,h.enqueue({type:"response-metadata",...af(g)}),h.enqueue({type:"text-start",id:"0"})),g.usage!=null&&(l.inputTokens=g.usage.prompt_tokens,l.outputTokens=g.usage.completion_tokens,l.totalTokens=g.usage.total_tokens);const c=g.choices[0];(c==null?void 0:c.finish_reason)!=null&&(o=sf(c.finish_reason)),(c==null?void 0:c.logprobs)!=null&&(i.openai.logprobs=c.logprobs),(c==null?void 0:c.text)!=null&&c.text.length>0&&h.enqueue({type:"text-delta",id:"0",delta:c.text})},flush(d){u||d.enqueue({type:"text-end",id:"0"}),d.enqueue({type:"finish",finishReason:o,providerMetadata:i,usage:l})}})),request:{body:a},response:{headers:n}}}},lf=P({prompt_tokens:U(),completion_tokens:U(),total_tokens:U()}),DI=P({id:x().nullish(),created:U().nullish(),model:x().nullish(),choices:Y(P({text:x(),finish_reason:x(),logprobs:P({tokens:Y(x()),token_logprobs:Y(U()),top_logprobs:Y(St(x(),U())).nullish()}).nullish()})),usage:lf.nullish()}),jI=Ae([P({id:x().nullish(),created:U().nullish(),model:x().nullish(),choices:Y(P({text:x(),finish_reason:x().nullish(),index:U(),logprobs:P({tokens:Y(x()),token_logprobs:Y(U()),top_logprobs:Y(St(x(),U())).nullish()}).nullish()})),usage:lf.nullish()}),tl]),LI=P({dimensions:U().optional(),user:x().optional()}),zI=class{constructor(t,e){this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=t,this.config=e}get provider(){return this.config.provider}async doEmbed({values:t,headers:e,abortSignal:r,providerOptions:a}){var n;if(t.length>this.maxEmbeddingsPerCall)throw new iv({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});const s=(n=await lr({provider:"openai",providerOptions:a,schema:LI}))!=null?n:{},{responseHeaders:o,value:i,rawValue:l}=await Kt({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:Ut(this.config.headers(),e),body:{model:this.modelId,input:t,encoding_format:"float",dimensions:s.dimensions,user:s.user},failedResponseHandler:ur,successfulResponseHandler:ln(UI),abortSignal:r,fetch:this.config.fetch});return{embeddings:i.data.map(u=>u.embedding),usage:i.usage?{tokens:i.usage.prompt_tokens}:void 0,response:{headers:o,body:l}}}},UI=P({data:Y(P({embedding:Y(U())})),usage:P({prompt_tokens:U()}).nullish()}),FI={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10},qI=new Set(["gpt-image-1"]),ZI=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2"}get maxImagesPerCall(){var t;return(t=FI[this.modelId])!=null?t:1}get provider(){return this.config.provider}async doGenerate({prompt:t,n:e,size:r,aspectRatio:a,seed:n,providerOptions:s,headers:o,abortSignal:i}){var l,u,d,h;const g=[];a!=null&&g.push({type:"unsupported-setting",setting:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),n!=null&&g.push({type:"unsupported-setting",setting:"seed"});const c=(d=(u=(l=this.config._internal)==null?void 0:l.currentDate)==null?void 0:u.call(l))!=null?d:new Date,{value:p,responseHeaders:f}=await Kt({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:Ut(this.config.headers(),o),body:{model:this.modelId,prompt:t,n:e,size:r,...(h=s.openai)!=null?h:{},...qI.has(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:ur,successfulResponseHandler:ln(VI),abortSignal:i,fetch:this.config.fetch});return{images:p.data.map(m=>m.b64_json),warnings:g,response:{timestamp:c,modelId:this.modelId,headers:f},providerMetadata:{openai:{images:p.data.map(m=>m.revised_prompt?{revisedPrompt:m.revised_prompt}:null)}}}}},VI=P({data:Y(P({b64_json:x(),revised_prompt:x().optional()}))}),BI=P({container:Ae([x(),P({fileIds:Y(x()).optional()})]).optional()}),HI=el({id:"openai.code_interpreter",name:"code_interpreter",inputSchema:P({})}),JI={codeInterpreter:HI,fileSearch:SI,webSearchPreview:II};function uf(t,e){return e?e.some(r=>t.startsWith(r)):!1}async function WI({prompt:t,systemMessageMode:e,fileIdPrefixes:r}){var a,n,s,o,i,l;const u=[],d=[];for(const{role:h,content:g}of t)switch(h){case"system":{switch(e){case"system":{u.push({role:"system",content:g});break}case"developer":{u.push({role:"developer",content:g});break}case"remove":{d.push({type:"other",message:"system messages are removed for this model"});break}default:{const c=e;throw new Error(`Unsupported system message mode: ${c}`)}}break}case"user":{u.push({role:"user",content:g.map((c,p)=>{var f,m,v;switch(c.type){case"text":return{type:"input_text",text:c.text};case"file":if(c.mediaType.startsWith("image/")){const w=c.mediaType==="image/*"?"image/jpeg":c.mediaType;return{type:"input_image",...c.data instanceof URL?{image_url:c.data.toString()}:typeof c.data=="string"&&uf(c.data,r)?{file_id:c.data}:{image_url:`data:${w};base64,${un(c.data)}`},detail:(m=(f=c.providerOptions)==null?void 0:f.openai)==null?void 0:m.imageDetail}}else if(c.mediaType==="application/pdf"){if(c.data instanceof URL)throw new Nt({functionality:"PDF file parts with URLs"});return{type:"input_file",...typeof c.data=="string"&&uf(c.data,r)?{file_id:c.data}:{filename:(v=c.filename)!=null?v:`part-${p}.pdf`,file_data:`data:application/pdf;base64,${un(c.data)}`}}}else throw new Nt({functionality:`file part media type ${c.mediaType}`})}})});break}case"assistant":{const c={};for(const p of g)switch(p.type){case"text":{u.push({role:"assistant",content:[{type:"output_text",text:p.text}],id:(s=(n=(a=p.providerOptions)==null?void 0:a.openai)==null?void 0:n.itemId)!=null?s:void 0});break}case"tool-call":{if(p.providerExecuted)break;u.push({type:"function_call",call_id:p.toolCallId,name:p.toolName,arguments:JSON.stringify(p.input),id:(l=(i=(o=p.providerOptions)==null?void 0:o.openai)==null?void 0:i.itemId)!=null?l:void 0});break}case"tool-result":{d.push({type:"other",message:"tool result parts in assistant messages are not supported for OpenAI responses"});break}case"reasoning":{const f=await lr({provider:"openai",providerOptions:p.providerOptions,schema:GI}),m=f==null?void 0:f.itemId;if(m!=null){const v=c[m],w=[];p.text.length>0?w.push({type:"summary_text",text:p.text}):v!==void 0&&d.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(p)}.`}),v===void 0?(c[m]={type:"reasoning",id:m,encrypted_content:f==null?void 0:f.reasoningEncryptedContent,summary:w},u.push(c[m])):v.summary.push(...w)}else d.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(p)}.`});break}}break}case"tool":{for(const c of g){const p=c.output;let f;switch(p.type){case"text":case"error-text":f=p.value;break;case"content":case"json":case"error-json":f=JSON.stringify(p.value);break}u.push({type:"function_call_output",call_id:c.toolCallId,output:f})}break}default:{const c=h;throw new Error(`Unsupported role: ${c}`)}}return{messages:u,warnings:d}}var GI=P({itemId:x().nullish(),reasoningEncryptedContent:x().nullish()});function cf({finishReason:t,hasToolCalls:e}){switch(t){case void 0:case null:return e?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return e?"tool-calls":"unknown"}}function KI({tools:t,toolChoice:e,strictJsonSchema:r}){t=t!=null&&t.length?t:void 0;const a=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:a};const n=[];for(const o of t)switch(o.type){case"function":n.push({type:"function",name:o.name,description:o.description,parameters:o.inputSchema,strict:r});break;case"provider-defined":{switch(o.id){case"openai.file_search":{const i=ef.parse(o.args);n.push({type:"file_search",vector_store_ids:i.vectorStoreIds,max_num_results:i.maxNumResults,ranking_options:i.ranking?{ranker:i.ranking.ranker}:void 0,filters:i.filters});break}case"openai.web_search_preview":{const i=tf.parse(o.args);n.push({type:"web_search_preview",search_context_size:i.searchContextSize,user_location:i.userLocation});break}case"openai.code_interpreter":{const i=BI.parse(o.args);n.push({type:"code_interpreter",container:i.container==null?{type:"auto",file_ids:void 0}:typeof i.container=="string"?i.container:{type:"auto",file_ids:i.container.fileIds}});break}default:{a.push({type:"unsupported-tool",tool:o});break}}break}default:a.push({type:"unsupported-tool",tool:o});break}if(e==null)return{tools:n,toolChoice:void 0,toolWarnings:a};const s=e.type;switch(s){case"auto":case"none":case"required":return{tools:n,toolChoice:s,toolWarnings:a};case"tool":return{tools:n,toolChoice:e.toolName==="code_interpreter"||e.toolName==="file_search"||e.toolName==="web_search_preview"?{type:e.toolName}:{type:"function",name:e.toolName},toolWarnings:a};default:{const o=s;throw new Nt({functionality:`tool choice type: ${o}`})}}}var df=20,pf=Y(P({token:x(),logprob:U(),top_logprobs:Y(P({token:x(),logprob:U()}))})),QI=class{constructor(t,e){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=t,this.config=e}get provider(){return this.config.provider}async getArgs({maxOutputTokens:t,temperature:e,stopSequences:r,topP:a,topK:n,presencePenalty:s,frequencyPenalty:o,seed:i,prompt:l,providerOptions:u,tools:d,toolChoice:h,responseFormat:g}){var c,p;const f=[],m=_T(this.modelId);n!=null&&f.push({type:"unsupported-setting",setting:"topK"}),i!=null&&f.push({type:"unsupported-setting",setting:"seed"}),s!=null&&f.push({type:"unsupported-setting",setting:"presencePenalty"}),o!=null&&f.push({type:"unsupported-setting",setting:"frequencyPenalty"}),r!=null&&f.push({type:"unsupported-setting",setting:"stopSequences"});const{messages:v,warnings:w}=await WI({prompt:l,systemMessageMode:m.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes});f.push(...w);const y=await lr({provider:"openai",providerOptions:u,schema:wT}),_=(c=y==null?void 0:y.strictJsonSchema)!=null?c:!1,E=typeof(y==null?void 0:y.logprobs)=="number"?y==null?void 0:y.logprobs:(y==null?void 0:y.logprobs)===!0?df:void 0,I=E?Array.isArray(y==null?void 0:y.include)?[...y==null?void 0:y.include,"message.output_text.logprobs"]:["message.output_text.logprobs"]:y==null?void 0:y.include,S={model:this.modelId,input:v,temperature:e,top_p:a,max_output_tokens:t,...((g==null?void 0:g.type)==="json"||(y==null?void 0:y.textVerbosity))&&{text:{...(g==null?void 0:g.type)==="json"&&{format:g.schema!=null?{type:"json_schema",strict:_,name:(p=g.name)!=null?p:"response",description:g.description,schema:g.schema}:{type:"json_object"}},...(y==null?void 0:y.textVerbosity)&&{verbosity:y.textVerbosity}}},metadata:y==null?void 0:y.metadata,parallel_tool_calls:y==null?void 0:y.parallelToolCalls,previous_response_id:y==null?void 0:y.previousResponseId,store:y==null?void 0:y.store,user:y==null?void 0:y.user,instructions:y==null?void 0:y.instructions,service_tier:y==null?void 0:y.serviceTier,include:I,prompt_cache_key:y==null?void 0:y.promptCacheKey,safety_identifier:y==null?void 0:y.safetyIdentifier,top_logprobs:E,...m.isReasoningModel&&((y==null?void 0:y.reasoningEffort)!=null||(y==null?void 0:y.reasoningSummary)!=null)&&{reasoning:{...(y==null?void 0:y.reasoningEffort)!=null&&{effort:y.reasoningEffort},...(y==null?void 0:y.reasoningSummary)!=null&&{summary:y.reasoningSummary}}},...m.requiredAutoTruncation&&{truncation:"auto"}};m.isReasoningModel?(S.temperature!=null&&(S.temperature=void 0,f.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),S.top_p!=null&&(S.top_p=void 0,f.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"}))):((y==null?void 0:y.reasoningEffort)!=null&&f.push({type:"unsupported-setting",setting:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),(y==null?void 0:y.reasoningSummary)!=null&&f.push({type:"unsupported-setting",setting:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),(y==null?void 0:y.serviceTier)==="flex"&&!m.supportsFlexProcessing&&(f.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete S.service_tier),(y==null?void 0:y.serviceTier)==="priority"&&!m.supportsPriorityProcessing&&(f.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete S.service_tier);const{tools:R,toolChoice:$,toolWarnings:z}=KI({tools:d,toolChoice:h,strictJsonSchema:_});return{args:{...S,tools:R,tool_choice:$},warnings:[...f,...z]}}async doGenerate(t){var e,r,a,n,s,o,i,l,u,d,h,g,c,p,f,m,v;const{args:w,warnings:y}=await this.getArgs(t),_=this.config.url({path:"/responses",modelId:this.modelId}),{responseHeaders:E,value:I,rawValue:S}=await Kt({url:_,headers:Ut(this.config.headers(),t.headers),body:w,failedResponseHandler:ur,successfulResponseHandler:ln(P({id:x(),created_at:U(),error:P({code:x(),message:x()}).nullish(),model:x(),output:Y(wn("type",[P({type:H("message"),role:H("assistant"),id:x(),content:Y(P({type:H("output_text"),text:x(),logprobs:pf.nullish(),annotations:Y(wn("type",[P({type:H("url_citation"),start_index:U(),end_index:U(),url:x(),title:x()}),P({type:H("file_citation"),start_index:U(),end_index:U(),file_id:x(),quote:x()})]))}))}),P({type:H("function_call"),call_id:x(),name:x(),arguments:x(),id:x()}),P({type:H("web_search_call"),id:x(),status:x().optional(),action:P({type:H("search"),query:x().optional()}).nullish()}),P({type:H("computer_call"),id:x(),status:x().optional()}),P({type:H("file_search_call"),id:x(),status:x().optional(),queries:Y(x()).nullish(),results:Y(P({attributes:P({file_id:x(),filename:x(),score:U(),text:x()})})).nullish()}),P({type:H("reasoning"),id:x(),encrypted_content:x().nullish(),summary:Y(P({type:H("summary_text"),text:x()}))})])),incomplete_details:P({reason:x()}).nullable(),usage:hf})),abortSignal:t.abortSignal,fetch:this.config.fetch});if(I.error)throw new Ue({message:I.error.message,url:_,requestBodyValues:w,statusCode:400,responseHeaders:E,responseBody:S,isRetryable:!1});const R=[],$=[];for(const L of I.output)switch(L.type){case"reasoning":{L.summary.length===0&&L.summary.push({type:"summary_text",text:""});for(const F of L.summary)R.push({type:"reasoning",text:F.text,providerMetadata:{openai:{itemId:L.id,reasoningEncryptedContent:(e=L.encrypted_content)!=null?e:null}}});break}case"message":{for(const F of L.content){(a=(r=t.providerOptions)==null?void 0:r.openai)!=null&&a.logprobs&&F.logprobs&&$.push(F.logprobs),R.push({type:"text",text:F.text,providerMetadata:{openai:{itemId:L.id}}});for(const M of F.annotations)M.type==="url_citation"?R.push({type:"source",sourceType:"url",id:(o=(s=(n=this.config).generateId)==null?void 0:s.call(n))!=null?o:Ot(),url:M.url,title:M.title}):M.type==="file_citation"&&R.push({type:"source",sourceType:"document",id:(u=(l=(i=this.config).generateId)==null?void 0:l.call(i))!=null?u:Ot(),mediaType:"text/plain",title:M.quote,filename:M.file_id})}break}case"function_call":{R.push({type:"tool-call",toolCallId:L.call_id,toolName:L.name,input:L.arguments,providerMetadata:{openai:{itemId:L.id}}});break}case"web_search_call":{R.push({type:"tool-call",toolCallId:L.id,toolName:"web_search_preview",input:(h=(d=L.action)==null?void 0:d.query)!=null?h:"",providerExecuted:!0}),R.push({type:"tool-result",toolCallId:L.id,toolName:"web_search_preview",result:{status:L.status||"completed",...((g=L.action)==null?void 0:g.query)&&{query:L.action.query}},providerExecuted:!0});break}case"computer_call":{R.push({type:"tool-call",toolCallId:L.id,toolName:"computer_use",input:"",providerExecuted:!0}),R.push({type:"tool-result",toolCallId:L.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:L.status||"completed"},providerExecuted:!0});break}case"file_search_call":{R.push({type:"tool-call",toolCallId:L.id,toolName:"file_search",input:"",providerExecuted:!0}),R.push({type:"tool-result",toolCallId:L.id,toolName:"file_search",result:{type:"file_search_tool_result",status:L.status||"completed",...L.queries&&{queries:L.queries},...L.results&&{results:L.results}},providerExecuted:!0});break}}const z={openai:{responseId:I.id}};return $.length>0&&(z.openai.logprobs=$),{content:R,finishReason:cf({finishReason:(c=I.incomplete_details)==null?void 0:c.reason,hasToolCalls:R.some(L=>L.type==="tool-call")}),usage:{inputTokens:I.usage.input_tokens,outputTokens:I.usage.output_tokens,totalTokens:I.usage.input_tokens+I.usage.output_tokens,reasoningTokens:(f=(p=I.usage.output_tokens_details)==null?void 0:p.reasoning_tokens)!=null?f:void 0,cachedInputTokens:(v=(m=I.usage.input_tokens_details)==null?void 0:m.cached_tokens)!=null?v:void 0},request:{body:w},response:{id:I.id,timestamp:new Date(I.created_at*1e3),modelId:I.model,headers:E,body:S},providerMetadata:z,warnings:y}}async doStream(t){const{args:e,warnings:r}=await this.getArgs(t),{responseHeaders:a,value:n}=await Kt({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:Ut(this.config.headers(),t.headers),body:{...e,stream:!0},failedResponseHandler:ur,successfulResponseHandler:Os(lT),abortSignal:t.abortSignal,fetch:this.config.fetch}),s=this;let o="unknown";const i={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=[];let u=null;const d={};let h=!1;const g={};return{stream:n.pipeThrough(new TransformStream({start(c){c.enqueue({type:"stream-start",warnings:r})},transform(c,p){var f,m,v,w,y,_,E,I,S,R,$,z,L,F,M,D,K,oe,ie;if(t.includeRawChunks&&p.enqueue({type:"raw",rawValue:c.rawValue}),!c.success){o="error",p.enqueue({type:"error",error:c.error});return}const C=c.value;if(mf(C))C.item.type==="function_call"?(d[C.output_index]={toolName:C.item.name,toolCallId:C.item.call_id},p.enqueue({type:"tool-input-start",id:C.item.call_id,toolName:C.item.name})):C.item.type==="web_search_call"?(d[C.output_index]={toolName:"web_search_preview",toolCallId:C.item.id},p.enqueue({type:"tool-input-start",id:C.item.id,toolName:"web_search_preview"})):C.item.type==="computer_call"?(d[C.output_index]={toolName:"computer_use",toolCallId:C.item.id},p.enqueue({type:"tool-input-start",id:C.item.id,toolName:"computer_use"})):C.item.type==="file_search_call"?(d[C.output_index]={toolName:"file_search",toolCallId:C.item.id},p.enqueue({type:"tool-input-start",id:C.item.id,toolName:"file_search"})):C.item.type==="message"?p.enqueue({type:"text-start",id:C.item.id,providerMetadata:{openai:{itemId:C.item.id}}}):fT(C)&&(g[C.item.id]={encryptedContent:C.item.encrypted_content,summaryParts:[0]},p.enqueue({type:"reasoning-start",id:`${C.item.id}:0`,providerMetadata:{openai:{itemId:C.item.id,reasoningEncryptedContent:(f=C.item.encrypted_content)!=null?f:null}}}));else if(ff(C)){if(C.item.type==="function_call")d[C.output_index]=void 0,h=!0,p.enqueue({type:"tool-input-end",id:C.item.call_id}),p.enqueue({type:"tool-call",toolCallId:C.item.call_id,toolName:C.item.name,input:C.item.arguments,providerMetadata:{openai:{itemId:C.item.id}}});else if(C.item.type==="web_search_call")d[C.output_index]=void 0,h=!0,p.enqueue({type:"tool-input-end",id:C.item.id}),p.enqueue({type:"tool-call",toolCallId:C.item.id,toolName:"web_search_preview",input:(v=(m=C.item.action)==null?void 0:m.query)!=null?v:"",providerExecuted:!0}),p.enqueue({type:"tool-result",toolCallId:C.item.id,toolName:"web_search_preview",result:{type:"web_search_tool_result",status:C.item.status||"completed",...((w=C.item.action)==null?void 0:w.query)&&{query:C.item.action.query}},providerExecuted:!0});else if(C.item.type==="computer_call")d[C.output_index]=void 0,h=!0,p.enqueue({type:"tool-input-end",id:C.item.id}),p.enqueue({type:"tool-call",toolCallId:C.item.id,toolName:"computer_use",input:"",providerExecuted:!0}),p.enqueue({type:"tool-result",toolCallId:C.item.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:C.item.status||"completed"},providerExecuted:!0});else if(C.item.type==="file_search_call")d[C.output_index]=void 0,h=!0,p.enqueue({type:"tool-input-end",id:C.item.id}),p.enqueue({type:"tool-call",toolCallId:C.item.id,toolName:"file_search",input:"",providerExecuted:!0}),p.enqueue({type:"tool-result",toolCallId:C.item.id,toolName:"file_search",result:{type:"file_search_tool_result",status:C.item.status||"completed",...C.item.queries&&{queries:C.item.queries},...C.item.results&&{results:C.item.results}},providerExecuted:!0});else if(C.item.type==="message")p.enqueue({type:"text-end",id:C.item.id});else if(cT(C)){const re=g[C.item.id];for(const B of re.summaryParts)p.enqueue({type:"reasoning-end",id:`${C.item.id}:${B}`,providerMetadata:{openai:{itemId:C.item.id,reasoningEncryptedContent:(y=C.item.encrypted_content)!=null?y:null}}});delete g[C.item.id]}}else if(hT(C)){const re=d[C.output_index];re!=null&&p.enqueue({type:"tool-input-delta",id:re.toolCallId,delta:C.delta})}else pT(C)?(u=C.response.id,p.enqueue({type:"response-metadata",id:C.response.id,timestamp:new Date(C.response.created_at*1e3),modelId:C.response.model})):uT(C)?(p.enqueue({type:"text-delta",id:C.item_id,delta:C.delta}),C.logprobs&&l.push(C.logprobs)):vT(C)?C.summary_index>0&&((_=g[C.item_id])==null||_.summaryParts.push(C.summary_index),p.enqueue({type:"reasoning-start",id:`${C.item_id}:${C.summary_index}`,providerMetadata:{openai:{itemId:C.item_id,reasoningEncryptedContent:(I=(E=g[C.item_id])==null?void 0:E.encryptedContent)!=null?I:null}}})):gT(C)?p.enqueue({type:"reasoning-delta",id:`${C.item_id}:${C.summary_index}`,delta:C.delta,providerMetadata:{openai:{itemId:C.item_id}}}):dT(C)?(o=cf({finishReason:(S=C.response.incomplete_details)==null?void 0:S.reason,hasToolCalls:h}),i.inputTokens=C.response.usage.input_tokens,i.outputTokens=C.response.usage.output_tokens,i.totalTokens=C.response.usage.input_tokens+C.response.usage.output_tokens,i.reasoningTokens=($=(R=C.response.usage.output_tokens_details)==null?void 0:R.reasoning_tokens)!=null?$:void 0,i.cachedInputTokens=(L=(z=C.response.usage.input_tokens_details)==null?void 0:z.cached_tokens)!=null?L:void 0):mT(C)?C.annotation.type==="url_citation"?p.enqueue({type:"source",sourceType:"url",id:(D=(M=(F=s.config).generateId)==null?void 0:M.call(F))!=null?D:Ot(),url:C.annotation.url,title:C.annotation.title}):C.annotation.type==="file_citation"&&p.enqueue({type:"source",sourceType:"document",id:(ie=(oe=(K=s.config).generateId)==null?void 0:oe.call(K))!=null?ie:Ot(),mediaType:"text/plain",title:C.annotation.quote,filename:C.annotation.file_id}):yT(C)&&p.enqueue({type:"error",error:C})},flush(c){const p={openai:{responseId:u}};l.length>0&&(p.openai.logprobs=l),c.enqueue({type:"finish",finishReason:o,usage:i,providerMetadata:p})}})),request:{body:e},response:{headers:a}}}},hf=P({input_tokens:U(),input_tokens_details:P({cached_tokens:U().nullish()}).nullish(),output_tokens:U(),output_tokens_details:P({reasoning_tokens:U().nullish()}).nullish()}),YI=P({type:H("response.output_text.delta"),item_id:x(),delta:x(),logprobs:pf.nullish()}),XI=P({type:H("error"),code:x(),message:x(),param:x().nullish(),sequence_number:U()}),eT=P({type:vt(["response.completed","response.incomplete"]),response:P({incomplete_details:P({reason:x()}).nullish(),usage:hf})}),tT=P({type:H("response.created"),response:P({id:x(),created_at:U(),model:x()})}),rT=P({type:H("response.output_item.added"),output_index:U(),item:wn("type",[P({type:H("message"),id:x()}),P({type:H("reasoning"),id:x(),encrypted_content:x().nullish()}),P({type:H("function_call"),id:x(),call_id:x(),name:x(),arguments:x()}),P({type:H("web_search_call"),id:x(),status:x(),action:P({type:H("search"),query:x().optional()}).nullish()}),P({type:H("computer_call"),id:x(),status:x()}),P({type:H("file_search_call"),id:x(),status:x(),queries:Y(x()).nullish(),results:Y(P({attributes:P({file_id:x(),filename:x(),score:U(),text:x()})})).optional()})])}),nT=P({type:H("response.output_item.done"),output_index:U(),item:wn("type",[P({type:H("message"),id:x()}),P({type:H("reasoning"),id:x(),encrypted_content:x().nullish()}),P({type:H("function_call"),id:x(),call_id:x(),name:x(),arguments:x(),status:H("completed")}),P({type:H("web_search_call"),id:x(),status:H("completed"),action:P({type:H("search"),query:x().optional()}).nullish()}),P({type:H("computer_call"),id:x(),status:H("completed")}),P({type:H("file_search_call"),id:x(),status:H("completed"),queries:Y(x()).nullish(),results:Y(P({attributes:P({file_id:x(),filename:x(),score:U(),text:x()})})).nullish()})])}),aT=P({type:H("response.function_call_arguments.delta"),item_id:x(),output_index:U(),delta:x()}),sT=P({type:H("response.output_text.annotation.added"),annotation:wn("type",[P({type:H("url_citation"),url:x(),title:x()}),P({type:H("file_citation"),file_id:x(),quote:x()})])}),oT=P({type:H("response.reasoning_summary_part.added"),item_id:x(),summary_index:U()}),iT=P({type:H("response.reasoning_summary_text.delta"),item_id:x(),summary_index:U(),delta:x()}),lT=Ae([YI,eT,tT,rT,nT,aT,sT,oT,iT,XI,P({type:x()}).loose()]);function uT(t){return t.type==="response.output_text.delta"}function ff(t){return t.type==="response.output_item.done"}function cT(t){return ff(t)&&t.item.type==="reasoning"}function dT(t){return t.type==="response.completed"||t.type==="response.incomplete"}function pT(t){return t.type==="response.created"}function hT(t){return t.type==="response.function_call_arguments.delta"}function mf(t){return t.type==="response.output_item.added"}function fT(t){return mf(t)&&t.item.type==="reasoning"}function mT(t){return t.type==="response.output_text.annotation.added"}function vT(t){return t.type==="response.reasoning_summary_part.added"}function gT(t){return t.type==="response.reasoning_summary_text.delta"}function yT(t){return t.type==="error"}function _T(t){const e=t.startsWith("o3")||t.startsWith("o4-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat"),r=t.startsWith("gpt-4")||t.startsWith("gpt-5-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-nano")&&!t.startsWith("gpt-5-chat")||t.startsWith("o3")||t.startsWith("o4-mini"),a={requiredAutoTruncation:!1,systemMessageMode:"system",supportsFlexProcessing:e,supportsPriorityProcessing:r};return t.startsWith("gpt-5-chat")?{...a,isReasoningModel:!1}:t.startsWith("o")||t.startsWith("gpt-5")||t.startsWith("codex-")||t.startsWith("computer-use")?t.startsWith("o1-mini")||t.startsWith("o1-preview")?{...a,isReasoningModel:!0,systemMessageMode:"remove"}:{...a,isReasoningModel:!0,systemMessageMode:"developer"}:{...a,isReasoningModel:!1}}var wT=P({metadata:Mt().nullish(),parallelToolCalls:nt().nullish(),previousResponseId:x().nullish(),store:nt().nullish(),user:x().nullish(),reasoningEffort:x().nullish(),strictJsonSchema:nt().nullish(),instructions:x().nullish(),reasoningSummary:x().nullish(),serviceTier:vt(["auto","flex","priority"]).nullish(),include:Y(vt(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),textVerbosity:vt(["low","medium","high"]).nullish(),promptCacheKey:x().nullish(),safetyIdentifier:x().nullish(),logprobs:Ae([nt(),U().min(1).max(df)]).optional()}),bT=P({instructions:x().nullish(),speed:U().min(.25).max(4).default(1).nullish()}),xT=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({text:t,voice:e="alloy",outputFormat:r="mp3",speed:a,instructions:n,language:s,providerOptions:o}){const i=[],l=await lr({provider:"openai",providerOptions:o,schema:bT}),u={model:this.modelId,input:t,voice:e,response_format:"mp3",speed:a,instructions:n};if(r&&(["mp3","opus","aac","flac","wav","pcm"].includes(r)?u.response_format=r:i.push({type:"unsupported-setting",setting:"outputFormat",details:`Unsupported output format: ${r}. Using mp3 instead.`})),l){const d={};for(const h in d){const g=d[h];g!==void 0&&(u[h]=g)}}return s&&i.push({type:"unsupported-setting",setting:"language",details:`OpenAI speech models do not support language selection. Language parameter "${s}" was ignored.`}),{requestBody:u,warnings:i}}async doGenerate(t){var e,r,a;const n=(a=(r=(e=this.config._internal)==null?void 0:e.currentDate)==null?void 0:r.call(e))!=null?a:new Date,{requestBody:s,warnings:o}=await this.getArgs(t),{value:i,responseHeaders:l,rawValue:u}=await Kt({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:Ut(this.config.headers(),t.headers),body:s,failedResponseHandler:ur,successfulResponseHandler:vI(),abortSignal:t.abortSignal,fetch:this.config.fetch});return{audio:i,warnings:o,request:{body:JSON.stringify(s)},response:{timestamp:n,modelId:this.modelId,headers:l,body:u}}}},ET=P({include:Y(x()).optional(),language:x().optional(),prompt:x().optional(),temperature:U().min(0).max(1).default(0).optional(),timestampGranularities:Y(vt(["word","segment"])).default(["segment"]).optional()}),vf={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"},ST=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({audio:t,mediaType:e,providerOptions:r}){const a=[],n=await lr({provider:"openai",providerOptions:r,schema:ET}),s=new FormData,o=t instanceof Uint8Array?new Blob([t]):new Blob([_I(t)]);if(s.append("model",this.modelId),s.append("file",new File([o],"audio",{type:e})),n){const i={include:n.include,language:n.language,prompt:n.prompt,response_format:"verbose_json",temperature:n.temperature,timestamp_granularities:n.timestampGranularities};for(const[l,u]of Object.entries(i))u!=null&&s.append(l,String(u))}return{formData:s,warnings:a}}async doGenerate(t){var e,r,a,n,s,o,i,l;const u=(a=(r=(e=this.config._internal)==null?void 0:e.currentDate)==null?void 0:r.call(e))!=null?a:new Date,{formData:d,warnings:h}=await this.getArgs(t),{value:g,responseHeaders:c,rawValue:p}=await mI({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:Ut(this.config.headers(),t.headers),formData:d,failedResponseHandler:ur,successfulResponseHandler:ln(IT),abortSignal:t.abortSignal,fetch:this.config.fetch}),f=g.language!=null&&g.language in vf?vf[g.language]:void 0;return{text:g.text,segments:(i=(o=(n=g.segments)==null?void 0:n.map(m=>({text:m.text,startSecond:m.start,endSecond:m.end})))!=null?o:(s=g.words)==null?void 0:s.map(m=>({text:m.word,startSecond:m.start,endSecond:m.end})))!=null?i:[],language:f,durationInSeconds:(l=g.duration)!=null?l:void 0,warnings:h,response:{timestamp:u,modelId:this.modelId,headers:c,body:p}}}},IT=P({text:x(),language:x().nullish(),duration:U().nullish(),words:Y(P({word:x(),start:U(),end:U()})).nullish(),segments:Y(P({id:U(),seek:U(),start:U(),end:U(),text:x(),tokens:Y(U()),temperature:U(),avg_logprob:U(),compression_ratio:U(),no_speech_prob:U()})).nullish()});function gf(t={}){var e,r;const a=(e=Gh(t.baseURL))!=null?e:"https://api.openai.com/v1",n=(r=t.name)!=null?r:"openai",s=()=>({Authorization:`Bearer ${Bh({apiKey:t.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":t.organization,"OpenAI-Project":t.project,...t.headers}),o=f=>new kI(f,{provider:`${n}.chat`,url:({path:m})=>`${a}${m}`,headers:s,fetch:t.fetch}),i=f=>new MI(f,{provider:`${n}.completion`,url:({path:m})=>`${a}${m}`,headers:s,fetch:t.fetch}),l=f=>new zI(f,{provider:`${n}.embedding`,url:({path:m})=>`${a}${m}`,headers:s,fetch:t.fetch}),u=f=>new ZI(f,{provider:`${n}.image`,url:({path:m})=>`${a}${m}`,headers:s,fetch:t.fetch}),d=f=>new ST(f,{provider:`${n}.transcription`,url:({path:m})=>`${a}${m}`,headers:s,fetch:t.fetch}),h=f=>new xT(f,{provider:`${n}.speech`,url:({path:m})=>`${a}${m}`,headers:s,fetch:t.fetch}),g=f=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return c(f)},c=f=>new QI(f,{provider:`${n}.responses`,url:({path:m})=>`${a}${m}`,headers:s,fetch:t.fetch,fileIdPrefixes:["file-"]}),p=function(f){return g(f)};return p.languageModel=g,p.chat=o,p.completion=i,p.responses=c,p.embedding=l,p.textEmbedding=l,p.textEmbeddingModel=l,p.image=u,p.imageModel=u,p.transcription=d,p.transcriptionModel=d,p.speech=h,p.speechModel=h,p.tools=JI,p}gf();function wa(t){var e,r;return(r=(e=t==null?void 0:t.providerOptions)==null?void 0:e.openaiCompatible)!=null?r:{}}function TT(t){const e=[];for(const{role:r,content:a,...n}of t){const s=wa({...n});switch(r){case"system":{e.push({role:"system",content:a,...s});break}case"user":{if(a.length===1&&a[0].type==="text"){e.push({role:"user",content:a[0].text,...wa(a[0])});break}e.push({role:"user",content:a.map(o=>{const i=wa(o);switch(o.type){case"text":return{type:"text",text:o.text,...i};case"file":if(o.mediaType.startsWith("image/")){const l=o.mediaType==="image/*"?"image/jpeg":o.mediaType;return{type:"image_url",image_url:{url:o.data instanceof URL?o.data.toString():`data:${l};base64,${un(o.data)}`},...i}}else throw new Nt({functionality:`file part media type ${o.mediaType}`})}}),...s});break}case"assistant":{let o="";const i=[];for(const l of a){const u=wa(l);switch(l.type){case"text":{o+=l.text;break}case"tool-call":{i.push({id:l.toolCallId,type:"function",function:{name:l.toolName,arguments:JSON.stringify(l.input)},...u});break}}}e.push({role:"assistant",content:o,tool_calls:i.length>0?i:void 0,...s});break}case"tool":{for(const o of a){const i=o.output;let l;switch(i.type){case"text":case"error-text":l=i.value;break;case"content":case"json":case"error-json":l=JSON.stringify(i.value);break}const u=wa(o);e.push({role:"tool",tool_call_id:o.toolCallId,content:l,...u})}break}default:{const o=r;throw new Error(`Unsupported role: ${o}`)}}}return e}function yf({id:t,model:e,created:r}){return{id:t??void 0,modelId:e??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function _f(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var wf=P({user:x().optional(),reasoningEffort:x().optional()}),kT=P({error:P({message:x(),type:x().nullish(),param:Mt().nullish(),code:Ae([x(),U()]).nullish()})}),PT={errorSchema:kT,errorToMessage:t=>t.error.message};function CT({tools:t,toolChoice:e}){t=t!=null&&t.length?t:void 0;const r=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};const a=[];for(const s of t)s.type==="provider-defined"?r.push({type:"unsupported-tool",tool:s}):a.push({type:"function",function:{name:s.name,description:s.description,parameters:s.inputSchema}});if(e==null)return{tools:a,toolChoice:void 0,toolWarnings:r};const n=e.type;switch(n){case"auto":case"none":case"required":return{tools:a,toolChoice:n,toolWarnings:r};case"tool":return{tools:a,toolChoice:{type:"function",function:{name:e.toolName}},toolWarnings:r};default:{const s=n;throw new Nt({functionality:`tool choice type: ${s}`})}}}var RT=class{constructor(t,e){this.specificationVersion="v2";var r,a;this.modelId=t,this.config=e;const n=(r=e.errorStructure)!=null?r:PT;this.chunkSchema=$T(n.errorSchema),this.failedResponseHandler=Wh(n),this.supportsStructuredOutputs=(a=e.supportsStructuredOutputs)!=null?a:!1}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var t,e,r;return(r=(e=(t=this.config).supportedUrls)==null?void 0:e.call(t))!=null?r:{}}async getArgs({prompt:t,maxOutputTokens:e,temperature:r,topP:a,topK:n,frequencyPenalty:s,presencePenalty:o,providerOptions:i,stopSequences:l,responseFormat:u,seed:d,toolChoice:h,tools:g}){var c,p,f;const m=[],v=Object.assign((c=await lr({provider:"openai-compatible",providerOptions:i,schema:wf}))!=null?c:{},(p=await lr({provider:this.providerOptionsName,providerOptions:i,schema:wf}))!=null?p:{});n!=null&&m.push({type:"unsupported-setting",setting:"topK"}),(u==null?void 0:u.type)==="json"&&u.schema!=null&&!this.supportsStructuredOutputs&&m.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:w,toolChoice:y,toolWarnings:_}=CT({tools:g,toolChoice:h});return{args:{model:this.modelId,user:v.user,max_tokens:e,temperature:r,top_p:a,frequency_penalty:s,presence_penalty:o,response_format:(u==null?void 0:u.type)==="json"?this.supportsStructuredOutputs===!0&&u.schema!=null?{type:"json_schema",json_schema:{schema:u.schema,name:(f=u.name)!=null?f:"response",description:u.description}}:{type:"json_object"}:void 0,stop:l,seed:d,...i==null?void 0:i[this.providerOptionsName],reasoning_effort:v.reasoningEffort,messages:TT(t),tools:w,tool_choice:y},warnings:[...m,..._]}}async doGenerate(t){var e,r,a,n,s,o,i,l,u,d,h,g,c,p,f,m,v;const{args:w,warnings:y}=await this.getArgs({...t}),_=JSON.stringify(w),{responseHeaders:E,value:I,rawValue:S}=await Kt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Ut(this.config.headers(),t.headers),body:w,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:ln(OT),abortSignal:t.abortSignal,fetch:this.config.fetch}),R=I.choices[0],$=[],z=R.message.content;z!=null&&z.length>0&&$.push({type:"text",text:z});const L=(e=R.message.reasoning_content)!=null?e:R.message.reasoning;if(L!=null&&L.length>0&&$.push({type:"reasoning",text:L}),R.message.tool_calls!=null)for(const D of R.message.tool_calls)$.push({type:"tool-call",toolCallId:(r=D.id)!=null?r:Ot(),toolName:D.function.name,input:D.function.arguments});const F={[this.providerOptionsName]:{},...await((n=(a=this.config.metadataExtractor)==null?void 0:a.extractMetadata)==null?void 0:n.call(a,{parsedBody:S}))},M=(s=I.usage)==null?void 0:s.completion_tokens_details;return(M==null?void 0:M.accepted_prediction_tokens)!=null&&(F[this.providerOptionsName].acceptedPredictionTokens=M==null?void 0:M.accepted_prediction_tokens),(M==null?void 0:M.rejected_prediction_tokens)!=null&&(F[this.providerOptionsName].rejectedPredictionTokens=M==null?void 0:M.rejected_prediction_tokens),{content:$,finishReason:_f(R.finish_reason),usage:{inputTokens:(i=(o=I.usage)==null?void 0:o.prompt_tokens)!=null?i:void 0,outputTokens:(u=(l=I.usage)==null?void 0:l.completion_tokens)!=null?u:void 0,totalTokens:(h=(d=I.usage)==null?void 0:d.total_tokens)!=null?h:void 0,reasoningTokens:(p=(c=(g=I.usage)==null?void 0:g.completion_tokens_details)==null?void 0:c.reasoning_tokens)!=null?p:void 0,cachedInputTokens:(v=(m=(f=I.usage)==null?void 0:f.prompt_tokens_details)==null?void 0:m.cached_tokens)!=null?v:void 0},providerMetadata:F,request:{body:_},response:{...yf(I),headers:E,body:S},warnings:y}}async doStream(t){var e;const{args:r,warnings:a}=await this.getArgs({...t}),n={...r,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},s=(e=this.config.metadataExtractor)==null?void 0:e.createStreamExtractor(),{responseHeaders:o,value:i}=await Kt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Ut(this.config.headers(),t.headers),body:n,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:Os(this.chunkSchema),abortSignal:t.abortSignal,fetch:this.config.fetch}),l=[];let u="unknown";const d={completionTokens:void 0,completionTokensDetails:{reasoningTokens:void 0,acceptedPredictionTokens:void 0,rejectedPredictionTokens:void 0},promptTokens:void 0,promptTokensDetails:{cachedTokens:void 0},totalTokens:void 0};let h=!0;const g=this.providerOptionsName;let c=!1,p=!1;return{stream:i.pipeThrough(new TransformStream({start(f){f.enqueue({type:"stream-start",warnings:a})},transform(f,m){var v,w,y,_,E,I,S,R,$,z,L,F,M;if(t.includeRawChunks&&m.enqueue({type:"raw",rawValue:f.rawValue}),!f.success){u="error",m.enqueue({type:"error",error:f.error});return}const D=f.value;if(s==null||s.processChunk(f.rawValue),"error"in D){u="error",m.enqueue({type:"error",error:D.error.message});return}if(h&&(h=!1,m.enqueue({type:"response-metadata",...yf(D)})),D.usage!=null){const{prompt_tokens:C,completion_tokens:re,total_tokens:B,prompt_tokens_details:de,completion_tokens_details:ae}=D.usage;d.promptTokens=C??void 0,d.completionTokens=re??void 0,d.totalTokens=B??void 0,(ae==null?void 0:ae.reasoning_tokens)!=null&&(d.completionTokensDetails.reasoningTokens=ae==null?void 0:ae.reasoning_tokens),(ae==null?void 0:ae.accepted_prediction_tokens)!=null&&(d.completionTokensDetails.acceptedPredictionTokens=ae==null?void 0:ae.accepted_prediction_tokens),(ae==null?void 0:ae.rejected_prediction_tokens)!=null&&(d.completionTokensDetails.rejectedPredictionTokens=ae==null?void 0:ae.rejected_prediction_tokens),(de==null?void 0:de.cached_tokens)!=null&&(d.promptTokensDetails.cachedTokens=de==null?void 0:de.cached_tokens)}const K=D.choices[0];if((K==null?void 0:K.finish_reason)!=null&&(u=_f(K.finish_reason)),(K==null?void 0:K.delta)==null)return;const oe=K.delta,ie=(v=oe.reasoning_content)!=null?v:oe.reasoning;if(ie&&(c||(m.enqueue({type:"reasoning-start",id:"reasoning-0"}),c=!0),m.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:ie})),oe.content&&(p||(m.enqueue({type:"text-start",id:"txt-0"}),p=!0),m.enqueue({type:"text-delta",id:"txt-0",delta:oe.content})),oe.tool_calls!=null)for(const C of oe.tool_calls){const re=C.index;if(l[re]==null){if(C.id==null)throw new Zn({data:C,message:"Expected 'id' to be a string."});if(((w=C.function)==null?void 0:w.name)==null)throw new Zn({data:C,message:"Expected 'function.name' to be a string."});m.enqueue({type:"tool-input-start",id:C.id,toolName:C.function.name}),l[re]={id:C.id,type:"function",function:{name:C.function.name,arguments:(y=C.function.arguments)!=null?y:""},hasFinished:!1};const de=l[re];((_=de.function)==null?void 0:_.name)!=null&&((E=de.function)==null?void 0:E.arguments)!=null&&(de.function.arguments.length>0&&m.enqueue({type:"tool-input-start",id:de.id,toolName:de.function.name}),Rs(de.function.arguments)&&(m.enqueue({type:"tool-input-end",id:de.id}),m.enqueue({type:"tool-call",toolCallId:(I=de.id)!=null?I:Ot(),toolName:de.function.name,input:de.function.arguments}),de.hasFinished=!0));continue}const B=l[re];B.hasFinished||(((S=C.function)==null?void 0:S.arguments)!=null&&(B.function.arguments+=($=(R=C.function)==null?void 0:R.arguments)!=null?$:""),m.enqueue({type:"tool-input-delta",id:B.id,delta:(z=C.function.arguments)!=null?z:""}),((L=B.function)==null?void 0:L.name)!=null&&((F=B.function)==null?void 0:F.arguments)!=null&&Rs(B.function.arguments)&&(m.enqueue({type:"tool-input-end",id:B.id}),m.enqueue({type:"tool-call",toolCallId:(M=B.id)!=null?M:Ot(),toolName:B.function.name,input:B.function.arguments}),B.hasFinished=!0))}},flush(f){var m,v,w,y,_,E;c&&f.enqueue({type:"reasoning-end",id:"reasoning-0"}),p&&f.enqueue({type:"text-end",id:"txt-0"});for(const S of l.filter(R=>!R.hasFinished))f.enqueue({type:"tool-input-end",id:S.id}),f.enqueue({type:"tool-call",toolCallId:(m=S.id)!=null?m:Ot(),toolName:S.function.name,input:S.function.arguments});const I={[g]:{},...s==null?void 0:s.buildMetadata()};d.completionTokensDetails.acceptedPredictionTokens!=null&&(I[g].acceptedPredictionTokens=d.completionTokensDetails.acceptedPredictionTokens),d.completionTokensDetails.rejectedPredictionTokens!=null&&(I[g].rejectedPredictionTokens=d.completionTokensDetails.rejectedPredictionTokens),f.enqueue({type:"finish",finishReason:u,usage:{inputTokens:(v=d.promptTokens)!=null?v:void 0,outputTokens:(w=d.completionTokens)!=null?w:void 0,totalTokens:(y=d.totalTokens)!=null?y:void 0,reasoningTokens:(_=d.completionTokensDetails.reasoningTokens)!=null?_:void 0,cachedInputTokens:(E=d.promptTokensDetails.cachedTokens)!=null?E:void 0},providerMetadata:I})}})),request:{body:n},response:{headers:o}}}},bf=P({prompt_tokens:U().nullish(),completion_tokens:U().nullish(),total_tokens:U().nullish(),prompt_tokens_details:P({cached_tokens:U().nullish()}).nullish(),completion_tokens_details:P({reasoning_tokens:U().nullish(),accepted_prediction_tokens:U().nullish(),rejected_prediction_tokens:U().nullish()}).nullish()}).nullish(),OT=P({id:x().nullish(),created:U().nullish(),model:x().nullish(),choices:Y(P({message:P({role:H("assistant").nullish(),content:x().nullish(),reasoning_content:x().nullish(),reasoning:x().nullish(),tool_calls:Y(P({id:x().nullish(),function:P({name:x(),arguments:x()})})).nullish()}),finish_reason:x().nullish()})),usage:bf}),$T=t=>Ae([P({id:x().nullish(),created:U().nullish(),model:x().nullish(),choices:Y(P({delta:P({role:vt(["assistant"]).nullish(),content:x().nullish(),reasoning_content:x().nullish(),reasoning:x().nullish(),tool_calls:Y(P({index:U(),id:x().nullish(),function:P({name:x().nullish(),arguments:x().nullish()})})).nullish()}).nullish(),finish_reason:x().nullish()})),usage:bf}),t]);P({echo:nt().optional(),logitBias:St(x(),U()).optional(),suffix:x().optional(),user:x().optional()});var AT=P({prompt_tokens:U(),completion_tokens:U(),total_tokens:U()});P({id:x().nullish(),created:U().nullish(),model:x().nullish(),choices:Y(P({text:x(),finish_reason:x()})),usage:AT.nullish()}),P({dimensions:U().optional(),user:x().optional()}),P({data:Y(P({embedding:Y(U())})),usage:P({prompt_tokens:U()}).nullish(),providerMetadata:St(x(),St(x(),Mt())).optional()}),P({data:Y(P({b64_json:x()}))});var xf=t=>{var e,r;return t==null?void 0:{deepseek:{promptCacheHitTokens:(e=t.prompt_cache_hit_tokens)!=null?e:NaN,promptCacheMissTokens:(r=t.prompt_cache_miss_tokens)!=null?r:NaN}}},NT={extractMetadata:async({parsedBody:t})=>{const e=await _a({value:t,schema:MT});return!e.success||e.value.usage==null?void 0:xf(e.value.usage)},createStreamExtractor:()=>{let t;return{processChunk:async e=>{var r,a;const n=await _a({value:e,schema:DT});n.success&&((a=(r=n.value.choices)==null?void 0:r[0])==null?void 0:a.finish_reason)==="stop"&&n.value.usage&&(t=n.value.usage)},buildMetadata:()=>xf(t)}}},Ef=P({prompt_cache_hit_tokens:U().nullish(),prompt_cache_miss_tokens:U().nullish()}),MT=P({usage:Ef.nullish()}),DT=P({choices:Y(P({finish_reason:x().nullish()})).nullish(),usage:Ef.nullish()});function Sf(t={}){var e;const r=Gh((e=t.baseURL)!=null?e:"https://api.deepseek.com/v1"),a=()=>({Authorization:`Bearer ${Bh({apiKey:t.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...t.headers}),n=o=>new RT(o,{provider:"deepseek.chat",url:({path:i})=>`${r}${i}`,headers:a,fetch:t.fetch,metadataExtractor:NT}),s=o=>n(o);return s.languageModel=n,s.chat=n,s.textEmbeddingModel=o=>{throw new go({modelId:o,modelType:"textEmbeddingModel"})},s.imageModel=o=>{throw new go({modelId:o,modelType:"imageModel"})},s}Sf();const jT=(t,e,r)=>{if(r.endsWith("content"))chrome.tabs.query({},a=>{a.forEach(n=>{chrome.tabs.sendMessage(n.id,{type:t,data:e,direction:r,tabId:n.id})})});else return chrome.runtime.sendMessage({direction:r,type:t,data:e})},LT=(t,e,r,a)=>{const n=(s,o,i)=>{if(s.type===t&&s.direction===r){const{data:l}=s;e(l,o,i),i(o)}};return chrome.runtime.onMessage.addListener(n),()=>chrome.runtime.onMessage.removeListener(n)};class zT{constructor(e){this._isStarted=!1,this._isClosed=!1,this.targetSessionId=e,this._messageListener=LT("mcp-server-to-client",r=>{var a;try{if(r.sessionId!==this.targetSessionId)return;const n=sn.parse(r.mcpMessage);(a=this.onmessage)==null||a.call(this,n)}catch(n){console.log("【Client Transport】处理server消息错误:",n)}},"content->side")}_throwError(e,r){if(e()){const a=new Error(r);throw console.log(r,a),this.onerror&&this.onerror(a),a}}async start(){this._throwError(()=>this._isClosed,"【Client Transport】 未启动,无法重新启动"),this._isStarted=!0}async send(e,r){this._throwError(()=>!this._isStarted,"【Client Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Client Transport】 已关闭,无法发送消息");const a=chrome.sessionRegistry.get(this.targetSessionId);this._throwError(()=>!a,`【Client Transport】sessionRegistry中未找到${this.targetSessionId}`);const n=a.tabIds[a.tabIds.length-1];jT("mcp-client-to-server",{sessionId:this.targetSessionId,tabId:n,mcpMessage:e},"side->content")}async close(){if(!this._isClosed)try{this._isClosed=!0,this._isStarted=!1,this._messageListener&&this._messageListener(),this.onclose&&this.onclose()}catch{this._throwError(()=>!0,"【Client Transport】 关闭时发生错误")}}}const UT=6e4;class FT{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this.setNotificationHandler(Ii,r=>{const a=this._requestHandlerAbortControllers.get(r.params.requestId);a==null||a.abort(r.params.reason)}),this.setNotificationHandler(ki,r=>{this._onprogress(r)}),this.setRequestHandler(Ti,r=>({}))}_setupTimeout(e,r,a,n,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,r),startTime:Date.now(),timeout:r,maxTotalTimeout:a,resetTimeoutOnProgress:s,onTimeout:n})}_resetTimeout(e){const r=this._timeoutInfo.get(e);if(!r)return!1;const a=Date.now()-r.startTime;if(r.maxTotalTimeout&&a>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),new Nr(ir.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:a});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){const r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var r,a,n;this._transport=e;const s=(r=this.transport)===null||r===void 0?void 0:r.onclose;this._transport.onclose=()=>{s==null||s(),this._onclose()};const o=(a=this.transport)===null||a===void 0?void 0:a.onerror;this._transport.onerror=l=>{o==null||o(l),this._onerror(l)};const i=(n=this._transport)===null||n===void 0?void 0:n.onmessage;this._transport.onmessage=(l,u)=>{i==null||i(l,u),Si(l)||UE(l)?this._onresponse(l):oh(l)?this._onrequest(l,u):zE(l)?this._onnotification(l):this._onerror(new Error(`Unknown message type: ${JSON.stringify(l)}`))},await this._transport.start()}_onclose(){var e;const r=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._transport=void 0,(e=this.onclose)===null||e===void 0||e.call(this);const a=new Nr(ir.ConnectionClosed,"Connection closed");for(const n of r.values())n(a)}_onerror(e){var r;(r=this.onerror)===null||r===void 0||r.call(this,e)}_onnotification(e){var r;const a=(r=this._notificationHandlers.get(e.method))!==null&&r!==void 0?r:this.fallbackNotificationHandler;a!==void 0&&Promise.resolve().then(()=>a(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){var a,n,s,o;const i=(a=this._requestHandlers.get(e.method))!==null&&a!==void 0?a:this.fallbackRequestHandler;if(i===void 0){(n=this._transport)===null||n===void 0||n.send({jsonrpc:"2.0",id:e.id,error:{code:ir.MethodNotFound,message:"Method not found"}}).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}const l=new AbortController;this._requestHandlerAbortControllers.set(e.id,l);const u={signal:l.signal,sessionId:(s=this._transport)===null||s===void 0?void 0:s.sessionId,_meta:(o=e.params)===null||o===void 0?void 0:o._meta,sendNotification:d=>this.notification(d,{relatedRequestId:e.id}),sendRequest:(d,h,g)=>this.request(d,h,{...g,relatedRequestId:e.id}),authInfo:r==null?void 0:r.authInfo,requestId:e.id,requestInfo:r==null?void 0:r.requestInfo};Promise.resolve().then(()=>i(e,u)).then(d=>{var h;if(!l.signal.aborted)return(h=this._transport)===null||h===void 0?void 0:h.send({result:d,jsonrpc:"2.0",id:e.id})},d=>{var h,g;if(!l.signal.aborted)return(h=this._transport)===null||h===void 0?void 0:h.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(d.code)?d.code:ir.InternalError,message:(g=d.message)!==null&&g!==void 0?g:"Internal error"}})}).catch(d=>this._onerror(new Error(`Failed to send response: ${d}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:r,...a}=e.params,n=Number(r),s=this._progressHandlers.get(n);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}const o=this._responseHandlers.get(n),i=this._timeoutInfo.get(n);if(i&&o&&i.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(l){o(l);return}s(a)}_onresponse(e){const r=Number(e.id),a=this._responseHandlers.get(r);if(a===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}if(this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),Si(e))a(e);else{const n=new Nr(e.error.code,e.error.message,e.error.data);a(n)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)===null||e===void 0?void 0:e.close())}request(e,r,a){const{relatedRequestId:n,resumptionToken:s,onresumptiontoken:o}=a??{};return new Promise((i,l)=>{var u,d,h,g,c,p;if(!this._transport){l(new Error("Not connected"));return}((u=this._options)===null||u===void 0?void 0:u.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),(d=a==null?void 0:a.signal)===null||d===void 0||d.throwIfAborted();const f=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:f};a!=null&&a.onprogress&&(this._progressHandlers.set(f,a.onprogress),m.params={...e.params,_meta:{...((h=e.params)===null||h===void 0?void 0:h._meta)||{},progressToken:f}});const v=_=>{var E;this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),(E=this._transport)===null||E===void 0||E.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(_)}},{relatedRequestId:n,resumptionToken:s,onresumptiontoken:o}).catch(I=>this._onerror(new Error(`Failed to send cancellation: ${I}`))),l(_)};this._responseHandlers.set(f,_=>{var E;if(!(!((E=a==null?void 0:a.signal)===null||E===void 0)&&E.aborted)){if(_ instanceof Error)return l(_);try{const I=r.parse(_.result);i(I)}catch(I){l(I)}}}),(g=a==null?void 0:a.signal)===null||g===void 0||g.addEventListener("abort",()=>{var _;v((_=a==null?void 0:a.signal)===null||_===void 0?void 0:_.reason)});const w=(c=a==null?void 0:a.timeout)!==null&&c!==void 0?c:UT,y=()=>v(new Nr(ir.RequestTimeout,"Request timed out",{timeout:w}));this._setupTimeout(f,w,a==null?void 0:a.maxTotalTimeout,y,(p=a==null?void 0:a.resetTimeoutOnProgress)!==null&&p!==void 0?p:!1),this._transport.send(m,{relatedRequestId:n,resumptionToken:s,onresumptiontoken:o}).catch(_=>{this._cleanupTimeout(f),l(_)})})}async notification(e,r){var a,n;if(!this._transport)throw new Error("Not connected");if(this.assertNotificationCapability(e.method),((n=(a=this._options)===null||a===void 0?void 0:a.debouncedNotificationMethods)!==null&&n!==void 0?n:[]).includes(e.method)&&!e.params&&!(r!=null&&r.relatedRequestId)){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{var l;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;const u={...e,jsonrpc:"2.0"};(l=this._transport)===null||l===void 0||l.send(u,r).catch(d=>this._onerror(d))});return}const i={...e,jsonrpc:"2.0"};await this._transport.send(i,r)}setRequestHandler(e,r){const a=e.shape.method.value;this.assertRequestHandlerCapability(a),this._requestHandlers.set(a,(n,s)=>Promise.resolve(r(e.parse(n),s)))}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){this._notificationHandlers.set(e.shape.method.value,a=>Promise.resolve(r(e.parse(a))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}}function qT(t,e){return Object.entries(e).reduce((r,[a,n])=>(n&&typeof n=="object"?r[a]=r[a]?{...r[a],...n}:n:r[a]=n,r),{...t})}var rl={exports:{}};/** @license URI.js v4.4.1 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js */(function(t,e){(function(r,a){a(e)})(ab,function(r){function a(){for(var T=arguments.length,b=Array(T),k=0;k<T;k++)b[k]=arguments[k];if(b.length>1){b[0]=b[0].slice(0,-1);for(var A=b.length-1,N=1;N<A;++N)b[N]=b[N].slice(1,-1);return b[A]=b[A].slice(1),b.join("")}else return b[0]}function n(T){return"(?:"+T+")"}function s(T){return T===void 0?"undefined":T===null?"null":Object.prototype.toString.call(T).split(" ").pop().split("]").shift().toLowerCase()}function o(T){return T.toUpperCase()}function i(T){return T!=null?T instanceof Array?T:typeof T.length!="number"||T.split||T.setInterval||T.call?[T]:Array.prototype.slice.call(T):[]}function l(T,b){var k=T;if(b)for(var A in b)k[A]=b[A];return k}function u(T){var b="[A-Za-z]",k="[0-9]",A=a(k,"[A-Fa-f]"),N=n(n("%[EFef]"+A+"%"+A+A+"%"+A+A)+"|"+n("%[89A-Fa-f]"+A+"%"+A+A)+"|"+n("%"+A+A)),ne="[\\:\\/\\?\\#\\[\\]\\@]",le="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",Oe=a(ne,le),He=T?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]",tt=T?"[\\uE000-\\uF8FF]":"[]",Ce=a(b,k,"[\\-\\.\\_\\~]",He);n(b+a(b,k,"[\\+\\-\\.]")+"*"),n(n(N+"|"+a(Ce,le,"[\\:]"))+"*");var Ze=n(n("25[0-5]")+"|"+n("2[0-4]"+k)+"|"+n("1"+k+k)+"|"+n("0?[1-9]"+k)+"|0?0?"+k),rt=n(Ze+"\\."+Ze+"\\."+Ze+"\\."+Ze),fe=n(A+"{1,4}"),Ke=n(n(fe+"\\:"+fe)+"|"+rt),ot=n(n(fe+"\\:")+"{6}"+Ke),Qe=n("\\:\\:"+n(fe+"\\:")+"{5}"+Ke),Vr=n(n(fe)+"?\\:\\:"+n(fe+"\\:")+"{4}"+Ke),fr=n(n(n(fe+"\\:")+"{0,1}"+fe)+"?\\:\\:"+n(fe+"\\:")+"{3}"+Ke),mr=n(n(n(fe+"\\:")+"{0,2}"+fe)+"?\\:\\:"+n(fe+"\\:")+"{2}"+Ke),qn=n(n(n(fe+"\\:")+"{0,3}"+fe)+"?\\:\\:"+fe+"\\:"+Ke),mn=n(n(n(fe+"\\:")+"{0,4}"+fe)+"?\\:\\:"+Ke),Ht=n(n(n(fe+"\\:")+"{0,5}"+fe)+"?\\:\\:"+fe),vr=n(n(n(fe+"\\:")+"{0,6}"+fe)+"?\\:\\:"),vn=n([ot,Qe,Vr,fr,mr,qn,mn,Ht,vr].join("|")),Ir=n(n(Ce+"|"+N)+"+");n("[vV]"+A+"+\\."+a(Ce,le,"[\\:]")+"+"),n(n(N+"|"+a(Ce,le))+"*");var Da=n(N+"|"+a(Ce,le,"[\\:\\@]"));return n(n(N+"|"+a(Ce,le,"[\\@]"))+"+"),n(n(Da+"|"+a("[\\/\\?]",tt))+"*"),{NOT_SCHEME:new RegExp(a("[^]",b,k,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(a("[^\\%\\:]",Ce,le),"g"),NOT_HOST:new RegExp(a("[^\\%\\[\\]\\:]",Ce,le),"g"),NOT_PATH:new RegExp(a("[^\\%\\/\\:\\@]",Ce,le),"g"),NOT_PATH_NOSCHEME:new RegExp(a("[^\\%\\/\\@]",Ce,le),"g"),NOT_QUERY:new RegExp(a("[^\\%]",Ce,le,"[\\:\\@\\/\\?]",tt),"g"),NOT_FRAGMENT:new RegExp(a("[^\\%]",Ce,le,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(a("[^]",Ce,le),"g"),UNRESERVED:new RegExp(Ce,"g"),OTHER_CHARS:new RegExp(a("[^\\%]",Ce,Oe),"g"),PCT_ENCODED:new RegExp(N,"g"),IPV4ADDRESS:new RegExp("^("+rt+")$"),IPV6ADDRESS:new RegExp("^\\[?("+vn+")"+n(n("\\%25|\\%(?!"+A+"{2})")+"("+Ir+")")+"?\\]?$")}}var d=u(!1),h=u(!0),g=function(){function T(b,k){var A=[],N=!0,ne=!1,le=void 0;try{for(var Oe=b[Symbol.iterator](),He;!(N=(He=Oe.next()).done)&&(A.push(He.value),!(k&&A.length===k));N=!0);}catch(tt){ne=!0,le=tt}finally{try{!N&&Oe.return&&Oe.return()}finally{if(ne)throw le}}return A}return function(b,k){if(Array.isArray(b))return b;if(Symbol.iterator in Object(b))return T(b,k);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),c=function(T){if(Array.isArray(T)){for(var b=0,k=Array(T.length);b<T.length;b++)k[b]=T[b];return k}else return Array.from(T)},p=2147483647,f=36,m=1,v=26,w=38,y=700,_=72,E=128,I="-",S=/^xn--/,R=/[^\0-\x7E]/,$=/[\x2E\u3002\uFF0E\uFF61]/g,z={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},L=f-m,F=Math.floor,M=String.fromCharCode;function D(T){throw new RangeError(z[T])}function K(T,b){for(var k=[],A=T.length;A--;)k[A]=b(T[A]);return k}function oe(T,b){var k=T.split("@"),A="";k.length>1&&(A=k[0]+"@",T=k[1]),T=T.replace($,".");var N=T.split("."),ne=K(N,b).join(".");return A+ne}function ie(T){for(var b=[],k=0,A=T.length;k<A;){var N=T.charCodeAt(k++);if(N>=55296&&N<=56319&&k<A){var ne=T.charCodeAt(k++);(ne&64512)==56320?b.push(((N&1023)<<10)+(ne&1023)+65536):(b.push(N),k--)}else b.push(N)}return b}var C=function(b){return String.fromCodePoint.apply(String,c(b))},re=function(b){return b-48<10?b-22:b-65<26?b-65:b-97<26?b-97:f},B=function(b,k){return b+22+75*(b<26)-((k!=0)<<5)},de=function(b,k,A){var N=0;for(b=A?F(b/y):b>>1,b+=F(b/k);b>L*v>>1;N+=f)b=F(b/L);return F(N+(L+1)*b/(b+w))},ae=function(b){var k=[],A=b.length,N=0,ne=E,le=_,Oe=b.lastIndexOf(I);Oe<0&&(Oe=0);for(var He=0;He<Oe;++He)b.charCodeAt(He)>=128&&D("not-basic"),k.push(b.charCodeAt(He));for(var tt=Oe>0?Oe+1:0;tt<A;){for(var Ce=N,Ze=1,rt=f;;rt+=f){tt>=A&&D("invalid-input");var fe=re(b.charCodeAt(tt++));(fe>=f||fe>F((p-N)/Ze))&&D("overflow"),N+=fe*Ze;var Ke=rt<=le?m:rt>=le+v?v:rt-le;if(fe<Ke)break;var ot=f-Ke;Ze>F(p/ot)&&D("overflow"),Ze*=ot}var Qe=k.length+1;le=de(N-Ce,Qe,Ce==0),F(N/Qe)>p-ne&&D("overflow"),ne+=F(N/Qe),N%=Qe,k.splice(N++,0,ne)}return String.fromCodePoint.apply(String,k)},ke=function(b){var k=[];b=ie(b);var A=b.length,N=E,ne=0,le=_,Oe=!0,He=!1,tt=void 0;try{for(var Ce=b[Symbol.iterator](),Ze;!(Oe=(Ze=Ce.next()).done);Oe=!0){var rt=Ze.value;rt<128&&k.push(M(rt))}}catch(ja){He=!0,tt=ja}finally{try{!Oe&&Ce.return&&Ce.return()}finally{if(He)throw tt}}var fe=k.length,Ke=fe;for(fe&&k.push(I);Ke<A;){var ot=p,Qe=!0,Vr=!1,fr=void 0;try{for(var mr=b[Symbol.iterator](),qn;!(Qe=(qn=mr.next()).done);Qe=!0){var mn=qn.value;mn>=N&&mn<ot&&(ot=mn)}}catch(ja){Vr=!0,fr=ja}finally{try{!Qe&&mr.return&&mr.return()}finally{if(Vr)throw fr}}var Ht=Ke+1;ot-N>F((p-ne)/Ht)&&D("overflow"),ne+=(ot-N)*Ht,N=ot;var vr=!0,vn=!1,Ir=void 0;try{for(var Da=b[Symbol.iterator](),Zm;!(vr=(Zm=Da.next()).done);vr=!0){var Vm=Zm.value;if(Vm<N&&++ne>p&&D("overflow"),Vm==N){for(var ho=ne,fo=f;;fo+=f){var mo=fo<=le?m:fo>=le+v?v:fo-le;if(ho<mo)break;var Bm=ho-mo,Hm=f-mo;k.push(M(B(mo+Bm%Hm,0))),ho=F(Bm/Hm)}k.push(M(B(ho,0))),le=de(ne,Ht,Ke==fe),ne=0,++Ke}}}catch(ja){vn=!0,Ir=ja}finally{try{!vr&&Da.return&&Da.return()}finally{if(vn)throw Ir}}++ne,++N}return k.join("")},_e=function(b){return oe(b,function(k){return S.test(k)?ae(k.slice(4).toLowerCase()):k})},Pe=function(b){return oe(b,function(k){return R.test(k)?"xn--"+ke(k):k})},xe={version:"2.1.0",ucs2:{decode:ie,encode:C},decode:ae,encode:ke,toASCII:Pe,toUnicode:_e},ve={};function Re(T){var b=T.charCodeAt(0),k=void 0;return b<16?k="%0"+b.toString(16).toUpperCase():b<128?k="%"+b.toString(16).toUpperCase():b<2048?k="%"+(b>>6|192).toString(16).toUpperCase()+"%"+(b&63|128).toString(16).toUpperCase():k="%"+(b>>12|224).toString(16).toUpperCase()+"%"+(b>>6&63|128).toString(16).toUpperCase()+"%"+(b&63|128).toString(16).toUpperCase(),k}function pt(T){for(var b="",k=0,A=T.length;k<A;){var N=parseInt(T.substr(k+1,2),16);if(N<128)b+=String.fromCharCode(N),k+=3;else if(N>=194&&N<224){if(A-k>=6){var ne=parseInt(T.substr(k+4,2),16);b+=String.fromCharCode((N&31)<<6|ne&63)}else b+=T.substr(k,6);k+=6}else if(N>=224){if(A-k>=9){var le=parseInt(T.substr(k+4,2),16),Oe=parseInt(T.substr(k+7,2),16);b+=String.fromCharCode((N&15)<<12|(le&63)<<6|Oe&63)}else b+=T.substr(k,9);k+=9}else b+=T.substr(k,3),k+=3}return b}function Ne(T,b){function k(A){var N=pt(A);return N.match(b.UNRESERVED)?N:A}return T.scheme&&(T.scheme=String(T.scheme).replace(b.PCT_ENCODED,k).toLowerCase().replace(b.NOT_SCHEME,"")),T.userinfo!==void 0&&(T.userinfo=String(T.userinfo).replace(b.PCT_ENCODED,k).replace(b.NOT_USERINFO,Re).replace(b.PCT_ENCODED,o)),T.host!==void 0&&(T.host=String(T.host).replace(b.PCT_ENCODED,k).toLowerCase().replace(b.NOT_HOST,Re).replace(b.PCT_ENCODED,o)),T.path!==void 0&&(T.path=String(T.path).replace(b.PCT_ENCODED,k).replace(T.scheme?b.NOT_PATH:b.NOT_PATH_NOSCHEME,Re).replace(b.PCT_ENCODED,o)),T.query!==void 0&&(T.query=String(T.query).replace(b.PCT_ENCODED,k).replace(b.NOT_QUERY,Re).replace(b.PCT_ENCODED,o)),T.fragment!==void 0&&(T.fragment=String(T.fragment).replace(b.PCT_ENCODED,k).replace(b.NOT_FRAGMENT,Re).replace(b.PCT_ENCODED,o)),T}function we(T){return T.replace(/^0*(.*)/,"$1")||"0"}function bt(T,b){var k=T.match(b.IPV4ADDRESS)||[],A=g(k,2),N=A[1];return N?N.split(".").map(we).join("."):T}function be(T,b){var k=T.match(b.IPV6ADDRESS)||[],A=g(k,3),N=A[1],ne=A[2];if(N){for(var le=N.toLowerCase().split("::").reverse(),Oe=g(le,2),He=Oe[0],tt=Oe[1],Ce=tt?tt.split(":").map(we):[],Ze=He.split(":").map(we),rt=b.IPV4ADDRESS.test(Ze[Ze.length-1]),fe=rt?7:8,Ke=Ze.length-fe,ot=Array(fe),Qe=0;Qe<fe;++Qe)ot[Qe]=Ce[Qe]||Ze[Ke+Qe]||"";rt&&(ot[fe-1]=bt(ot[fe-1],b));var Vr=ot.reduce(function(Ht,vr,vn){if(!vr||vr==="0"){var Ir=Ht[Ht.length-1];Ir&&Ir.index+Ir.length===vn?Ir.length++:Ht.push({index:vn,length:1})}return Ht},[]),fr=Vr.sort(function(Ht,vr){return vr.length-Ht.length})[0],mr=void 0;if(fr&&fr.length>1){var qn=ot.slice(0,fr.index),mn=ot.slice(fr.index+fr.length);mr=qn.join(":")+"::"+mn.join(":")}else mr=ot.join(":");return ne&&(mr+="%"+ne),mr}else return T}var se=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,Se="".match(/(){0}/)[1]===void 0;function Ie(T){var b=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},k={},A=b.iri!==!1?h:d;b.reference==="suffix"&&(T=(b.scheme?b.scheme+":":"")+"//"+T);var N=T.match(se);if(N){Se?(k.scheme=N[1],k.userinfo=N[3],k.host=N[4],k.port=parseInt(N[5],10),k.path=N[6]||"",k.query=N[7],k.fragment=N[8],isNaN(k.port)&&(k.port=N[5])):(k.scheme=N[1]||void 0,k.userinfo=T.indexOf("@")!==-1?N[3]:void 0,k.host=T.indexOf("//")!==-1?N[4]:void 0,k.port=parseInt(N[5],10),k.path=N[6]||"",k.query=T.indexOf("?")!==-1?N[7]:void 0,k.fragment=T.indexOf("#")!==-1?N[8]:void 0,isNaN(k.port)&&(k.port=T.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?N[4]:void 0)),k.host&&(k.host=be(bt(k.host,A),A)),k.scheme===void 0&&k.userinfo===void 0&&k.host===void 0&&k.port===void 0&&!k.path&&k.query===void 0?k.reference="same-document":k.scheme===void 0?k.reference="relative":k.fragment===void 0?k.reference="absolute":k.reference="uri",b.reference&&b.reference!=="suffix"&&b.reference!==k.reference&&(k.error=k.error||"URI is not a "+b.reference+" reference.");var ne=ve[(b.scheme||k.scheme||"").toLowerCase()];if(!b.unicodeSupport&&(!ne||!ne.unicodeSupport)){if(k.host&&(b.domainHost||ne&&ne.domainHost))try{k.host=xe.toASCII(k.host.replace(A.PCT_ENCODED,pt).toLowerCase())}catch(le){k.error=k.error||"Host's domain name can not be converted to ASCII via punycode: "+le}Ne(k,d)}else Ne(k,A);ne&&ne.parse&&ne.parse(k,b)}else k.error=k.error||"URI can not be parsed.";return k}function ye(T,b){var k=b.iri!==!1?h:d,A=[];return T.userinfo!==void 0&&(A.push(T.userinfo),A.push("@")),T.host!==void 0&&A.push(be(bt(String(T.host),k),k).replace(k.IPV6ADDRESS,function(N,ne,le){return"["+ne+(le?"%25"+le:"")+"]"})),(typeof T.port=="number"||typeof T.port=="string")&&(A.push(":"),A.push(String(T.port))),A.length?A.join(""):void 0}var Xe=/^\.\.?\//,Le=/^\/\.(\/|$)/,J=/^\/\.\.(\/|$)/,Me=/^\/?(?:.|\n)*?(?=\/|$)/;function ze(T){for(var b=[];T.length;)if(T.match(Xe))T=T.replace(Xe,"");else if(T.match(Le))T=T.replace(Le,"/");else if(T.match(J))T=T.replace(J,"/"),b.pop();else if(T==="."||T==="..")T="";else{var k=T.match(Me);if(k){var A=k[0];T=T.slice(A.length),b.push(A)}else throw new Error("Unexpected dot segment condition")}return b.join("")}function pe(T){var b=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},k=b.iri?h:d,A=[],N=ve[(b.scheme||T.scheme||"").toLowerCase()];if(N&&N.serialize&&N.serialize(T,b),T.host&&!k.IPV6ADDRESS.test(T.host)){if(b.domainHost||N&&N.domainHost)try{T.host=b.iri?xe.toUnicode(T.host):xe.toASCII(T.host.replace(k.PCT_ENCODED,pt).toLowerCase())}catch(Oe){T.error=T.error||"Host's domain name can not be converted to "+(b.iri?"Unicode":"ASCII")+" via punycode: "+Oe}}Ne(T,k),b.reference!=="suffix"&&T.scheme&&(A.push(T.scheme),A.push(":"));var ne=ye(T,b);if(ne!==void 0&&(b.reference!=="suffix"&&A.push("//"),A.push(ne),T.path&&T.path.charAt(0)!=="/"&&A.push("/")),T.path!==void 0){var le=T.path;!b.absolutePath&&(!N||!N.absolutePath)&&(le=ze(le)),ne===void 0&&(le=le.replace(/^\/\//,"/%2F")),A.push(le)}return T.query!==void 0&&(A.push("?"),A.push(T.query)),T.fragment!==void 0&&(A.push("#"),A.push(T.fragment)),A.join("")}function Be(T,b){var k=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},A=arguments[3],N={};return A||(T=Ie(pe(T,k),k),b=Ie(pe(b,k),k)),k=k||{},!k.tolerant&&b.scheme?(N.scheme=b.scheme,N.userinfo=b.userinfo,N.host=b.host,N.port=b.port,N.path=ze(b.path||""),N.query=b.query):(b.userinfo!==void 0||b.host!==void 0||b.port!==void 0?(N.userinfo=b.userinfo,N.host=b.host,N.port=b.port,N.path=ze(b.path||""),N.query=b.query):(b.path?(b.path.charAt(0)==="/"?N.path=ze(b.path):((T.userinfo!==void 0||T.host!==void 0||T.port!==void 0)&&!T.path?N.path="/"+b.path:T.path?N.path=T.path.slice(0,T.path.lastIndexOf("/")+1)+b.path:N.path=b.path,N.path=ze(N.path)),N.query=b.query):(N.path=T.path,b.query!==void 0?N.query=b.query:N.query=T.query),N.userinfo=T.userinfo,N.host=T.host,N.port=T.port),N.scheme=T.scheme),N.fragment=b.fragment,N}function hr(T,b,k){var A=l({scheme:"null"},k);return pe(Be(Ie(T,A),Ie(b,A),A,!0),A)}function Ft(T,b){return typeof T=="string"?T=pe(Ie(T,b),b):s(T)==="object"&&(T=Ie(pe(T,b),b)),T}function mt(T,b,k){return typeof T=="string"?T=pe(Ie(T,k),k):s(T)==="object"&&(T=pe(T,k)),typeof b=="string"?b=pe(Ie(b,k),k):s(b)==="object"&&(b=pe(b,k)),T===b}function Yt(T,b){return T&&T.toString().replace(!b||!b.iri?d.ESCAPE:h.ESCAPE,Re)}function xt(T,b){return T&&T.toString().replace(!b||!b.iri?d.PCT_ENCODED:h.PCT_ENCODED,pt)}var qt={scheme:"http",domainHost:!0,parse:function(b,k){return b.host||(b.error=b.error||"HTTP URIs must have a host."),b},serialize:function(b,k){var A=String(b.scheme).toLowerCase()==="https";return(b.port===(A?443:80)||b.port==="")&&(b.port=void 0),b.path||(b.path="/"),b}},Sr={scheme:"https",domainHost:qt.domainHost,parse:qt.parse,serialize:qt.serialize};function pn(T){return typeof T.secure=="boolean"?T.secure:String(T.scheme).toLowerCase()==="wss"}var Ge={scheme:"ws",domainHost:!0,parse:function(b,k){var A=b;return A.secure=pn(A),A.resourceName=(A.path||"/")+(A.query?"?"+A.query:""),A.path=void 0,A.query=void 0,A},serialize:function(b,k){if((b.port===(pn(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){var A=b.resourceName.split("?"),N=g(A,2),ne=N[0],le=N[1];b.path=ne&&ne!=="/"?ne:void 0,b.query=le,b.resourceName=void 0}return b.fragment=void 0,b}},Zt={scheme:"wss",domainHost:Ge.domainHost,parse:Ge.parse,serialize:Ge.serialize},Xt={},Ra="[A-Za-z0-9\\-\\.\\_\\~\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]",Vt="[0-9A-Fa-f]",Kl=n(n("%[EFef]"+Vt+"%"+Vt+Vt+"%"+Vt+Vt)+"|"+n("%[89A-Fa-f]"+Vt+"%"+Vt+Vt)+"|"+n("%"+Vt+Vt)),Un="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",Oa="[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",$a=a(Oa,'[\\"\\\\]'),Aa="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",qr=new RegExp(Ra,"g"),ht=new RegExp(Kl,"g"),Na=new RegExp(a("[^]",Un,"[\\.]",'[\\"]',$a),"g"),Ma=new RegExp(a("[^]",Ra,Aa),"g"),Bt=Ma;function Fn(T){var b=pt(T);return b.match(qr)?b:T}var ue={scheme:"mailto",parse:function(b,k){var A=b,N=A.to=A.path?A.path.split(","):[];if(A.path=void 0,A.query){for(var ne=!1,le={},Oe=A.query.split("&"),He=0,tt=Oe.length;He<tt;++He){var Ce=Oe[He].split("=");switch(Ce[0]){case"to":for(var Ze=Ce[1].split(","),rt=0,fe=Ze.length;rt<fe;++rt)N.push(Ze[rt]);break;case"subject":A.subject=xt(Ce[1],k);break;case"body":A.body=xt(Ce[1],k);break;default:ne=!0,le[xt(Ce[0],k)]=xt(Ce[1],k);break}}ne&&(A.headers=le)}A.query=void 0;for(var Ke=0,ot=N.length;Ke<ot;++Ke){var Qe=N[Ke].split("@");if(Qe[0]=xt(Qe[0]),k.unicodeSupport)Qe[1]=xt(Qe[1],k).toLowerCase();else try{Qe[1]=xe.toASCII(xt(Qe[1],k).toLowerCase())}catch(Vr){A.error=A.error||"Email address's domain name can not be converted to ASCII via punycode: "+Vr}N[Ke]=Qe.join("@")}return A},serialize:function(b,k){var A=b,N=i(b.to);if(N){for(var ne=0,le=N.length;ne<le;++ne){var Oe=String(N[ne]),He=Oe.lastIndexOf("@"),tt=Oe.slice(0,He).replace(ht,Fn).replace(ht,o).replace(Na,Re),Ce=Oe.slice(He+1);try{Ce=k.iri?xe.toUnicode(Ce):xe.toASCII(xt(Ce,k).toLowerCase())}catch(Ke){A.error=A.error||"Email address's domain name can not be converted to "+(k.iri?"Unicode":"ASCII")+" via punycode: "+Ke}N[ne]=tt+"@"+Ce}A.path=N.join(",")}var Ze=b.headers=b.headers||{};b.subject&&(Ze.subject=b.subject),b.body&&(Ze.body=b.body);var rt=[];for(var fe in Ze)Ze[fe]!==Xt[fe]&&rt.push(fe.replace(ht,Fn).replace(ht,o).replace(Ma,Re)+"="+Ze[fe].replace(ht,Fn).replace(ht,o).replace(Bt,Re));return rt.length&&(A.query=rt.join("&")),A}},ct=/^([^\:]+)\:(.*)/,Zr={scheme:"urn",parse:function(b,k){var A=b.path&&b.path.match(ct),N=b;if(A){var ne=k.scheme||N.scheme||"urn",le=A[1].toLowerCase(),Oe=A[2],He=ne+":"+(k.nid||le),tt=ve[He];N.nid=le,N.nss=Oe,N.path=void 0,tt&&(N=tt.parse(N,k))}else N.error=N.error||"URN can not be parsed.";return N},serialize:function(b,k){var A=k.scheme||b.scheme||"urn",N=b.nid,ne=A+":"+(k.nid||N),le=ve[ne];le&&(b=le.serialize(b,k));var Oe=b,He=b.nss;return Oe.path=(N||k.nid)+":"+He,Oe}},hn=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,fn={scheme:"urn:uuid",parse:function(b,k){var A=b;return A.uuid=A.nss,A.nss=void 0,!k.tolerant&&(!A.uuid||!A.uuid.match(hn))&&(A.error=A.error||"UUID is not valid."),A},serialize:function(b,k){var A=b;return A.nss=(b.uuid||"").toLowerCase(),A}};ve[qt.scheme]=qt,ve[Sr.scheme]=Sr,ve[Ge.scheme]=Ge,ve[Zt.scheme]=Zt,ve[ue.scheme]=ue,ve[Zr.scheme]=Zr,ve[fn.scheme]=fn,r.SCHEMES=ve,r.pctEncChar=Re,r.pctDecChars=pt,r.parse=Ie,r.removeDotSegments=ze,r.serialize=pe,r.resolveComponents=Be,r.resolve=hr,r.normalize=Ft,r.equal=mt,r.escapeComponent=Yt,r.unescapeComponent=xt,Object.defineProperty(r,"__esModule",{value:!0})})})(rl,rl.exports);var ZT=rl.exports,nl=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var a,n,s;if(Array.isArray(e)){if(a=e.length,a!=r.length)return!1;for(n=a;n--!==0;)if(!t(e[n],r[n]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),a=s.length,a!==Object.keys(r).length)return!1;for(n=a;n--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[n]))return!1;for(n=a;n--!==0;){var o=s[n];if(!t(e[o],r[o]))return!1}return!0}return e!==e&&r!==r},VT=function(e){for(var r=0,a=e.length,n=0,s;n<a;)r++,s=e.charCodeAt(n++),s>=55296&&s<=56319&&n<a&&(s=e.charCodeAt(n),(s&64512)==56320&&n++);return r},Cn={copy:BT,checkDataType:al,checkDataTypes:HT,coerceToTypes:JT,toHash:sl,getProperty:ol,escapeQuotes:il,equal:nl,ucs2length:VT,varOccurences:KT,varReplace:QT,schemaHasRules:YT,schemaHasRulesExcept:XT,schemaUnknownRules:ek,toQuotedString:ll,getPathExpr:tk,getPath:rk,getData:sk,unescapeFragment:ok,unescapeJsonPointer:cl,escapeFragment:ik,escapeJsonPointer:ul};function BT(t,e){e=e||{};for(var r in t)e[r]=t[r];return e}function al(t,e,r,a){var n=a?" !== ":" === ",s=a?" || ":" && ",o=a?"!":"",i=a?"":"!";switch(t){case"null":return e+n+"null";case"array":return o+"Array.isArray("+e+")";case"object":return"("+o+e+s+"typeof "+e+n+'"object"'+s+i+"Array.isArray("+e+"))";case"integer":return"(typeof "+e+n+'"number"'+s+i+"("+e+" % 1)"+s+e+n+e+(r?s+o+"isFinite("+e+")":"")+")";case"number":return"(typeof "+e+n+'"'+t+'"'+(r?s+o+"isFinite("+e+")":"")+")";default:return"typeof "+e+n+'"'+t+'"'}}function HT(t,e,r){switch(t.length){case 1:return al(t[0],e,r,!0);default:var a="",n=sl(t);n.array&&n.object&&(a=n.null?"(":"(!"+e+" || ",a+="typeof "+e+' !== "object")',delete n.null,delete n.array,delete n.object),n.number&&delete n.integer;for(var s in n)a+=(a?" && ":"")+al(s,e,r,!0);return a}}var If=sl(["string","number","integer","boolean","null"]);function JT(t,e){if(Array.isArray(e)){for(var r=[],a=0;a<e.length;a++){var n=e[a];(If[n]||t==="array"&&n==="array")&&(r[r.length]=n)}if(r.length)return r}else{if(If[e])return[e];if(t==="array"&&e==="array")return["array"]}}function sl(t){for(var e={},r=0;r<t.length;r++)e[t[r]]=!0;return e}var WT=/^[a-z$_][a-z$_0-9]*$/i,GT=/'|\\/g;function ol(t){return typeof t=="number"?"["+t+"]":WT.test(t)?"."+t:"['"+il(t)+"']"}function il(t){return t.replace(GT,"\\$&").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\f/g,"\\f").replace(/\t/g,"\\t")}function KT(t,e){e+="[^0-9]";var r=t.match(new RegExp(e,"g"));return r?r.length:0}function QT(t,e,r){return e+="([^0-9])",r=r.replace(/\$/g,"$$$$"),t.replace(new RegExp(e,"g"),r+"$1")}function YT(t,e){if(typeof t=="boolean")return!t;for(var r in t)if(e[r])return!0}function XT(t,e,r){if(typeof t=="boolean")return!t&&r!="not";for(var a in t)if(a!=r&&e[a])return!0}function ek(t,e){if(typeof t!="boolean"){for(var r in t)if(!e[r])return r}}function ll(t){return"'"+il(t)+"'"}function tk(t,e,r,a){var n=r?"'/' + "+e+(a?"":".replace(/~/g, '~0').replace(/\\//g, '~1')"):a?"'[' + "+e+" + ']'":"'[\\'' + "+e+" + '\\']'";return Tf(t,n)}function rk(t,e,r){var a=ll(r?"/"+ul(e):ol(e));return Tf(t,a)}var nk=/^\/(?:[^~]|~0|~1)*$/,ak=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function sk(t,e,r){var a,n,s,o;if(t==="")return"rootData";if(t[0]=="/"){if(!nk.test(t))throw new Error("Invalid JSON-pointer: "+t);n=t,s="rootData"}else{if(o=t.match(ak),!o)throw new Error("Invalid JSON-pointer: "+t);if(a=+o[1],n=o[2],n=="#"){if(a>=e)throw new Error("Cannot access property/index "+a+" levels up, current level is "+e);return r[e-a]}if(a>e)throw new Error("Cannot access data "+a+" levels up, current level is "+e);if(s="data"+(e-a||""),!n)return s}for(var i=s,l=n.split("/"),u=0;u<l.length;u++){var d=l[u];d&&(s+=ol(cl(d)),i+=" && "+s)}return i}function Tf(t,e){return t=='""'?e:(t+" + "+e).replace(/([^\\])' \+ '/g,"$1")}function ok(t){return cl(decodeURIComponent(t))}function ik(t){return encodeURIComponent(ul(t))}function ul(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function cl(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}var lk=Cn,kf=uk;function uk(t){lk.copy(t,this)}var Pf={exports:{}},Mr=Pf.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var a=typeof r=="function"?r:r.pre||function(){},n=r.post||function(){};$s(e,a,n,t,"",t)};Mr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0},Mr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},Mr.propsKeywords={definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},Mr.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 $s(t,e,r,a,n,s,o,i,l,u){if(a&&typeof a=="object"&&!Array.isArray(a)){e(a,n,s,o,i,l,u);for(var d in a){var h=a[d];if(Array.isArray(h)){if(d in Mr.arrayKeywords)for(var g=0;g<h.length;g++)$s(t,e,r,h[g],n+"/"+d+"/"+g,s,n,d,a,g)}else if(d in Mr.propsKeywords){if(h&&typeof h=="object")for(var c in h)$s(t,e,r,h[c],n+"/"+d+"/"+ck(c),s,n,d,a,c)}else(d in Mr.keywords||t.allKeys&&!(d in Mr.skipKeywords))&&$s(t,e,r,h,n+"/"+d,s,n,d,a)}r(a,n,s,o,i,l,u)}}function ck(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}var dk=Pf.exports,ba=ZT,Cf=nl,As=Cn,Ns=kf,pk=dk,dl=Dr;Dr.normalizeId=jr,Dr.fullPath=Ds,Dr.url=js,Dr.ids=gk,Dr.inlineRef=pl,Dr.schema=Ms;function Dr(t,e,r){var a=this._refs[r];if(typeof a=="string")if(this._refs[a])a=this._refs[a];else return Dr.call(this,t,e,a);if(a=a||this._schemas[r],a instanceof Ns)return pl(a.schema,this._opts.inlineRefs)?a.schema:a.validate||this._compile(a);var n=Ms.call(this,e,r),s,o,i;return n&&(s=n.schema,e=n.root,i=n.baseId),s instanceof Ns?o=s.validate||t.call(this,s.schema,e,void 0,i):s!==void 0&&(o=pl(s,this._opts.inlineRefs)?s:t.call(this,s,e,void 0,i)),o}function Ms(t,e){var r=ba.parse(e),a=Of(r),n=Ds(this._getId(t.schema));if(Object.keys(t.schema).length===0||a!==n){var s=jr(a),o=this._refs[s];if(typeof o=="string")return hk.call(this,t,o,r);if(o instanceof Ns)o.validate||this._compile(o),t=o;else if(o=this._schemas[s],o instanceof Ns){if(o.validate||this._compile(o),s==jr(e))return{schema:o,root:t,baseId:n};t=o}else return;if(!t.schema)return;n=Ds(this._getId(t.schema))}return Rf.call(this,r,n,t.schema,t)}function hk(t,e,r){var a=Ms.call(this,t,e);if(a){var n=a.schema,s=a.baseId;t=a.root;var o=this._getId(n);return o&&(s=js(s,o)),Rf.call(this,r,s,n,t)}}var fk=As.toHash(["properties","patternProperties","enum","dependencies","definitions"]);function Rf(t,e,r,a){if(t.fragment=t.fragment||"",t.fragment.slice(0,1)=="/"){for(var n=t.fragment.split("/"),s=1;s<n.length;s++){var o=n[s];if(o){if(o=As.unescapeFragment(o),r=r[o],r===void 0)break;var i;if(!fk[o]&&(i=this._getId(r),i&&(e=js(e,i)),r.$ref)){var l=js(e,r.$ref),u=Ms.call(this,a,l);u&&(r=u.schema,a=u.root,e=u.baseId)}}}if(r!==void 0&&r!==a.schema)return{schema:r,root:a,baseId:e}}}var mk=As.toHash(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum"]);function pl(t,e){if(e===!1)return!1;if(e===void 0||e===!0)return hl(t);if(e)return fl(t)<=e}function hl(t){var e;if(Array.isArray(t)){for(var r=0;r<t.length;r++)if(e=t[r],typeof e=="object"&&!hl(e))return!1}else for(var a in t)if(a=="$ref"||(e=t[a],typeof e=="object"&&!hl(e)))return!1;return!0}function fl(t){var e=0,r;if(Array.isArray(t)){for(var a=0;a<t.length;a++)if(r=t[a],typeof r=="object"&&(e+=fl(r)),e==1/0)return 1/0}else for(var n in t){if(n=="$ref")return 1/0;if(mk[n])e++;else if(r=t[n],typeof r=="object"&&(e+=fl(r)+1),e==1/0)return 1/0}return e}function Ds(t,e){e!==!1&&(t=jr(t));var r=ba.parse(t);return Of(r)}function Of(t){return ba.serialize(t).split("#")[0]+"#"}var vk=/#\/?$/;function jr(t){return t?t.replace(vk,""):""}function js(t,e){return e=jr(e),ba.resolve(t,e)}function gk(t){var e=jr(this._getId(t)),r={"":e},a={"":Ds(e,!1)},n={},s=this;return pk(t,{allKeys:!0},function(o,i,l,u,d,h,g){if(i!==""){var c=s._getId(o),p=r[u],f=a[u]+"/"+d;if(g!==void 0&&(f+="/"+(typeof g=="number"?g:As.escapeFragment(g))),typeof c=="string"){c=p=jr(p?ba.resolve(p,c):c);var m=s._refs[c];if(typeof m=="string"&&(m=s._refs[m]),m&&m.schema){if(!Cf(o,m.schema))throw new Error('id "'+c+'" resolves to more than one schema')}else if(c!=jr(f))if(c[0]=="#"){if(n[c]&&!Cf(o,n[c]))throw new Error('id "'+c+'" resolves to more than one schema');n[c]=o}else s._refs[c]=f}r[i]=p,a[i]=f}}),n}var ml=dl,vl={Validation:$f(yk),MissingRef:$f(gl)};function yk(t){this.message="validation failed",this.errors=t,this.ajv=this.validation=!0}gl.message=function(t,e){return"can't resolve reference "+e+" from id "+t};function gl(t,e,r){this.message=r||gl.message(t,e),this.missingRef=ml.url(t,e),this.missingSchema=ml.normalizeId(ml.fullPath(this.missingRef))}function $f(t){return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var Af=function(t,e){e||(e={}),typeof e=="function"&&(e={cmp:e});var r=typeof e.cycles=="boolean"?e.cycles:!1,a=e.cmp&&function(s){return function(o){return function(i,l){var u={key:i,value:o[i]},d={key:l,value:o[l]};return s(u,d)}}}(e.cmp),n=[];return function s(o){if(o&&o.toJSON&&typeof o.toJSON=="function"&&(o=o.toJSON()),o!==void 0){if(typeof o=="number")return isFinite(o)?""+o:"null";if(typeof o!="object")return JSON.stringify(o);var i,l;if(Array.isArray(o)){for(l="[",i=0;i<o.length;i++)i&&(l+=","),l+=s(o[i])||"null";return l+"]"}if(o===null)return"null";if(n.indexOf(o)!==-1){if(r)return JSON.stringify("__cycle__");throw new TypeError("Converting circular structure to JSON")}var u=n.push(o)-1,d=Object.keys(o).sort(a&&a(o));for(l="",i=0;i<d.length;i++){var h=d[i],g=s(o[h]);g&&(l&&(l+=","),l+=JSON.stringify(h)+":"+g)}return n.splice(u,1),"{"+l+"}"}}(t)},Nf=function(e,r,a){var n="",s=e.schema.$async===!0,o=e.util.schemaHasRulesExcept(e.schema,e.RULES.all,"$ref"),i=e.self._getId(e.schema);if(e.opts.strictKeywords){var l=e.util.schemaUnknownRules(e.schema,e.RULES.keywords);if(l){var u="unknown keyword: "+l;if(e.opts.strictKeywords==="log")e.logger.warn(u);else throw new Error(u)}}if(e.isTop&&(n+=" var validate = ",s&&(e.async=!0,n+="async "),n+="function(data, dataPath, parentData, parentDataProperty, rootData) { 'use strict'; ",i&&(e.opts.sourceCode||e.opts.processCode)&&(n+=" "+("/*# sourceURL="+i+" */")+" ")),typeof e.schema=="boolean"||!(o||e.schema.$ref)){var r="false schema",d=e.level,h=e.dataLevel,g=e.schema[r],c=e.schemaPath+e.util.getProperty(r),p=e.errSchemaPath+"/"+r,E=!e.opts.allErrors,R,f="data"+(h||""),_="valid"+d;if(e.schema===!1){e.isTop?E=!0:n+=" var "+_+" = false; ";var m=m||[];m.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(R||"false schema")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(p)+" , params: {} ",e.opts.messages!==!1&&(n+=" , message: 'boolean schema is false' "),e.opts.verbose&&(n+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var v=n;n=m.pop(),!e.compositeRule&&E?e.async?n+=" throw new ValidationError(["+v+"]); ":n+=" validate.errors = ["+v+"]; return false; ":n+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else e.isTop?s?n+=" return data; ":n+=" validate.errors = null; return true; ":n+=" var "+_+" = true; ";return e.isTop&&(n+=" }; return validate; "),n}if(e.isTop){var w=e.isTop,d=e.level=0,h=e.dataLevel=0,f="data";if(e.rootId=e.resolve.fullPath(e.self._getId(e.root.schema)),e.baseId=e.baseId||e.rootId,delete e.isTop,e.dataPathArr=[""],e.schema.default!==void 0&&e.opts.useDefaults&&e.opts.strictDefaults){var y="default is ignored in the schema root";if(e.opts.strictDefaults==="log")e.logger.warn(y);else throw new Error(y)}n+=" var vErrors = null; ",n+=" var errors = 0; ",n+=" if (rootData === undefined) rootData = data; "}else{var d=e.level,h=e.dataLevel,f="data"+(h||"");if(i&&(e.baseId=e.resolve.url(e.baseId,i)),s&&!e.async)throw new Error("async schema in sync schema");n+=" var errs_"+d+" = errors;"}var _="valid"+d,E=!e.opts.allErrors,I="",S="",R,$=e.schema.type,z=Array.isArray($);if($&&e.opts.nullable&&e.schema.nullable===!0&&(z?$.indexOf("null")==-1&&($=$.concat("null")):$!="null"&&($=[$,"null"],z=!0)),z&&$.length==1&&($=$[0],z=!1),e.schema.$ref&&o){if(e.opts.extendRefs=="fail")throw new Error('$ref: validation keywords used in schema at path "'+e.errSchemaPath+'" (see option extendRefs)');e.opts.extendRefs!==!0&&(o=!1,e.logger.warn('$ref: keywords ignored in schema at path "'+e.errSchemaPath+'"'))}if(e.schema.$comment&&e.opts.$comment&&(n+=" "+e.RULES.all.$comment.code(e,"$comment")),$){if(e.opts.coerceTypes)var L=e.util.coerceToTypes(e.opts.coerceTypes,$);var F=e.RULES.types[$];if(L||z||F===!0||F&&!Le(F)){var c=e.schemaPath+".type",p=e.errSchemaPath+"/type",c=e.schemaPath+".type",p=e.errSchemaPath+"/type",M=z?"checkDataTypes":"checkDataType";if(n+=" if ("+e.util[M]($,f,e.opts.strictNumbers,!0)+") { ",L){var D="dataType"+d,K="coerced"+d;n+=" var "+D+" = typeof "+f+"; var "+K+" = undefined; ",e.opts.coerceTypes=="array"&&(n+=" if ("+D+" == 'object' && Array.isArray("+f+") && "+f+".length == 1) { "+f+" = "+f+"[0]; "+D+" = typeof "+f+"; if ("+e.util.checkDataType(e.schema.type,f,e.opts.strictNumbers)+") "+K+" = "+f+"; } "),n+=" if ("+K+" !== undefined) ; ";var oe=L;if(oe)for(var ie,C=-1,re=oe.length-1;C<re;)ie=oe[C+=1],ie=="string"?n+=" else if ("+D+" == 'number' || "+D+" == 'boolean') "+K+" = '' + "+f+"; else if ("+f+" === null) "+K+" = ''; ":ie=="number"||ie=="integer"?(n+=" else if ("+D+" == 'boolean' || "+f+" === null || ("+D+" == 'string' && "+f+" && "+f+" == +"+f+" ",ie=="integer"&&(n+=" && !("+f+" % 1)"),n+=")) "+K+" = +"+f+"; "):ie=="boolean"?n+=" else if ("+f+" === 'false' || "+f+" === 0 || "+f+" === null) "+K+" = false; else if ("+f+" === 'true' || "+f+" === 1) "+K+" = true; ":ie=="null"?n+=" else if ("+f+" === '' || "+f+" === 0 || "+f+" === false) "+K+" = null; ":e.opts.coerceTypes=="array"&&ie=="array"&&(n+=" else if ("+D+" == 'string' || "+D+" == 'number' || "+D+" == 'boolean' || "+f+" == null) "+K+" = ["+f+"]; ");n+=" else { ";var m=m||[];m.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(R||"type")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(p)+" , params: { type: '",z?n+=""+$.join(","):n+=""+$,n+="' } ",e.opts.messages!==!1&&(n+=" , message: 'should be ",z?n+=""+$.join(","):n+=""+$,n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var v=n;n=m.pop(),!e.compositeRule&&E?e.async?n+=" throw new ValidationError(["+v+"]); ":n+=" validate.errors = ["+v+"]; return false; ":n+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } if ("+K+" !== undefined) { ";var B=h?"data"+(h-1||""):"parentData",de=h?e.dataPathArr[h]:"parentDataProperty";n+=" "+f+" = "+K+"; ",h||(n+="if ("+B+" !== undefined)"),n+=" "+B+"["+de+"] = "+K+"; } "}else{var m=m||[];m.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(R||"type")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(p)+" , params: { type: '",z?n+=""+$.join(","):n+=""+$,n+="' } ",e.opts.messages!==!1&&(n+=" , message: 'should be ",z?n+=""+$.join(","):n+=""+$,n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var v=n;n=m.pop(),!e.compositeRule&&E?e.async?n+=" throw new ValidationError(["+v+"]); ":n+=" validate.errors = ["+v+"]; return false; ":n+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}n+=" } "}}if(e.schema.$ref&&!o)n+=" "+e.RULES.all.$ref.code(e,"$ref")+" ",E&&(n+=" } if (errors === ",w?n+="0":n+="errs_"+d,n+=") { ",S+="}");else{var ae=e.RULES;if(ae){for(var F,ke=-1,_e=ae.length-1;ke<_e;)if(F=ae[ke+=1],Le(F)){if(F.type&&(n+=" if ("+e.util.checkDataType(F.type,f,e.opts.strictNumbers)+") { "),e.opts.useDefaults){if(F.type=="object"&&e.schema.properties){var g=e.schema.properties,Pe=Object.keys(g),xe=Pe;if(xe)for(var ve,Re=-1,pt=xe.length-1;Re<pt;){ve=xe[Re+=1];var Ne=g[ve];if(Ne.default!==void 0){var we=f+e.util.getProperty(ve);if(e.compositeRule){if(e.opts.strictDefaults){var y="default is ignored for: "+we;if(e.opts.strictDefaults==="log")e.logger.warn(y);else throw new Error(y)}}else n+=" if ("+we+" === undefined ",e.opts.useDefaults=="empty"&&(n+=" || "+we+" === null || "+we+" === '' "),n+=" ) "+we+" = ",e.opts.useDefaults=="shared"?n+=" "+e.useDefault(Ne.default)+" ":n+=" "+JSON.stringify(Ne.default)+" ",n+="; "}}}else if(F.type=="array"&&Array.isArray(e.schema.items)){var bt=e.schema.items;if(bt){for(var Ne,C=-1,be=bt.length-1;C<be;)if(Ne=bt[C+=1],Ne.default!==void 0){var we=f+"["+C+"]";if(e.compositeRule){if(e.opts.strictDefaults){var y="default is ignored for: "+we;if(e.opts.strictDefaults==="log")e.logger.warn(y);else throw new Error(y)}}else n+=" if ("+we+" === undefined ",e.opts.useDefaults=="empty"&&(n+=" || "+we+" === null || "+we+" === '' "),n+=" ) "+we+" = ",e.opts.useDefaults=="shared"?n+=" "+e.useDefault(Ne.default)+" ":n+=" "+JSON.stringify(Ne.default)+" ",n+="; "}}}}var se=F.rules;if(se){for(var Se,Ie=-1,ye=se.length-1;Ie<ye;)if(Se=se[Ie+=1],J(Se)){var Xe=Se.code(e,Se.keyword,F.type);Xe&&(n+=" "+Xe+" ",E&&(I+="}"))}}if(E&&(n+=" "+I+" ",I=""),F.type&&(n+=" } ",$&&$===F.type&&!L)){n+=" else { ";var c=e.schemaPath+".type",p=e.errSchemaPath+"/type",m=m||[];m.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(R||"type")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(p)+" , params: { type: '",z?n+=""+$.join(","):n+=""+$,n+="' } ",e.opts.messages!==!1&&(n+=" , message: 'should be ",z?n+=""+$.join(","):n+=""+$,n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var v=n;n=m.pop(),!e.compositeRule&&E?e.async?n+=" throw new ValidationError(["+v+"]); ":n+=" validate.errors = ["+v+"]; return false; ":n+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } "}E&&(n+=" if (errors === ",w?n+="0":n+="errs_"+d,n+=") { ",S+="}")}}}E&&(n+=" "+S+" "),w?(s?(n+=" if (errors === 0) return data; ",n+=" else throw new ValidationError(vErrors); "):(n+=" validate.errors = vErrors; ",n+=" return errors === 0; "),n+=" }; return validate;"):n+=" var "+_+" = errors === errs_"+d+";";function Le(ze){for(var pe=ze.rules,Be=0;Be<pe.length;Be++)if(J(pe[Be]))return!0}function J(ze){return e.schema[ze.keyword]!==void 0||ze.implements&&Me(ze)}function Me(ze){for(var pe=ze.implements,Be=0;Be<pe.length;Be++)if(e.schema[pe[Be]]!==void 0)return!0}return n},Ls=dl,zs=Cn,Mf=vl,_k=Af,Df=Nf,wk=zs.ucs2length,bk=nl,xk=Mf.Validation,Ek=yl;function yl(t,e,r,a){var n=this,s=this._opts,o=[void 0],i={},l=[],u={},d=[],h={},g=[];e=e||{schema:t,refVal:o,refs:i};var c=Sk.call(this,t,e,a),p=this._compilations[c.index];if(c.compiling)return p.callValidate=y;var f=this._formats,m=this.RULES;try{var v=_(t,e,r,a);p.validate=v;var w=p.callValidate;return w&&(w.schema=v.schema,w.errors=null,w.refs=v.refs,w.refVal=v.refVal,w.root=v.root,w.$async=v.$async,s.sourceCode&&(w.source=v.source)),v}finally{Ik.call(this,t,e,a)}function y(){var M=p.validate,D=M.apply(this,arguments);return y.errors=M.errors,D}function _(M,D,K,oe){var ie=!D||D&&D.schema==M;if(D.schema!=e.schema)return yl.call(n,M,D,K,oe);var C=M.$async===!0,re=Df({isTop:!0,schema:M,isRoot:ie,baseId:oe,root:D,schemaPath:"",errSchemaPath:"#",errorPath:'""',MissingRefError:Mf.MissingRef,RULES:m,validate:Df,util:zs,resolve:Ls,resolveRef:E,usePattern:z,useDefault:L,useCustomRule:F,opts:s,formats:f,logger:n.logger,self:n});re=Us(o,Pk)+Us(l,Tk)+Us(d,kk)+Us(g,Ck)+re,s.processCode&&(re=s.processCode(re,M));var B;try{var de=new Function("self","RULES","formats","root","refVal","defaults","customRules","equal","ucs2length","ValidationError",re);B=de(n,m,f,e,o,d,g,bk,wk,xk),o[0]=B}catch(ae){throw n.logger.error("Error compiling schema, function code:",re),ae}return B.schema=M,B.errors=null,B.refs=i,B.refVal=o,B.root=ie?B:D,C&&(B.$async=!0),s.sourceCode===!0&&(B.source={code:re,patterns:l,defaults:d}),B}function E(M,D,K){D=Ls.url(M,D);var oe=i[D],ie,C;if(oe!==void 0)return ie=o[oe],C="refVal["+oe+"]",$(ie,C);if(!K&&e.refs){var re=e.refs[D];if(re!==void 0)return ie=e.refVal[re],C=I(D,ie),$(ie,C)}C=I(D);var B=Ls.call(n,_,e,D);if(B===void 0){var de=r&&r[D];de&&(B=Ls.inlineRef(de,s.inlineRefs)?de:yl.call(n,de,e,r,M))}if(B===void 0)S(D);else return R(D,B),$(B,C)}function I(M,D){var K=o.length;return o[K]=D,i[M]=K,"refVal"+K}function S(M){delete i[M]}function R(M,D){var K=i[M];o[K]=D}function $(M,D){return typeof M=="object"||typeof M=="boolean"?{code:D,schema:M,inline:!0}:{code:D,$async:M&&!!M.$async}}function z(M){var D=u[M];return D===void 0&&(D=u[M]=l.length,l[D]=M),"pattern"+D}function L(M){switch(typeof M){case"boolean":case"number":return""+M;case"string":return zs.toQuotedString(M);case"object":if(M===null)return"null";var D=_k(M),K=h[D];return K===void 0&&(K=h[D]=d.length,d[K]=M),"default"+K}}function F(M,D,K,oe){if(n._opts.validateSchema!==!1){var ie=M.definition.dependencies;if(ie&&!ie.every(function(xe){return Object.prototype.hasOwnProperty.call(K,xe)}))throw new Error("parent schema must have all required keywords: "+ie.join(","));var C=M.definition.validateSchema;if(C){var re=C(D);if(!re){var B="keyword schema is invalid: "+n.errorsText(C.errors);if(n._opts.validateSchema=="log")n.logger.error(B);else throw new Error(B)}}}var de=M.definition.compile,ae=M.definition.inline,ke=M.definition.macro,_e;if(de)_e=de.call(n,D,K,oe);else if(ke)_e=ke.call(n,D,K,oe),s.validateSchema!==!1&&n.validateSchema(_e,!0);else if(ae)_e=ae.call(n,oe,M.keyword,D,K);else if(_e=M.definition.validate,!_e)return;if(_e===void 0)throw new Error('custom keyword "'+M.keyword+'"failed to compile');var Pe=g.length;return g[Pe]=_e,{code:"customRule"+Pe,validate:_e}}}function Sk(t,e,r){var a=jf.call(this,t,e,r);return a>=0?{index:a,compiling:!0}:(a=this._compilations.length,this._compilations[a]={schema:t,root:e,baseId:r},{index:a,compiling:!1})}function Ik(t,e,r){var a=jf.call(this,t,e,r);a>=0&&this._compilations.splice(a,1)}function jf(t,e,r){for(var a=0;a<this._compilations.length;a++){var n=this._compilations[a];if(n.schema==t&&n.root==e&&n.baseId==r)return a}return-1}function Tk(t,e){return"var pattern"+t+" = new RegExp("+zs.toQuotedString(e[t])+");"}function kk(t){return"var default"+t+" = defaults["+t+"];"}function Pk(t,e){return e[t]===void 0?"":"var refVal"+t+" = refVal["+t+"];"}function Ck(t){return"var customRule"+t+" = customRules["+t+"];"}function Us(t,e){if(!t.length)return"";for(var r="",a=0;a<t.length;a++)r+=e(a,t);return r}var Lf={exports:{}},Fs=Lf.exports=function(){this._cache={}};Fs.prototype.put=function(e,r){this._cache[e]=r},Fs.prototype.get=function(e){return this._cache[e]},Fs.prototype.del=function(e){delete this._cache[e]},Fs.prototype.clear=function(){this._cache={}};var Rk=Lf.exports,Ok=Cn,$k=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Ak=[0,31,28,31,30,31,30,31,31,30,31,30,31],Nk=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,zf=/^(?=.{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,Mk=/^(?:[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,Dk=/^(?:[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,Uf=/^(?:(?:[^\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,Ff=/^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i,qf=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,Zf=/^(?:\/(?:[^~/]|~0|~1)*)*$/,Vf=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Bf=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,jk=qs;function qs(t){return t=t=="full"?"full":"fast",Ok.copy(qs[t])}qs.fast={date:/^\d\d\d\d-[0-1]\d-[0-3]\d$/,time:/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,"date-time":/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,"uri-template":Uf,url:Ff,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,hostname:zf,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,regex:Wf,uuid:qf,"json-pointer":Zf,"json-pointer-uri-fragment":Vf,"relative-json-pointer":Bf},qs.full={date:Hf,time:Jf,"date-time":Uk,uri:qk,"uri-reference":Dk,"uri-template":Uf,url:Ff,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:zf,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,regex:Wf,uuid:qf,"json-pointer":Zf,"json-pointer-uri-fragment":Vf,"relative-json-pointer":Bf};function Lk(t){return t%4===0&&(t%100!==0||t%400===0)}function Hf(t){var e=t.match($k);if(!e)return!1;var r=+e[1],a=+e[2],n=+e[3];return a>=1&&a<=12&&n>=1&&n<=(a==2&&Lk(r)?29:Ak[a])}function Jf(t,e){var r=t.match(Nk);if(!r)return!1;var a=r[1],n=r[2],s=r[3],o=r[5];return(a<=23&&n<=59&&s<=59||a==23&&n==59&&s==60)&&(!e||o)}var zk=/t|\s/i;function Uk(t){var e=t.split(zk);return e.length==2&&Hf(e[0])&&Jf(e[1],!0)}var Fk=/\/|:/;function qk(t){return Fk.test(t)&&Mk.test(t)}var Zk=/[^\\]\\Z/;function Wf(t){if(Zk.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}var Vk=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,d="data"+(o||""),h="valid"+s,g,c;if(i=="#"||i=="#/")e.isRoot?(g=e.async,c="validate"):(g=e.root.schema.$async===!0,c="root.refVal[0]");else{var p=e.resolveRef(e.baseId,i,e.isRoot);if(p===void 0){var f=e.MissingRefError.message(e.baseId,i);if(e.opts.missingRefs=="fail"){e.logger.error(f);var m=m||[];m.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '$ref' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { ref: '"+e.util.escapeQuotes(i)+"' } ",e.opts.messages!==!1&&(n+=" , message: 'can\\'t resolve reference "+e.util.escapeQuotes(i)+"' "),e.opts.verbose&&(n+=" , schema: "+e.util.toQuotedString(i)+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),n+=" } "):n+=" {} ";var v=n;n=m.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+v+"]); ":n+=" validate.errors = ["+v+"]; return false; ":n+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",u&&(n+=" if (false) { ")}else if(e.opts.missingRefs=="ignore")e.logger.warn(f),u&&(n+=" if (true) { ");else throw new e.MissingRefError(e.baseId,i,f)}else if(p.inline){var w=e.util.copy(e);w.level++;var y="valid"+w.level;w.schema=p.schema,w.schemaPath="",w.errSchemaPath=i;var _=e.validate(w).replace(/validate\.schema/g,p.code);n+=" "+_+" ",u&&(n+=" if ("+y+") { ")}else g=p.$async===!0||e.async&&p.$async!==!1,c=p.code}if(c){var m=m||[];m.push(n),n="",e.opts.passContext?n+=" "+c+".call(this, ":n+=" "+c+"( ",n+=" "+d+", (dataPath || '')",e.errorPath!='""'&&(n+=" + "+e.errorPath);var E=o?"data"+(o-1||""):"parentData",I=o?e.dataPathArr[o]:"parentDataProperty";n+=" , "+E+" , "+I+", rootData) ";var S=n;if(n=m.pop(),g){if(!e.async)throw new Error("async schema referenced by sync schema");u&&(n+=" var "+h+"; "),n+=" try { await "+S+"; ",u&&(n+=" "+h+" = true; "),n+=" } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; ",u&&(n+=" "+h+" = false; "),n+=" } ",u&&(n+=" if ("+h+") { ")}else n+=" if (!"+S+") { if (vErrors === null) vErrors = "+c+".errors; else vErrors = vErrors.concat("+c+".errors); errors = vErrors.length; } ",u&&(n+=" else { ")}return n},Bk=function(e,r,a){var n=" ",s=e.schema[r],o=e.schemaPath+e.util.getProperty(r),i=e.errSchemaPath+"/"+r,l=!e.opts.allErrors,u=e.util.copy(e),d="";u.level++;var h="valid"+u.level,g=u.baseId,c=!0,p=s;if(p)for(var f,m=-1,v=p.length-1;m<v;)f=p[m+=1],(e.opts.strictKeywords?typeof f=="object"&&Object.keys(f).length>0||f===!1:e.util.schemaHasRules(f,e.RULES.all))&&(c=!1,u.schema=f,u.schemaPath=o+"["+m+"]",u.errSchemaPath=i+"/"+m,n+=" "+e.validate(u)+" ",u.baseId=g,l&&(n+=" if ("+h+") { ",d+="}"));return l&&(c?n+=" if (true) { ":n+=" "+d.slice(0,-1)+" "),n},Hk=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,h="data"+(o||""),g="valid"+s,c="errs__"+s,p=e.util.copy(e),f="";p.level++;var m="valid"+p.level,v=i.every(function(R){return e.opts.strictKeywords?typeof R=="object"&&Object.keys(R).length>0||R===!1:e.util.schemaHasRules(R,e.RULES.all)});if(v){var w=p.baseId;n+=" var "+c+" = errors; var "+g+" = false; ";var y=e.compositeRule;e.compositeRule=p.compositeRule=!0;var _=i;if(_)for(var E,I=-1,S=_.length-1;I<S;)E=_[I+=1],p.schema=E,p.schemaPath=l+"["+I+"]",p.errSchemaPath=u+"/"+I,n+=" "+e.validate(p)+" ",p.baseId=w,n+=" "+g+" = "+g+" || "+m+"; if (!"+g+") { ",f+="}";e.compositeRule=p.compositeRule=y,n+=" "+f+" if (!"+g+") { var err = ",e.createErrors!==!1?(n+=" { keyword: 'anyOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: {} ",e.opts.messages!==!1&&(n+=" , message: 'should match some schema in anyOf' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&d&&(e.async?n+=" throw new ValidationError(vErrors); ":n+=" validate.errors = vErrors; return false; "),n+=" } else { errors = "+c+"; if (vErrors !== null) { if ("+c+") vErrors.length = "+c+"; else vErrors = null; } ",e.opts.allErrors&&(n+=" } ")}else d&&(n+=" if (true) { ");return n},Jk=function(e,r,a){var n=" ",s=e.schema[r],o=e.errSchemaPath+"/"+r;e.opts.allErrors;var i=e.util.toQuotedString(s);return e.opts.$comment===!0?n+=" console.log("+i+");":typeof e.opts.$comment=="function"&&(n+=" self._opts.$comment("+i+", "+e.util.toQuotedString(o)+", validate.root.schema);"),n},Wk=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,h="data"+(o||""),g="valid"+s,c=e.opts.$data&&i&&i.$data;c&&(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; "),c||(n+=" var schema"+s+" = validate.schema"+l+";"),n+="var "+g+" = equal("+h+", schema"+s+"); if (!"+g+") { ";var p=p||[];p.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'const' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { allowedValue: schema"+s+" } ",e.opts.messages!==!1&&(n+=" , message: 'should be equal to constant' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var f=n;return n=p.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+f+"]); ":n+=" validate.errors = ["+f+"]; return false; ":n+=" var err = "+f+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" }",d&&(n+=" else { "),n},Gk=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,h="data"+(o||""),g="valid"+s,c="errs__"+s,p=e.util.copy(e),f="";p.level++;var m="valid"+p.level,v="i"+s,w=p.dataLevel=e.dataLevel+1,y="data"+w,_=e.baseId,E=e.opts.strictKeywords?typeof i=="object"&&Object.keys(i).length>0||i===!1:e.util.schemaHasRules(i,e.RULES.all);if(n+="var "+c+" = errors;var "+g+";",E){var I=e.compositeRule;e.compositeRule=p.compositeRule=!0,p.schema=i,p.schemaPath=l,p.errSchemaPath=u,n+=" var "+m+" = false; for (var "+v+" = 0; "+v+" < "+h+".length; "+v+"++) { ",p.errorPath=e.util.getPathExpr(e.errorPath,v,e.opts.jsonPointers,!0);var S=h+"["+v+"]";p.dataPathArr[w]=v;var R=e.validate(p);p.baseId=_,e.util.varOccurences(R,y)<2?n+=" "+e.util.varReplace(R,y,S)+" ":n+=" var "+y+" = "+S+"; "+R+" ",n+=" if ("+m+") break; } ",e.compositeRule=p.compositeRule=I,n+=" "+f+" if (!"+m+") {"}else n+=" if ("+h+".length == 0) {";var $=$||[];$.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'contains' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: {} ",e.opts.messages!==!1&&(n+=" , message: 'should contain a valid item' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var z=n;return n=$.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+z+"]); ":n+=" validate.errors = ["+z+"]; return false; ":n+=" var err = "+z+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } else { ",E&&(n+=" errors = "+c+"; if (vErrors !== null) { if ("+c+") vErrors.length = "+c+"; else vErrors = null; } "),e.opts.allErrors&&(n+=" } "),n},Kk=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,h="data"+(o||""),g="errs__"+s,c=e.util.copy(e),p="";c.level++;var f="valid"+c.level,m={},v={},w=e.opts.ownProperties;for(I in i)if(I!="__proto__"){var y=i[I],_=Array.isArray(y)?v:m;_[I]=y}n+="var "+g+" = errors;";var E=e.errorPath;n+="var missing"+s+";";for(var I in v)if(_=v[I],_.length){if(n+=" if ( "+h+e.util.getProperty(I)+" !== undefined ",w&&(n+=" && Object.prototype.hasOwnProperty.call("+h+", '"+e.util.escapeQuotes(I)+"') "),d){n+=" && ( ";var S=_;if(S)for(var R,$=-1,z=S.length-1;$<z;){R=S[$+=1],$&&(n+=" || ");var L=e.util.getProperty(R),F=h+L;n+=" ( ( "+F+" === undefined ",w&&(n+=" || ! Object.prototype.hasOwnProperty.call("+h+", '"+e.util.escapeQuotes(R)+"') "),n+=") && (missing"+s+" = "+e.util.toQuotedString(e.opts.jsonPointers?R:L)+") ) "}n+=")) { ";var M="missing"+s,D="' + "+M+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.opts.jsonPointers?e.util.getPathExpr(E,M,!0):E+" + "+M);var K=K||[];K.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'dependencies' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { property: '"+e.util.escapeQuotes(I)+"', missingProperty: '"+D+"', depsCount: "+_.length+", deps: '"+e.util.escapeQuotes(_.length==1?_[0]:_.join(", "))+"' } ",e.opts.messages!==!1&&(n+=" , message: 'should have ",_.length==1?n+="property "+e.util.escapeQuotes(_[0]):n+="properties "+e.util.escapeQuotes(_.join(", ")),n+=" when property "+e.util.escapeQuotes(I)+" is present' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var oe=n;n=K.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+oe+"]); ":n+=" validate.errors = ["+oe+"]; return false; ":n+=" var err = "+oe+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else{n+=" ) { ";var ie=_;if(ie)for(var R,C=-1,re=ie.length-1;C<re;){R=ie[C+=1];var L=e.util.getProperty(R),D=e.util.escapeQuotes(R),F=h+L;e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(E,R,e.opts.jsonPointers)),n+=" if ( "+F+" === undefined ",w&&(n+=" || ! Object.prototype.hasOwnProperty.call("+h+", '"+e.util.escapeQuotes(R)+"') "),n+=") { var err = ",e.createErrors!==!1?(n+=" { keyword: 'dependencies' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { property: '"+e.util.escapeQuotes(I)+"', missingProperty: '"+D+"', depsCount: "+_.length+", deps: '"+e.util.escapeQuotes(_.length==1?_[0]:_.join(", "))+"' } ",e.opts.messages!==!1&&(n+=" , message: 'should have ",_.length==1?n+="property "+e.util.escapeQuotes(_[0]):n+="properties "+e.util.escapeQuotes(_.join(", ")),n+=" when property "+e.util.escapeQuotes(I)+" is present' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}n+=" } ",d&&(p+="}",n+=" else { ")}e.errorPath=E;var B=c.baseId;for(var I in m){var y=m[I];(e.opts.strictKeywords?typeof y=="object"&&Object.keys(y).length>0||y===!1:e.util.schemaHasRules(y,e.RULES.all))&&(n+=" "+f+" = true; if ( "+h+e.util.getProperty(I)+" !== undefined ",w&&(n+=" && Object.prototype.hasOwnProperty.call("+h+", '"+e.util.escapeQuotes(I)+"') "),n+=") { ",c.schema=y,c.schemaPath=l+e.util.getProperty(I),c.errSchemaPath=u+"/"+e.util.escapeFragment(I),n+=" "+e.validate(c)+" ",c.baseId=B,n+=" } ",d&&(n+=" if ("+f+") { ",p+="}"))}return d&&(n+=" "+p+" if ("+g+" == errors) {"),n},Qk=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,h="data"+(o||""),g="valid"+s,c=e.opts.$data&&i&&i.$data;c&&(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ");var p="i"+s,f="schema"+s;c||(n+=" var "+f+" = validate.schema"+l+";"),n+="var "+g+";",c&&(n+=" if (schema"+s+" === undefined) "+g+" = true; else if (!Array.isArray(schema"+s+")) "+g+" = false; else {"),n+=""+g+" = false;for (var "+p+"=0; "+p+"<"+f+".length; "+p+"++) if (equal("+h+", "+f+"["+p+"])) { "+g+" = true; break; }",c&&(n+=" } "),n+=" if (!"+g+") { ";var m=m||[];m.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'enum' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { allowedValues: schema"+s+" } ",e.opts.messages!==!1&&(n+=" , message: 'should be equal to one of the allowed values' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var v=n;return n=m.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+v+"]); ":n+=" validate.errors = ["+v+"]; return false; ":n+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" }",d&&(n+=" else { "),n},Yk=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,h="data"+(o||"");if(e.opts.format===!1)return d&&(n+=" if (true) { "),n;var g=e.opts.$data&&i&&i.$data,c;g?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",c="schema"+s):c=i;var p=e.opts.unknownFormats,f=Array.isArray(p);if(g){var m="format"+s,v="isObject"+s,w="formatType"+s;n+=" var "+m+" = formats["+c+"]; var "+v+" = typeof "+m+" == 'object' && !("+m+" instanceof RegExp) && "+m+".validate; var "+w+" = "+v+" && "+m+".type || 'string'; if ("+v+") { ",e.async&&(n+=" var async"+s+" = "+m+".async; "),n+=" "+m+" = "+m+".validate; } if ( ",g&&(n+=" ("+c+" !== undefined && typeof "+c+" != 'string') || "),n+=" (",p!="ignore"&&(n+=" ("+c+" && !"+m+" ",f&&(n+=" && self._opts.unknownFormats.indexOf("+c+") == -1 "),n+=") || "),n+=" ("+m+" && "+w+" == '"+a+"' && !(typeof "+m+" == 'function' ? ",e.async?n+=" (async"+s+" ? await "+m+"("+h+") : "+m+"("+h+")) ":n+=" "+m+"("+h+") ",n+=" : "+m+".test("+h+"))))) {"}else{var m=e.formats[i];if(!m){if(p=="ignore")return e.logger.warn('unknown format "'+i+'" ignored in schema at path "'+e.errSchemaPath+'"'),d&&(n+=" if (true) { "),n;if(f&&p.indexOf(i)>=0)return d&&(n+=" if (true) { "),n;throw new Error('unknown format "'+i+'" is used in schema at path "'+e.errSchemaPath+'"')}var v=typeof m=="object"&&!(m instanceof RegExp)&&m.validate,w=v&&m.type||"string";if(v){var y=m.async===!0;m=m.validate}if(w!=a)return d&&(n+=" if (true) { "),n;if(y){if(!e.async)throw new Error("async format in sync schema");var _="formats"+e.util.getProperty(i)+".validate";n+=" if (!(await "+_+"("+h+"))) { "}else{n+=" if (! ";var _="formats"+e.util.getProperty(i);v&&(_+=".validate"),typeof m=="function"?n+=" "+_+"("+h+") ":n+=" "+_+".test("+h+") ",n+=") { "}}var E=E||[];E.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'format' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { format: ",g?n+=""+c:n+=""+e.util.toQuotedString(i),n+=" } ",e.opts.messages!==!1&&(n+=` , message: 'should match format "`,g?n+="' + "+c+" + '":n+=""+e.util.escapeQuotes(i),n+=`"' `),e.opts.verbose&&(n+=" , schema: ",g?n+="validate.schema"+l:n+=""+e.util.toQuotedString(i),n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var I=n;return n=E.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+I+"]); ":n+=" validate.errors = ["+I+"]; return false; ":n+=" var err = "+I+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } ",d&&(n+=" else { "),n},Xk=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,h="data"+(o||""),g="valid"+s,c="errs__"+s,p=e.util.copy(e);p.level++;var f="valid"+p.level,m=e.schema.then,v=e.schema.else,w=m!==void 0&&(e.opts.strictKeywords?typeof m=="object"&&Object.keys(m).length>0||m===!1:e.util.schemaHasRules(m,e.RULES.all)),y=v!==void 0&&(e.opts.strictKeywords?typeof v=="object"&&Object.keys(v).length>0||v===!1:e.util.schemaHasRules(v,e.RULES.all)),_=p.baseId;if(w||y){var E;p.createErrors=!1,p.schema=i,p.schemaPath=l,p.errSchemaPath=u,n+=" var "+c+" = errors; var "+g+" = true; ";var I=e.compositeRule;e.compositeRule=p.compositeRule=!0,n+=" "+e.validate(p)+" ",p.baseId=_,p.createErrors=!0,n+=" errors = "+c+"; if (vErrors !== null) { if ("+c+") vErrors.length = "+c+"; else vErrors = null; } ",e.compositeRule=p.compositeRule=I,w?(n+=" if ("+f+") { ",p.schema=e.schema.then,p.schemaPath=e.schemaPath+".then",p.errSchemaPath=e.errSchemaPath+"/then",n+=" "+e.validate(p)+" ",p.baseId=_,n+=" "+g+" = "+f+"; ",w&&y?(E="ifClause"+s,n+=" var "+E+" = 'then'; "):E="'then'",n+=" } ",y&&(n+=" else { ")):n+=" if (!"+f+") { ",y&&(p.schema=e.schema.else,p.schemaPath=e.schemaPath+".else",p.errSchemaPath=e.errSchemaPath+"/else",n+=" "+e.validate(p)+" ",p.baseId=_,n+=" "+g+" = "+f+"; ",w&&y?(E="ifClause"+s,n+=" var "+E+" = 'else'; "):E="'else'",n+=" } "),n+=" if (!"+g+") { var err = ",e.createErrors!==!1?(n+=" { keyword: 'if' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { failingKeyword: "+E+" } ",e.opts.messages!==!1&&(n+=` , message: 'should match "' + `+E+` + '" schema' `),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&d&&(e.async?n+=" throw new ValidationError(vErrors); ":n+=" validate.errors = vErrors; return false; "),n+=" } ",d&&(n+=" else { ")}else d&&(n+=" if (true) { ");return n},eP=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,h="data"+(o||""),g="valid"+s,c="errs__"+s,p=e.util.copy(e),f="";p.level++;var m="valid"+p.level,v="i"+s,w=p.dataLevel=e.dataLevel+1,y="data"+w,_=e.baseId;if(n+="var "+c+" = errors;var "+g+";",Array.isArray(i)){var E=e.schema.additionalItems;if(E===!1){n+=" "+g+" = "+h+".length <= "+i.length+"; ";var I=u;u=e.errSchemaPath+"/additionalItems",n+=" if (!"+g+") { ";var S=S||[];S.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'additionalItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { limit: "+i.length+" } ",e.opts.messages!==!1&&(n+=" , message: 'should NOT have more than "+i.length+" items' "),e.opts.verbose&&(n+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var R=n;n=S.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+R+"]); ":n+=" validate.errors = ["+R+"]; return false; ":n+=" var err = "+R+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } ",u=I,d&&(f+="}",n+=" else { ")}var $=i;if($){for(var z,L=-1,F=$.length-1;L<F;)if(z=$[L+=1],e.opts.strictKeywords?typeof z=="object"&&Object.keys(z).length>0||z===!1:e.util.schemaHasRules(z,e.RULES.all)){n+=" "+m+" = true; if ("+h+".length > "+L+") { ";var M=h+"["+L+"]";p.schema=z,p.schemaPath=l+"["+L+"]",p.errSchemaPath=u+"/"+L,p.errorPath=e.util.getPathExpr(e.errorPath,L,e.opts.jsonPointers,!0),p.dataPathArr[w]=L;var D=e.validate(p);p.baseId=_,e.util.varOccurences(D,y)<2?n+=" "+e.util.varReplace(D,y,M)+" ":n+=" var "+y+" = "+M+"; "+D+" ",n+=" } ",d&&(n+=" if ("+m+") { ",f+="}")}}if(typeof E=="object"&&(e.opts.strictKeywords?typeof E=="object"&&Object.keys(E).length>0||E===!1:e.util.schemaHasRules(E,e.RULES.all))){p.schema=E,p.schemaPath=e.schemaPath+".additionalItems",p.errSchemaPath=e.errSchemaPath+"/additionalItems",n+=" "+m+" = true; if ("+h+".length > "+i.length+") { for (var "+v+" = "+i.length+"; "+v+" < "+h+".length; "+v+"++) { ",p.errorPath=e.util.getPathExpr(e.errorPath,v,e.opts.jsonPointers,!0);var M=h+"["+v+"]";p.dataPathArr[w]=v;var D=e.validate(p);p.baseId=_,e.util.varOccurences(D,y)<2?n+=" "+e.util.varReplace(D,y,M)+" ":n+=" var "+y+" = "+M+"; "+D+" ",d&&(n+=" if (!"+m+") break; "),n+=" } } ",d&&(n+=" if ("+m+") { ",f+="}")}}else if(e.opts.strictKeywords?typeof i=="object"&&Object.keys(i).length>0||i===!1:e.util.schemaHasRules(i,e.RULES.all)){p.schema=i,p.schemaPath=l,p.errSchemaPath=u,n+=" for (var "+v+" = 0; "+v+" < "+h+".length; "+v+"++) { ",p.errorPath=e.util.getPathExpr(e.errorPath,v,e.opts.jsonPointers,!0);var M=h+"["+v+"]";p.dataPathArr[w]=v;var D=e.validate(p);p.baseId=_,e.util.varOccurences(D,y)<2?n+=" "+e.util.varReplace(D,y,M)+" ":n+=" var "+y+" = "+M+"; "+D+" ",d&&(n+=" if (!"+m+") break; "),n+=" }"}return d&&(n+=" "+f+" if ("+c+" == errors) {"),n},Gf=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,_,h="data"+(o||""),g=e.opts.$data&&i&&i.$data,c;g?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",c="schema"+s):c=i;var p=r=="maximum",f=p?"exclusiveMaximum":"exclusiveMinimum",m=e.schema[f],v=e.opts.$data&&m&&m.$data,w=p?"<":">",y=p?">":"<",_=void 0;if(!(g||typeof i=="number"||i===void 0))throw new Error(r+" must be number");if(!(v||m===void 0||typeof m=="number"||typeof m=="boolean"))throw new Error(f+" must be number or boolean");if(v){var E=e.util.getData(m.$data,o,e.dataPathArr),I="exclusive"+s,S="exclType"+s,R="exclIsNumber"+s,$="op"+s,z="' + "+$+" + '";n+=" var schemaExcl"+s+" = "+E+"; ",E="schemaExcl"+s,n+=" var "+I+"; var "+S+" = typeof "+E+"; if ("+S+" != 'boolean' && "+S+" != 'undefined' && "+S+" != 'number') { ";var _=f,L=L||[];L.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(_||"_exclusiveLimit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: {} ",e.opts.messages!==!1&&(n+=" , message: '"+f+" should be boolean' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var F=n;n=L.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+F+"]); ":n+=" validate.errors = ["+F+"]; return false; ":n+=" var err = "+F+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } else if ( ",g&&(n+=" ("+c+" !== undefined && typeof "+c+" != 'number') || "),n+=" "+S+" == 'number' ? ( ("+I+" = "+c+" === undefined || "+E+" "+w+"= "+c+") ? "+h+" "+y+"= "+E+" : "+h+" "+y+" "+c+" ) : ( ("+I+" = "+E+" === true) ? "+h+" "+y+"= "+c+" : "+h+" "+y+" "+c+" ) || "+h+" !== "+h+") { var op"+s+" = "+I+" ? '"+w+"' : '"+w+"='; ",i===void 0&&(_=f,u=e.errSchemaPath+"/"+f,c=E,g=v)}else{var R=typeof m=="number",z=w;if(R&&g){var $="'"+z+"'";n+=" if ( ",g&&(n+=" ("+c+" !== undefined && typeof "+c+" != 'number') || "),n+=" ( "+c+" === undefined || "+m+" "+w+"= "+c+" ? "+h+" "+y+"= "+m+" : "+h+" "+y+" "+c+" ) || "+h+" !== "+h+") { "}else{R&&i===void 0?(I=!0,_=f,u=e.errSchemaPath+"/"+f,c=m,y+="="):(R&&(c=Math[p?"min":"max"](m,i)),m===(R?c:!0)?(I=!0,_=f,u=e.errSchemaPath+"/"+f,y+="="):(I=!1,z+="="));var $="'"+z+"'";n+=" if ( ",g&&(n+=" ("+c+" !== undefined && typeof "+c+" != 'number') || "),n+=" "+h+" "+y+" "+c+" || "+h+" !== "+h+") { "}}_=_||r;var L=L||[];L.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(_||"_limit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { comparison: "+$+", limit: "+c+", exclusive: "+I+" } ",e.opts.messages!==!1&&(n+=" , message: 'should be "+z+" ",g?n+="' + "+c:n+=""+c+"'"),e.opts.verbose&&(n+=" , schema: ",g?n+="validate.schema"+l:n+=""+i,n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var F=n;return n=L.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+F+"]); ":n+=" validate.errors = ["+F+"]; return false; ":n+=" var err = "+F+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } ",d&&(n+=" else { "),n},Kf=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,f,h="data"+(o||""),g=e.opts.$data&&i&&i.$data,c;if(g?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",c="schema"+s):c=i,!(g||typeof i=="number"))throw new Error(r+" must be number");var p=r=="maxItems"?">":"<";n+="if ( ",g&&(n+=" ("+c+" !== undefined && typeof "+c+" != 'number') || "),n+=" "+h+".length "+p+" "+c+") { ";var f=r,m=m||[];m.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(f||"_limitItems")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { limit: "+c+" } ",e.opts.messages!==!1&&(n+=" , message: 'should NOT have ",r=="maxItems"?n+="more":n+="fewer",n+=" than ",g?n+="' + "+c+" + '":n+=""+i,n+=" items' "),e.opts.verbose&&(n+=" , schema: ",g?n+="validate.schema"+l:n+=""+i,n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var v=n;return n=m.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+v+"]); ":n+=" validate.errors = ["+v+"]; return false; ":n+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+="} ",d&&(n+=" else { "),n},Qf=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,f,h="data"+(o||""),g=e.opts.$data&&i&&i.$data,c;if(g?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",c="schema"+s):c=i,!(g||typeof i=="number"))throw new Error(r+" must be number");var p=r=="maxLength"?">":"<";n+="if ( ",g&&(n+=" ("+c+" !== undefined && typeof "+c+" != 'number') || "),e.opts.unicode===!1?n+=" "+h+".length ":n+=" ucs2length("+h+") ",n+=" "+p+" "+c+") { ";var f=r,m=m||[];m.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(f||"_limitLength")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { limit: "+c+" } ",e.opts.messages!==!1&&(n+=" , message: 'should NOT be ",r=="maxLength"?n+="longer":n+="shorter",n+=" than ",g?n+="' + "+c+" + '":n+=""+i,n+=" characters' "),e.opts.verbose&&(n+=" , schema: ",g?n+="validate.schema"+l:n+=""+i,n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var v=n;return n=m.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+v+"]); ":n+=" validate.errors = ["+v+"]; return false; ":n+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+="} ",d&&(n+=" else { "),n},Yf=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,f,h="data"+(o||""),g=e.opts.$data&&i&&i.$data,c;if(g?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",c="schema"+s):c=i,!(g||typeof i=="number"))throw new Error(r+" must be number");var p=r=="maxProperties"?">":"<";n+="if ( ",g&&(n+=" ("+c+" !== undefined && typeof "+c+" != 'number') || "),n+=" Object.keys("+h+").length "+p+" "+c+") { ";var f=r,m=m||[];m.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(f||"_limitProperties")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { limit: "+c+" } ",e.opts.messages!==!1&&(n+=" , message: 'should NOT have ",r=="maxProperties"?n+="more":n+="fewer",n+=" than ",g?n+="' + "+c+" + '":n+=""+i,n+=" properties' "),e.opts.verbose&&(n+=" , schema: ",g?n+="validate.schema"+l:n+=""+i,n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var v=n;return n=m.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+v+"]); ":n+=" validate.errors = ["+v+"]; return false; ":n+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+="} ",d&&(n+=" else { "),n},tP=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,h="data"+(o||""),g=e.opts.$data&&i&&i.$data,c;if(g?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",c="schema"+s):c=i,!(g||typeof i=="number"))throw new Error(r+" must be number");n+="var division"+s+";if (",g&&(n+=" "+c+" !== undefined && ( typeof "+c+" != 'number' || "),n+=" (division"+s+" = "+h+" / "+c+", ",e.opts.multipleOfPrecision?n+=" Math.abs(Math.round(division"+s+") - division"+s+") > 1e-"+e.opts.multipleOfPrecision+" ":n+=" division"+s+" !== parseInt(division"+s+") ",n+=" ) ",g&&(n+=" ) "),n+=" ) { ";var p=p||[];p.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'multipleOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { multipleOf: "+c+" } ",e.opts.messages!==!1&&(n+=" , message: 'should be multiple of ",g?n+="' + "+c:n+=""+c+"'"),e.opts.verbose&&(n+=" , schema: ",g?n+="validate.schema"+l:n+=""+i,n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var f=n;return n=p.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+f+"]); ":n+=" validate.errors = ["+f+"]; return false; ":n+=" var err = "+f+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+="} ",d&&(n+=" else { "),n},rP=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,h="data"+(o||""),g="errs__"+s,c=e.util.copy(e);c.level++;var p="valid"+c.level;if(e.opts.strictKeywords?typeof i=="object"&&Object.keys(i).length>0||i===!1:e.util.schemaHasRules(i,e.RULES.all)){c.schema=i,c.schemaPath=l,c.errSchemaPath=u,n+=" var "+g+" = errors; ";var f=e.compositeRule;e.compositeRule=c.compositeRule=!0,c.createErrors=!1;var m;c.opts.allErrors&&(m=c.opts.allErrors,c.opts.allErrors=!1),n+=" "+e.validate(c)+" ",c.createErrors=!0,m&&(c.opts.allErrors=m),e.compositeRule=c.compositeRule=f,n+=" if ("+p+") { ";var v=v||[];v.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: {} ",e.opts.messages!==!1&&(n+=" , message: 'should NOT be valid' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var w=n;n=v.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+w+"]); ":n+=" validate.errors = ["+w+"]; return false; ":n+=" var err = "+w+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } else { errors = "+g+"; if (vErrors !== null) { if ("+g+") vErrors.length = "+g+"; else vErrors = null; } ",e.opts.allErrors&&(n+=" } ")}else n+=" var err = ",e.createErrors!==!1?(n+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: {} ",e.opts.messages!==!1&&(n+=" , message: 'should NOT be valid' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",d&&(n+=" if (false) { ");return n},nP=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,h="data"+(o||""),g="valid"+s,c="errs__"+s,p=e.util.copy(e),f="";p.level++;var m="valid"+p.level,v=p.baseId,w="prevValid"+s,y="passingSchemas"+s;n+="var "+c+" = errors , "+w+" = false , "+g+" = false , "+y+" = null; ";var _=e.compositeRule;e.compositeRule=p.compositeRule=!0;var E=i;if(E)for(var I,S=-1,R=E.length-1;S<R;)I=E[S+=1],(e.opts.strictKeywords?typeof I=="object"&&Object.keys(I).length>0||I===!1:e.util.schemaHasRules(I,e.RULES.all))?(p.schema=I,p.schemaPath=l+"["+S+"]",p.errSchemaPath=u+"/"+S,n+=" "+e.validate(p)+" ",p.baseId=v):n+=" var "+m+" = true; ",S&&(n+=" if ("+m+" && "+w+") { "+g+" = false; "+y+" = ["+y+", "+S+"]; } else { ",f+="}"),n+=" if ("+m+") { "+g+" = "+w+" = true; "+y+" = "+S+"; }";return e.compositeRule=p.compositeRule=_,n+=""+f+"if (!"+g+") { var err = ",e.createErrors!==!1?(n+=" { keyword: 'oneOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { passingSchemas: "+y+" } ",e.opts.messages!==!1&&(n+=" , message: 'should match exactly one schema in oneOf' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&d&&(e.async?n+=" throw new ValidationError(vErrors); ":n+=" validate.errors = vErrors; return false; "),n+="} else { errors = "+c+"; if (vErrors !== null) { if ("+c+") vErrors.length = "+c+"; else vErrors = null; }",e.opts.allErrors&&(n+=" } "),n},aP=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,h="data"+(o||""),g=e.opts.$data&&i&&i.$data,c;g?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",c="schema"+s):c=i;var p=g?"(new RegExp("+c+"))":e.usePattern(i);n+="if ( ",g&&(n+=" ("+c+" !== undefined && typeof "+c+" != 'string') || "),n+=" !"+p+".test("+h+") ) { ";var f=f||[];f.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'pattern' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { pattern: ",g?n+=""+c:n+=""+e.util.toQuotedString(i),n+=" } ",e.opts.messages!==!1&&(n+=` , message: 'should match pattern "`,g?n+="' + "+c+" + '":n+=""+e.util.escapeQuotes(i),n+=`"' `),e.opts.verbose&&(n+=" , schema: ",g?n+="validate.schema"+l:n+=""+e.util.toQuotedString(i),n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var m=n;return n=f.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+m+"]); ":n+=" validate.errors = ["+m+"]; return false; ":n+=" var err = "+m+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+="} ",d&&(n+=" else { "),n},sP=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,h="data"+(o||""),g="errs__"+s,c=e.util.copy(e),p="";c.level++;var f="valid"+c.level,m="key"+s,v="idx"+s,w=c.dataLevel=e.dataLevel+1,y="data"+w,_="dataProperties"+s,E=Object.keys(i||{}).filter(C),I=e.schema.patternProperties||{},S=Object.keys(I).filter(C),R=e.schema.additionalProperties,$=E.length||S.length,z=R===!1,L=typeof R=="object"&&Object.keys(R).length,F=e.opts.removeAdditional,M=z||L||F,D=e.opts.ownProperties,K=e.baseId,oe=e.schema.required;if(oe&&!(e.opts.$data&&oe.$data)&&oe.length<e.opts.loopRequired)var ie=e.util.toHash(oe);function C(mt){return mt!=="__proto__"}if(n+="var "+g+" = errors;var "+f+" = true;",D&&(n+=" var "+_+" = undefined;"),M){if(D?n+=" "+_+" = "+_+" || Object.keys("+h+"); for (var "+v+"=0; "+v+"<"+_+".length; "+v+"++) { var "+m+" = "+_+"["+v+"]; ":n+=" for (var "+m+" in "+h+") { ",$){if(n+=" var isAdditional"+s+" = !(false ",E.length)if(E.length>8)n+=" || validate.schema"+l+".hasOwnProperty("+m+") ";else{var re=E;if(re)for(var B,de=-1,ae=re.length-1;de<ae;)B=re[de+=1],n+=" || "+m+" == "+e.util.toQuotedString(B)+" "}if(S.length){var ke=S;if(ke)for(var _e,Pe=-1,xe=ke.length-1;Pe<xe;)_e=ke[Pe+=1],n+=" || "+e.usePattern(_e)+".test("+m+") "}n+=" ); if (isAdditional"+s+") { "}if(F=="all")n+=" delete "+h+"["+m+"]; ";else{var ve=e.errorPath,Re="' + "+m+" + '";if(e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers)),z)if(F)n+=" delete "+h+"["+m+"]; ";else{n+=" "+f+" = false; ";var pt=u;u=e.errSchemaPath+"/additionalProperties";var Ne=Ne||[];Ne.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'additionalProperties' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { additionalProperty: '"+Re+"' } ",e.opts.messages!==!1&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is an invalid additional property":n+="should NOT have additional properties",n+="' "),e.opts.verbose&&(n+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var we=n;n=Ne.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+we+"]); ":n+=" validate.errors = ["+we+"]; return false; ":n+=" var err = "+we+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",u=pt,d&&(n+=" break; ")}else if(L)if(F=="failing"){n+=" var "+g+" = errors; ";var bt=e.compositeRule;e.compositeRule=c.compositeRule=!0,c.schema=R,c.schemaPath=e.schemaPath+".additionalProperties",c.errSchemaPath=e.errSchemaPath+"/additionalProperties",c.errorPath=e.opts._errorDataPathProperty?e.errorPath:e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers);var be=h+"["+m+"]";c.dataPathArr[w]=m;var se=e.validate(c);c.baseId=K,e.util.varOccurences(se,y)<2?n+=" "+e.util.varReplace(se,y,be)+" ":n+=" var "+y+" = "+be+"; "+se+" ",n+=" if (!"+f+") { errors = "+g+"; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete "+h+"["+m+"]; } ",e.compositeRule=c.compositeRule=bt}else{c.schema=R,c.schemaPath=e.schemaPath+".additionalProperties",c.errSchemaPath=e.errSchemaPath+"/additionalProperties",c.errorPath=e.opts._errorDataPathProperty?e.errorPath:e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers);var be=h+"["+m+"]";c.dataPathArr[w]=m;var se=e.validate(c);c.baseId=K,e.util.varOccurences(se,y)<2?n+=" "+e.util.varReplace(se,y,be)+" ":n+=" var "+y+" = "+be+"; "+se+" ",d&&(n+=" if (!"+f+") break; ")}e.errorPath=ve}$&&(n+=" } "),n+=" } ",d&&(n+=" if ("+f+") { ",p+="}")}var Se=e.opts.useDefaults&&!e.compositeRule;if(E.length){var Ie=E;if(Ie)for(var B,ye=-1,Xe=Ie.length-1;ye<Xe;){B=Ie[ye+=1];var Le=i[B];if(e.opts.strictKeywords?typeof Le=="object"&&Object.keys(Le).length>0||Le===!1:e.util.schemaHasRules(Le,e.RULES.all)){var J=e.util.getProperty(B),be=h+J,Me=Se&&Le.default!==void 0;c.schema=Le,c.schemaPath=l+J,c.errSchemaPath=u+"/"+e.util.escapeFragment(B),c.errorPath=e.util.getPath(e.errorPath,B,e.opts.jsonPointers),c.dataPathArr[w]=e.util.toQuotedString(B);var se=e.validate(c);if(c.baseId=K,e.util.varOccurences(se,y)<2){se=e.util.varReplace(se,y,be);var ze=be}else{var ze=y;n+=" var "+y+" = "+be+"; "}if(Me)n+=" "+se+" ";else{if(ie&&ie[B]){n+=" if ( "+ze+" === undefined ",D&&(n+=" || ! Object.prototype.hasOwnProperty.call("+h+", '"+e.util.escapeQuotes(B)+"') "),n+=") { "+f+" = false; ";var ve=e.errorPath,pt=u,pe=e.util.escapeQuotes(B);e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(ve,B,e.opts.jsonPointers)),u=e.errSchemaPath+"/required";var Ne=Ne||[];Ne.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { missingProperty: '"+pe+"' } ",e.opts.messages!==!1&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is a required property":n+="should have required property \\'"+pe+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var we=n;n=Ne.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+we+"]); ":n+=" validate.errors = ["+we+"]; return false; ":n+=" var err = "+we+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",u=pt,e.errorPath=ve,n+=" } else { "}else d?(n+=" if ( "+ze+" === undefined ",D&&(n+=" || ! Object.prototype.hasOwnProperty.call("+h+", '"+e.util.escapeQuotes(B)+"') "),n+=") { "+f+" = true; } else { "):(n+=" if ("+ze+" !== undefined ",D&&(n+=" && Object.prototype.hasOwnProperty.call("+h+", '"+e.util.escapeQuotes(B)+"') "),n+=" ) { ");n+=" "+se+" } "}}d&&(n+=" if ("+f+") { ",p+="}")}}if(S.length){var Be=S;if(Be)for(var _e,hr=-1,Ft=Be.length-1;hr<Ft;){_e=Be[hr+=1];var Le=I[_e];if(e.opts.strictKeywords?typeof Le=="object"&&Object.keys(Le).length>0||Le===!1:e.util.schemaHasRules(Le,e.RULES.all)){c.schema=Le,c.schemaPath=e.schemaPath+".patternProperties"+e.util.getProperty(_e),c.errSchemaPath=e.errSchemaPath+"/patternProperties/"+e.util.escapeFragment(_e),D?n+=" "+_+" = "+_+" || Object.keys("+h+"); for (var "+v+"=0; "+v+"<"+_+".length; "+v+"++) { var "+m+" = "+_+"["+v+"]; ":n+=" for (var "+m+" in "+h+") { ",n+=" if ("+e.usePattern(_e)+".test("+m+")) { ",c.errorPath=e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers);var be=h+"["+m+"]";c.dataPathArr[w]=m;var se=e.validate(c);c.baseId=K,e.util.varOccurences(se,y)<2?n+=" "+e.util.varReplace(se,y,be)+" ":n+=" var "+y+" = "+be+"; "+se+" ",d&&(n+=" if (!"+f+") break; "),n+=" } ",d&&(n+=" else "+f+" = true; "),n+=" } ",d&&(n+=" if ("+f+") { ",p+="}")}}}return d&&(n+=" "+p+" if ("+g+" == errors) {"),n},oP=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,h="data"+(o||""),g="errs__"+s,c=e.util.copy(e),p="";c.level++;var f="valid"+c.level;if(n+="var "+g+" = errors;",e.opts.strictKeywords?typeof i=="object"&&Object.keys(i).length>0||i===!1:e.util.schemaHasRules(i,e.RULES.all)){c.schema=i,c.schemaPath=l,c.errSchemaPath=u;var m="key"+s,v="idx"+s,w="i"+s,y="' + "+m+" + '",_=c.dataLevel=e.dataLevel+1,E="data"+_,I="dataProperties"+s,S=e.opts.ownProperties,R=e.baseId;S&&(n+=" var "+I+" = undefined; "),S?n+=" "+I+" = "+I+" || Object.keys("+h+"); for (var "+v+"=0; "+v+"<"+I+".length; "+v+"++) { var "+m+" = "+I+"["+v+"]; ":n+=" for (var "+m+" in "+h+") { ",n+=" var startErrs"+s+" = errors; ";var $=m,z=e.compositeRule;e.compositeRule=c.compositeRule=!0;var L=e.validate(c);c.baseId=R,e.util.varOccurences(L,E)<2?n+=" "+e.util.varReplace(L,E,$)+" ":n+=" var "+E+" = "+$+"; "+L+" ",e.compositeRule=c.compositeRule=z,n+=" if (!"+f+") { for (var "+w+"=startErrs"+s+"; "+w+"<errors; "+w+"++) { vErrors["+w+"].propertyName = "+m+"; } var err = ",e.createErrors!==!1?(n+=" { keyword: 'propertyNames' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { propertyName: '"+y+"' } ",e.opts.messages!==!1&&(n+=" , message: 'property name \\'"+y+"\\' is invalid' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&d&&(e.async?n+=" throw new ValidationError(vErrors); ":n+=" validate.errors = vErrors; return false; "),d&&(n+=" break; "),n+=" } }"}return d&&(n+=" "+p+" if ("+g+" == errors) {"),n},iP=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,h="data"+(o||""),g="valid"+s,c=e.opts.$data&&i&&i.$data;c&&(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ");var p="schema"+s;if(!c)if(i.length<e.opts.loopRequired&&e.schema.properties&&Object.keys(e.schema.properties).length){var f=[],m=i;if(m)for(var v,w=-1,y=m.length-1;w<y;){v=m[w+=1];var _=e.schema.properties[v];_&&(e.opts.strictKeywords?typeof _=="object"&&Object.keys(_).length>0||_===!1:e.util.schemaHasRules(_,e.RULES.all))||(f[f.length]=v)}}else var f=i;if(c||f.length){var E=e.errorPath,I=c||f.length>=e.opts.loopRequired,S=e.opts.ownProperties;if(d)if(n+=" var missing"+s+"; ",I){c||(n+=" var "+p+" = validate.schema"+l+"; ");var R="i"+s,$="schema"+s+"["+R+"]",z="' + "+$+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(E,$,e.opts.jsonPointers)),n+=" var "+g+" = true; ",c&&(n+=" if (schema"+s+" === undefined) "+g+" = true; else if (!Array.isArray(schema"+s+")) "+g+" = false; else {"),n+=" for (var "+R+" = 0; "+R+" < "+p+".length; "+R+"++) { "+g+" = "+h+"["+p+"["+R+"]] !== undefined ",S&&(n+=" && Object.prototype.hasOwnProperty.call("+h+", "+p+"["+R+"]) "),n+="; if (!"+g+") break; } ",c&&(n+=" } "),n+=" if (!"+g+") { ";var L=L||[];L.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { missingProperty: '"+z+"' } ",e.opts.messages!==!1&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is a required property":n+="should have required property \\'"+z+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var F=n;n=L.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+F+"]); ":n+=" validate.errors = ["+F+"]; return false; ":n+=" var err = "+F+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } else { "}else{n+=" if ( ";var M=f;if(M)for(var D,R=-1,K=M.length-1;R<K;){D=M[R+=1],R&&(n+=" || ");var oe=e.util.getProperty(D),ie=h+oe;n+=" ( ( "+ie+" === undefined ",S&&(n+=" || ! Object.prototype.hasOwnProperty.call("+h+", '"+e.util.escapeQuotes(D)+"') "),n+=") && (missing"+s+" = "+e.util.toQuotedString(e.opts.jsonPointers?D:oe)+") ) "}n+=") { ";var $="missing"+s,z="' + "+$+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.opts.jsonPointers?e.util.getPathExpr(E,$,!0):E+" + "+$);var L=L||[];L.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { missingProperty: '"+z+"' } ",e.opts.messages!==!1&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is a required property":n+="should have required property \\'"+z+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var F=n;n=L.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+F+"]); ":n+=" validate.errors = ["+F+"]; return false; ":n+=" var err = "+F+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } else { "}else if(I){c||(n+=" var "+p+" = validate.schema"+l+"; ");var R="i"+s,$="schema"+s+"["+R+"]",z="' + "+$+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(E,$,e.opts.jsonPointers)),c&&(n+=" if ("+p+" && !Array.isArray("+p+")) { var err = ",e.createErrors!==!1?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { missingProperty: '"+z+"' } ",e.opts.messages!==!1&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is a required property":n+="should have required property \\'"+z+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if ("+p+" !== undefined) { "),n+=" for (var "+R+" = 0; "+R+" < "+p+".length; "+R+"++) { if ("+h+"["+p+"["+R+"]] === undefined ",S&&(n+=" || ! Object.prototype.hasOwnProperty.call("+h+", "+p+"["+R+"]) "),n+=") { var err = ",e.createErrors!==!1?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { missingProperty: '"+z+"' } ",e.opts.messages!==!1&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is a required property":n+="should have required property \\'"+z+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ",c&&(n+=" } ")}else{var C=f;if(C)for(var D,re=-1,B=C.length-1;re<B;){D=C[re+=1];var oe=e.util.getProperty(D),z=e.util.escapeQuotes(D),ie=h+oe;e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(E,D,e.opts.jsonPointers)),n+=" if ( "+ie+" === undefined ",S&&(n+=" || ! Object.prototype.hasOwnProperty.call("+h+", '"+e.util.escapeQuotes(D)+"') "),n+=") { var err = ",e.createErrors!==!1?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { missingProperty: '"+z+"' } ",e.opts.messages!==!1&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is a required property":n+="should have required property \\'"+z+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}e.errorPath=E}else d&&(n+=" if (true) {");return n},lP=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,h="data"+(o||""),g="valid"+s,c=e.opts.$data&&i&&i.$data,p;if(c?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",p="schema"+s):p=i,(i||c)&&e.opts.uniqueItems!==!1){c&&(n+=" var "+g+"; if ("+p+" === false || "+p+" === undefined) "+g+" = true; else if (typeof "+p+" != 'boolean') "+g+" = false; else { "),n+=" var i = "+h+".length , "+g+" = true , j; if (i > 1) { ";var f=e.schema.items&&e.schema.items.type,m=Array.isArray(f);if(!f||f=="object"||f=="array"||m&&(f.indexOf("object")>=0||f.indexOf("array")>=0))n+=" outer: for (;i--;) { for (j = i; j--;) { if (equal("+h+"[i], "+h+"[j])) { "+g+" = false; break outer; } } } ";else{n+=" var itemIndices = {}, item; for (;i--;) { var item = "+h+"[i]; ";var v="checkDataType"+(m?"s":"");n+=" if ("+e.util[v](f,"item",e.opts.strictNumbers,!0)+") continue; ",m&&(n+=` if (typeof item == 'string') item = '"' + item; `),n+=" if (typeof itemIndices[item] == 'number') { "+g+" = false; j = itemIndices[item]; break; } itemIndices[item] = i; } "}n+=" } ",c&&(n+=" } "),n+=" if (!"+g+") { ";var w=w||[];w.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'uniqueItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { i: i, j: j } ",e.opts.messages!==!1&&(n+=" , message: 'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)' "),e.opts.verbose&&(n+=" , schema: ",c?n+="validate.schema"+l:n+=""+i,n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var y=n;n=w.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+y+"]); ":n+=" validate.errors = ["+y+"]; return false; ":n+=" var err = "+y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } ",d&&(n+=" else { ")}else d&&(n+=" if (true) { ");return n},uP={$ref:Vk,allOf:Bk,anyOf:Hk,$comment:Jk,const:Wk,contains:Gk,dependencies:Kk,enum:Qk,format:Yk,if:Xk,items:eP,maximum:Gf,minimum:Gf,maxItems:Kf,minItems:Kf,maxLength:Qf,minLength:Qf,maxProperties:Yf,minProperties:Yf,multipleOf:tP,not:rP,oneOf:nP,pattern:aP,properties:sP,propertyNames:oP,required:iP,uniqueItems:lP,validate:Nf},Xf=uP,_l=Cn.toHash,cP=function(){var e=[{type:"number",rules:[{maximum:["exclusiveMaximum"]},{minimum:["exclusiveMinimum"]},"multipleOf","format"]},{type:"string",rules:["maxLength","minLength","pattern","format"]},{type:"array",rules:["maxItems","minItems","items","contains","uniqueItems"]},{type:"object",rules:["maxProperties","minProperties","required","dependencies","propertyNames",{properties:["additionalProperties","patternProperties"]}]},{rules:["$ref","const","enum","not","anyOf","oneOf","allOf","if"]}],r=["type","$comment"],a=["$schema","$id","id","$data","$async","title","description","default","definitions","examples","readOnly","writeOnly","contentMediaType","contentEncoding","additionalItems","then","else"],n=["number","integer","string","array","object","boolean","null"];return e.all=_l(r),e.types=_l(n),e.forEach(function(s){s.rules=s.rules.map(function(o){var i;if(typeof o=="object"){var l=Object.keys(o)[0];i=o[l],o=l,i.forEach(function(d){r.push(d),e.all[d]=!0})}r.push(o);var u=e.all[o]={keyword:o,code:Xf[o],implements:i};return u}),e.all.$comment={keyword:"$comment",code:Xf.$comment},s.type&&(e.types[s.type]=s)}),e.keywords=_l(r.concat(a)),e.custom={},e},em=["multipleOf","maximum","exclusiveMaximum","minimum","exclusiveMinimum","maxLength","minLength","pattern","additionalItems","maxItems","minItems","uniqueItems","maxProperties","minProperties","required","additionalProperties","enum","format","const"],dP=function(t,e){for(var r=0;r<e.length;r++){t=JSON.parse(JSON.stringify(t));var a=e[r].split("/"),n=t,s;for(s=1;s<a.length;s++)n=n[a[s]];for(s=0;s<em.length;s++){var o=em[s],i=n[o];i&&(n[o]={anyOf:[i,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]})}}return t},pP=vl.MissingRef,hP=tm;function tm(t,e,r){var a=this;if(typeof this._opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");typeof e=="function"&&(r=e,e=void 0);var n=s(t).then(function(){var i=a._addSchema(t,void 0,e);return i.validate||o(i)});return r&&n.then(function(i){r(null,i)},r),n;function s(i){var l=i.$schema;return l&&!a.getSchema(l)?tm.call(a,{$ref:l},!0):Promise.resolve()}function o(i){try{return a._compile(i)}catch(u){if(u instanceof pP)return l(u);throw u}function l(u){var d=u.missingSchema;if(c(d))throw new Error("Schema "+d+" is loaded but "+u.missingRef+" cannot be resolved");var h=a._loadingSchemas[d];return h||(h=a._loadingSchemas[d]=a._opts.loadSchema(d),h.then(g,g)),h.then(function(p){if(!c(d))return s(p).then(function(){c(d)||a.addSchema(p,d,void 0,e)})}).then(function(){return o(i)});function g(){delete a._loadingSchemas[d]}function c(p){return a._refs[p]||a._schemas[p]}}}}var fP=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,h,g="data"+(o||""),c="valid"+s,p="errs__"+s,f=e.opts.$data&&i&&i.$data,m;f?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",m="schema"+s):m=i;var v=this,w="definition"+s,y=v.definition,_="",E,I,S,R,$;if(f&&y.$data){$="keywordValidate"+s;var z=y.validateSchema;n+=" var "+w+" = RULES.custom['"+r+"'].definition; var "+$+" = "+w+".validate;"}else{if(R=e.useCustomRule(v,i,e.schema,e),!R)return;m="validate.schema"+l,$=R.code,E=y.compile,I=y.inline,S=y.macro}var L=$+".errors",F="i"+s,M="ruleErr"+s,D=y.async;if(D&&!e.async)throw new Error("async keyword in sync schema");if(I||S||(n+=""+L+" = null;"),n+="var "+p+" = errors;var "+c+";",f&&y.$data&&(_+="}",n+=" if ("+m+" === undefined) { "+c+" = true; } else { ",z&&(_+="}",n+=" "+c+" = "+w+".validateSchema("+m+"); if ("+c+") { ")),I)y.statements?n+=" "+R.validate+" ":n+=" "+c+" = "+R.validate+"; ";else if(S){var K=e.util.copy(e),_="";K.level++;var oe="valid"+K.level;K.schema=R.validate,K.schemaPath="";var ie=e.compositeRule;e.compositeRule=K.compositeRule=!0;var C=e.validate(K).replace(/validate\.schema/g,$);e.compositeRule=K.compositeRule=ie,n+=" "+C}else{var re=re||[];re.push(n),n="",n+=" "+$+".call( ",e.opts.passContext?n+="this":n+="self",E||y.schema===!1?n+=" , "+g+" ":n+=" , "+m+" , "+g+" , validate.schema"+e.schemaPath+" ",n+=" , (dataPath || '')",e.errorPath!='""'&&(n+=" + "+e.errorPath);var B=o?"data"+(o-1||""):"parentData",de=o?e.dataPathArr[o]:"parentDataProperty";n+=" , "+B+" , "+de+" , rootData ) ";var ae=n;n=re.pop(),y.errors===!1?(n+=" "+c+" = ",D&&(n+="await "),n+=""+ae+"; "):D?(L="customErrors"+s,n+=" var "+L+" = null; try { "+c+" = await "+ae+"; } catch (e) { "+c+" = false; if (e instanceof ValidationError) "+L+" = e.errors; else throw e; } "):n+=" "+L+" = null; "+c+" = "+ae+"; "}if(y.modifying&&(n+=" if ("+B+") "+g+" = "+B+"["+de+"];"),n+=""+_,y.valid)d&&(n+=" if (true) { ");else{n+=" if ( ",y.valid===void 0?(n+=" !",S?n+=""+oe:n+=""+c):n+=" "+!y.valid+" ",n+=") { ",h=v.keyword;var re=re||[];re.push(n),n="";var re=re||[];re.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(h||"custom")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { keyword: '"+v.keyword+"' } ",e.opts.messages!==!1&&(n+=` , message: 'should pass "`+v.keyword+`" keyword validation' `),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+g+" "),n+=" } "):n+=" {} ";var ke=n;n=re.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+ke+"]); ":n+=" validate.errors = ["+ke+"]; return false; ":n+=" var err = "+ke+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";var _e=n;n=re.pop(),I?y.errors?y.errors!="full"&&(n+=" for (var "+F+"="+p+"; "+F+"<errors; "+F+"++) { var "+M+" = vErrors["+F+"]; if ("+M+".dataPath === undefined) "+M+".dataPath = (dataPath || '') + "+e.errorPath+"; if ("+M+".schemaPath === undefined) { "+M+'.schemaPath = "'+u+'"; } ',e.opts.verbose&&(n+=" "+M+".schema = "+m+"; "+M+".data = "+g+"; "),n+=" } "):y.errors===!1?n+=" "+_e+" ":(n+=" if ("+p+" == errors) { "+_e+" } else { for (var "+F+"="+p+"; "+F+"<errors; "+F+"++) { var "+M+" = vErrors["+F+"]; if ("+M+".dataPath === undefined) "+M+".dataPath = (dataPath || '') + "+e.errorPath+"; if ("+M+".schemaPath === undefined) { "+M+'.schemaPath = "'+u+'"; } ',e.opts.verbose&&(n+=" "+M+".schema = "+m+"; "+M+".data = "+g+"; "),n+=" } } "):S?(n+=" var err = ",e.createErrors!==!1?(n+=" { keyword: '"+(h||"custom")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { keyword: '"+v.keyword+"' } ",e.opts.messages!==!1&&(n+=` , message: 'should pass "`+v.keyword+`" keyword validation' `),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+g+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&d&&(e.async?n+=" throw new ValidationError(vErrors); ":n+=" validate.errors = vErrors; return false; ")):y.errors===!1?n+=" "+_e+" ":(n+=" if (Array.isArray("+L+")) { if (vErrors === null) vErrors = "+L+"; else vErrors = vErrors.concat("+L+"); errors = vErrors.length; for (var "+F+"="+p+"; "+F+"<errors; "+F+"++) { var "+M+" = vErrors["+F+"]; if ("+M+".dataPath === undefined) "+M+".dataPath = (dataPath || '') + "+e.errorPath+"; "+M+'.schemaPath = "'+u+'"; ',e.opts.verbose&&(n+=" "+M+".schema = "+m+"; "+M+".data = "+g+"; "),n+=" } } else { "+_e+" } "),n+=" } ",d&&(n+=" else { ")}return n};const rm={$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 nm=rm,mP={$id:"https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js",definitions:{simpleTypes:nm.definitions.simpleTypes},type:"object",dependencies:{schema:["validate"],$data:["validate"],statements:["inline"],valid:{not:{required:["macro"]}}},properties:{type:nm.properties.type,schema:{type:"boolean"},statements:{type:"boolean"},dependencies:{type:"array",items:{type:"string"}},metaSchema:{type:"object"},modifying:{type:"boolean"},valid:{type:"boolean"},$data:{type:"boolean"},async:{type:"boolean"},errors:{anyOf:[{type:"boolean"},{const:"full"}]}}},vP=/^[a-z_$][a-z0-9_$-]*$/i,gP=fP,yP=mP,_P={add:wP,get:bP,remove:xP,validate:wl};function wP(t,e){var r=this.RULES;if(r.keywords[t])throw new Error("Keyword "+t+" is already defined");if(!vP.test(t))throw new Error("Keyword "+t+" is not a valid identifier");if(e){this.validateKeyword(e,!0);var a=e.type;if(Array.isArray(a))for(var n=0;n<a.length;n++)o(t,a[n],e);else o(t,a,e);var s=e.metaSchema;s&&(e.$data&&this._opts.$data&&(s={anyOf:[s,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]}),e.validateSchema=this.compile(s,!0))}r.keywords[t]=r.all[t]=!0;function o(i,l,u){for(var d,h=0;h<r.length;h++){var g=r[h];if(g.type==l){d=g;break}}d||(d={type:l,rules:[]},r.push(d));var c={keyword:i,definition:u,custom:!0,code:gP,implements:u.implements};d.rules.push(c),r.custom[i]=c}return this}function bP(t){var e=this.RULES.custom[t];return e?e.definition:this.RULES.keywords[t]||!1}function xP(t){var e=this.RULES;delete e.keywords[t],delete e.all[t],delete e.custom[t];for(var r=0;r<e.length;r++)for(var a=e[r].rules,n=0;n<a.length;n++)if(a[n].keyword==t){a.splice(n,1);break}return this}function wl(t,e){wl.errors=null;var r=this._validateKeyword=this._validateKeyword||this.compile(yP,!0);if(r(t))return!0;if(wl.errors=r.errors,e)throw new Error("custom keyword definition is invalid: "+this.errorsText(r.errors));return!1}const EP={$schema:"http://json-schema.org/draft-07/schema#",$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON Schema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1};var am=Ek,cn=dl,SP=Rk,sm=kf,IP=Af,TP=jk,kP=cP,om=dP,im=Cn,PP=et;et.prototype.validate=RP,et.prototype.compile=OP,et.prototype.addSchema=$P,et.prototype.addMetaSchema=AP,et.prototype.validateSchema=NP,et.prototype.getSchema=DP,et.prototype.removeSchema=LP,et.prototype.addFormat=HP,et.prototype.errorsText=BP,et.prototype._addSchema=zP,et.prototype._compile=UP,et.prototype.compileAsync=hP;var Zs=_P;et.prototype.addKeyword=Zs.add,et.prototype.getKeyword=Zs.get,et.prototype.removeKeyword=Zs.remove,et.prototype.validateKeyword=Zs.validate;var lm=vl;et.ValidationError=lm.Validation,et.MissingRefError=lm.MissingRef,et.$dataMetaSchema=om;var Vs="http://json-schema.org/draft-07/schema",um=["removeAdditional","useDefaults","coerceTypes","strictDefaults"],CP=["/properties"];function et(t){if(!(this instanceof et))return new et(t);t=this._opts=im.copy(t)||{},YP(this),this._schemas={},this._refs={},this._fragments={},this._formats=TP(t.format),this._cache=t.cache||new SP,this._loadingSchemas={},this._compilations=[],this.RULES=kP(),this._getId=FP(t),t.loopRequired=t.loopRequired||1/0,t.errorDataPath=="property"&&(t._errorDataPathProperty=!0),t.serialize===void 0&&(t.serialize=IP),this._metaOpts=QP(this),t.formats&&GP(this),t.keywords&&KP(this),JP(this),typeof t.meta=="object"&&this.addMetaSchema(t.meta),t.nullable&&this.addKeyword("nullable",{metaSchema:{type:"boolean"}}),WP(this)}function RP(t,e){var r;if(typeof t=="string"){if(r=this.getSchema(t),!r)throw new Error('no schema with key or ref "'+t+'"')}else{var a=this._addSchema(t);r=a.validate||this._compile(a)}var n=r(e);return r.$async!==!0&&(this.errors=r.errors),n}function OP(t,e){var r=this._addSchema(t,void 0,e);return r.validate||this._compile(r)}function $P(t,e,r,a){if(Array.isArray(t)){for(var n=0;n<t.length;n++)this.addSchema(t[n],void 0,r,a);return this}var s=this._getId(t);if(s!==void 0&&typeof s!="string")throw new Error("schema id must be string");return e=cn.normalizeId(e||s),dm(this,e),this._schemas[e]=this._addSchema(t,r,a,!0),this}function AP(t,e,r){return this.addSchema(t,e,r,!0),this}function NP(t,e){var r=t.$schema;if(r!==void 0&&typeof r!="string")throw new Error("$schema must be a string");if(r=r||this._opts.defaultMeta||MP(this),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;var a=this.validate(r,t);if(!a&&e){var n="schema is invalid: "+this.errorsText();if(this._opts.validateSchema=="log")this.logger.error(n);else throw new Error(n)}return a}function MP(t){var e=t._opts.meta;return t._opts.defaultMeta=typeof e=="object"?t._getId(e)||e:t.getSchema(Vs)?Vs:void 0,t._opts.defaultMeta}function DP(t){var e=cm(this,t);switch(typeof e){case"object":return e.validate||this._compile(e);case"string":return this.getSchema(e);case"undefined":return jP(this,t)}}function jP(t,e){var r=cn.schema.call(t,{schema:{}},e);if(r){var a=r.schema,n=r.root,s=r.baseId,o=am.call(t,a,n,void 0,s);return t._fragments[e]=new sm({ref:e,fragment:!0,schema:a,root:n,baseId:s,validate:o}),o}}function cm(t,e){return e=cn.normalizeId(e),t._schemas[e]||t._refs[e]||t._fragments[e]}function LP(t){if(t instanceof RegExp)return Bs(this,this._schemas,t),Bs(this,this._refs,t),this;switch(typeof t){case"undefined":return Bs(this,this._schemas),Bs(this,this._refs),this._cache.clear(),this;case"string":var e=cm(this,t);return e&&this._cache.del(e.cacheKey),delete this._schemas[t],delete this._refs[t],this;case"object":var r=this._opts.serialize,a=r?r(t):t;this._cache.del(a);var n=this._getId(t);n&&(n=cn.normalizeId(n),delete this._schemas[n],delete this._refs[n])}return this}function Bs(t,e,r){for(var a in e){var n=e[a];!n.meta&&(!r||r.test(a))&&(t._cache.del(n.cacheKey),delete e[a])}}function zP(t,e,r,a){if(typeof t!="object"&&typeof t!="boolean")throw new Error("schema should be object or boolean");var n=this._opts.serialize,s=n?n(t):t,o=this._cache.get(s);if(o)return o;a=a||this._opts.addUsedSchema!==!1;var i=cn.normalizeId(this._getId(t));i&&a&&dm(this,i);var l=this._opts.validateSchema!==!1&&!e,u;l&&!(u=i&&i==cn.normalizeId(t.$schema))&&this.validateSchema(t,!0);var d=cn.ids.call(this,t),h=new sm({id:i,schema:t,localRefs:d,cacheKey:s,meta:r});return i[0]!="#"&&a&&(this._refs[i]=h),this._cache.put(s,h),l&&u&&this.validateSchema(t,!0),h}function UP(t,e){if(t.compiling)return t.validate=n,n.schema=t.schema,n.errors=null,n.root=e||n,t.schema.$async===!0&&(n.$async=!0),n;t.compiling=!0;var r;t.meta&&(r=this._opts,this._opts=this._metaOpts);var a;try{a=am.call(this,t.schema,e,t.localRefs)}catch(s){throw delete t.validate,s}finally{t.compiling=!1,t.meta&&(this._opts=r)}return t.validate=a,t.refs=a.refs,t.refVal=a.refVal,t.root=a.root,a;function n(){var s=t.validate,o=s.apply(this,arguments);return n.errors=s.errors,o}}function FP(t){switch(t.schemaId){case"auto":return VP;case"id":return qP;default:return ZP}}function qP(t){return t.$id&&this.logger.warn("schema $id ignored",t.$id),t.id}function ZP(t){return t.id&&this.logger.warn("schema id ignored",t.id),t.$id}function VP(t){if(t.$id&&t.id&&t.$id!=t.id)throw new Error("schema $id is different from id");return t.$id||t.id}function BP(t,e){if(t=t||this.errors,!t)return"No errors";e=e||{};for(var r=e.separator===void 0?", ":e.separator,a=e.dataVar===void 0?"data":e.dataVar,n="",s=0;s<t.length;s++){var o=t[s];o&&(n+=a+o.dataPath+" "+o.message+r)}return n.slice(0,-r.length)}function HP(t,e){return typeof e=="string"&&(e=new RegExp(e)),this._formats[t]=e,this}function JP(t){var e;if(t._opts.$data&&(e=EP,t.addMetaSchema(e,e.$id,!0)),t._opts.meta!==!1){var r=rm;t._opts.$data&&(r=om(r,CP)),t.addMetaSchema(r,Vs,!0),t._refs["http://json-schema.org/schema"]=Vs}}function WP(t){var e=t._opts.schemas;if(e)if(Array.isArray(e))t.addSchema(e);else for(var r in e)t.addSchema(e[r],r)}function GP(t){for(var e in t._opts.formats){var r=t._opts.formats[e];t.addFormat(e,r)}}function KP(t){for(var e in t._opts.keywords){var r=t._opts.keywords[e];t.addKeyword(e,r)}}function dm(t,e){if(t._schemas[e]||t._refs[e])throw new Error('schema with key or id "'+e+'" already exists')}function QP(t){for(var e=im.copy(t._opts),r=0;r<um.length;r++)delete e[um[r]];return e}function YP(t){var e=t._opts.logger;if(e===!1)t.logger={log:bl,warn:bl,error:bl};else{if(e===void 0&&(e=console),!(typeof e=="object"&&e.log&&e.warn&&e.error))throw new Error("logger must implement log, warn and error methods");t.logger=e}}function bl(){}const XP=sb(PP);class Hs extends FT{constructor(e,r){var a;super(r),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._capabilities=(a=r==null?void 0:r.capabilities)!==null&&a!==void 0?a:{},this._ajv=new XP}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=qT(this._capabilities,e)}assertCapability(e,r){var a;if(!(!((a=this._serverCapabilities)===null||a===void 0)&&a[e]))throw new Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),e.sessionId===void 0)try{const a=await this.request({method:"initialize",params:{protocolVersion:_s,capabilities:this._capabilities,clientInfo:this._clientInfo}},dh,r);if(a===void 0)throw new Error(`Server sent invalid initialize result: ${a}`);if(!jE.includes(a.protocolVersion))throw new Error(`Server's protocol version is not supported: ${a.protocolVersion}`);this._serverCapabilities=a.capabilities,this._serverVersion=a.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(a.protocolVersion),this._instructions=a.instructions,await this.notification({method:"notifications/initialized"})}catch(a){throw this.close(),a}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){var r,a,n,s,o;switch(e){case"logging/setLevel":if(!(!((r=this._serverCapabilities)===null||r===void 0)&&r.logging))throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!(!((a=this._serverCapabilities)===null||a===void 0)&&a.prompts))throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n.resources))throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!(!((s=this._serverCapabilities)===null||s===void 0)&&s.tools))throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!(!((o=this._serverCapabilities)===null||o===void 0)&&o.completions))throw new Error(`Server does not support completions (required for ${e})`);break}}assertNotificationCapability(e){var r;switch(e){case"notifications/roots/list_changed":if(!(!((r=this._capabilities.roots)===null||r===void 0)&&r.listChanged))throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break}}async ping(e){return this.request({method:"ping"},on,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},Nh,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},on,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},Sh,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},xh,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},gh,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},yh,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},_h,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},on,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},on,r)}async callTool(e,r=Ss,a){const n=await this.request({method:"tools/call",params:e},r,a),s=this.getToolOutputValidator(e.name);if(s){if(!n.structuredContent&&!n.isError)throw new Nr(ir.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(n.structuredContent)try{if(!s(n.structuredContent))throw new Nr(ir.InvalidParams,`Structured content does not match the tool's output schema: ${this._ajv.errorsText(s.errors)}`)}catch(o){throw o instanceof Nr?o:new Nr(ir.InvalidParams,`Failed to validate structured content: ${o instanceof Error?o.message:String(o)}`)}}return n}cacheToolOutputSchemas(e){this._cachedToolOutputValidators.clear();for(const r of e)if(r.outputSchema)try{const a=this._ajv.compile(r.outputSchema);this._cachedToolOutputValidators.set(r.name,a)}catch{}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,r){const a=await this.request({method:"tools/list",params:e},Th,r);return this.cacheToolOutputSchemas(a.tools),a}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}class pm extends Event{constructor(e,r){var a,n;super(e),this.code=(a=r==null?void 0:r.code)!=null?a:void 0,this.message=(n=r==null?void 0:r.message)!=null?n:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,r,a){return a(hm(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(hm(this),r)}}function eC(t){const e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function xl(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(xl).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${xl(t.cause)}`:t.message:`${t}`}function hm(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var fm=t=>{throw TypeError(t)},El=(t,e,r)=>e.has(t)||fm("Cannot "+r),Ee=(t,e,r)=>(El(t,e,"read from private field"),r?r.call(t):e.get(t)),ut=(t,e,r)=>e.has(t)?fm("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),We=(t,e,r,a)=>(El(t,e,"write to private field"),e.set(t,r),r),Er=(t,e,r)=>(El(t,e,"access private method"),r),Tt,dn,Rn,Js,Ws,xa,On,Ea,Lr,$n,An,Nn,Sa,Qt,Sl,Il,Tl,mm,kl,Pl,Ia,Cl,Rl;class Gs extends EventTarget{constructor(e,r){var a,n;super(),ut(this,Qt),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,ut(this,Tt),ut(this,dn),ut(this,Rn),ut(this,Js),ut(this,Ws),ut(this,xa),ut(this,On),ut(this,Ea,null),ut(this,Lr),ut(this,$n),ut(this,An,null),ut(this,Nn,null),ut(this,Sa,null),ut(this,Il,async s=>{var o;Ee(this,$n).reset();const{body:i,redirected:l,status:u,headers:d}=s;if(u===204){Er(this,Qt,Ia).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?We(this,Rn,new URL(s.url)):We(this,Rn,void 0),u!==200){Er(this,Qt,Ia).call(this,`Non-200 status code (${u})`,u);return}if(!(d.get("content-type")||"").startsWith("text/event-stream")){Er(this,Qt,Ia).call(this,'Invalid content type, expected "text/event-stream"',u);return}if(Ee(this,Tt)===this.CLOSED)return;We(this,Tt,this.OPEN);const h=new Event("open");if((o=Ee(this,Sa))==null||o.call(this,h),this.dispatchEvent(h),typeof i!="object"||!i||!("getReader"in i)){Er(this,Qt,Ia).call(this,"Invalid response body, expected a web ReadableStream",u),this.close();return}const g=new TextDecoder,c=i.getReader();let p=!0;do{const{done:f,value:m}=await c.read();m&&Ee(this,$n).feed(g.decode(m,{stream:!f})),f&&(p=!1,Ee(this,$n).reset(),Er(this,Qt,Cl).call(this))}while(p)}),ut(this,Tl,s=>{We(this,Lr,void 0),!(s.name==="AbortError"||s.type==="aborted")&&Er(this,Qt,Cl).call(this,xl(s))}),ut(this,kl,s=>{typeof s.id=="string"&&We(this,Ea,s.id);const o=new MessageEvent(s.event||"message",{data:s.data,origin:Ee(this,Rn)?Ee(this,Rn).origin:Ee(this,dn).origin,lastEventId:s.id||""});Ee(this,Nn)&&(!s.event||s.event==="message")&&Ee(this,Nn).call(this,o),this.dispatchEvent(o)}),ut(this,Pl,s=>{We(this,xa,s)}),ut(this,Rl,()=>{We(this,On,void 0),Ee(this,Tt)===this.CONNECTING&&Er(this,Qt,Sl).call(this)});try{if(e instanceof URL)We(this,dn,e);else if(typeof e=="string")We(this,dn,new URL(e,tC()));else throw new Error("Invalid URL")}catch{throw eC("An invalid or illegal string was specified")}We(this,$n,Zh({onEvent:Ee(this,kl),onRetry:Ee(this,Pl)})),We(this,Tt,this.CONNECTING),We(this,xa,3e3),We(this,Ws,(a=r==null?void 0:r.fetch)!=null?a:globalThis.fetch),We(this,Js,(n=r==null?void 0:r.withCredentials)!=null?n:!1),Er(this,Qt,Sl).call(this)}get readyState(){return Ee(this,Tt)}get url(){return Ee(this,dn).href}get withCredentials(){return Ee(this,Js)}get onerror(){return Ee(this,An)}set onerror(e){We(this,An,e)}get onmessage(){return Ee(this,Nn)}set onmessage(e){We(this,Nn,e)}get onopen(){return Ee(this,Sa)}set onopen(e){We(this,Sa,e)}addEventListener(e,r,a){const n=r;super.addEventListener(e,n,a)}removeEventListener(e,r,a){const n=r;super.removeEventListener(e,n,a)}close(){Ee(this,On)&&clearTimeout(Ee(this,On)),Ee(this,Tt)!==this.CLOSED&&(Ee(this,Lr)&&Ee(this,Lr).abort(),We(this,Tt,this.CLOSED),We(this,Lr,void 0))}}Tt=new WeakMap,dn=new WeakMap,Rn=new WeakMap,Js=new WeakMap,Ws=new WeakMap,xa=new WeakMap,On=new WeakMap,Ea=new WeakMap,Lr=new WeakMap,$n=new WeakMap,An=new WeakMap,Nn=new WeakMap,Sa=new WeakMap,Qt=new WeakSet,Sl=function(){We(this,Tt,this.CONNECTING),We(this,Lr,new AbortController),Ee(this,Ws)(Ee(this,dn),Er(this,Qt,mm).call(this)).then(Ee(this,Il)).catch(Ee(this,Tl))},Il=new WeakMap,Tl=new WeakMap,mm=function(){var t;const e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Ee(this,Ea)?{"Last-Event-ID":Ee(this,Ea)}:void 0},cache:"no-store",signal:(t=Ee(this,Lr))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},kl=new WeakMap,Pl=new WeakMap,Ia=function(t,e){var r;Ee(this,Tt)!==this.CLOSED&&We(this,Tt,this.CLOSED);const a=new pm("error",{code:e,message:t});(r=Ee(this,An))==null||r.call(this,a),this.dispatchEvent(a)},Cl=function(t,e){var r;if(Ee(this,Tt)===this.CLOSED)return;We(this,Tt,this.CONNECTING);const a=new pm("error",{code:e,message:t});(r=Ee(this,An))==null||r.call(this,a),this.dispatchEvent(a),We(this,On,setTimeout(Ee(this,Rl),Ee(this,xa)))},Rl=new WeakMap,Gs.CONNECTING=0,Gs.OPEN=1,Gs.CLOSED=2;function tC(){const t="document"in globalThis?globalThis.document:void 0;return t&&typeof t=="object"&&"baseURI"in t&&typeof t.baseURI=="string"?t.baseURI:void 0}class rC extends Error{constructor(e,r,a){super(`SSE error: ${r}`),this.code=e,this.event=a}}class Ol{constructor(e,r){this._url=e,this._resourceMetadataUrl=void 0,this._eventSourceInit=r==null?void 0:r.eventSourceInit,this._requestInit=r==null?void 0:r.requestInit,this._authProvider=r==null?void 0:r.authProvider,this._fetch=r==null?void 0:r.fetch}async _authThenStart(){var e;if(!this._authProvider)throw new Gt("No auth provider");let r;try{r=await Pn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(a){throw(e=this.onerror)===null||e===void 0||e.call(this,a),a}if(r!=="AUTHORIZED")throw new Gt;return await this._startOrAuth()}async _commonHeaders(){var e;const r={};if(this._authProvider){const a=await this._authProvider.tokens();a&&(r.Authorization=`Bearer ${a.access_token}`)}return this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion),new Headers({...r,...(e=this._requestInit)===null||e===void 0?void 0:e.headers})}_startOrAuth(){var e,r,a;const n=(a=(r=(e=this===null||this===void 0?void 0:this._eventSourceInit)===null||e===void 0?void 0:e.fetch)!==null&&r!==void 0?r:this._fetch)!==null&&a!==void 0?a:fetch;return new Promise((s,o)=>{this._eventSource=new Gs(this._url.href,{...this._eventSourceInit,fetch:async(i,l)=>{const u=await this._commonHeaders();u.set("Accept","text/event-stream");const d=await n(i,{...l,headers:u});return d.status===401&&d.headers.has("www-authenticate")&&(this._resourceMetadataUrl=Ji(d)),d}}),this._abortController=new AbortController,this._eventSource.onerror=i=>{var l;if(i.code===401&&this._authProvider){this._authThenStart().then(s,o);return}const u=new rC(i.code,i.message,i);o(u),(l=this.onerror)===null||l===void 0||l.call(this,u)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",i=>{var l;const u=i;try{if(this._endpoint=new URL(u.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(d){o(d),(l=this.onerror)===null||l===void 0||l.call(this,d),this.close();return}s()}),this._eventSource.onmessage=i=>{var l,u;const d=i;let h;try{h=sn.parse(JSON.parse(d.data))}catch(g){(l=this.onerror)===null||l===void 0||l.call(this,g);return}(u=this.onmessage)===null||u===void 0||u.call(this,h)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new Gt("No auth provider");if(await Pn(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new Gt("Failed to authorize")}async close(){var e,r,a;(e=this._abortController)===null||e===void 0||e.abort(),(r=this._eventSource)===null||r===void 0||r.close(),(a=this.onclose)===null||a===void 0||a.call(this)}async send(e){var r,a,n;if(!this._endpoint)throw new Error("Not connected");try{const s=await this._commonHeaders();s.set("content-type","application/json");const o={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:(r=this._abortController)===null||r===void 0?void 0:r.signal},i=await((a=this._fetch)!==null&&a!==void 0?a:fetch)(this._endpoint,o);if(!i.ok){if(i.status===401&&this._authProvider){if(this._resourceMetadataUrl=Ji(i),await Pn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new Gt;return this.send(e)}const l=await i.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${i.status}): ${l}`)}}catch(s){throw(n=this.onerror)===null||n===void 0||n.call(this,s),s}}setProtocolVersion(e){this._protocolVersion=e}}const nC="mcp";class vm{constructor(e){this._url=e}start(){if(this._socket)throw new Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,r)=>{this._socket=new WebSocket(this._url,nC),this._socket.onerror=a=>{var n;const s="error"in a?a.error:new Error(`WebSocket error: ${JSON.stringify(a)}`);r(s),(n=this.onerror)===null||n===void 0||n.call(this,s)},this._socket.onopen=()=>{e()},this._socket.onclose=()=>{var a;(a=this.onclose)===null||a===void 0||a.call(this)},this._socket.onmessage=a=>{var n,s;let o;try{o=sn.parse(JSON.parse(a.data))}catch(i){(n=this.onerror)===null||n===void 0||n.call(this,i);return}(s=this.onmessage)===null||s===void 0||s.call(this,o)}})}async close(){var e;(e=this._socket)===null||e===void 0||e.close()}send(e){return new Promise((r,a)=>{var n;if(!this._socket){a(new Error("Not connected"));return}(n=this._socket)===null||n===void 0||n.send(JSON.stringify(e)),r()})}}function Ks(){const t=["224340fQYLJj","function","onmessage","port2","341XVdnBD","313767JEBgqL","950bpstaX","1354759gUhUbE","wRKyh","onclose","2044SvCTUj","endpoint","24msSkHx","164VuWYGY","mOWMr","EkZCC","addEventListener","postMessage","120705iyGzUz","8878392ivIdKn","close","_listen","3619482FaLQHc","start","_endpoint","kgkem","bzNYT","MessageChannel transport error: ","stringify","onmessageerror","HvyCv","undefined","Jwyua","message","_globalObject","parse","authInfo","thraG","220pGvxgp","_port","EGhzU","onerror","data","MhriV"];return Ks=function(){return t},Ks()}(function(t,e){const r=gt,a=gt,n=t();for(;;)try{if(parseInt(r(417))/1*(parseInt(r(421))/2)+parseInt(r(433))/3+parseInt(r(424))/4*(-parseInt(a(429))/5)+parseInt(a(423))/6*(-parseInt(a(418))/7)+-parseInt(a(430))/8+-parseInt(r(416))/9*(-parseInt(r(405))/10)+-parseInt(r(415))/11*(-parseInt(r(411))/12)===e)break;n.push(n.shift())}catch{n.push(n.shift())}})(Ks,650197);const aC=()=>{const t=gt,e={EGhzU:function(r,a){return r!==a},kIrDB:"undefined",llYQe:function(r,a){return r!==a},PZfJg:function(r,a){return r(a)},Jwyua:"return this"};return typeof globalThis<"u"?globalThis:e[t(407)](typeof window,e.kIrDB)?window:e.llYQe(typeof global,e.kIrDB)?global:typeof self!==t(398)?self:e.PZfJg(Function,e[t(399)])()},sC=(t,e,r)=>{const a=gt,n=gt,s={};s[a(410)]=n(398),s.dBkaX=function(i,l){return i===l},s[n(393)]="function";const o=s;typeof window!==o[n(410)]?t.postMessage(e,"*",r):n(428)in t&&o.dBkaX(typeof t.postMessage,o[a(393)])&&t.postMessage(e,r)};class gm{constructor(e){const r=gt;this[r(406)]=e}async start(){const e=gt,r=gt;this[e(406)]&&(this[e(406)][e(413)]=a=>{var n,s;const o=e,i=r;try{const l=sn[o(402)](a.data[o(400)]);(n=this[o(413)])==null||n.call(this,l,a[i(409)].extra)}catch(l){const u=new Error("MessageChannel failed to parse message: "+l);(s=this[i(408)])==null||s.call(this,u)}},this._port[e(396)]=a=>{var n;const s=r,o=r,i=new Error(s(394)+JSON[o(395)](a));(n=this.onerror)==null||n.call(this,i)},this[e(406)][e(434)]())}async send(e,r){const a={lEyuq:function(n){return n()},YihNw:function(n,s){return n(s)}};return new Promise((n,s)=>{var o;const i=gt,l=gt;try{const u={};u[i(403)]=r==null?void 0:r[i(403)];const d={};d[l(400)]=e,d.extra=u,this[l(406)]&&this[i(406)].postMessage(d),a.lEyuq(n)}catch(u){const d=u instanceof Error?u:new Error(a.YihNw(String,u));(o=this[l(408)])==null||o.call(this,d),s(d)}})}async close(){var e,r;const a=gt,n=gt;(e=this._port)==null||e[a(431)](),this._port=void 0,(r=this[n(420)])==null||r.call(this)}}class oC extends gm{constructor(e,r=aC()){const a=gt,n=gt,s={EkZCC:function(i,l,u,d){return i(l,u,d)}};super(),this[a(391)]=e,this[n(401)]=r;const o=new MessageChannel;this[n(406)]=o.port1,s[n(426)](sC,this[a(401)],{endpoint:this[n(391)]},[o[n(414)]])}}function gt(t,e){const r=Ks();return gt=function(a,n){return a=a-(17*-491+-669+9407),r[a]},gt(t,e)}(function(t,e){const r=qe,a=qe,n=t();for(;;)try{if(parseInt(r(355))/1+-parseInt(r(356))/2*(-parseInt(r(373))/3)+-parseInt(r(337))/4+parseInt(a(357))/5+-parseInt(a(389))/6*(-parseInt(r(396))/7)+parseInt(a(325))/8*(parseInt(r(382))/9)+-parseInt(r(366))/10===e)break;n.push(n.shift())}catch{n.push(n.shift())}})(Qs,-763475+-52067*10+1724410);const iC=async(t,e,r)=>{var a;const n=qe,s=qe,o={};o[n(345)]="tools/list",o.rqstG="tools/call",o.WqUnk="resources/list",o[n(329)]=s(358),o[n(365)]=n(335),o.ookoz="resources/unsubscribe",o[n(385)]=n(340),o.VTIWq="prompts/list",o.SkoRK=n(376),o.QUtUV=n(388),o.XtowM=s(332);const i=o,{id:l,method:u,params:d}=r;let h={};switch(u){case i[s(345)]:h=await e.listTools(d);break;case i.rqstG:h=await e.callTool(d);break;case i[n(334)]:h=await e[n(350)](d);break;case i[s(329)]:h=await e.listResourceTemplates(d);break;case n(372):h=await e[n(383)](d);break;case i.HgYgW:h=await e.subscribeResource(d);break;case i.ookoz:h=await e.unsubscribeResource(d);break;case i[n(385)]:h=await e.getPrompt(d);break;case i.VTIWq:h=await e.listPrompts(d);break;case i[n(344)]:h=await e[n(376)]();break;case i.QUtUV:h=await e.complete(d);break;case n(390):h=await e[n(336)](d==null?void 0:d.level);break}const g={};g[n(361)]=h,g[n(394)]=i[n(364)],g.id=l,await((a=t==null?void 0:t.transport)==null?void 0:a[n(392)](g))},lC=async(t,e,r)=>{var a;const n=qe,s=qe,o={};o.jQBBS="sampling/createMessage",o.EZqgC="elicitation/create",o[n(370)]=s(376),o.aVeaL=s(332);const i=o,{id:l,method:u,params:d}=r;let h={};switch(u){case n(368):const c={};c.method=u,c[s(367)]=d,h=await e.request(c,Dh);break;case i[s(391)]:const p={};p.method=u,p[s(367)]=d,h=await e[s(381)](p,Oh);break;case i.EZqgC:const f={};f.method=u,f.params=d,h=await e.request(f,Ah);break;case i[s(370)]:const m={};m.method=u,h=await e[s(381)](m,on);break}const g={};return g[s(361)]=h,g.jsonrpc=i[s(387)],g.id=l,await((a=t==null?void 0:t[n(371)])==null?void 0:a.send(g)),h},uC=(t,e)=>{const r=qe,a={gXsjT:function(s,o){return s===o},oegpC:r(351),lZOUC:function(s,o,i,l){return s(o,i,l)},ifIKG:"2.0"},n=t._onrequest;t._onrequest=async(s,o)=>{var i,l,u,d,h;const g=r,c=r,{id:p,method:f}=s;try{a[g(333)](f,a.oegpC)?await n[g(386)](t,s,o):await a.lZOUC(iC,t,e,s)}catch(m){const{code:v,message:w,data:y}=m;try{if(v){const _={};_.code=v,_.message=w,_.data=y;const E={};E.error=_,E[g(394)]=a[c(331)],E.id=p,await((i=t==null?void 0:t.transport)==null?void 0:i.send(E))}else(u=(l=t==null?void 0:t[c(371)])==null?void 0:l.onerror)==null||u.call(l,m)}catch(_){(h=(d=t==null?void 0:t[g(371)])==null?void 0:d.onerror)==null||h.call(d,_)}}}},cC=(t,e)=>{const r=qe,a=qe,n={};n[r(363)]=function(o,i){return o!==i},n[r(398)]=r(353),n.hzhyg="notifications/cancelled";const s=n;t._onnotification=async o=>{var i,l;const u=r,d=a,{method:h,params:g}=o;if(s[u(363)](h,s[d(398)])&&(s[u(363)](h,s.hzhyg)||g!=null&&g.forward))try{await e.notification(o)}catch(c){(l=(i=t==null?void 0:t.transport)==null?void 0:i.onerror)==null||l.call(i,c)}}},dC=(t,e)=>async r=>{var a,n,s,o,i;const l=qe,u=qe,d={};d.SEmWX=l(332);const h=d;try{return await lC(t,e,r)}catch(g){const{code:c,message:p,data:f}=g;try{if(c){const m={};m[u(377)]=c,m.message=p,m.data=f;const v={};v[u(348)]=m,v.jsonrpc=h[l(338)],v.id=r.id,await((a=t==null?void 0:t.transport)==null?void 0:a[u(392)](v))}else(s=(n=t==null?void 0:t.transport)==null?void 0:n[u(339)])==null||s.call(n,g)}catch(m){(i=(o=t==null?void 0:t[l(371)])==null?void 0:o[u(339)])==null||i.call(o,m)}}},pC=(t,e)=>async r=>{var a,n,s;const o=qe,i=qe,l={};l.dtUgZ=function(g,c){return g!==c},l.jgCIb=o(353),l.uUjKY="2.0";const u=l,{method:d,params:h}=r;if(u.dtUgZ(d,u.jgCIb)&&(d!==o(400)||h!=null&&h.forward))try{const g={...r};g[o(394)]=u[i(352)],await((a=e==null?void 0:e[o(371)])==null?void 0:a[o(392)](g))}catch(g){(s=(n=t==null?void 0:t[o(371)])==null?void 0:n[i(339)])==null||s.call(n,g)}};function qe(t,e){const r=Qs();return qe=function(a,n){return a=a-(9*-113+-1439*-1+-97),r[a]},qe(t,e)}const hC=(t,e)=>async r=>{var a,n,s,o,i,l;const u=qe,d=qe,h={};h[u(401)]=d(332);const g=h;try{await((a=e==null?void 0:e.transport)==null?void 0:a.send(r))}catch(c){const{code:p,message:f,data:m}=c;try{if(p){const v={};v.code=p,v[u(399)]=f,v.data=m;const w={};w[u(348)]=v,w[u(394)]=g.OhJjz,w.id=r.id,await((n=t==null?void 0:t[u(371)])==null?void 0:n.send(w))}else(o=(s=t==null?void 0:t.transport)==null?void 0:s[d(339)])==null||o.call(s,c)}catch(v){(l=(i=t==null?void 0:t.transport)==null?void 0:i.onerror)==null||l.call(i,v)}}},$l=()=>{const t=qe,e=qe,r={vnkqu:function(u,d){return u!==d},wxDWr:function(u,d){return u(d)},GdkkV:function(u,d){return u===d}},a=[],n=(u,d)=>{const h=qe,g=qe;if(d){const c=[];for(const p of a)try{c.push(p(u,d))}catch{}for(const p of c)if(r[h(379)](p,null))return p}else for(const c of a)try{r[g(343)](c,u)}catch{}},s=u=>{const d=qe;r[d(384)](typeof u,d(369))&&!a.includes(u)&&a.push(u)},o=u=>{const d=a.indexOf(u);d!==-1&&a.splice(d,1*-6854+8*-33+7119)},i=()=>{const u=qe;a[u(374)]=7102*1+5522+-526*24},l={};return l[t(346)]=n,l[e(330)]=s,l.removeListener=o,l[t(359)]=i,l},fC=t=>{const e=qe,r=qe,a={xwPeb:function(n){return n()},Mfvzm:function(n){return n()}};{const{handleListener:n,addListener:s,removeListener:o,clearListener:i}=a[e(326)]($l);t._onresponse=n,t[e(395)]=s,t.removeResponseListener=o,t.clearResponseListener=i}{const{handleListener:n,addListener:s,removeListener:o,clearListener:i}=a[r(326)]($l);t[r(328)]=n,t.addRequestListener=s,t[r(354)]=o,t[r(341)]=i}{const{handleListener:n,addListener:s,removeListener:o,clearListener:i}=a[e(375)]($l);t[e(342)]=n,t[e(327)]=s,t.removeNotificationListener=o,t.clearNotificationListener=i}};function Qs(){const t=["uUjKY","notifications/initialized","removeRequestListener","96194JysfjF","36346SGEWAV","1357830AJaOeY","resources/templates/list","clearListener","iQqcJ","result","tqDZP","sSeCz","XtowM","HgYgW","3913230mjiatC","params","roots/list","function","bfmJT","transport","resources/read","27FNuDmk","length","Mfvzm","ping","code","_onresponse","vnkqu","cjSoZ","request","9gIMIPC","readResource","GdkkV","ptMjy","call","aVeaL","completion/complete","5035122lFbpzR","logging/setLevel","jQBBS","send","_requestHandlers","jsonrpc","addResponseListener","7SpcenI","ElOQH","MDIkN","message","notifications/cancelled","OhJjz","clear","672216JzFEyR","xwPeb","addNotificationListener","fallbackRequestHandler","sYzPD","addListener","ifIKG","2.0","gXsjT","WqUnk","resources/subscribe","setLoggingLevel","2491772kFUWFh","SEmWX","onerror","prompts/get","clearRequestListener","fallbackNotificationHandler","wxDWr","SkoRK","uTeHc","handleListener","Zybtx","error","originalOnResponse","listResources","initialize"];return Qs=function(){return t},Qs()}const mC=(t,{beforeInit:e,afterInit:r}={})=>{const a=qe,n=qe,s={tqDZP:function(i,l){return i===l},cjSoZ:"function",iQqcJ:a(378),Zybtx:function(i,l){return i(l)},ElOQH:function(i){return i()}},o=new Map(t._notificationHandlers);t[a(393)][a(402)](),t._notificationHandlers[a(402)](),s.tqDZP(typeof e,s[a(380)])&&e(),s[a(362)](t._onresponse.name,s[a(360)])&&(t[n(349)]=t._onresponse),s[a(347)](fC,t),t.addResponseListener(i=>{const l=n;t.originalOnResponse[l(386)](t,i)}),s.tqDZP(typeof r,s[n(380)])&&s[a(397)](r),t[n(327)](i=>{const{method:l}=i,u=o.get(l);s.tqDZP(typeof u,s.cjSoZ)&&u(i)})},vC=cr,gC=cr;(function(t,e){const r=cr,a=cr,n=t();for(;;)try{if(-parseInt(r(393))/1+parseInt(r(397))/2*(-parseInt(r(400))/3)+-parseInt(a(398))/4+parseInt(r(390))/5*(parseInt(a(388))/6)+-parseInt(r(389))/7+-parseInt(r(402))/8*(-parseInt(a(395))/9)+parseInt(a(399))/10*(parseInt(a(385))/11)===e)break;n.push(n.shift())}catch{n.push(n.shift())}})(Ys,-1*-881393+2*180895+1*-644809);function cr(t,e){const r=Ys();return cr=function(a,n){return a=a-(-1861+-499*4+4241),r[a]},cr(t,e)}function Ys(){const t=["toString","getRandomValues","2101mUsYMI","EQHzo","padStart","30UvDAkd","1609706yzlqYx","974735GrhZVO","randomUUID","REzPF","562771BvAnoG","dHTfU","2047455boiYXf","randomBytes","14664qHAdbF","3772144jLpQch","52310AkWksx","318MkjaVb","from","40WRwnSc"];return Ys=function(){return t},Ys()}const yC=()=>{const t=cr,e=cr,r={};r.REzPF=function(n,s){return n&s},r.suJHI=function(n,s){return n===s},r[t(386)]=function(n,s){return n&s},r[e(394)]="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";const a=r;return a.suJHI(typeof crypto,"object")&&crypto.randomUUID?crypto[e(391)]():a.dHTfU.replace(/[xy]/g,n=>{const s=t,o=t,i=a[s(392)](crypto[s(384)](new Uint8Array(-25*-62+7113+2*-4331))[741*2+-1385*-2+4252*-1],8648+-107*62+-1999);return(a.suJHI(n,"x")?i:a[o(386)](i,-4377+4*1095)|5079+461*-11).toString(9449+4*-461+-7589)})},_C=t=>{const e=cr,r=cr,a=new Uint8Array(t);return crypto.getRandomValues(a),Array[e(401)](a,n=>n[r(403)](-3*1739+-6509+2*5871)[e(387)](2,"0")).join("")},zr={};zr[vC(391)]=yC,zr[gC(396)]=_C;const $t=dr;(function(t,e){const r=dr,a=dr,n=t();for(;;)try{if(parseInt(r(521))/1*(parseInt(a(499))/2)+parseInt(a(543))/3*(parseInt(a(514))/4)+parseInt(r(502))/5*(parseInt(a(539))/6)+parseInt(r(553))/7+parseInt(r(516))/8*(-parseInt(r(518))/9)+-parseInt(r(531))/10+-parseInt(r(545))/11*(parseInt(r(541))/12)===e)break;n.push(n.shift())}catch{n.push(n.shift())}})(Xs,1472653*1+-2*-897917+-2275789);const wC=(t,e)=>{const r=dr,a=dr,n={FyYHt:function(l,u,d){return l(u,d)},Fxtoq:function(l,u,d){return l(u,d)}};uC(t,e),cC(t,e);const s=dC(e,t),o=n[r(510)](hC,e,t),i=n[a(549)](pC,e,t);e[a(537)](s),e[r(519)](o),e.addNotificationListener(i),t[a(556)]=()=>{const l=a;e.removeRequestListener(s),e[l(530)](o),e[l(529)](i)}},Al=(t,e,r)=>{const a=dr,n={pMiva:function(i,l){return i instanceof l},TeTEy:a(546),fyZbd:function(i,l,u){return i(l,u)}},s=()=>{var i;const l=a;n.pMiva(r,Ol)&&((i=r._eventSource)==null||i.addEventListener(n[l(547)],()=>{var u;const d=l;(u=r[d(509)])==null||u[d(546)]()})),wC(t,e)},o={};o.afterInit=s,n.fyZbd(mC,e,o)},ym=(t,e=zr.randomUUID())=>{const r=dr,a=dr,n={OfssH:function(d,h,g){return d(h,g)}},s={};s[r(528)]=e;const o=s,i={};i[r(528)]=e;const l={};l[a(558)]=i,l[r(534)]=r(524);const u={requestInit:l,eventSourceInit:{async fetch(d,h){const g=r,c=a,p=new Headers((h==null?void 0:h[g(558)])||{});Object.entries(o)[c(498)](([m,v])=>{p[c(527)](m,v)});const f={...h};return f[c(558)]=p,n.OfssH(fetch,d,f)},withCredentials:!0}};return t&&(u.requestInit[r(558)].Authorization=r(533)+t,o.Authorization="Bearer "+t),u},_m=(t,e=zr[$t(517)]())=>{const r=$t,a=$t,n={};n.nwQhY="include";const s=n,o={};o["stream-session-id"]=e;const i={};i.headers=o,i.credentials=s[r(520)];const l={};l[r(544)]=i;const u=l;return t&&(u.requestInit.headers[a(552)]=a(533)+t),u},Nl=async(t,e,r)=>{const a=$t,n=$t,s={CFfFC:function(i){return i()},egwVO:function(i,l,u,d){return i(l,u,d)}},o=s.CFfFC(r);try{return await t[a(538)](o),o}catch(i){if(i instanceof Gt){const l=await e();return await o[n(505)](l),await s[a(525)](Nl,t,e,r)}else throw i}};function dr(t,e){const r=Xs();return dr=function(a,n){return a=a-(74*-67+-8341+-73*-189),r[a]},dr(t,e)}const wm=(t,e)=>{const r=$t,a=$t,n={};n.RsKXs=function(o,i){return o in i},n.PBhps="waitForOAuthCode",n[r(535)]="function",n[r(507)]="waitForOAuthCode need to be provided when authProvider is provided";const s=n;if(s.RsKXs(s[a(551)],t))return t[a(523)];if(typeof e===s.yTKoP)return e;throw new Error(s.RZhOv)},bC=async t=>{const e=$t,r=$t,a={TFSRn:function($,z,L){return $(z,L)},HwvVa:"mcp-sse-proxy-client",ufTHS:function($){return $()},WIVYl:function($,z,L,F){return $(z,L,F)},jniGY:"sessionId"},{client:n,url:s,token:o,sessionId:i,authProvider:l,requestInit:u,eventSourceInit:d,waitForOAuthCode:h}=t,g={};g.authProvider=l,g.requestInit=u,g.eventSourceInit=d;const c=g,p=i||zr.randomUUID(),f=a[e(506)](ym,o,p);if(u){const $={...f.requestInit,...u};$.headers={...f[e(544)].headers,...u.headers},c.requestInit=$}else c[r(544)]=f.requestInit;if(d){const $={...f[e(559)],...d};c.eventSourceInit=$}else c.eventSourceInit=f.eventSourceInit;const m={};m.listChanged=!0;const v={};v.roots=m,v.sampling={},v[e(511)]={};const w=v,y={};y[r(536)]=a.HwvVa,y.version=e(526);const _={};_.capabilities=w;const E=new Hs(y,_),I=()=>new Ol(new URL(s),c);let S=a[r(504)](I);if(l){const $=a[e(506)](wm,l,h);S=await a[r(513)](Nl,E,$,I)}else await E[e(538)](S);a[r(513)](Al,E,n,S),S[r(557)]=S[r(542)].searchParams[r(532)](a.jniGY);const R={};return R.transport=S,R.sessionId=S[e(557)],R};function Xs(){const t=["ufTHS","finishAuth","TFSRn","RZhOv","Vajmx","_eventSource","FyYHt","elicitation","transport","WIVYl","13320uyrBtN","sampling","8WTwLJD","randomUUID","6438654bkJHij","addResponseListener","nwQhY","11721GVgRMJ","?sessionId=","waitForOAuthCode","include","egwVO","1.0.0","set","sse-session-id","removeNotificationListener","removeResponseListener","11838520fNkjrV","get","Bearer ","credentials","yTKoP","name","addRequestListener","connect","18VhCgQv","mcp-socket-proxy-client","2819364JNqkQZ","_endpoint","699JyrxCR","requestInit","44ofbsvb","close","TeTEy","QgzDy","Fxtoq","roots","PBhps","Authorization","11309130xGCFwl","&token=","version","onclose","sessionId","headers","eventSourceInit","forEach","62FcOkCa","mcp-stream-proxy-client","zXcpO","1794855cQEXDT","biJOc"];return Xs=function(){return t},Xs()}const xC=async t=>{const e=$t,r=$t,a={Vajmx:e(500),biJOc:function($){return $()},zXcpO:function($,z,L){return $(z,L)},zDnjZ:function($,z,L,F){return $(z,L,F)},FQMAh:function($,z,L,F){return $(z,L,F)}},{client:n,url:s,token:o,sessionId:i,authProvider:l,requestInit:u,reconnectionOptions:d,waitForOAuthCode:h}=t,g={};g.authProvider=l,g.requestInit=u,g.reconnectionOptions=d;const c=g,p=i||zr.randomUUID(),f=_m(o,p);if(u){const $={...f.requestInit,...u};$.headers={...f.requestInit.headers,...u.headers},c[e(544)]=$}else c.requestInit=f.requestInit;const m={};m.listChanged=!0;const v={};v[r(550)]=m,v.sampling={},v.elicitation={};const w=v,y={};y[e(536)]=a[r(508)],y[e(555)]="1.0.0";const _={};_.capabilities=w;const E=new Hs(y,_),I=()=>new Ps(new URL(s),c);let S=a[e(503)](I);if(l){const $=a[e(501)](wm,l,h);S=await a.zDnjZ(Nl,E,$,I)}else await E.connect(S);a.FQMAh(Al,E,n,S);const R={};return R.transport=S,R[r(557)]=S.sessionId,R},EC=async t=>{const e=$t,r=$t,a={QgzDy:e(540),jkaVB:function(v,w,y,_){return v(w,y,_)}},{client:n,url:s,token:o,sessionId:i}=t,l={};l.listChanged=!0;const u={};u[e(550)]=l,u[e(515)]={},u[r(511)]={};const d=u,h={};h.name=a[r(548)],h[r(555)]=r(526);const g={};g.capabilities=d;const c=new Hs(h,g),p=i||zr[r(517)](),f=new vm(new URL(s+e(522)+p+r(554)+o));await c.connect(f),a.jkaVB(Al,c,n,f);const m={};return m[e(512)]=f,m[r(557)]=p,m},Ta=kt,eo=kt;function kt(t,e){const r=to();return kt=function(a,n){return a=a-(-16761+51*337),r[a]},kt(t,e)}(function(t,e){const r=kt,a=kt,n=t();for(;;)try{if(-parseInt(r(440))/1+-parseInt(r(458))/2*(parseInt(r(448))/3)+-parseInt(r(451))/4*(parseInt(a(449))/5)+-parseInt(a(455))/6+-parseInt(r(427))/7+-parseInt(a(438))/8*(parseInt(a(459))/9)+parseInt(r(430))/10*(parseInt(a(436))/11)===e)break;n.push(n.shift())}catch{n.push(n.shift())}})(to,-220880+1*-333337+-2*-384996);function to(){const t=["650XPHLhD","redirectToAuthorization","10856jPvMVb","GET","qcFPW","_redirectUrl","2187414WnlGuZ","resolve","tokens","3976YyOqUl","27ejNHsa","Content-Type","waitForOAuthCode","2903796yvWZFa","_clientMetadata","application/x-www-form-urlencoded","10beEWJk","json","code","_callBackPromise","reject","saveClientInformation","20776349mLNCcF","_codeVerifier","629912aTknXq","_tokens","52074GwcpRo","state","_state","_redirectCallback","_clientInformation","redirect_uris","Failed to redirect: ","clientInformation","381aduWsB"];return to=function(){return t},to()}const SC=()=>zr.randomBytes(3485*1+-261+-3184);class M2{constructor(e){const r=kt,a=kt;this._callBackPromise={};const{clientMetadata:n,state:s,redirectCallback:o,getAuthCodeByState:i,waitForOAuthCode:l}=e;this[r(428)]=n,this[r(454)]=n[r(445)][0],this._state=s||SC(),this._redirectCallback=o||this.redirectCallbackFunction,this._getAuthCodeByState=i||this.getAuthCodeByStateFunction,this[a(426)]=l||this.waitForOAuthCodeFunction()}async redirectCallbackFunction(e){var r,a,n,s,o,i;const l=kt,u=kt,d={qITTp:function(p,f,m){return p(f,m)},qcFPW:l(452)},h=await d.qITTp(fetch,e,{method:d[l(453)]});!h.ok&&((a=(r=this._callBackPromise).reject)==null||a.call(r,u(446)+h.statusText));const g=await this._getAuthCodeByState(this[u(454)],this[l(442)]);if(!g.ok){(s=(n=this[l(433)]).reject)==null||s.call(n,"Failed to fetch auth code: "+g.statusText);return}const c=await g[l(431)]();(i=(o=this[u(433)])[l(456)])==null||i.call(o,c[l(432)])}async getAuthCodeByStateFunction(e,r){const a=kt,n=kt,s={};s.tuSmb=a(429);const o=s,i={};i[a(460)]=o.tuSmb;const l={};return l[n(441)]=r,fetch(e,{method:"POST",headers:i,body:new URLSearchParams(l)})}waitForOAuthCodeFunction(){const e=kt,r=this[e(433)];return()=>new Promise((a,n)=>{const s=e;r.resolve=a,r[s(434)]=n})}get redirectUrl(){return this[kt(454)]}get clientMetadata(){return this._clientMetadata}state(){return this._state}[Ta(447)](){return this[Ta(444)]}[eo(435)](e){const r=Ta;this[r(444)]=e}[eo(457)](){return this[eo(439)]}saveTokens(e){this._tokens=e}[eo(450)](e){this[Ta(443)](e)}saveCodeVerifier(e){this._codeVerifier=e}codeVerifier(){if(!this[Ta(437)])throw new Error("No code verifier saved");return this._codeVerifier}}(function(t,e){for(var r=no,a=no,n=t();;)try{var s=parseInt(r(361))/1*(parseInt(a(363))/2)+-parseInt(r(358))/3+parseInt(r(359))/4*(parseInt(r(357))/5)+parseInt(a(354))/6*(parseInt(r(360))/7)+parseInt(a(362))/8+parseInt(a(364))/9+-parseInt(a(356))/10*(parseInt(r(355))/11);if(s===e)break;n.push(n.shift())}catch{n.push(n.shift())}})(ro,-73523*-3+1*-407717+530518);function ro(){var t=["40ecBYYe","1095owKKYD","486870YOVwZy","5752xWiyTO","561484biNVMw","1fWJmxQ","1866064SPnyhb","1109522vMiuMX","1602351pPEGwH","12sVyMLL","2573296LTwOhv"];return ro=function(){return t},ro()}function no(t,e){var r=ro();return no=function(a,n){a=a-(-1*-642+503*-5+2227);var s=r[a];return s},no(t,e)}class IC{constructor(e,r){const a={name:"web-mcp-client",version:"1.0.0"},n={roots:{listChanged:!0},sampling:{},elicitation:{}};this.client=new Hs(e||a,r||{capabilities:n}),this.client.onclose=()=>{var s;(s=this.onclose)==null||s.call(this)},this.client.onerror=s=>{var o;(o=this.onerror)==null||o.call(this,s)}}async connect(e){if(typeof e.start=="function")return this.transport=e,this.transport.onclose=void 0,this.transport.onerror=void 0,this.transport.onmessage=void 0,await this.client.connect(this.transport),{transport:this.transport,sessionId:this.transport.sessionId};const{url:r,token:a,sessionId:n,type:s,agent:o,onError:i}=e;if(o===!0){const d={client:this.client,url:r,token:a,sessionId:n};let h;return await(async()=>{const{transport:c,sessionId:p}=s==="sse"?await bC(d):s==="socket"?await EC(d):await xC(d);c.onerror=async f=>{i==null||i(f)},h={transport:c,sessionId:p}})(),h}const l=new URL(r);let u;if(s==="channel"&&(u=new oC(r),await this.client.connect(u)),s==="sse"){const d=ym(a,n);u=new Ol(l,d),await this.client.connect(u)}if(s==="socket"&&(u=new vm(new URL(`${r}?sessionId=${n}&token=${a}`)),u.sessionId=n,await this.client.connect(u)),typeof u>"u"){const d=_m(a,n);u=new Ps(l,d),await this.client.connect(u)}return this.transport=u,{transport:this.transport,sessionId:this.transport.sessionId}}async close(){await this.client.close()}getServerCapabilities(){return this.client.getServerCapabilities()}getServerVersion(){return this.client.getServerVersion()}getInstructions(){return this.client.getInstructions()}async ping(e){return await this.client.ping(e)}async complete(e,r){return await this.client.complete(e,r)}async setLoggingLevel(e,r){return await this.client.setLoggingLevel(e,r)}async getPrompt(e,r){return await this.client.getPrompt(e,r)}async listPrompts(e,r){return await this.client.listPrompts(e,r)}async listResources(e,r){return await this.client.listResources(e,r)}async listResourceTemplates(e,r){return await this.client.listResourceTemplates(e,r)}async readResource(e,r){return await this.client.readResource(e,r)}async subscribeResource(e,r){return await this.client.subscribeResource(e,r)}async unsubscribeResource(e,r){return await this.client.unsubscribeResource(e,r)}async callTool(e,r){return await this.client.callTool(e,Ss,r)}async listTools(e,r){return await this.client.listTools(e,r)}async sendRootsListChanged(){return await this.client.sendRootsListChanged()}request(e,r,a){return this.client.request(e,r,a)}async notification(e,r){return await this.client.notification(e,r)}setRequestHandler(e,r){this.client.setRequestHandler(e,r)}removeRequestHandler(e){this.client.removeRequestHandler(e)}setNotificationHandler(e,r){this.client.setNotificationHandler(e,r)}removeNotificationHandler(e){this.client.removeNotificationHandler(e)}onElicit(e){this.client.setRequestHandler($h,e)}onCreateMessage(e){this.client.setRequestHandler(Rh,e)}onListRoots(e){this.client.setRequestHandler(Mh,e)}onToolListChanged(e){this.client.setNotificationHandler(kh,e)}onPromptListChanged(e){this.client.setNotificationHandler(Ih,e)}onResourceListChanged(e){this.client.setNotificationHandler(wh,e)}onResourceUpdated(e){this.client.setNotificationHandler(bh,e)}onLoggingMessage(e){this.client.setNotificationHandler(Ch,e)}async onPagehide(e){e.persisted||(TC(this.transport)?await this.transport.terminateSession():this.transport&&typeof this.transport.close=="function"&&await this.transport.close())}}const TC=t=>t instanceof Ps,Ml=async t=>{const e={};try{const r=await t.listTools();for(const{name:a,description:n,inputSchema:s}of r.tools){const o=async(i,l)=>t.callTool({name:a,arguments:i},{signal:l==null?void 0:l.abortSignal});e[a]=iw({description:n,inputSchema:ls({...s,properties:s.properties??{},additionalProperties:!1}),execute:o})}return e}catch(r){throw r}},kC={openai:gf,deepseek:Sf};class PC{constructor({llmConfig:e,mcpServers:r}){if(this.mcpServers={},this.mcpClients={},this.mcpTools={},this.ignoreToolnames=[],this.messages=[],!e)throw new Error("llmConfig is required to initialize AgentModelProvider");if(this.mcpServers=r||{},this.mcpClients={},this.mcpTools={},e.llm)this.llm=e.llm;else if(e.providerType){const a=e.providerType;let n;typeof a=="string"?n=kC[a]:n=a,this.llm=n({apiKey:e.apiKey,baseURL:e.baseURL})}else throw new Error("Either llmConfig.llm or llmConfig.providerType must be provided")}async _createOneClient(e){try{let r;"type"in e&&e.type.toLocaleLowerCase()==="streamablehttp"?r=new Ps(new URL(e.url)):"type"in e&&e.type==="extension"?r=new zT(e.sessionId):r=e;const a=new IC({name:"mcp-web-client",version:"1.0.0"},{capabilities:{roots:{listChanged:!0},sampling:{},elicitation:{}}});return await a.connect(r),a.__transport__=r,a}catch(r){return this.onError&&this.onError((r==null?void 0:r.message)||"Failed to create MCP client",r),console.error("Failed to create MCP client",e,r),null}}async _closeOneClient(e){var r,a,n;try{const s=e.__transport__;if(s&&s instanceof Cs||s&&s instanceof gm)return;await((r=s==null?void 0:s.terminateSession)==null?void 0:r.call(s)),await((a=s==null?void 0:s.close)==null?void 0:a.call(s)),await((n=e==null?void 0:e.close)==null?void 0:n.call(e))}catch{}}async _createMpcClients(){const e=Object.entries(this.mcpServers),r=await Promise.all(e.map(async([a,n])=>{const s=await this._createOneClient(n);return{serverName:a,client:s}}));this.mcpClients={},r.forEach(({serverName:a,client:n})=>{this.mcpClients[a]=n})}async _createMpcTools(){const e=Object.entries(this.mcpClients),r=await Promise.all(e.map(async([a,n])=>{try{const s=n?await Ml(n):null;return{serverName:a,tools:s}}catch(s){return this.onError&&this.onError((s==null?void 0:s.message)||"Failed to query tools",s),console.error("Failed to query tools",s),{serverName:a,tools:null}}}));this.mcpTools={},r.forEach(({serverName:a,tools:n})=>{const s=n&&typeof n=="object"?n:{};this.mcpTools[a]=s})}async closeAll(){await Promise.all(Object.values(this.mcpClients).map(async e=>{try{await this._closeOneClient(e)}catch(r){this.onError&&this.onError((r==null?void 0:r.message)||"Failed to close client",r),console.error("Failed to close client",r)}}))}async initClientsAndTools(){var e;await this._createMpcClients(),await this._createMpcTools(),(e=this.onUpdatedTools)==null||e.call(this)}async updateMcpServers(e){await this.closeAll(),this.mcpServers=e||this.mcpServers,await this.initClientsAndTools()}async insertMcpServer(e,r){var s,o;if(this.mcpServers[e])return!1;const a=await this._createOneClient(r);if(!a)return(s=this.onError)==null||s.call(this,`Failed to create MCP client: ${e}`),null;this.mcpClients[e]=a;const n=await Ml(a);return this.mcpTools[e]=n&&typeof n=="object"?n:{},this.mcpServers[e]=r,(o=this.onUpdatedTools)==null||o.call(this),a}async removeMcpServer(e){var n;if(!this.mcpServers[e])return;delete this.mcpServers[e];const r=this.mcpClients[e];delete this.mcpClients[e];try{await this._closeOneClient(r)}catch{}const a=this.mcpTools[e];delete this.mcpTools[e],a&&Object.keys(a).forEach(s=>{this.ignoreToolnames=this.ignoreToolnames.filter(o=>o!==s)}),(n=this.onUpdatedTools)==null||n.call(this)}_tempMergeTools(e={}){const r=Object.values(this.mcpTools).reduce((a,n)=>({...a,...n}),{});return Object.assign(r,e),this.ignoreToolnames.forEach(a=>{delete r[a]}),r}async _chat(e,{model:r,maxSteps:a=5,...n}){var i;if(!this.llm)throw new Error("LLM is not initialized");await this.initClientsAndTools();const s={model:this.llm(r),stopWhen:_i(a),...n,tools:this._tempMergeTools(n.tools)};n.message&&!n.messages&&(this.messages.push({role:"user",content:n.message}),s.messages=[...this.messages]);const o=e(s);return(i=o==null?void 0:o.response)==null||i.then(l=>{this.messages.push(...l.messages)}),o}async chat(e){return this._chat(Yx,e)}async chatStream(e){return this._chat(gE,e)}}var Mn={},CC=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then},bm={},At={};let Dl;const RC=[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];At.getSymbolSize=function(e){if(!e)throw new Error('"version" cannot be null or undefined');if(e<1||e>40)throw new Error('"version" should be in range from 1 to 40');return e*4+17},At.getSymbolTotalCodewords=function(e){return RC[e]},At.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e},At.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');Dl=e},At.isKanjiModeEnabled=function(){return typeof Dl<"u"},At.toSJIS=function(e){return Dl(e)};var ao={};(function(t){t.L={bit:1},t.M={bit:0},t.Q={bit:3},t.H={bit:2};function e(r){if(typeof r!="string")throw new Error("Param is not a string");switch(r.toLowerCase()){case"l":case"low":return t.L;case"m":case"medium":return t.M;case"q":case"quartile":return t.Q;case"h":case"high":return t.H;default:throw new Error("Unknown EC Level: "+r)}}t.isValid=function(a){return a&&typeof a.bit<"u"&&a.bit>=0&&a.bit<4},t.from=function(a,n){if(t.isValid(a))return a;try{return e(a)}catch{return n}}})(ao);function xm(){this.buffer=[],this.length=0}xm.prototype={get:function(t){const e=Math.floor(t/8);return(this.buffer[e]>>>7-t%8&1)===1},put:function(t,e){for(let r=0;r<e;r++)this.putBit((t>>>e-r-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){const e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),t&&(this.buffer[e]|=128>>>this.length%8),this.length++}};var OC=xm;function ka(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)}ka.prototype.set=function(t,e,r,a){const n=t*this.size+e;this.data[n]=r,a&&(this.reservedBit[n]=!0)},ka.prototype.get=function(t,e){return this.data[t*this.size+e]},ka.prototype.xor=function(t,e,r){this.data[t*this.size+e]^=r},ka.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};var $C=ka,Em={};(function(t){const e=At.getSymbolSize;t.getRowColCoords=function(a){if(a===1)return[];const n=Math.floor(a/7)+2,s=e(a),o=s===145?26:Math.ceil((s-13)/(2*n-2))*2,i=[s-7];for(let l=1;l<n-1;l++)i[l]=i[l-1]-o;return i.push(6),i.reverse()},t.getPositions=function(a){const n=[],s=t.getRowColCoords(a),o=s.length;for(let i=0;i<o;i++)for(let l=0;l<o;l++)i===0&&l===0||i===0&&l===o-1||i===o-1&&l===0||n.push([s[i],s[l]]);return n}})(Em);var Sm={};const AC=At.getSymbolSize,Im=7;Sm.getPositions=function(e){const r=AC(e);return[[0,0],[r-Im,0],[0,r-Im]]};var Tm={};(function(t){t.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const e={N1:3,N2:3,N3:40,N4:10};t.isValid=function(n){return n!=null&&n!==""&&!isNaN(n)&&n>=0&&n<=7},t.from=function(n){return t.isValid(n)?parseInt(n,10):void 0},t.getPenaltyN1=function(n){const s=n.size;let o=0,i=0,l=0,u=null,d=null;for(let h=0;h<s;h++){i=l=0,u=d=null;for(let g=0;g<s;g++){let c=n.get(h,g);c===u?i++:(i>=5&&(o+=e.N1+(i-5)),u=c,i=1),c=n.get(g,h),c===d?l++:(l>=5&&(o+=e.N1+(l-5)),d=c,l=1)}i>=5&&(o+=e.N1+(i-5)),l>=5&&(o+=e.N1+(l-5))}return o},t.getPenaltyN2=function(n){const s=n.size;let o=0;for(let i=0;i<s-1;i++)for(let l=0;l<s-1;l++){const u=n.get(i,l)+n.get(i,l+1)+n.get(i+1,l)+n.get(i+1,l+1);(u===4||u===0)&&o++}return o*e.N2},t.getPenaltyN3=function(n){const s=n.size;let o=0,i=0,l=0;for(let u=0;u<s;u++){i=l=0;for(let d=0;d<s;d++)i=i<<1&2047|n.get(u,d),d>=10&&(i===1488||i===93)&&o++,l=l<<1&2047|n.get(d,u),d>=10&&(l===1488||l===93)&&o++}return o*e.N3},t.getPenaltyN4=function(n){let s=0;const o=n.data.length;for(let l=0;l<o;l++)s+=n.data[l];return Math.abs(Math.ceil(s*100/o/5)-10)*e.N4};function r(a,n,s){switch(a){case t.Patterns.PATTERN000:return(n+s)%2===0;case t.Patterns.PATTERN001:return n%2===0;case t.Patterns.PATTERN010:return s%3===0;case t.Patterns.PATTERN011:return(n+s)%3===0;case t.Patterns.PATTERN100:return(Math.floor(n/2)+Math.floor(s/3))%2===0;case t.Patterns.PATTERN101:return n*s%2+n*s%3===0;case t.Patterns.PATTERN110:return(n*s%2+n*s%3)%2===0;case t.Patterns.PATTERN111:return(n*s%3+(n+s)%2)%2===0;default:throw new Error("bad maskPattern:"+a)}}t.applyMask=function(n,s){const o=s.size;for(let i=0;i<o;i++)for(let l=0;l<o;l++)s.isReserved(l,i)||s.xor(l,i,r(n,l,i))},t.getBestMask=function(n,s){const o=Object.keys(t.Patterns).length;let i=0,l=1/0;for(let u=0;u<o;u++){s(u),t.applyMask(u,n);const d=t.getPenaltyN1(n)+t.getPenaltyN2(n)+t.getPenaltyN3(n)+t.getPenaltyN4(n);t.applyMask(u,n),d<l&&(l=d,i=u)}return i}})(Tm);var so={};const Ur=ao,oo=[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],io=[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];so.getBlocksCount=function(e,r){switch(r){case Ur.L:return oo[(e-1)*4+0];case Ur.M:return oo[(e-1)*4+1];case Ur.Q:return oo[(e-1)*4+2];case Ur.H:return oo[(e-1)*4+3];default:return}},so.getTotalCodewordsCount=function(e,r){switch(r){case Ur.L:return io[(e-1)*4+0];case Ur.M:return io[(e-1)*4+1];case Ur.Q:return io[(e-1)*4+2];case Ur.H:return io[(e-1)*4+3];default:return}};var km={},lo={};const Pa=new Uint8Array(512),uo=new Uint8Array(256);(function(){let e=1;for(let r=0;r<255;r++)Pa[r]=e,uo[e]=r,e<<=1,e&256&&(e^=285);for(let r=255;r<512;r++)Pa[r]=Pa[r-255]})(),lo.log=function(e){if(e<1)throw new Error("log("+e+")");return uo[e]},lo.exp=function(e){return Pa[e]},lo.mul=function(e,r){return e===0||r===0?0:Pa[uo[e]+uo[r]]},function(t){const e=lo;t.mul=function(a,n){const s=new Uint8Array(a.length+n.length-1);for(let o=0;o<a.length;o++)for(let i=0;i<n.length;i++)s[o+i]^=e.mul(a[o],n[i]);return s},t.mod=function(a,n){let s=new Uint8Array(a);for(;s.length-n.length>=0;){const o=s[0];for(let l=0;l<n.length;l++)s[l]^=e.mul(n[l],o);let i=0;for(;i<s.length&&s[i]===0;)i++;s=s.slice(i)}return s},t.generateECPolynomial=function(a){let n=new Uint8Array([1]);for(let s=0;s<a;s++)n=t.mul(n,new Uint8Array([1,e.exp(s)]));return n}}(km);const Pm=km;function jl(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}jl.prototype.initialize=function(e){this.degree=e,this.genPoly=Pm.generateECPolynomial(this.degree)},jl.prototype.encode=function(e){if(!this.genPoly)throw new Error("Encoder not initialized");const r=new Uint8Array(e.length+this.degree);r.set(e);const a=Pm.mod(r,this.genPoly),n=this.degree-a.length;if(n>0){const s=new Uint8Array(this.degree);return s.set(a,n),s}return a};var NC=jl,Cm={},Fr={},Ll={};Ll.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40};var pr={};const Rm="[0-9]+",MC="[A-Z $%*+\\-./:]+";let Ca="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";Ca=Ca.replace(/u/g,"\\u");const DC="(?:(?![A-Z0-9 $%*+\\-./:]|"+Ca+`)(?:.|[\r
|
|
72
|
+
]))+`;pr.KANJI=new RegExp(Ca,"g"),pr.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),pr.BYTE=new RegExp(DC,"g"),pr.NUMERIC=new RegExp(Rm,"g"),pr.ALPHANUMERIC=new RegExp(MC,"g");const jC=new RegExp("^"+Ca+"$"),LC=new RegExp("^"+Rm+"$"),zC=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");pr.testKanji=function(e){return jC.test(e)},pr.testNumeric=function(e){return LC.test(e)},pr.testAlphanumeric=function(e){return zC.test(e)},function(t){const e=Ll,r=pr;t.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},t.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},t.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},t.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},t.MIXED={bit:-1},t.getCharCountIndicator=function(s,o){if(!s.ccBits)throw new Error("Invalid mode: "+s);if(!e.isValid(o))throw new Error("Invalid version: "+o);return o>=1&&o<10?s.ccBits[0]:o<27?s.ccBits[1]:s.ccBits[2]},t.getBestModeForData=function(s){return r.testNumeric(s)?t.NUMERIC:r.testAlphanumeric(s)?t.ALPHANUMERIC:r.testKanji(s)?t.KANJI:t.BYTE},t.toString=function(s){if(s&&s.id)return s.id;throw new Error("Invalid mode")},t.isValid=function(s){return s&&s.bit&&s.ccBits};function a(n){if(typeof n!="string")throw new Error("Param is not a string");switch(n.toLowerCase()){case"numeric":return t.NUMERIC;case"alphanumeric":return t.ALPHANUMERIC;case"kanji":return t.KANJI;case"byte":return t.BYTE;default:throw new Error("Unknown mode: "+n)}}t.from=function(s,o){if(t.isValid(s))return s;try{return a(s)}catch{return o}}}(Fr),function(t){const e=At,r=so,a=ao,n=Fr,s=Ll,o=7973,i=e.getBCHDigit(o);function l(g,c,p){for(let f=1;f<=40;f++)if(c<=t.getCapacity(f,p,g))return f}function u(g,c){return n.getCharCountIndicator(g,c)+4}function d(g,c){let p=0;return g.forEach(function(f){const m=u(f.mode,c);p+=m+f.getBitsLength()}),p}function h(g,c){for(let p=1;p<=40;p++)if(d(g,p)<=t.getCapacity(p,c,n.MIXED))return p}t.from=function(c,p){return s.isValid(c)?parseInt(c,10):p},t.getCapacity=function(c,p,f){if(!s.isValid(c))throw new Error("Invalid QR Code version");typeof f>"u"&&(f=n.BYTE);const m=e.getSymbolTotalCodewords(c),v=r.getTotalCodewordsCount(c,p),w=(m-v)*8;if(f===n.MIXED)return w;const y=w-u(f,c);switch(f){case n.NUMERIC:return Math.floor(y/10*3);case n.ALPHANUMERIC:return Math.floor(y/11*2);case n.KANJI:return Math.floor(y/13);case n.BYTE:default:return Math.floor(y/8)}},t.getBestVersionForData=function(c,p){let f;const m=a.from(p,a.M);if(Array.isArray(c)){if(c.length>1)return h(c,m);if(c.length===0)return 1;f=c[0]}else f=c;return l(f.mode,f.getLength(),m)},t.getEncodedBits=function(c){if(!s.isValid(c)||c<7)throw new Error("Invalid QR Code version");let p=c<<12;for(;e.getBCHDigit(p)-i>=0;)p^=o<<e.getBCHDigit(p)-i;return c<<12|p}}(Cm);var Om={};const zl=At,$m=1335,UC=21522,Am=zl.getBCHDigit($m);Om.getEncodedBits=function(e,r){const a=e.bit<<3|r;let n=a<<10;for(;zl.getBCHDigit(n)-Am>=0;)n^=$m<<zl.getBCHDigit(n)-Am;return(a<<10|n)^UC};var Nm={};const FC=Fr;function Dn(t){this.mode=FC.NUMERIC,this.data=t.toString()}Dn.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)},Dn.prototype.getLength=function(){return this.data.length},Dn.prototype.getBitsLength=function(){return Dn.getBitsLength(this.data.length)},Dn.prototype.write=function(e){let r,a,n;for(r=0;r+3<=this.data.length;r+=3)a=this.data.substr(r,3),n=parseInt(a,10),e.put(n,10);const s=this.data.length-r;s>0&&(a=this.data.substr(r),n=parseInt(a,10),e.put(n,s*3+1))};var qC=Dn;const ZC=Fr,Ul=["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 jn(t){this.mode=ZC.ALPHANUMERIC,this.data=t}jn.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)},jn.prototype.getLength=function(){return this.data.length},jn.prototype.getBitsLength=function(){return jn.getBitsLength(this.data.length)},jn.prototype.write=function(e){let r;for(r=0;r+2<=this.data.length;r+=2){let a=Ul.indexOf(this.data[r])*45;a+=Ul.indexOf(this.data[r+1]),e.put(a,11)}this.data.length%2&&e.put(Ul.indexOf(this.data[r]),6)};var VC=jn;const BC=Fr;function Ln(t){this.mode=BC.BYTE,typeof t=="string"?this.data=new TextEncoder().encode(t):this.data=new Uint8Array(t)}Ln.getBitsLength=function(e){return e*8},Ln.prototype.getLength=function(){return this.data.length},Ln.prototype.getBitsLength=function(){return Ln.getBitsLength(this.data.length)},Ln.prototype.write=function(t){for(let e=0,r=this.data.length;e<r;e++)t.put(this.data[e],8)};var HC=Ln;const JC=Fr,WC=At;function zn(t){this.mode=JC.KANJI,this.data=t}zn.getBitsLength=function(e){return e*13},zn.prototype.getLength=function(){return this.data.length},zn.prototype.getBitsLength=function(){return zn.getBitsLength(this.data.length)},zn.prototype.write=function(t){let e;for(e=0;e<this.data.length;e++){let r=WC.toSJIS(this.data[e]);if(r>=33088&&r<=40956)r-=33088;else if(r>=57408&&r<=60351)r-=49472;else throw new Error("Invalid SJIS character: "+this.data[e]+`
|
|
73
|
+
Make sure your charset is UTF-8`);r=(r>>>8&255)*192+(r&255),t.put(r,13)}};var GC=zn,Mm={exports:{}};(function(t){var e={single_source_shortest_paths:function(r,a,n){var s={},o={};o[a]=0;var i=e.PriorityQueue.make();i.push(a,0);for(var l,u,d,h,g,c,p,f,m;!i.empty();){l=i.pop(),u=l.value,h=l.cost,g=r[u]||{};for(d in g)g.hasOwnProperty(d)&&(c=g[d],p=h+c,f=o[d],m=typeof o[d]>"u",(m||f>p)&&(o[d]=p,i.push(d,p),s[d]=u))}if(typeof n<"u"&&typeof o[n]>"u"){var v=["Could not find a path from ",a," to ",n,"."].join("");throw new Error(v)}return s},extract_shortest_path_from_predecessor_list:function(r,a){for(var n=[],s=a;s;)n.push(s),r[s],s=r[s];return n.reverse(),n},find_path:function(r,a,n){var s=e.single_source_shortest_paths(r,a,n);return e.extract_shortest_path_from_predecessor_list(s,n)},PriorityQueue:{make:function(r){var a=e.PriorityQueue,n={},s;r=r||{};for(s in a)a.hasOwnProperty(s)&&(n[s]=a[s]);return n.queue=[],n.sorter=r.sorter||a.default_sorter,n},default_sorter:function(r,a){return r.cost-a.cost},push:function(r,a){var n={value:r,cost:a};this.queue.push(n),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};t.exports=e})(Mm);var KC=Mm.exports;(function(t){const e=Fr,r=qC,a=VC,n=HC,s=GC,o=pr,i=At,l=KC;function u(v){return unescape(encodeURIComponent(v)).length}function d(v,w,y){const _=[];let E;for(;(E=v.exec(y))!==null;)_.push({data:E[0],index:E.index,mode:w,length:E[0].length});return _}function h(v){const w=d(o.NUMERIC,e.NUMERIC,v),y=d(o.ALPHANUMERIC,e.ALPHANUMERIC,v);let _,E;return i.isKanjiModeEnabled()?(_=d(o.BYTE,e.BYTE,v),E=d(o.KANJI,e.KANJI,v)):(_=d(o.BYTE_KANJI,e.BYTE,v),E=[]),w.concat(y,_,E).sort(function(S,R){return S.index-R.index}).map(function(S){return{data:S.data,mode:S.mode,length:S.length}})}function g(v,w){switch(w){case e.NUMERIC:return r.getBitsLength(v);case e.ALPHANUMERIC:return a.getBitsLength(v);case e.KANJI:return s.getBitsLength(v);case e.BYTE:return n.getBitsLength(v)}}function c(v){return v.reduce(function(w,y){const _=w.length-1>=0?w[w.length-1]:null;return _&&_.mode===y.mode?(w[w.length-1].data+=y.data,w):(w.push(y),w)},[])}function p(v){const w=[];for(let y=0;y<v.length;y++){const _=v[y];switch(_.mode){case e.NUMERIC:w.push([_,{data:_.data,mode:e.ALPHANUMERIC,length:_.length},{data:_.data,mode:e.BYTE,length:_.length}]);break;case e.ALPHANUMERIC:w.push([_,{data:_.data,mode:e.BYTE,length:_.length}]);break;case e.KANJI:w.push([_,{data:_.data,mode:e.BYTE,length:u(_.data)}]);break;case e.BYTE:w.push([{data:_.data,mode:e.BYTE,length:u(_.data)}])}}return w}function f(v,w){const y={},_={start:{}};let E=["start"];for(let I=0;I<v.length;I++){const S=v[I],R=[];for(let $=0;$<S.length;$++){const z=S[$],L=""+I+$;R.push(L),y[L]={node:z,lastCount:0},_[L]={};for(let F=0;F<E.length;F++){const M=E[F];y[M]&&y[M].node.mode===z.mode?(_[M][L]=g(y[M].lastCount+z.length,z.mode)-g(y[M].lastCount,z.mode),y[M].lastCount+=z.length):(y[M]&&(y[M].lastCount=z.length),_[M][L]=g(z.length,z.mode)+4+e.getCharCountIndicator(z.mode,w))}}E=R}for(let I=0;I<E.length;I++)_[E[I]].end=0;return{map:_,table:y}}function m(v,w){let y;const _=e.getBestModeForData(v);if(y=e.from(w,_),y!==e.BYTE&&y.bit<_.bit)throw new Error('"'+v+'" cannot be encoded with mode '+e.toString(y)+`.
|
|
74
|
+
Suggested mode is: `+e.toString(_));switch(y===e.KANJI&&!i.isKanjiModeEnabled()&&(y=e.BYTE),y){case e.NUMERIC:return new r(v);case e.ALPHANUMERIC:return new a(v);case e.KANJI:return new s(v);case e.BYTE:return new n(v)}}t.fromArray=function(w){return w.reduce(function(y,_){return typeof _=="string"?y.push(m(_,null)):_.data&&y.push(m(_.data,_.mode)),y},[])},t.fromString=function(w,y){const _=h(w,i.isKanjiModeEnabled()),E=p(_),I=f(E,y),S=l.find_path(I.map,"start","end"),R=[];for(let $=1;$<S.length-1;$++)R.push(I.table[S[$]].node);return t.fromArray(c(R))},t.rawSplit=function(w){return t.fromArray(h(w,i.isKanjiModeEnabled()))}})(Nm);const co=At,Fl=ao,QC=OC,YC=$C,XC=Em,e2=Sm,ql=Tm,Zl=so,t2=NC,po=Cm,r2=Om,n2=Fr,Vl=Nm;function a2(t,e){const r=t.size,a=e2.getPositions(e);for(let n=0;n<a.length;n++){const s=a[n][0],o=a[n][1];for(let i=-1;i<=7;i++)if(!(s+i<=-1||r<=s+i))for(let l=-1;l<=7;l++)o+l<=-1||r<=o+l||(i>=0&&i<=6&&(l===0||l===6)||l>=0&&l<=6&&(i===0||i===6)||i>=2&&i<=4&&l>=2&&l<=4?t.set(s+i,o+l,!0,!0):t.set(s+i,o+l,!1,!0))}}function s2(t){const e=t.size;for(let r=8;r<e-8;r++){const a=r%2===0;t.set(r,6,a,!0),t.set(6,r,a,!0)}}function o2(t,e){const r=XC.getPositions(e);for(let a=0;a<r.length;a++){const n=r[a][0],s=r[a][1];for(let o=-2;o<=2;o++)for(let i=-2;i<=2;i++)o===-2||o===2||i===-2||i===2||o===0&&i===0?t.set(n+o,s+i,!0,!0):t.set(n+o,s+i,!1,!0)}}function i2(t,e){const r=t.size,a=po.getEncodedBits(e);let n,s,o;for(let i=0;i<18;i++)n=Math.floor(i/3),s=i%3+r-8-3,o=(a>>i&1)===1,t.set(n,s,o,!0),t.set(s,n,o,!0)}function Bl(t,e,r){const a=t.size,n=r2.getEncodedBits(e,r);let s,o;for(s=0;s<15;s++)o=(n>>s&1)===1,s<6?t.set(s,8,o,!0):s<8?t.set(s+1,8,o,!0):t.set(a-15+s,8,o,!0),s<8?t.set(8,a-s-1,o,!0):s<9?t.set(8,15-s-1+1,o,!0):t.set(8,15-s-1,o,!0);t.set(a-8,8,1,!0)}function l2(t,e){const r=t.size;let a=-1,n=r-1,s=7,o=0;for(let i=r-1;i>0;i-=2)for(i===6&&i--;;){for(let l=0;l<2;l++)if(!t.isReserved(n,i-l)){let u=!1;o<e.length&&(u=(e[o]>>>s&1)===1),t.set(n,i-l,u),s--,s===-1&&(o++,s=7)}if(n+=a,n<0||r<=n){n-=a,a=-a;break}}}function u2(t,e,r){const a=new QC;r.forEach(function(l){a.put(l.mode.bit,4),a.put(l.getLength(),n2.getCharCountIndicator(l.mode,t)),l.write(a)});const n=co.getSymbolTotalCodewords(t),s=Zl.getTotalCodewordsCount(t,e),o=(n-s)*8;for(a.getLengthInBits()+4<=o&&a.put(0,4);a.getLengthInBits()%8!==0;)a.putBit(0);const i=(o-a.getLengthInBits())/8;for(let l=0;l<i;l++)a.put(l%2?17:236,8);return c2(a,t,e)}function c2(t,e,r){const a=co.getSymbolTotalCodewords(e),n=Zl.getTotalCodewordsCount(e,r),s=a-n,o=Zl.getBlocksCount(e,r),i=a%o,l=o-i,u=Math.floor(a/o),d=Math.floor(s/o),h=d+1,g=u-d,c=new t2(g);let p=0;const f=new Array(o),m=new Array(o);let v=0;const w=new Uint8Array(t.buffer);for(let S=0;S<o;S++){const R=S<l?d:h;f[S]=w.slice(p,p+R),m[S]=c.encode(f[S]),p+=R,v=Math.max(v,R)}const y=new Uint8Array(a);let _=0,E,I;for(E=0;E<v;E++)for(I=0;I<o;I++)E<f[I].length&&(y[_++]=f[I][E]);for(E=0;E<g;E++)for(I=0;I<o;I++)y[_++]=m[I][E];return y}function d2(t,e,r,a){let n;if(Array.isArray(t))n=Vl.fromArray(t);else if(typeof t=="string"){let u=e;if(!u){const d=Vl.rawSplit(t);u=po.getBestVersionForData(d,r)}n=Vl.fromString(t,u||40)}else throw new Error("Invalid data");const s=po.getBestVersionForData(n,r);if(!s)throw new Error("The amount of data is too big to be stored in a QR Code");if(!e)e=s;else if(e<s)throw new Error(`
|
|
71
75
|
The chosen QR Code version cannot contain this amount of data.
|
|
72
76
|
Minimum version required to store current data is: `+s+`.
|
|
73
|
-
`);const
|
|
74
|
-
`;return typeof
|
|
77
|
+
`);const o=u2(e,r,n),i=co.getSymbolSize(e),l=new YC(i);return a2(l,e),s2(l),o2(l,e),Bl(l,r,0),e>=7&&i2(l,e),l2(l,o),isNaN(a)&&(a=ql.getBestMask(l,Bl.bind(null,l,r))),ql.applyMask(a,l),Bl(l,r,a),{modules:l,version:e,errorCorrectionLevel:r,maskPattern:a,segments:n}}bm.create=function(e,r){if(typeof e>"u"||e==="")throw new Error("No input text");let a=Fl.M,n,s;return typeof r<"u"&&(a=Fl.from(r.errorCorrectionLevel,Fl.M),n=po.from(r.version),s=ql.from(r.maskPattern),r.toSJISFunc&&co.setToSJISFunction(r.toSJISFunc)),d2(e,n,a,s)};var Dm={},Hl={};(function(t){function e(r){if(typeof r=="number"&&(r=r.toString()),typeof r!="string")throw new Error("Color should be defined as hex string");let a=r.slice().replace("#","").split("");if(a.length<3||a.length===5||a.length>8)throw new Error("Invalid hex color: "+r);(a.length===3||a.length===4)&&(a=Array.prototype.concat.apply([],a.map(function(s){return[s,s]}))),a.length===6&&a.push("F","F");const n=parseInt(a.join(""),16);return{r:n>>24&255,g:n>>16&255,b:n>>8&255,a:n&255,hex:"#"+a.slice(0,6).join("")}}t.getOptions=function(a){a||(a={}),a.color||(a.color={});const n=typeof a.margin>"u"||a.margin===null||a.margin<0?4:a.margin,s=a.width&&a.width>=21?a.width:void 0,o=a.scale||4;return{width:s,scale:s?4:o,margin:n,color:{dark:e(a.color.dark||"#000000ff"),light:e(a.color.light||"#ffffffff")},type:a.type,rendererOpts:a.rendererOpts||{}}},t.getScale=function(a,n){return n.width&&n.width>=a+n.margin*2?n.width/(a+n.margin*2):n.scale},t.getImageWidth=function(a,n){const s=t.getScale(a,n);return Math.floor((a+n.margin*2)*s)},t.qrToImageData=function(a,n,s){const o=n.modules.size,i=n.modules.data,l=t.getScale(o,s),u=Math.floor((o+s.margin*2)*l),d=s.margin*l,h=[s.color.light,s.color.dark];for(let g=0;g<u;g++)for(let c=0;c<u;c++){let p=(g*u+c)*4,f=s.color.light;if(g>=d&&c>=d&&g<u-d&&c<u-d){const m=Math.floor((g-d)/l),v=Math.floor((c-d)/l);f=h[i[m*o+v]?1:0]}a[p++]=f.r,a[p++]=f.g,a[p++]=f.b,a[p]=f.a}}})(Hl),function(t){const e=Hl;function r(n,s,o){n.clearRect(0,0,s.width,s.height),s.style||(s.style={}),s.height=o,s.width=o,s.style.height=o+"px",s.style.width=o+"px"}function a(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}t.render=function(s,o,i){let l=i,u=o;typeof l>"u"&&(!o||!o.getContext)&&(l=o,o=void 0),o||(u=a()),l=e.getOptions(l);const d=e.getImageWidth(s.modules.size,l),h=u.getContext("2d"),g=h.createImageData(d,d);return e.qrToImageData(g.data,s,l),r(h,u,d),h.putImageData(g,0,0),u},t.renderToDataURL=function(s,o,i){let l=i;typeof l>"u"&&(!o||!o.getContext)&&(l=o,o=void 0),l||(l={});const u=t.render(s,o,l),d=l.type||"image/png",h=l.rendererOpts||{};return u.toDataURL(d,h.quality)}}(Dm);var jm={};const p2=Hl;function Lm(t,e){const r=t.a/255,a=e+'="'+t.hex+'"';return r<1?a+" "+e+'-opacity="'+r.toFixed(2).slice(1)+'"':a}function Jl(t,e,r){let a=t+e;return typeof r<"u"&&(a+=" "+r),a}function h2(t,e,r){let a="",n=0,s=!1,o=0;for(let i=0;i<t.length;i++){const l=Math.floor(i%e),u=Math.floor(i/e);!l&&!s&&(s=!0),t[i]?(o++,i>0&&l>0&&t[i-1]||(a+=s?Jl("M",l+r,.5+u+r):Jl("m",n,0),n=0,s=!1),l+1<e&&t[i+1]||(a+=Jl("h",o),o=0)):n++}return a}jm.render=function(e,r,a){const n=p2.getOptions(r),s=e.modules.size,o=e.modules.data,i=s+n.margin*2,l=n.color.light.a?"<path "+Lm(n.color.light,"fill")+' d="M0 0h'+i+"v"+i+'H0z"/>':"",u="<path "+Lm(n.color.dark,"stroke")+' d="'+h2(o,s,n.margin)+'"/>',d='viewBox="0 0 '+i+" "+i+'"',g='<svg xmlns="http://www.w3.org/2000/svg" '+(n.width?'width="'+n.width+'" height="'+n.width+'" ':"")+d+' shape-rendering="crispEdges">'+l+u+`</svg>
|
|
78
|
+
`;return typeof a=="function"&&a(null,g),g};const f2=CC,Wl=bm,zm=Dm,m2=jm;function Gl(t,e,r,a,n){const s=[].slice.call(arguments,1),o=s.length,i=typeof s[o-1]=="function";if(!i&&!f2())throw new Error("Callback required as last argument");if(i){if(o<2)throw new Error("Too few arguments provided");o===2?(n=r,r=e,e=a=void 0):o===3&&(e.getContext&&typeof n>"u"?(n=a,a=void 0):(n=a,a=r,r=e,e=void 0))}else{if(o<1)throw new Error("Too few arguments provided");return o===1?(r=e,e=a=void 0):o===2&&!e.getContext&&(a=r,r=e,e=void 0),new Promise(function(l,u){try{const d=Wl.create(r,a);l(t(d,e,a))}catch(d){u(d)}})}try{const l=Wl.create(r,a);n(null,t(l,e,a))}catch(l){n(l)}}Mn.create=Wl.create,Mn.toCanvas=Gl.bind(null,zm.render),Mn.toDataURL=Gl.bind(null,zm.renderToDataURL),Mn.toString=Gl.bind(null,function(t,e,r){return m2.render(t,r)});class Um{constructor(e,{size:r=200,margin:a=4,color:n="#000",bgColor:s="#fff"}){this.value=e,this.size=r,this.margin=a,this.color=n,this.bgColor=s}get qrCodeOption(){return{width:this.size,margin:this.margin,color:{dark:this.color,light:this.bgColor}}}async toDataURL(){return Mn.toDataURL(this.value,this.qrCodeOption)}async toCanvas(e){return Mn.toCanvas(e,this.value,this.qrCodeOption)}async toImage(e){e.src=await this.toDataURL()}}const v2="https://agent.opentiny.design/tiny-robot",Fm="https://ai.opentiny.design/next-remoter",qm=t=>[{action:"qr-code",show:!0,text:"弹出二维码",icon:`<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
75
79
|
<rect x="3" y="3" width="6" height="6" rx="1" stroke="currentColor" stroke-width="2" fill="none"/>
|
|
76
80
|
<rect x="15" y="3" width="6" height="6" rx="1" stroke="currentColor" stroke-width="2" fill="none"/>
|
|
77
81
|
<rect x="3" y="15" width="6" height="6" rx="1" stroke="currentColor" stroke-width="2" fill="none"/>
|
|
@@ -84,7 +88,7 @@ Minimum version required to store current data is: `+s+`.
|
|
|
84
88
|
<path d="M20 2H4C2.9 2 2 2.9 2 4V22L6 18H20C21.1 18 22 17.1 22 16V4C22 2.9 21.1 2 20 2ZM20 16H6L4 18V4H20V16Z" fill="currentColor"/>
|
|
85
89
|
<path d="M7 9H17V11H7V9Z" fill="currentColor"/>
|
|
86
90
|
<path d="M7 12H14V14H7V12Z" fill="currentColor"/>
|
|
87
|
-
</svg>`},{action:"remote-control",show:!0,text:`识别码:${
|
|
91
|
+
</svg>`},{action:"remote-control",show:!0,text:`识别码:${t.sessionId.slice(-6)}`,showCopyIcon:!0,icon:`<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
88
92
|
<rect x="3" y="3" width="18" height="18" rx="2" stroke="currentColor" stroke-width="2" fill="none"/>
|
|
89
93
|
<rect x="6" y="6" width="3" height="2" rx="0.5" fill="currentColor"/>
|
|
90
94
|
<rect x="10" y="6" width="3" height="2" rx="0.5" fill="currentColor"/>
|
|
@@ -95,28 +99,28 @@ Minimum version required to store current data is: `+s+`.
|
|
|
95
99
|
<rect x="6" y="12" width="3" height="2" rx="0.5" fill="currentColor"/>
|
|
96
100
|
<rect x="10" y="12" width="3" height="2" rx="0.5" fill="currentColor"/>
|
|
97
101
|
<rect x="14" y="12" width="3" height="2" rx="0.5" fill="currentColor"/>
|
|
98
|
-
</svg>`},{action:"remote-url",show:!0,text:`${
|
|
102
|
+
</svg>`},{action:"remote-url",show:!0,text:`${t.remoteUrl}`,tip:t.remoteUrl,showCopyIcon:!0,icon:`<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
99
103
|
<path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
|
|
100
104
|
<path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
|
|
101
|
-
</svg>`}];class
|
|
105
|
+
</svg>`}];class g2{constructor(e){if(this.isExpanded=!1,!e.sessionId)throw new Error("sessionId is required");this.options={...e,qrCodeUrl:e.qrCodeUrl||Fm,remoteUrl:e.remoteUrl||v2},this.menuItems=this.mergeMenuItems(e.menuItems),this.init()}get sessionPrefix(){var e;return(e=this.options.qrCodeUrl)!=null&&e.includes("?")?"&sessionId=":"?sessionId="}mergeMenuItems(e){return e?qm(this.options).map(r=>{const a=e.find(n=>n.action===r.action);return a?{...r,...a,show:a.show!==void 0?a.show:r.show}:r}):qm(this.options)}init(){this.createFloatingBlock(),this.createDropdownMenu(),this.bindEvents(),this.addStyles()}createFloatingBlock(){this.floatingBlock=document.createElement("div"),this.floatingBlock.className="tiny-remoter-floating-block",this.floatingBlock.innerHTML=`
|
|
102
106
|
<div class="tiny-remoter-floating-block__icon">
|
|
103
|
-
<img style="display: block; width: 56px;" src="${
|
|
107
|
+
<img style="display: block; width: 56px;" src="${Fm}/svgs/logo-next-no-bg-left.svg" alt="icon" />
|
|
104
108
|
</div>
|
|
105
|
-
`,document.body.appendChild(this.floatingBlock)}createDropdownMenu(){this.dropdownMenu=document.createElement("div"),this.dropdownMenu.className="tiny-remoter-floating-dropdown";const
|
|
106
|
-
<div class="tiny-remoter-dropdown-item" data-action="${
|
|
109
|
+
`,document.body.appendChild(this.floatingBlock)}createDropdownMenu(){this.dropdownMenu=document.createElement("div"),this.dropdownMenu.className="tiny-remoter-floating-dropdown";const e=this.menuItems.filter(r=>r.show!==!1).map(r=>`
|
|
110
|
+
<div class="tiny-remoter-dropdown-item" data-action="${r.action}">
|
|
107
111
|
<div class="tiny-remoter-dropdown-item__icon">
|
|
108
|
-
${
|
|
112
|
+
${r.icon}
|
|
109
113
|
</div>
|
|
110
|
-
<span title="${
|
|
111
|
-
${
|
|
112
|
-
<div class="tiny-remoter-copy-icon" data-action="${
|
|
114
|
+
<span title="${r.tip}">${r.text}</span>
|
|
115
|
+
${r.showCopyIcon?`
|
|
116
|
+
<div class="tiny-remoter-copy-icon" data-action="${r.action}">
|
|
113
117
|
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
114
118
|
<path d="M16 1H4C2.9 1 2 1.9 2 3V17H4V3H16V1ZM19 5H8C6.9 5 6 5.9 6 7V21C6 22.1 6.9 23 8 23H19C20.1 23 21 22.1 21 21V7C21 5.9 20.1 5 19 5ZM19 21H8V7H19V21Z" fill="currentColor"/>
|
|
115
119
|
</svg>
|
|
116
120
|
</div>
|
|
117
121
|
`:""}
|
|
118
122
|
</div>
|
|
119
|
-
`).join("");this.dropdownMenu.innerHTML=
|
|
123
|
+
`).join("");this.dropdownMenu.innerHTML=e,document.body.appendChild(this.dropdownMenu)}bindEvents(){this.floatingBlock.addEventListener("click",()=>{this.toggleDropdown()}),this.dropdownMenu.addEventListener("click",e=>{const r=e.target,a=r.closest(".tiny-remoter-copy-icon");if(a){e.stopPropagation();const o=a.dataset.action;o&&this.handleAction(o);return}const n=r.closest(".tiny-remoter-dropdown-item"),s=n==null?void 0:n.dataset.action;s&&this.handleAction(s)}),document.addEventListener("click",e=>{const r=e.target;!this.floatingBlock.contains(r)&&!this.dropdownMenu.contains(r)&&this.closeDropdown()}),document.addEventListener("keydown",e=>{e.key==="Escape"&&this.closeDropdown()})}toggleDropdown(){this.isExpanded?this.closeDropdown():this.openDropdown()}openDropdown(){this.isExpanded=!0,this.floatingBlock.classList.add("expanded"),this.dropdownMenu.classList.add("show")}closeDropdown(){this.isExpanded=!1,this.floatingBlock.classList.remove("expanded"),this.dropdownMenu.classList.remove("show")}handleAction(e){switch(e){case"qr-code":this.showQRCode();break;case"ai-chat":this.showAIChat();break;case"remote-control":this.copyRemoteControl();break;case"remote-url":this.copyRemoteURL();break}this.closeDropdown()}copyRemoteControl(){this.copyToClipboard(this.options.sessionId.slice(-6))}copyRemoteURL(){this.copyToClipboard(this.options.remoteUrl+this.sessionPrefix+this.options.sessionId)}async copyToClipboard(e){try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(e),this.showCopyFeedback(!0);else{const r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.left="-999999px",r.style.top="-999999px",document.body.appendChild(r),r.focus(),r.select();const a=document.execCommand("copy");document.body.removeChild(r),a?this.showCopyFeedback(!0):this.showCopyFeedback(!1)}}catch(r){console.error("复制失败:",r),this.showCopyFeedback(!1)}}showCopyFeedback(e){const r=e?"复制成功!":"复制失败,请手动复制",a=document.createElement("div");a.className=`tiny-remoter-copy-feedback ${e?"success":"error"}`,a.textContent=r,document.body.appendChild(a),setTimeout(()=>a.classList.add("show"),10),setTimeout(()=>{a.classList.remove("show"),setTimeout(()=>{a.parentNode&&a.parentNode.removeChild(a)},300)},1500)}async showQRCode(){const r=await new Um((this.options.qrCodeUrl||"")+this.sessionPrefix+this.options.sessionId,{}).toDataURL(),a=this.createModal("扫码前往智能遥控器",`
|
|
120
124
|
<div style="text-align: center; padding: 32px;">
|
|
121
125
|
<!-- 二维码容器 - 添加渐变背景和阴影效果 -->
|
|
122
126
|
<div style="
|
|
@@ -154,7 +158,7 @@ Minimum version required to store current data is: `+s+`.
|
|
|
154
158
|
position: relative;
|
|
155
159
|
z-index: 1;
|
|
156
160
|
">
|
|
157
|
-
<img src="${
|
|
161
|
+
<img src="${r}" alt="二维码" style="
|
|
158
162
|
width: 100%;
|
|
159
163
|
height: 100%;
|
|
160
164
|
object-fit: contain;
|
|
@@ -197,18 +201,18 @@ Minimum version required to store current data is: `+s+`.
|
|
|
197
201
|
<span>支持微信、浏览器等多种方式</span>
|
|
198
202
|
</div>
|
|
199
203
|
</div>
|
|
200
|
-
`);this.showModal(
|
|
204
|
+
`);this.showModal(a)}showAIChat(){var e,r;(r=(e=this.options).onShowAIChat)==null||r.call(e)}createModal(e,r){const a=document.createElement("div");a.className="tiny-remoter-floating-modal",a.innerHTML=`
|
|
201
205
|
<div class="tiny-remoter-modal-overlay"></div>
|
|
202
206
|
<div class="tiny-remoter-modal-content">
|
|
203
207
|
<div class="tiny-remoter-modal-header">
|
|
204
|
-
<h3>${
|
|
208
|
+
<h3>${e}</h3>
|
|
205
209
|
<button class="tiny-remoter-modal-close">×</button>
|
|
206
210
|
</div>
|
|
207
211
|
<div class="tiny-remoter-modal-body">
|
|
208
|
-
${
|
|
212
|
+
${r}
|
|
209
213
|
</div>
|
|
210
214
|
</div>
|
|
211
|
-
`;const
|
|
215
|
+
`;const n=a.querySelector(".tiny-remoter-modal-close"),s=a.querySelector(".tiny-remoter-modal-overlay");return n.addEventListener("click",()=>this.hideModal(a)),s.addEventListener("click",()=>this.hideModal(a)),a}showModal(e){document.body.appendChild(e),setTimeout(()=>e.classList.add("show"),10)}hideModal(e){e.classList.remove("show"),setTimeout(()=>{e.parentNode&&e.parentNode.removeChild(e)},100)}addStyles(){const e=document.createElement("style");e.textContent=`
|
|
212
216
|
/* 浮动块样式 */
|
|
213
217
|
.tiny-remoter-floating-block {
|
|
214
218
|
position: fixed;
|
|
@@ -517,4 +521,4 @@ Minimum version required to store current data is: `+s+`.
|
|
|
517
521
|
color: white;
|
|
518
522
|
}
|
|
519
523
|
}
|
|
520
|
-
`,document.head.appendChild(
|
|
524
|
+
`,document.head.appendChild(e)}destroy(){this.floatingBlock.parentNode&&this.floatingBlock.parentNode.removeChild(this.floatingBlock),this.dropdownMenu.parentNode&&this.dropdownMenu.parentNode.removeChild(this.dropdownMenu)}}const y2=(t={})=>new g2(t);gr.AgentModelProvider=PC,gr.QrCode=Um,gr.createRemoter=y2,gr.getAISDKTools=Ml,Object.defineProperty(gr,Symbol.toStringTag,{value:"Module"})});
|