@gram-ai/elements 1.20.2 → 1.21.2
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/bin/cli.js +14 -12
- package/dist/components/Chat/stories/ConnectionConfiguration.stories.d.ts +2 -2
- package/dist/components/Chat/stories/ToolApproval.stories.d.ts +2 -0
- package/dist/components/ui/dialog.d.ts +1 -1
- package/dist/components/ui/tooltip.d.ts +3 -1
- package/dist/constants/tailwind.d.ts +1 -0
- package/dist/contexts/portal-container-context.d.ts +2 -0
- package/dist/contexts/portal-container.d.ts +7 -0
- package/dist/elements.cjs +1 -160
- package/dist/elements.cjs.map +1 -1
- package/dist/elements.css +1 -1
- package/dist/elements.js +11 -47215
- package/dist/elements.js.map +1 -1
- package/dist/hooks/usePortalContainer.d.ts +8 -0
- package/dist/hooks/useSession.d.ts +1 -2
- package/dist/index-BVvrv2G3.cjs +169 -0
- package/dist/index-BVvrv2G3.cjs.map +1 -0
- package/dist/index-OU3wjArm.js +54670 -0
- package/dist/index-OU3wjArm.js.map +1 -0
- package/dist/index.d.ts +3 -1
- package/dist/lib/auth.d.ts +2 -2
- package/dist/lib/errorTracking.config.d.ts +16 -0
- package/dist/lib/errorTracking.d.ts +24 -0
- package/dist/lib/tools.d.ts +3 -2
- package/dist/profiler-DPH9zydw.cjs +2 -0
- package/dist/profiler-DPH9zydw.cjs.map +1 -0
- package/dist/profiler-D_HNXmyv.js +278 -0
- package/dist/profiler-D_HNXmyv.js.map +1 -0
- package/dist/startRecording-B97e4Mlu.cjs +3 -0
- package/dist/startRecording-B97e4Mlu.cjs.map +1 -0
- package/dist/startRecording-DOMzQAAr.js +1212 -0
- package/dist/startRecording-DOMzQAAr.js.map +1 -0
- package/dist/types/index.d.ts +45 -15
- package/package.json +16 -2
- package/src/components/Chat/index.tsx +31 -3
- package/src/components/Chat/stories/Composer.stories.tsx +0 -7
- package/src/components/Chat/stories/ConnectionConfiguration.stories.tsx +7 -14
- package/src/components/Chat/stories/CustomComponents.stories.tsx +0 -7
- package/src/components/Chat/stories/Density.stories.tsx +0 -7
- package/src/components/Chat/stories/ErrorBoundary.stories.tsx +4 -23
- package/src/components/Chat/stories/FrontendTools.stories.tsx +0 -7
- package/src/components/Chat/stories/Model.stories.tsx +0 -7
- package/src/components/Chat/stories/Plugins.stories.tsx +0 -7
- package/src/components/Chat/stories/Radius.stories.tsx +0 -7
- package/src/components/Chat/stories/ToolApproval.stories.tsx +51 -7
- package/src/components/Chat/stories/Tools.stories.tsx +0 -7
- package/src/components/Chat/stories/Variants.stories.tsx +5 -2
- package/src/components/Chat/stories/Welcome.stories.tsx +0 -8
- package/src/components/assistant-ui/assistant-sidecar.tsx +1 -4
- package/src/components/assistant-ui/attachment.tsx +1 -4
- package/src/components/assistant-ui/error-boundary.tsx +6 -0
- package/src/components/assistant-ui/thread-list.tsx +3 -1
- package/src/components/assistant-ui/thread.tsx +10 -12
- package/src/components/ui/dialog.tsx +10 -1
- package/src/components/ui/popover.tsx +10 -12
- package/src/components/ui/tooltip.tsx +7 -2
- package/src/constants/tailwind.ts +2 -0
- package/src/contexts/ElementsProvider.tsx +13 -1
- package/src/contexts/portal-container-context.ts +4 -0
- package/src/contexts/portal-container.tsx +20 -0
- package/src/global.css +129 -16
- package/src/hooks/useAuth.ts +6 -16
- package/src/hooks/usePortalContainer.ts +16 -0
- package/src/hooks/useSession.ts +1 -3
- package/src/index.ts +5 -0
- package/src/lib/api.test.ts +5 -5
- package/src/lib/auth.ts +4 -4
- package/src/lib/errorTracking.config.ts +16 -0
- package/src/lib/errorTracking.ts +104 -0
- package/src/lib/tools.ts +37 -8
- package/src/types/index.ts +48 -16
- package/src/vite-env.d.ts +3 -0
- package/dist/components/Chat/stories/ColorScheme.stories.d.ts +0 -8
- package/src/components/Chat/stories/ColorScheme.stories.tsx +0 -52
package/dist/elements.cjs
CHANGED
|
@@ -1,161 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const
|
|
2
|
-
Error message: ${Ti(n)}`,cause:n}),this[wb]=!0,this.text=t}static isInstance(t){return ce.hasMarker(t,_b)}};wb=zP;var xb="AI_NoSuchModelError",Sb=`vercel.ai.error.${xb}`,UP=Symbol.for(Sb),Ib,LP=class extends ce{constructor({errorName:e=xb,modelId:t,modelType:n,message:i=`No such ${n}: ${t}`}){super({name:e,message:i}),this[Ib]=!0,this.modelId=t,this.modelType=n}static isInstance(e){return ce.hasMarker(e,Sb)}};Ib=UP;var kb="AI_TypeValidationError",Eb=`vercel.ai.error.${kb}`,FP=Symbol.for(Eb),Tb,BP=class Dc extends ce{constructor({value:t,cause:n}){super({name:kb,message:`Type validation failed: Value: ${JSON.stringify(t)}.
|
|
3
|
-
Error message: ${Ti(n)}`,cause:n}),this[Tb]=!0,this.value=t}static isInstance(t){return ce.hasMarker(t,Eb)}static wrap({value:t,cause:n}){return Dc.isInstance(n)&&n.value===t?n:new Dc({value:t,cause:n})}};Tb=FP;var Un=BP;let gm=class extends Error{constructor(t,n){super(t),this.name="ParseError",this.type=n.type,this.field=n.field,this.value=n.value,this.line=n.line}};function Du(e){}function ZP(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=Du,onError:n=Du,onRetry:i=Du,onComment:r}=e;let o="",a=!0,s,u="",l="";function c(m){const y=a?m.replace(/^\xEF\xBB\xBF/,""):m,[v,_]=qP(`${o}${y}`);for(const x of v)d(x);o=_,a=!1}function d(m){if(m===""){p();return}if(m.startsWith(":")){r&&r(m.slice(m.startsWith(": ")?2:1));return}const y=m.indexOf(":");if(y!==-1){const v=m.slice(0,y),_=m[y+1]===" "?2:1,x=m.slice(y+_);f(v,x,m);return}f(m,"",m)}function f(m,y,v){switch(m){case"event":l=y;break;case"data":u=`${u}${y}
|
|
4
|
-
`;break;case"id":s=y.includes("\0")?void 0:y;break;case"retry":/^\d+$/.test(y)?i(parseInt(y,10)):n(new gm(`Invalid \`retry\` value: "${y}"`,{type:"invalid-retry",value:y,line:v}));break;default:n(new gm(`Unknown field "${m.length>20?`${m.slice(0,20)}…`:m}"`,{type:"unknown-field",field:m,value:y,line:v}));break}}function p(){u.length>0&&t({id:s,event:l||void 0,data:u.endsWith(`
|
|
5
|
-
`)?u.slice(0,-1):u}),s=void 0,u="",l=""}function g(m={}){o&&m.consume&&d(o),a=!0,s=void 0,u="",l="",o=""}return{feed:c,reset:g}}function qP(e){const t=[];let n="",i=0;for(;i<e.length;){const r=e.indexOf("\r",i),o=e.indexOf(`
|
|
6
|
-
`,i);let a=-1;if(r!==-1&&o!==-1?a=Math.min(r,o):r!==-1?r===e.length-1?a=-1:a=r:o!==-1&&(a=o),a===-1){n=e.slice(i);break}else{const s=e.slice(i,a);t.push(s),i=a+1,e[i-1]==="\r"&&e[i]===`
|
|
7
|
-
`&&i++}}return[t,n]}let uo=class extends TransformStream{constructor({onError:t,onRetry:n,onComment:i}={}){let r;super({start(o){r=ZP({onEvent:a=>{o.enqueue(a)},onError(a){t==="terminate"?o.error(a):typeof t=="function"&&t(a)},onRetry:n,onComment:i})},transform(o){r.feed(o)}})}};const Bd=Object.freeze({status:"aborted"});function P(e,t,n){function i(s,u){if(s._zod||Object.defineProperty(s,"_zod",{value:{def:u,constr:a,traits:new Set},enumerable:!1}),s._zod.traits.has(e))return;s._zod.traits.add(e),t(s,u);const l=a.prototype,c=Object.keys(l);for(let d=0;d<c.length;d++){const f=c[d];f in s||(s[f]=l[f].bind(s))}}const r=n?.Parent??Object;class o extends r{}Object.defineProperty(o,"name",{value:e});function a(s){var u;const l=n?.Parent?new o:this;i(l,s),(u=l._zod).deferred??(u.deferred=[]);for(const c of l._zod.deferred)c();return l}return Object.defineProperty(a,"init",{value:i}),Object.defineProperty(a,Symbol.hasInstance,{value:s=>n?.Parent&&s instanceof n.Parent?!0:s?._zod?.traits?.has(e)}),Object.defineProperty(a,"name",{value:e}),a}const $b=Symbol("zod_brand");class Er extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class sl extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}const ys={};function st(e){return e&&Object.assign(ys,e),ys}function VP(e){return e}function HP(e){return e}function JP(e){}function WP(e){throw new Error("Unexpected value in exhaustive check")}function GP(e){}function Zd(e){const t=Object.values(e).filter(i=>typeof i=="number");return Object.entries(e).filter(([i,r])=>t.indexOf(+i)===-1).map(([i,r])=>r)}function q(e,t="|"){return e.map(n=>ae(n)).join(t)}function bs(e,t){return typeof t=="bigint"?t.toString():t}function Fo(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Dr(e){return e==null}function ll(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function Cb(e,t){const n=(e.toString().split(".")[1]||"").length,i=t.toString();let r=(i.split(".")[1]||"").length;if(r===0&&/\d?e-\d?/.test(i)){const u=i.match(/\d?e-(\d?)/);u?.[1]&&(r=Number.parseInt(u[1]))}const o=n>r?n:r,a=Number.parseInt(e.toFixed(o).replace(".","")),s=Number.parseInt(t.toFixed(o).replace(".",""));return a%s/10**o}const vm=Symbol("evaluating");function ve(e,t,n){let i;Object.defineProperty(e,t,{get(){if(i!==vm)return i===void 0&&(i=vm,i=n()),i},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function KP(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function pr(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function qn(...e){const t={};for(const n of e){const i=Object.getOwnPropertyDescriptors(n);Object.assign(t,i)}return Object.defineProperties({},t)}function YP(e){return qn(e._zod.def)}function XP(e,t){return t?t.reduce((n,i)=>n?.[i],e):e}function QP(e){const t=Object.keys(e),n=t.map(i=>e[i]);return Promise.all(n).then(i=>{const r={};for(let o=0;o<t.length;o++)r[t[o]]=i[o];return r})}function eR(e=10){const t="abcdefghijklmnopqrstuvwxyz";let n="";for(let i=0;i<e;i++)n+=t[Math.floor(Math.random()*t.length)];return n}function zc(e){return JSON.stringify(e)}function Ab(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const qd="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function pi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Pb=Fo(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Cr(e){if(pi(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(pi(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function ul(e){return Cr(e)?{...e}:Array.isArray(e)?[...e]:e}function tR(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}const nR=e=>{const t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},_s=new Set(["string","number","symbol"]),Rb=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Ln(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Gt(e,t,n){const i=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(i._zod.parent=e),i}function M(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function rR(e){let t;return new Proxy({},{get(n,i,r){return t??(t=e()),Reflect.get(t,i,r)},set(n,i,r,o){return t??(t=e()),Reflect.set(t,i,r,o)},has(n,i){return t??(t=e()),Reflect.has(t,i)},deleteProperty(n,i){return t??(t=e()),Reflect.deleteProperty(t,i)},ownKeys(n){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(n,i){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,i)},defineProperty(n,i,r){return t??(t=e()),Reflect.defineProperty(t,i,r)}})}function ae(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function Ob(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const Nb={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]},jb={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Mb(e,t){const n=e._zod.def,i=qn(e._zod.def,{get shape(){const r={};for(const o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&(r[o]=n.shape[o])}return pr(this,"shape",r),r},checks:[]});return Gt(e,i)}function Db(e,t){const n=e._zod.def,i=qn(e._zod.def,{get shape(){const r={...e._zod.def.shape};for(const o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&delete r[o]}return pr(this,"shape",r),r},checks:[]});return Gt(e,i)}function zb(e,t){if(!Cr(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0)throw new Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");const r=qn(e._zod.def,{get shape(){const o={...e._zod.def.shape,...t};return pr(this,"shape",o),o},checks:[]});return Gt(e,r)}function Ub(e,t){if(!Cr(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n={...e._zod.def,get shape(){const i={...e._zod.def.shape,...t};return pr(this,"shape",i),i},checks:e._zod.def.checks};return Gt(e,n)}function Lb(e,t){const n=qn(e._zod.def,{get shape(){const i={...e._zod.def.shape,...t._zod.def.shape};return pr(this,"shape",i),i},get catchall(){return t._zod.def.catchall},checks:[]});return Gt(e,n)}function Fb(e,t,n){const i=qn(t._zod.def,{get shape(){const r=t._zod.def.shape,o={...r};if(n)for(const a in n){if(!(a in r))throw new Error(`Unrecognized key: "${a}"`);n[a]&&(o[a]=e?new e({type:"optional",innerType:r[a]}):r[a])}else for(const a in r)o[a]=e?new e({type:"optional",innerType:r[a]}):r[a];return pr(this,"shape",o),o},checks:[]});return Gt(t,i)}function Bb(e,t,n){const i=qn(t._zod.def,{get shape(){const r=t._zod.def.shape,o={...r};if(n)for(const a in n){if(!(a in o))throw new Error(`Unrecognized key: "${a}"`);n[a]&&(o[a]=new e({type:"nonoptional",innerType:r[a]}))}else for(const a in r)o[a]=new e({type:"nonoptional",innerType:r[a]});return pr(this,"shape",o),o},checks:[]});return Gt(t,i)}function xr(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function rn(e,t){return t.map(n=>{var i;return(i=n).path??(i.path=[]),n.path.unshift(e),n})}function Ji(e){return typeof e=="string"?e:e?.message}function Ht(e,t,n){const i={...e,path:e.path??[]};if(!e.message){const r=Ji(e.inst?._zod.def?.error?.(e))??Ji(t?.error?.(e))??Ji(n.customError?.(e))??Ji(n.localeError?.(e))??"Invalid input";i.message=r}return delete i.inst,delete i.continue,t?.reportInput||delete i.input,i}function cl(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function dl(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function fi(...e){const[t,n,i]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:i}:{...t}}function iR(e){return Object.entries(e).filter(([t,n])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function Zb(e){const t=atob(e),n=new Uint8Array(t.length);for(let i=0;i<t.length;i++)n[i]=t.charCodeAt(i);return n}function qb(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function oR(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n="=".repeat((4-t.length%4)%4);return Zb(t+n)}function aR(e){return qb(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function sR(e){const t=e.replace(/^0x/,"");if(t.length%2!==0)throw new Error("Invalid hex string length");const n=new Uint8Array(t.length/2);for(let i=0;i<t.length;i+=2)n[i/2]=Number.parseInt(t.slice(i,i+2),16);return n}function lR(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}class uR{constructor(...t){}}const Vb=Object.freeze(Object.defineProperty({__proto__:null,BIGINT_FORMAT_RANGES:jb,Class:uR,NUMBER_FORMAT_RANGES:Nb,aborted:xr,allowsEval:Pb,assert:GP,assertEqual:VP,assertIs:JP,assertNever:WP,assertNotEqual:HP,assignProp:pr,base64ToUint8Array:Zb,base64urlToUint8Array:oR,cached:Fo,captureStackTrace:qd,cleanEnum:iR,cleanRegex:ll,clone:Gt,cloneDef:YP,createTransparentProxy:rR,defineLazy:ve,esc:zc,escapeRegex:Ln,extend:zb,finalizeIssue:Ht,floatSafeRemainder:Cb,getElementAtPath:XP,getEnumValues:Zd,getLengthableOrigin:dl,getParsedType:nR,getSizableOrigin:cl,hexToUint8Array:sR,isObject:pi,isPlainObject:Cr,issue:fi,joinValues:q,jsonStringifyReplacer:bs,merge:Lb,mergeDefs:qn,normalizeParams:M,nullish:Dr,numKeys:tR,objectClone:KP,omit:Db,optionalKeys:Ob,partial:Fb,pick:Mb,prefixIssues:rn,primitiveTypes:Rb,promiseAllObject:QP,propertyKeyTypes:_s,randomString:eR,required:Bb,safeExtend:Ub,shallowClone:ul,slugify:Ab,stringifyPrimitive:ae,uint8ArrayToBase64:qb,uint8ArrayToBase64url:aR,uint8ArrayToHex:lR,unwrapMessage:Ji},Symbol.toStringTag,{value:"Module"})),Hb=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,bs,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Vd=P("$ZodError",Hb),Dt=P("$ZodError",Hb,{Parent:Error});function Hd(e,t=n=>n.message){const n={},i=[];for(const r of e.issues)r.path.length>0?(n[r.path[0]]=n[r.path[0]]||[],n[r.path[0]].push(t(r))):i.push(t(r));return{formErrors:i,fieldErrors:n}}function Jd(e,t=n=>n.message){const n={_errors:[]},i=r=>{for(const o of r.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(a=>i({issues:a}));else if(o.code==="invalid_key")i({issues:o.issues});else if(o.code==="invalid_element")i({issues:o.issues});else if(o.path.length===0)n._errors.push(t(o));else{let a=n,s=0;for(;s<o.path.length;){const u=o.path[s];s===o.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(t(o))):a[u]=a[u]||{_errors:[]},a=a[u],s++}}};return i(e),n}function Jb(e,t=n=>n.message){const n={errors:[]},i=(r,o=[])=>{var a,s;for(const u of r.issues)if(u.code==="invalid_union"&&u.errors.length)u.errors.map(l=>i({issues:l},u.path));else if(u.code==="invalid_key")i({issues:u.issues},u.path);else if(u.code==="invalid_element")i({issues:u.issues},u.path);else{const l=[...o,...u.path];if(l.length===0){n.errors.push(t(u));continue}let c=n,d=0;for(;d<l.length;){const f=l[d],p=d===l.length-1;typeof f=="string"?(c.properties??(c.properties={}),(a=c.properties)[f]??(a[f]={errors:[]}),c=c.properties[f]):(c.items??(c.items=[]),(s=c.items)[f]??(s[f]={errors:[]}),c=c.items[f]),p&&c.errors.push(t(u)),d++}}};return i(e),n}function Wb(e){const t=[],n=e.map(i=>typeof i=="object"?i.key:i);for(const i of n)typeof i=="number"?t.push(`[${i}]`):typeof i=="symbol"?t.push(`[${JSON.stringify(String(i))}]`):/[^\w$]/.test(i)?t.push(`[${JSON.stringify(i)}]`):(t.length&&t.push("."),t.push(i));return t.join("")}function Gb(e){const t=[],n=[...e.issues].sort((i,r)=>(i.path??[]).length-(r.path??[]).length);for(const i of n)t.push(`✖ ${i.message}`),i.path?.length&&t.push(` → at ${Wb(i.path)}`);return t.join(`
|
|
8
|
-
`)}const Bo=e=>(t,n,i,r)=>{const o=i?Object.assign(i,{async:!1}):{async:!1},a=t._zod.run({value:n,issues:[]},o);if(a instanceof Promise)throw new Er;if(a.issues.length){const s=new(r?.Err??e)(a.issues.map(u=>Ht(u,o,st())));throw qd(s,r?.callee),s}return a.value},Uc=Bo(Dt),Zo=e=>async(t,n,i,r)=>{const o=i?Object.assign(i,{async:!0}):{async:!0};let a=t._zod.run({value:n,issues:[]},o);if(a instanceof Promise&&(a=await a),a.issues.length){const s=new(r?.Err??e)(a.issues.map(u=>Ht(u,o,st())));throw qd(s,r?.callee),s}return a.value},Lc=Zo(Dt),qo=e=>(t,n,i)=>{const r=i?{...i,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},r);if(o instanceof Promise)throw new Er;return o.issues.length?{success:!1,error:new(e??Vd)(o.issues.map(a=>Ht(a,r,st())))}:{success:!0,data:o.value}},Kb=qo(Dt),Vo=e=>async(t,n,i)=>{const r=i?Object.assign(i,{async:!0}):{async:!0};let o=t._zod.run({value:n,issues:[]},r);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map(a=>Ht(a,r,st())))}:{success:!0,data:o.value}},Yb=Vo(Dt),Wd=e=>(t,n,i)=>{const r=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return Bo(e)(t,n,r)},cR=Wd(Dt),Gd=e=>(t,n,i)=>Bo(e)(t,n,i),dR=Gd(Dt),Kd=e=>async(t,n,i)=>{const r=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return Zo(e)(t,n,r)},pR=Kd(Dt),Yd=e=>async(t,n,i)=>Zo(e)(t,n,i),fR=Yd(Dt),Xd=e=>(t,n,i)=>{const r=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return qo(e)(t,n,r)},hR=Xd(Dt),Qd=e=>(t,n,i)=>qo(e)(t,n,i),mR=Qd(Dt),ep=e=>async(t,n,i)=>{const r=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return Vo(e)(t,n,r)},gR=ep(Dt),tp=e=>async(t,n,i)=>Vo(e)(t,n,i),vR=tp(Dt),Xb=/^[cC][^\s-]{8,}$/,Qb=/^[0-9a-z]+$/,e_=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,t_=/^[0-9a-vA-V]{20}$/,n_=/^[A-Za-z0-9]{27}$/,r_=/^[a-zA-Z0-9_-]{21}$/,i_=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,yR=/^[-+]?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)?)??$/,o_=/^([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})$/,hi=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|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,bR=hi(4),_R=hi(6),wR=hi(7),a_=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,xR=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,SR=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,s_=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,IR=s_,kR=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,ER="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function l_(){return new RegExp(ER,"u")}const u_=/^(?:(?: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])$/,c_=/^(([0-9a-fA-F]{1,4}:){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}|:))$/,d_=e=>{const t=Ln(e??":");return new RegExp(`^(?:[0-9A-F]{2}${t}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${t}){5}[0-9a-f]{2}$`)},p_=/^((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])$/,f_=/^(([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])$/,h_=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,np=/^[A-Za-z0-9_-]*$/,m_=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,g_=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,v_=/^\+(?:[0-9]){6,14}[0-9]$/,y_="(?:(?:\\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])))",b_=new RegExp(`^${y_}$`);function __(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 w_(e){return new RegExp(`^${__(e)}$`)}function x_(e){const t=__({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const i=`${t}(?:${n.join("|")})`;return new RegExp(`^${y_}T(?:${i})$`)}const S_=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},I_=/^-?\d+n?$/,k_=/^-?\d+$/,E_=/^-?\d+(?:\.\d+)?/,T_=/^(?:true|false)$/i,$_=/^null$/i,C_=/^undefined$/i,A_=/^[^A-Z]*$/,P_=/^[^a-z]*$/,R_=/^[0-9a-fA-F]*$/;function Ho(e,t){return new RegExp(`^[A-Za-z0-9+/]{${e}}${t}$`)}function Jo(e){return new RegExp(`^[A-Za-z0-9_-]{${e}}$`)}const TR=/^[0-9a-fA-F]{32}$/,$R=Ho(22,"=="),CR=Jo(22),AR=/^[0-9a-fA-F]{40}$/,PR=Ho(27,"="),RR=Jo(27),OR=/^[0-9a-fA-F]{64}$/,NR=Ho(43,"="),jR=Jo(43),MR=/^[0-9a-fA-F]{96}$/,DR=Ho(64,""),zR=Jo(64),UR=/^[0-9a-fA-F]{128}$/,LR=Ho(86,"=="),FR=Jo(86),rp=Object.freeze(Object.defineProperty({__proto__:null,base64:h_,base64url:np,bigint:I_,boolean:T_,browserEmail:kR,cidrv4:p_,cidrv6:f_,cuid:Xb,cuid2:Qb,date:b_,datetime:x_,domain:g_,duration:i_,e164:v_,email:a_,emoji:l_,extendedDuration:yR,guid:o_,hex:R_,hostname:m_,html5Email:xR,idnEmail:IR,integer:k_,ipv4:u_,ipv6:c_,ksuid:n_,lowercase:A_,mac:d_,md5_base64:$R,md5_base64url:CR,md5_hex:TR,nanoid:r_,null:$_,number:E_,rfc5322Email:SR,sha1_base64:PR,sha1_base64url:RR,sha1_hex:AR,sha256_base64:NR,sha256_base64url:jR,sha256_hex:OR,sha384_base64:DR,sha384_base64url:zR,sha384_hex:MR,sha512_base64:LR,sha512_base64url:FR,sha512_hex:UR,string:S_,time:w_,ulid:e_,undefined:C_,unicodeEmail:s_,uppercase:P_,uuid:hi,uuid4:bR,uuid6:_R,uuid7:wR,xid:t_},Symbol.toStringTag,{value:"Module"})),Fe=P("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),O_={number:"number",bigint:"bigint",object:"date"},ip=P("$ZodCheckLessThan",(e,t)=>{Fe.init(e,t);const n=O_[typeof t.value];e._zod.onattach.push(i=>{const r=i._zod.bag,o=(t.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<o&&(t.inclusive?r.maximum=t.value:r.exclusiveMaximum=t.value)}),e._zod.check=i=>{(t.inclusive?i.value<=t.value:i.value<t.value)||i.issues.push({origin:n,code:"too_big",maximum:t.value,input:i.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),op=P("$ZodCheckGreaterThan",(e,t)=>{Fe.init(e,t);const n=O_[typeof t.value];e._zod.onattach.push(i=>{const r=i._zod.bag,o=(t.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>o&&(t.inclusive?r.minimum=t.value:r.exclusiveMinimum=t.value)}),e._zod.check=i=>{(t.inclusive?i.value>=t.value:i.value>t.value)||i.issues.push({origin:n,code:"too_small",minimum:t.value,input:i.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),N_=P("$ZodCheckMultipleOf",(e,t)=>{Fe.init(e,t),e._zod.onattach.push(n=>{var i;(i=n._zod.bag).multipleOf??(i.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):Cb(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})}}),j_=P("$ZodCheckNumberFormat",(e,t)=>{Fe.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),i=n?"int":"number",[r,o]=Nb[t.format];e._zod.onattach.push(a=>{const s=a._zod.bag;s.format=t.format,s.minimum=r,s.maximum=o,n&&(s.pattern=k_)}),e._zod.check=a=>{const s=a.value;if(n){if(!Number.isInteger(s)){a.issues.push({expected:i,format:t.format,code:"invalid_type",continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?a.issues.push({input:s,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:i,continue:!t.abort}):a.issues.push({input:s,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:i,continue:!t.abort});return}}s<r&&a.issues.push({origin:"number",input:s,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),s>o&&a.issues.push({origin:"number",input:s,code:"too_big",maximum:o,inst:e})}}),M_=P("$ZodCheckBigIntFormat",(e,t)=>{Fe.init(e,t);const[n,i]=jb[t.format];e._zod.onattach.push(r=>{const o=r._zod.bag;o.format=t.format,o.minimum=n,o.maximum=i}),e._zod.check=r=>{const o=r.value;o<n&&r.issues.push({origin:"bigint",input:o,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort}),o>i&&r.issues.push({origin:"bigint",input:o,code:"too_big",maximum:i,inst:e})}}),D_=P("$ZodCheckMaxSize",(e,t)=>{var n;Fe.init(e,t),(n=e._zod.def).when??(n.when=i=>{const r=i.value;return!Dr(r)&&r.size!==void 0}),e._zod.onattach.push(i=>{const r=i._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<r&&(i._zod.bag.maximum=t.maximum)}),e._zod.check=i=>{const r=i.value;r.size<=t.maximum||i.issues.push({origin:cl(r),code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),z_=P("$ZodCheckMinSize",(e,t)=>{var n;Fe.init(e,t),(n=e._zod.def).when??(n.when=i=>{const r=i.value;return!Dr(r)&&r.size!==void 0}),e._zod.onattach.push(i=>{const r=i._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>r&&(i._zod.bag.minimum=t.minimum)}),e._zod.check=i=>{const r=i.value;r.size>=t.minimum||i.issues.push({origin:cl(r),code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),U_=P("$ZodCheckSizeEquals",(e,t)=>{var n;Fe.init(e,t),(n=e._zod.def).when??(n.when=i=>{const r=i.value;return!Dr(r)&&r.size!==void 0}),e._zod.onattach.push(i=>{const r=i._zod.bag;r.minimum=t.size,r.maximum=t.size,r.size=t.size}),e._zod.check=i=>{const r=i.value,o=r.size;if(o===t.size)return;const a=o>t.size;i.issues.push({origin:cl(r),...a?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:i.value,inst:e,continue:!t.abort})}}),L_=P("$ZodCheckMaxLength",(e,t)=>{var n;Fe.init(e,t),(n=e._zod.def).when??(n.when=i=>{const r=i.value;return!Dr(r)&&r.length!==void 0}),e._zod.onattach.push(i=>{const r=i._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<r&&(i._zod.bag.maximum=t.maximum)}),e._zod.check=i=>{const r=i.value;if(r.length<=t.maximum)return;const a=dl(r);i.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),F_=P("$ZodCheckMinLength",(e,t)=>{var n;Fe.init(e,t),(n=e._zod.def).when??(n.when=i=>{const r=i.value;return!Dr(r)&&r.length!==void 0}),e._zod.onattach.push(i=>{const r=i._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>r&&(i._zod.bag.minimum=t.minimum)}),e._zod.check=i=>{const r=i.value;if(r.length>=t.minimum)return;const a=dl(r);i.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),B_=P("$ZodCheckLengthEquals",(e,t)=>{var n;Fe.init(e,t),(n=e._zod.def).when??(n.when=i=>{const r=i.value;return!Dr(r)&&r.length!==void 0}),e._zod.onattach.push(i=>{const r=i._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=i=>{const r=i.value,o=r.length;if(o===t.length)return;const a=dl(r),s=o>t.length;i.issues.push({origin:a,...s?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:i.value,inst:e,continue:!t.abort})}}),Wo=P("$ZodCheckStringFormat",(e,t)=>{var n,i;Fe.init(e,t),e._zod.onattach.push(r=>{const o=r._zod.bag;o.format=t.format,t.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(i=e._zod).check??(i.check=()=>{})}),Z_=P("$ZodCheckRegex",(e,t)=>{Wo.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})}}),q_=P("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=A_),Wo.init(e,t)}),V_=P("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=P_),Wo.init(e,t)}),H_=P("$ZodCheckIncludes",(e,t)=>{Fe.init(e,t);const n=Ln(t.includes),i=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=i,e._zod.onattach.push(r=>{const o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(i)}),e._zod.check=r=>{r.value.includes(t.includes,t.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),J_=P("$ZodCheckStartsWith",(e,t)=>{Fe.init(e,t);const n=new RegExp(`^${Ln(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(i=>{const r=i._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(n)}),e._zod.check=i=>{i.value.startsWith(t.prefix)||i.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:i.value,inst:e,continue:!t.abort})}}),W_=P("$ZodCheckEndsWith",(e,t)=>{Fe.init(e,t);const n=new RegExp(`.*${Ln(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(i=>{const r=i._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(n)}),e._zod.check=i=>{i.value.endsWith(t.suffix)||i.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:i.value,inst:e,continue:!t.abort})}});function ym(e,t,n){e.issues.length&&t.issues.push(...rn(n,e.issues))}const G_=P("$ZodCheckProperty",(e,t)=>{Fe.init(e,t),e._zod.check=n=>{const i=t.schema._zod.run({value:n.value[t.property],issues:[]},{});if(i instanceof Promise)return i.then(r=>ym(r,n,t.property));ym(i,n,t.property)}}),K_=P("$ZodCheckMimeType",(e,t)=>{Fe.init(e,t);const n=new Set(t.mime);e._zod.onattach.push(i=>{i._zod.bag.mime=t.mime}),e._zod.check=i=>{n.has(i.value.type)||i.issues.push({code:"invalid_value",values:t.mime,input:i.value.type,inst:e,continue:!t.abort})}}),Y_=P("$ZodCheckOverwrite",(e,t)=>{Fe.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class X_{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 i=t.split(`
|
|
9
|
-
`).filter(a=>a),r=Math.min(...i.map(a=>a.length-a.trimStart().length)),o=i.map(a=>a.slice(r)).map(a=>" ".repeat(this.indent*2)+a);for(const a of o)this.content.push(a)}compile(){const t=Function,n=this?.args,r=[...(this?.content??[""]).map(o=>` ${o}`)];return new t(...n,r.join(`
|
|
10
|
-
`))}}const Q_={major:4,minor:2,patch:1},de=P("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Q_;const i=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&i.unshift(e);for(const r of i)for(const o of r._zod.onattach)o(e);if(i.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const r=(a,s,u)=>{let l=xr(a),c;for(const d of s){if(d._zod.def.when){if(!d._zod.def.when(a))continue}else if(l)continue;const f=a.issues.length,p=d._zod.check(a);if(p instanceof Promise&&u?.async===!1)throw new Er;if(c||p instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await p,a.issues.length!==f&&(l||(l=xr(a,f)))});else{if(a.issues.length===f)continue;l||(l=xr(a,f))}}return c?c.then(()=>a):a},o=(a,s,u)=>{if(xr(a))return a.aborted=!0,a;const l=r(s,i,u);if(l instanceof Promise){if(u.async===!1)throw new Er;return l.then(c=>e._zod.parse(c,u))}return e._zod.parse(l,u)};e._zod.run=(a,s)=>{if(s.skipChecks)return e._zod.parse(a,s);if(s.direction==="backward"){const l=e._zod.parse({value:a.value,issues:[]},{...s,skipChecks:!0});return l instanceof Promise?l.then(c=>o(c,a,s)):o(l,a,s)}const u=e._zod.parse(a,s);if(u instanceof Promise){if(s.async===!1)throw new Er;return u.then(l=>r(l,i,s))}return r(u,i,s)}}e["~standard"]={validate:r=>{try{const o=Kb(e,r);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return Yb(e,r).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}}),Go=P("$ZodString",(e,t)=>{de.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??S_(e._zod.bag),e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Oe=P("$ZodStringFormat",(e,t)=>{Wo.init(e,t),Go.init(e,t)}),ew=P("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=o_),Oe.init(e,t)}),tw=P("$ZodUUID",(e,t)=>{if(t.version){const i={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(i===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=hi(i))}else t.pattern??(t.pattern=hi());Oe.init(e,t)}),nw=P("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=a_),Oe.init(e,t)}),rw=P("$ZodURL",(e,t)=>{Oe.init(e,t),e._zod.check=n=>{try{const i=n.value.trim(),r=new URL(i);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(r.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(r.protocol.endsWith(":")?r.protocol.slice(0,-1):r.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=r.href:n.value=i;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),iw=P("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=l_()),Oe.init(e,t)}),ow=P("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=r_),Oe.init(e,t)}),aw=P("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Xb),Oe.init(e,t)}),sw=P("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Qb),Oe.init(e,t)}),lw=P("$ZodULID",(e,t)=>{t.pattern??(t.pattern=e_),Oe.init(e,t)}),uw=P("$ZodXID",(e,t)=>{t.pattern??(t.pattern=t_),Oe.init(e,t)}),cw=P("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=n_),Oe.init(e,t)}),dw=P("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=x_(t)),Oe.init(e,t)}),pw=P("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=b_),Oe.init(e,t)}),fw=P("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=w_(t)),Oe.init(e,t)}),hw=P("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=i_),Oe.init(e,t)}),mw=P("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=u_),Oe.init(e,t),e._zod.bag.format="ipv4"}),gw=P("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=c_),Oe.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),vw=P("$ZodMAC",(e,t)=>{t.pattern??(t.pattern=d_(t.delimiter)),Oe.init(e,t),e._zod.bag.format="mac"}),yw=P("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=p_),Oe.init(e,t)}),bw=P("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=f_),Oe.init(e,t),e._zod.check=n=>{const i=n.value.split("/");try{if(i.length!==2)throw new Error;const[r,o]=i;if(!o)throw new Error;const a=Number(o);if(`${a}`!==o)throw new Error;if(a<0||a>128)throw new Error;new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function ap(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const _w=P("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=h_),Oe.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{ap(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function ww(e){if(!np.test(e))return!1;const t=e.replace(/[-_]/g,i=>i==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return ap(n)}const xw=P("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=np),Oe.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{ww(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),Sw=P("$ZodE164",(e,t)=>{t.pattern??(t.pattern=v_),Oe.init(e,t)});function Iw(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[i]=n;if(!i)return!1;const r=JSON.parse(atob(i));return!("typ"in r&&r?.typ!=="JWT"||!r.alg||t&&(!("alg"in r)||r.alg!==t))}catch{return!1}}const kw=P("$ZodJWT",(e,t)=>{Oe.init(e,t),e._zod.check=n=>{Iw(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),Ew=P("$ZodCustomStringFormat",(e,t)=>{Oe.init(e,t),e._zod.check=n=>{t.fn(n.value)||n.issues.push({code:"invalid_format",format:t.format,input:n.value,inst:e,continue:!t.abort})}}),sp=P("$ZodNumber",(e,t)=>{de.init(e,t),e._zod.pattern=e._zod.bag.pattern??E_,e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const r=n.value;if(typeof r=="number"&&!Number.isNaN(r)&&Number.isFinite(r))return n;const o=typeof r=="number"?Number.isNaN(r)?"NaN":Number.isFinite(r)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:r,inst:e,...o?{received:o}:{}}),n}}),Tw=P("$ZodNumberFormat",(e,t)=>{j_.init(e,t),sp.init(e,t)}),lp=P("$ZodBoolean",(e,t)=>{de.init(e,t),e._zod.pattern=T_,e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=!!n.value}catch{}const r=n.value;return typeof r=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:r,inst:e}),n}}),up=P("$ZodBigInt",(e,t)=>{de.init(e,t),e._zod.pattern=I_,e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=BigInt(n.value)}catch{}return typeof n.value=="bigint"||n.issues.push({expected:"bigint",code:"invalid_type",input:n.value,inst:e}),n}}),$w=P("$ZodBigIntFormat",(e,t)=>{M_.init(e,t),up.init(e,t)}),Cw=P("$ZodSymbol",(e,t)=>{de.init(e,t),e._zod.parse=(n,i)=>{const r=n.value;return typeof r=="symbol"||n.issues.push({expected:"symbol",code:"invalid_type",input:r,inst:e}),n}}),Aw=P("$ZodUndefined",(e,t)=>{de.init(e,t),e._zod.pattern=C_,e._zod.values=new Set([void 0]),e._zod.optin="optional",e._zod.optout="optional",e._zod.parse=(n,i)=>{const r=n.value;return typeof r>"u"||n.issues.push({expected:"undefined",code:"invalid_type",input:r,inst:e}),n}}),Pw=P("$ZodNull",(e,t)=>{de.init(e,t),e._zod.pattern=$_,e._zod.values=new Set([null]),e._zod.parse=(n,i)=>{const r=n.value;return r===null||n.issues.push({expected:"null",code:"invalid_type",input:r,inst:e}),n}}),Rw=P("$ZodAny",(e,t)=>{de.init(e,t),e._zod.parse=n=>n}),Ow=P("$ZodUnknown",(e,t)=>{de.init(e,t),e._zod.parse=n=>n}),Nw=P("$ZodNever",(e,t)=>{de.init(e,t),e._zod.parse=(n,i)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)}),jw=P("$ZodVoid",(e,t)=>{de.init(e,t),e._zod.parse=(n,i)=>{const r=n.value;return typeof r>"u"||n.issues.push({expected:"void",code:"invalid_type",input:r,inst:e}),n}}),Mw=P("$ZodDate",(e,t)=>{de.init(e,t),e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=new Date(n.value)}catch{}const r=n.value,o=r instanceof Date;return o&&!Number.isNaN(r.getTime())||n.issues.push({expected:"date",code:"invalid_type",input:r,...o?{received:"Invalid Date"}:{},inst:e}),n}});function bm(e,t,n){e.issues.length&&t.issues.push(...rn(n,e.issues)),t.value[n]=e.value}const Dw=P("$ZodArray",(e,t)=>{de.init(e,t),e._zod.parse=(n,i)=>{const r=n.value;if(!Array.isArray(r))return n.issues.push({expected:"array",code:"invalid_type",input:r,inst:e}),n;n.value=Array(r.length);const o=[];for(let a=0;a<r.length;a++){const s=r[a],u=t.element._zod.run({value:s,issues:[]},i);u instanceof Promise?o.push(u.then(l=>bm(l,n,a))):bm(u,n,a)}return o.length?Promise.all(o).then(()=>n):n}});function ws(e,t,n,i){e.issues.length&&t.issues.push(...rn(n,e.issues)),e.value===void 0?n in i&&(t.value[n]=void 0):t.value[n]=e.value}function zw(e){const t=Object.keys(e.shape);for(const i of t)if(!e.shape?.[i]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${i}": expected a Zod schema`);const n=Ob(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function Uw(e,t,n,i,r,o){const a=[],s=r.keySet,u=r.catchall._zod,l=u.def.type;for(const c in t){if(s.has(c))continue;if(l==="never"){a.push(c);continue}const d=u.run({value:t[c],issues:[]},i);d instanceof Promise?e.push(d.then(f=>ws(f,n,c,t))):ws(d,n,c,t)}return a.length&&n.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:o}),e.length?Promise.all(e).then(()=>n):n}const Lw=P("$ZodObject",(e,t)=>{if(de.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const s=t.shape;Object.defineProperty(t,"shape",{get:()=>{const u={...s};return Object.defineProperty(t,"shape",{value:u}),u}})}const i=Fo(()=>zw(t));ve(e._zod,"propValues",()=>{const s=t.shape,u={};for(const l in s){const c=s[l]._zod;if(c.values){u[l]??(u[l]=new Set);for(const d of c.values)u[l].add(d)}}return u});const r=pi,o=t.catchall;let a;e._zod.parse=(s,u)=>{a??(a=i.value);const l=s.value;if(!r(l))return s.issues.push({expected:"object",code:"invalid_type",input:l,inst:e}),s;s.value={};const c=[],d=a.shape;for(const f of a.keys){const g=d[f]._zod.run({value:l[f],issues:[]},u);g instanceof Promise?c.push(g.then(m=>ws(m,s,f,l))):ws(g,s,f,l)}return o?Uw(c,l,s,u,i.value,e):c.length?Promise.all(c).then(()=>s):s}}),Fw=P("$ZodObjectJIT",(e,t)=>{Lw.init(e,t);const n=e._zod.parse,i=Fo(()=>zw(t)),r=f=>{const p=new X_(["shape","payload","ctx"]),g=i.value,m=x=>{const b=zc(x);return`shape[${b}]._zod.run({ value: input[${b}], issues: [] }, ctx)`};p.write("const input = payload.value;");const y=Object.create(null);let v=0;for(const x of g.keys)y[x]=`key_${v++}`;p.write("const newResult = {};");for(const x of g.keys){const b=y[x],C=zc(x);p.write(`const ${b} = ${m(x)};`),p.write(`
|
|
11
|
-
if (${b}.issues.length) {
|
|
12
|
-
payload.issues = payload.issues.concat(${b}.issues.map(iss => ({
|
|
13
|
-
...iss,
|
|
14
|
-
path: iss.path ? [${C}, ...iss.path] : [${C}]
|
|
15
|
-
})));
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
if (${b}.value === undefined) {
|
|
20
|
-
if (${C} in input) {
|
|
21
|
-
newResult[${C}] = undefined;
|
|
22
|
-
}
|
|
23
|
-
} else {
|
|
24
|
-
newResult[${C}] = ${b}.value;
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
`)}p.write("payload.value = newResult;"),p.write("return payload;");const _=p.compile();return(x,b)=>_(f,x,b)};let o;const a=pi,s=!ys.jitless,l=s&&Pb.value,c=t.catchall;let d;e._zod.parse=(f,p)=>{d??(d=i.value);const g=f.value;return a(g)?s&&l&&p?.async===!1&&p.jitless!==!0?(o||(o=r(t.shape)),f=o(f,p),c?Uw([],g,f,p,d,e):f):n(f,p):(f.issues.push({expected:"object",code:"invalid_type",input:g,inst:e}),f)}});function _m(e,t,n,i){for(const o of e)if(o.issues.length===0)return t.value=o.value,t;const r=e.filter(o=>!xr(o));return r.length===1?(t.value=r[0].value,r[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(o=>o.issues.map(a=>Ht(a,i,st())))}),t)}const pl=P("$ZodUnion",(e,t)=>{de.init(e,t),ve(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),ve(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),ve(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),ve(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){const r=t.options.map(o=>o._zod.pattern);return new RegExp(`^(${r.map(o=>ll(o.source)).join("|")})$`)}});const n=t.options.length===1,i=t.options[0]._zod.run;e._zod.parse=(r,o)=>{if(n)return i(r,o);let a=!1;const s=[];for(const u of t.options){const l=u._zod.run({value:r.value,issues:[]},o);if(l instanceof Promise)s.push(l),a=!0;else{if(l.issues.length===0)return l;s.push(l)}}return a?Promise.all(s).then(u=>_m(u,r,e,o)):_m(s,r,e,o)}});function wm(e,t,n,i){const r=e.filter(o=>o.issues.length===0);return r.length===1?(t.value=r[0].value,t):(r.length===0?t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(o=>o.issues.map(a=>Ht(a,i,st())))}):t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:[],inclusive:!1}),t)}const Bw=P("$ZodXor",(e,t)=>{pl.init(e,t),t.inclusive=!1;const n=t.options.length===1,i=t.options[0]._zod.run;e._zod.parse=(r,o)=>{if(n)return i(r,o);let a=!1;const s=[];for(const u of t.options){const l=u._zod.run({value:r.value,issues:[]},o);l instanceof Promise?(s.push(l),a=!0):s.push(l)}return a?Promise.all(s).then(u=>wm(u,r,e,o)):wm(s,r,e,o)}}),Zw=P("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,pl.init(e,t);const n=e._zod.parse;ve(e._zod,"propValues",()=>{const r={};for(const o of t.options){const a=o._zod.propValues;if(!a||Object.keys(a).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(o)}"`);for(const[s,u]of Object.entries(a)){r[s]||(r[s]=new Set);for(const l of u)r[s].add(l)}}return r});const i=Fo(()=>{const r=t.options,o=new Map;for(const a of r){const s=a._zod.propValues?.[t.discriminator];if(!s||s.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(a)}"`);for(const u of s){if(o.has(u))throw new Error(`Duplicate discriminator value "${String(u)}"`);o.set(u,a)}}return o});e._zod.parse=(r,o)=>{const a=r.value;if(!pi(a))return r.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),r;const s=i.value.get(a?.[t.discriminator]);return s?s._zod.run(r,o):t.unionFallback?n(r,o):(r.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,input:a,path:[t.discriminator],inst:e}),r)}}),qw=P("$ZodIntersection",(e,t)=>{de.init(e,t),e._zod.parse=(n,i)=>{const r=n.value,o=t.left._zod.run({value:r,issues:[]},i),a=t.right._zod.run({value:r,issues:[]},i);return o instanceof Promise||a instanceof Promise?Promise.all([o,a]).then(([u,l])=>xm(n,u,l)):xm(n,o,a)}});function Fc(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(Cr(e)&&Cr(t)){const n=Object.keys(t),i=Object.keys(e).filter(o=>n.indexOf(o)!==-1),r={...e,...t};for(const o of i){const a=Fc(e[o],t[o]);if(!a.valid)return{valid:!1,mergeErrorPath:[o,...a.mergeErrorPath]};r[o]=a.data}return{valid:!0,data:r}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let i=0;i<e.length;i++){const r=e[i],o=t[i],a=Fc(r,o);if(!a.valid)return{valid:!1,mergeErrorPath:[i,...a.mergeErrorPath]};n.push(a.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function xm(e,t,n){if(t.issues.length&&e.issues.push(...t.issues),n.issues.length&&e.issues.push(...n.issues),xr(e))return e;const i=Fc(t.value,n.value);if(!i.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return e.value=i.data,e}const cp=P("$ZodTuple",(e,t)=>{de.init(e,t);const n=t.items;e._zod.parse=(i,r)=>{const o=i.value;if(!Array.isArray(o))return i.issues.push({input:o,inst:e,expected:"tuple",code:"invalid_type"}),i;i.value=[];const a=[],s=[...n].reverse().findIndex(c=>c._zod.optin!=="optional"),u=s===-1?0:n.length-s;if(!t.rest){const c=o.length>n.length,d=o.length<u-1;if(c||d)return i.issues.push({...c?{code:"too_big",maximum:n.length}:{code:"too_small",minimum:n.length},input:o,inst:e,origin:"array"}),i}let l=-1;for(const c of n){if(l++,l>=o.length&&l>=u)continue;const d=c._zod.run({value:o[l],issues:[]},r);d instanceof Promise?a.push(d.then(f=>Na(f,i,l))):Na(d,i,l)}if(t.rest){const c=o.slice(n.length);for(const d of c){l++;const f=t.rest._zod.run({value:d,issues:[]},r);f instanceof Promise?a.push(f.then(p=>Na(p,i,l))):Na(f,i,l)}}return a.length?Promise.all(a).then(()=>i):i}});function Na(e,t,n){e.issues.length&&t.issues.push(...rn(n,e.issues)),t.value[n]=e.value}const Vw=P("$ZodRecord",(e,t)=>{de.init(e,t),e._zod.parse=(n,i)=>{const r=n.value;if(!Cr(r))return n.issues.push({expected:"record",code:"invalid_type",input:r,inst:e}),n;const o=[],a=t.keyType._zod.values;if(a){n.value={};const s=new Set;for(const l of a)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){s.add(typeof l=="number"?l.toString():l);const c=t.valueType._zod.run({value:r[l],issues:[]},i);c instanceof Promise?o.push(c.then(d=>{d.issues.length&&n.issues.push(...rn(l,d.issues)),n.value[l]=d.value})):(c.issues.length&&n.issues.push(...rn(l,c.issues)),n.value[l]=c.value)}let u;for(const l in r)s.has(l)||(u=u??[],u.push(l));u&&u.length>0&&n.issues.push({code:"unrecognized_keys",input:r,inst:e,keys:u})}else{n.value={};for(const s of Reflect.ownKeys(r)){if(s==="__proto__")continue;const u=t.keyType._zod.run({value:s,issues:[]},i);if(u instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(u.issues.length){t.mode==="loose"?n.value[s]=r[s]:n.issues.push({code:"invalid_key",origin:"record",issues:u.issues.map(c=>Ht(c,i,st())),input:s,path:[s],inst:e});continue}const l=t.valueType._zod.run({value:r[s],issues:[]},i);l instanceof Promise?o.push(l.then(c=>{c.issues.length&&n.issues.push(...rn(s,c.issues)),n.value[u.value]=c.value})):(l.issues.length&&n.issues.push(...rn(s,l.issues)),n.value[u.value]=l.value)}}return o.length?Promise.all(o).then(()=>n):n}}),Hw=P("$ZodMap",(e,t)=>{de.init(e,t),e._zod.parse=(n,i)=>{const r=n.value;if(!(r instanceof Map))return n.issues.push({expected:"map",code:"invalid_type",input:r,inst:e}),n;const o=[];n.value=new Map;for(const[a,s]of r){const u=t.keyType._zod.run({value:a,issues:[]},i),l=t.valueType._zod.run({value:s,issues:[]},i);u instanceof Promise||l instanceof Promise?o.push(Promise.all([u,l]).then(([c,d])=>{Sm(c,d,n,a,r,e,i)})):Sm(u,l,n,a,r,e,i)}return o.length?Promise.all(o).then(()=>n):n}});function Sm(e,t,n,i,r,o,a){e.issues.length&&(_s.has(typeof i)?n.issues.push(...rn(i,e.issues)):n.issues.push({code:"invalid_key",origin:"map",input:r,inst:o,issues:e.issues.map(s=>Ht(s,a,st()))})),t.issues.length&&(_s.has(typeof i)?n.issues.push(...rn(i,t.issues)):n.issues.push({origin:"map",code:"invalid_element",input:r,inst:o,key:i,issues:t.issues.map(s=>Ht(s,a,st()))})),n.value.set(e.value,t.value)}const Jw=P("$ZodSet",(e,t)=>{de.init(e,t),e._zod.parse=(n,i)=>{const r=n.value;if(!(r instanceof Set))return n.issues.push({input:r,inst:e,expected:"set",code:"invalid_type"}),n;const o=[];n.value=new Set;for(const a of r){const s=t.valueType._zod.run({value:a,issues:[]},i);s instanceof Promise?o.push(s.then(u=>Im(u,n))):Im(s,n)}return o.length?Promise.all(o).then(()=>n):n}});function Im(e,t){e.issues.length&&t.issues.push(...e.issues),t.value.add(e.value)}const Ww=P("$ZodEnum",(e,t)=>{de.init(e,t);const n=Zd(t.entries),i=new Set(n);e._zod.values=i,e._zod.pattern=new RegExp(`^(${n.filter(r=>_s.has(typeof r)).map(r=>typeof r=="string"?Ln(r):r.toString()).join("|")})$`),e._zod.parse=(r,o)=>{const a=r.value;return i.has(a)||r.issues.push({code:"invalid_value",values:n,input:a,inst:e}),r}}),Gw=P("$ZodLiteral",(e,t)=>{if(de.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");const n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map(i=>typeof i=="string"?Ln(i):i?Ln(i.toString()):String(i)).join("|")})$`),e._zod.parse=(i,r)=>{const o=i.value;return n.has(o)||i.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),i}}),Kw=P("$ZodFile",(e,t)=>{de.init(e,t),e._zod.parse=(n,i)=>{const r=n.value;return r instanceof File||n.issues.push({expected:"file",code:"invalid_type",input:r,inst:e}),n}}),Yw=P("$ZodTransform",(e,t)=>{de.init(e,t),e._zod.parse=(n,i)=>{if(i.direction==="backward")throw new sl(e.constructor.name);const r=t.transform(n.value,n);if(i.async)return(r instanceof Promise?r:Promise.resolve(r)).then(a=>(n.value=a,n));if(r instanceof Promise)throw new Er;return n.value=r,n}});function km(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}const Xw=P("$ZodOptional",(e,t)=>{de.init(e,t),e._zod.optin="optional",e._zod.optout="optional",ve(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),ve(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${ll(n.source)})?$`):void 0}),e._zod.parse=(n,i)=>{if(t.innerType._zod.optin==="optional"){const r=t.innerType._zod.run(n,i);return r instanceof Promise?r.then(o=>km(o,n.value)):km(r,n.value)}return n.value===void 0?n:t.innerType._zod.run(n,i)}}),Qw=P("$ZodNullable",(e,t)=>{de.init(e,t),ve(e._zod,"optin",()=>t.innerType._zod.optin),ve(e._zod,"optout",()=>t.innerType._zod.optout),ve(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${ll(n.source)}|null)$`):void 0}),ve(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,i)=>n.value===null?n:t.innerType._zod.run(n,i)}),ex=P("$ZodDefault",(e,t)=>{de.init(e,t),e._zod.optin="optional",ve(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,i)=>{if(i.direction==="backward")return t.innerType._zod.run(n,i);if(n.value===void 0)return n.value=t.defaultValue,n;const r=t.innerType._zod.run(n,i);return r instanceof Promise?r.then(o=>Em(o,t)):Em(r,t)}});function Em(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const tx=P("$ZodPrefault",(e,t)=>{de.init(e,t),e._zod.optin="optional",ve(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,i)=>(i.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,i))}),nx=P("$ZodNonOptional",(e,t)=>{de.init(e,t),ve(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(i=>i!==void 0)):void 0}),e._zod.parse=(n,i)=>{const r=t.innerType._zod.run(n,i);return r instanceof Promise?r.then(o=>Tm(o,e)):Tm(r,e)}});function Tm(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 rx=P("$ZodSuccess",(e,t)=>{de.init(e,t),e._zod.parse=(n,i)=>{if(i.direction==="backward")throw new sl("ZodSuccess");const r=t.innerType._zod.run(n,i);return r instanceof Promise?r.then(o=>(n.value=o.issues.length===0,n)):(n.value=r.issues.length===0,n)}}),ix=P("$ZodCatch",(e,t)=>{de.init(e,t),ve(e._zod,"optin",()=>t.innerType._zod.optin),ve(e._zod,"optout",()=>t.innerType._zod.optout),ve(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,i)=>{if(i.direction==="backward")return t.innerType._zod.run(n,i);const r=t.innerType._zod.run(n,i);return r instanceof Promise?r.then(o=>(n.value=o.value,o.issues.length&&(n.value=t.catchValue({...n,error:{issues:o.issues.map(a=>Ht(a,i,st()))},input:n.value}),n.issues=[]),n)):(n.value=r.value,r.issues.length&&(n.value=t.catchValue({...n,error:{issues:r.issues.map(o=>Ht(o,i,st()))},input:n.value}),n.issues=[]),n)}}),ox=P("$ZodNaN",(e,t)=>{de.init(e,t),e._zod.parse=(n,i)=>((typeof n.value!="number"||!Number.isNaN(n.value))&&n.issues.push({input:n.value,inst:e,expected:"nan",code:"invalid_type"}),n)}),ax=P("$ZodPipe",(e,t)=>{de.init(e,t),ve(e._zod,"values",()=>t.in._zod.values),ve(e._zod,"optin",()=>t.in._zod.optin),ve(e._zod,"optout",()=>t.out._zod.optout),ve(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,i)=>{if(i.direction==="backward"){const o=t.out._zod.run(n,i);return o instanceof Promise?o.then(a=>ja(a,t.in,i)):ja(o,t.in,i)}const r=t.in._zod.run(n,i);return r instanceof Promise?r.then(o=>ja(o,t.out,i)):ja(r,t.out,i)}});function ja(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const dp=P("$ZodCodec",(e,t)=>{de.init(e,t),ve(e._zod,"values",()=>t.in._zod.values),ve(e._zod,"optin",()=>t.in._zod.optin),ve(e._zod,"optout",()=>t.out._zod.optout),ve(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,i)=>{if((i.direction||"forward")==="forward"){const o=t.in._zod.run(n,i);return o instanceof Promise?o.then(a=>Ma(a,t,i)):Ma(o,t,i)}else{const o=t.out._zod.run(n,i);return o instanceof Promise?o.then(a=>Ma(a,t,i)):Ma(o,t,i)}}});function Ma(e,t,n){if(e.issues.length)return e.aborted=!0,e;if((n.direction||"forward")==="forward"){const r=t.transform(e.value,e);return r instanceof Promise?r.then(o=>Da(e,o,t.out,n)):Da(e,r,t.out,n)}else{const r=t.reverseTransform(e.value,e);return r instanceof Promise?r.then(o=>Da(e,o,t.in,n)):Da(e,r,t.in,n)}}function Da(e,t,n,i){return e.issues.length?(e.aborted=!0,e):n._zod.run({value:t,issues:e.issues},i)}const sx=P("$ZodReadonly",(e,t)=>{de.init(e,t),ve(e._zod,"propValues",()=>t.innerType._zod.propValues),ve(e._zod,"values",()=>t.innerType._zod.values),ve(e._zod,"optin",()=>t.innerType?._zod?.optin),ve(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,i)=>{if(i.direction==="backward")return t.innerType._zod.run(n,i);const r=t.innerType._zod.run(n,i);return r instanceof Promise?r.then($m):$m(r)}});function $m(e){return e.value=Object.freeze(e.value),e}const lx=P("$ZodTemplateLiteral",(e,t)=>{de.init(e,t);const n=[];for(const i of t.parts)if(typeof i=="object"&&i!==null){if(!i._zod.pattern)throw new Error(`Invalid template literal part, no pattern found: ${[...i._zod.traits].shift()}`);const r=i._zod.pattern instanceof RegExp?i._zod.pattern.source:i._zod.pattern;if(!r)throw new Error(`Invalid template literal part: ${i._zod.traits}`);const o=r.startsWith("^")?1:0,a=r.endsWith("$")?r.length-1:r.length;n.push(r.slice(o,a))}else if(i===null||Rb.has(typeof i))n.push(Ln(`${i}`));else throw new Error(`Invalid template literal part: ${i}`);e._zod.pattern=new RegExp(`^${n.join("")}$`),e._zod.parse=(i,r)=>typeof i.value!="string"?(i.issues.push({input:i.value,inst:e,expected:"template_literal",code:"invalid_type"}),i):(e._zod.pattern.lastIndex=0,e._zod.pattern.test(i.value)||i.issues.push({input:i.value,inst:e,code:"invalid_format",format:t.format??"template_literal",pattern:e._zod.pattern.source}),i)}),ux=P("$ZodFunction",(e,t)=>(de.init(e,t),e._def=t,e._zod.def=t,e.implement=n=>{if(typeof n!="function")throw new Error("implement() must be called with a function");return function(...i){const r=e._def.input?Uc(e._def.input,i):i,o=Reflect.apply(n,this,r);return e._def.output?Uc(e._def.output,o):o}},e.implementAsync=n=>{if(typeof n!="function")throw new Error("implementAsync() must be called with a function");return async function(...i){const r=e._def.input?await Lc(e._def.input,i):i,o=await Reflect.apply(n,this,r);return e._def.output?await Lc(e._def.output,o):o}},e._zod.parse=(n,i)=>typeof n.value!="function"?(n.issues.push({code:"invalid_type",expected:"function",input:n.value,inst:e}),n):(e._def.output&&e._def.output._zod.def.type==="promise"?n.value=e.implementAsync(n.value):n.value=e.implement(n.value),n),e.input=(...n)=>{const i=e.constructor;return Array.isArray(n[0])?new i({type:"function",input:new cp({type:"tuple",items:n[0],rest:n[1]}),output:e._def.output}):new i({type:"function",input:n[0],output:e._def.output})},e.output=n=>{const i=e.constructor;return new i({type:"function",input:e._def.input,output:n})},e)),cx=P("$ZodPromise",(e,t)=>{de.init(e,t),e._zod.parse=(n,i)=>Promise.resolve(n.value).then(r=>t.innerType._zod.run({value:r,issues:[]},i))}),dx=P("$ZodLazy",(e,t)=>{de.init(e,t),ve(e._zod,"innerType",()=>t.getter()),ve(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),ve(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),ve(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),ve(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(n,i)=>e._zod.innerType._zod.run(n,i)}),px=P("$ZodCustom",(e,t)=>{Fe.init(e,t),de.init(e,t),e._zod.parse=(n,i)=>n,e._zod.check=n=>{const i=n.value,r=t.fn(i);if(r instanceof Promise)return r.then(o=>Cm(o,n,i,e));Cm(r,n,i,e)}});function Cm(e,t,n,i){if(!e){const r={code:"custom",input:n,inst:i,path:[...i._zod.def.path??[]],continue:!i._zod.def.abort};i._zod.def.params&&(r.params=i._zod.def.params),t.issues.push(fi(r))}}const BR=()=>{const e={string:{unit:"حرف",verb:"أن يحوي"},file:{unit:"بايت",verb:"أن يحوي"},array:{unit:"عنصر",verb:"أن يحوي"},set:{unit:"عنصر",verb:"أن يحوي"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"number";case"object":{if(Array.isArray(r))return"array";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"مدخل",email:"بريد إلكتروني",url:"رابط",emoji:"إيموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاريخ ووقت بمعيار ISO",date:"تاريخ بمعيار ISO",time:"وقت بمعيار ISO",duration:"مدة بمعيار ISO",ipv4:"عنوان IPv4",ipv6:"عنوان IPv6",cidrv4:"مدى عناوين بصيغة IPv4",cidrv6:"مدى عناوين بصيغة IPv6",base64:"نَص بترميز base64-encoded",base64url:"نَص بترميز base64url-encoded",json_string:"نَص على هيئة JSON",e164:"رقم هاتف بمعيار E.164",jwt:"JWT",template_literal:"مدخل"};return r=>{switch(r.code){case"invalid_type":return`مدخلات غير مقبولة: يفترض إدخال ${r.expected}، ولكن تم إدخال ${n(r.input)}`;case"invalid_value":return r.values.length===1?`مدخلات غير مقبولة: يفترض إدخال ${ae(r.values[0])}`:`اختيار غير مقبول: يتوقع انتقاء أحد هذه الخيارات: ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?` أكبر من اللازم: يفترض أن تكون ${r.origin??"القيمة"} ${o} ${r.maximum.toString()} ${a.unit??"عنصر"}`:`أكبر من اللازم: يفترض أن تكون ${r.origin??"القيمة"} ${o} ${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`أصغر من اللازم: يفترض لـ ${r.origin} أن يكون ${o} ${r.minimum.toString()} ${a.unit}`:`أصغر من اللازم: يفترض لـ ${r.origin} أن يكون ${o} ${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`نَص غير مقبول: يجب أن يبدأ بـ "${r.prefix}"`:o.format==="ends_with"?`نَص غير مقبول: يجب أن ينتهي بـ "${o.suffix}"`:o.format==="includes"?`نَص غير مقبول: يجب أن يتضمَّن "${o.includes}"`:o.format==="regex"?`نَص غير مقبول: يجب أن يطابق النمط ${o.pattern}`:`${i[o.format]??r.format} غير مقبول`}case"not_multiple_of":return`رقم غير مقبول: يجب أن يكون من مضاعفات ${r.divisor}`;case"unrecognized_keys":return`معرف${r.keys.length>1?"ات":""} غريب${r.keys.length>1?"ة":""}: ${q(r.keys,"، ")}`;case"invalid_key":return`معرف غير مقبول في ${r.origin}`;case"invalid_union":return"مدخل غير مقبول";case"invalid_element":return`مدخل غير مقبول في ${r.origin}`;default:return"مدخل غير مقبول"}}};function ZR(){return{localeError:BR()}}const qR=()=>{const e={string:{unit:"simvol",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"element",verb:"olmalıdır"},set:{unit:"element",verb:"olmalıdır"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"number";case"object":{if(Array.isArray(r))return"array";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return r=>{switch(r.code){case"invalid_type":return`Yanlış dəyər: gözlənilən ${r.expected}, daxil olan ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Yanlış dəyər: gözlənilən ${ae(r.values[0])}`:`Yanlış seçim: aşağıdakılardan biri olmalıdır: ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Çox böyük: gözlənilən ${r.origin??"dəyər"} ${o}${r.maximum.toString()} ${a.unit??"element"}`:`Çox böyük: gözlənilən ${r.origin??"dəyər"} ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`Çox kiçik: gözlənilən ${r.origin} ${o}${r.minimum.toString()} ${a.unit}`:`Çox kiçik: gözlənilən ${r.origin} ${o}${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`Yanlış mətn: "${o.prefix}" ilə başlamalıdır`:o.format==="ends_with"?`Yanlış mətn: "${o.suffix}" ilə bitməlidir`:o.format==="includes"?`Yanlış mətn: "${o.includes}" daxil olmalıdır`:o.format==="regex"?`Yanlış mətn: ${o.pattern} şablonuna uyğun olmalıdır`:`Yanlış ${i[o.format]??r.format}`}case"not_multiple_of":return`Yanlış ədəd: ${r.divisor} ilə bölünə bilən olmalıdır`;case"unrecognized_keys":return`Tanınmayan açar${r.keys.length>1?"lar":""}: ${q(r.keys,", ")}`;case"invalid_key":return`${r.origin} daxilində yanlış açar`;case"invalid_union":return"Yanlış dəyər";case"invalid_element":return`${r.origin} daxilində yanlış dəyər`;default:return"Yanlış dəyər"}}};function VR(){return{localeError:qR()}}function Am(e,t,n,i){const r=Math.abs(e),o=r%10,a=r%100;return a>=11&&a<=19?i:o===1?t:o>=2&&o<=4?n:i}const HR=()=>{const e={string:{unit:{one:"сімвал",few:"сімвалы",many:"сімвалаў"},verb:"мець"},array:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},set:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},file:{unit:{one:"байт",few:"байты",many:"байтаў"},verb:"мець"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"лік";case"object":{if(Array.isArray(r))return"масіў";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"увод",email:"email адрас",url:"URL",emoji:"эмодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата і час",date:"ISO дата",time:"ISO час",duration:"ISO працягласць",ipv4:"IPv4 адрас",ipv6:"IPv6 адрас",cidrv4:"IPv4 дыяпазон",cidrv6:"IPv6 дыяпазон",base64:"радок у фармаце base64",base64url:"радок у фармаце base64url",json_string:"JSON радок",e164:"нумар E.164",jwt:"JWT",template_literal:"увод"};return r=>{switch(r.code){case"invalid_type":return`Няправільны ўвод: чакаўся ${r.expected}, атрымана ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Няправільны ўвод: чакалася ${ae(r.values[0])}`:`Няправільны варыянт: чакаўся адзін з ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);if(a){const s=Number(r.maximum),u=Am(s,a.unit.one,a.unit.few,a.unit.many);return`Занадта вялікі: чакалася, што ${r.origin??"значэнне"} павінна ${a.verb} ${o}${r.maximum.toString()} ${u}`}return`Занадта вялікі: чакалася, што ${r.origin??"значэнне"} павінна быць ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);if(a){const s=Number(r.minimum),u=Am(s,a.unit.one,a.unit.few,a.unit.many);return`Занадта малы: чакалася, што ${r.origin} павінна ${a.verb} ${o}${r.minimum.toString()} ${u}`}return`Занадта малы: чакалася, што ${r.origin} павінна быць ${o}${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`Няправільны радок: павінен пачынацца з "${o.prefix}"`:o.format==="ends_with"?`Няправільны радок: павінен заканчвацца на "${o.suffix}"`:o.format==="includes"?`Няправільны радок: павінен змяшчаць "${o.includes}"`:o.format==="regex"?`Няправільны радок: павінен адпавядаць шаблону ${o.pattern}`:`Няправільны ${i[o.format]??r.format}`}case"not_multiple_of":return`Няправільны лік: павінен быць кратным ${r.divisor}`;case"unrecognized_keys":return`Нераспазнаны ${r.keys.length>1?"ключы":"ключ"}: ${q(r.keys,", ")}`;case"invalid_key":return`Няправільны ключ у ${r.origin}`;case"invalid_union":return"Няправільны ўвод";case"invalid_element":return`Няправільнае значэнне ў ${r.origin}`;default:return"Няправільны ўвод"}}};function JR(){return{localeError:HR()}}const WR=e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"число";case"object":{if(Array.isArray(e))return"масив";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return t},GR=()=>{const e={string:{unit:"символа",verb:"да съдържа"},file:{unit:"байта",verb:"да съдържа"},array:{unit:"елемента",verb:"да съдържа"},set:{unit:"елемента",verb:"да съдържа"}};function t(i){return e[i]??null}const n={regex:"вход",email:"имейл адрес",url:"URL",emoji:"емоджи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO време",date:"ISO дата",time:"ISO време",duration:"ISO продължителност",ipv4:"IPv4 адрес",ipv6:"IPv6 адрес",cidrv4:"IPv4 диапазон",cidrv6:"IPv6 диапазон",base64:"base64-кодиран низ",base64url:"base64url-кодиран низ",json_string:"JSON низ",e164:"E.164 номер",jwt:"JWT",template_literal:"вход"};return i=>{switch(i.code){case"invalid_type":return`Невалиден вход: очакван ${i.expected}, получен ${WR(i.input)}`;case"invalid_value":return i.values.length===1?`Невалиден вход: очакван ${ae(i.values[0])}`:`Невалидна опция: очаквано едно от ${q(i.values,"|")}`;case"too_big":{const r=i.inclusive?"<=":"<",o=t(i.origin);return o?`Твърде голямо: очаква се ${i.origin??"стойност"} да съдържа ${r}${i.maximum.toString()} ${o.unit??"елемента"}`:`Твърде голямо: очаква се ${i.origin??"стойност"} да бъде ${r}${i.maximum.toString()}`}case"too_small":{const r=i.inclusive?">=":">",o=t(i.origin);return o?`Твърде малко: очаква се ${i.origin} да съдържа ${r}${i.minimum.toString()} ${o.unit}`:`Твърде малко: очаква се ${i.origin} да бъде ${r}${i.minimum.toString()}`}case"invalid_format":{const r=i;if(r.format==="starts_with")return`Невалиден низ: трябва да започва с "${r.prefix}"`;if(r.format==="ends_with")return`Невалиден низ: трябва да завършва с "${r.suffix}"`;if(r.format==="includes")return`Невалиден низ: трябва да включва "${r.includes}"`;if(r.format==="regex")return`Невалиден низ: трябва да съвпада с ${r.pattern}`;let o="Невалиден";return r.format==="emoji"&&(o="Невалидно"),r.format==="datetime"&&(o="Невалидно"),r.format==="date"&&(o="Невалидна"),r.format==="time"&&(o="Невалидно"),r.format==="duration"&&(o="Невалидна"),`${o} ${n[r.format]??i.format}`}case"not_multiple_of":return`Невалидно число: трябва да бъде кратно на ${i.divisor}`;case"unrecognized_keys":return`Неразпознат${i.keys.length>1?"и":""} ключ${i.keys.length>1?"ове":""}: ${q(i.keys,", ")}`;case"invalid_key":return`Невалиден ключ в ${i.origin}`;case"invalid_union":return"Невалиден вход";case"invalid_element":return`Невалидна стойност в ${i.origin}`;default:return"Невалиден вход"}}};function KR(){return{localeError:GR()}}const YR=()=>{const e={string:{unit:"caràcters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"number";case"object":{if(Array.isArray(r))return"array";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"entrada",email:"adreça electrònica",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i hora ISO",date:"data ISO",time:"hora ISO",duration:"durada ISO",ipv4:"adreça IPv4",ipv6:"adreça IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"};return r=>{switch(r.code){case"invalid_type":return`Tipus invàlid: s'esperava ${r.expected}, s'ha rebut ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Valor invàlid: s'esperava ${ae(r.values[0])}`:`Opció invàlida: s'esperava una de ${q(r.values," o ")}`;case"too_big":{const o=r.inclusive?"com a màxim":"menys de",a=t(r.origin);return a?`Massa gran: s'esperava que ${r.origin??"el valor"} contingués ${o} ${r.maximum.toString()} ${a.unit??"elements"}`:`Massa gran: s'esperava que ${r.origin??"el valor"} fos ${o} ${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?"com a mínim":"més de",a=t(r.origin);return a?`Massa petit: s'esperava que ${r.origin} contingués ${o} ${r.minimum.toString()} ${a.unit}`:`Massa petit: s'esperava que ${r.origin} fos ${o} ${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`Format invàlid: ha de començar amb "${o.prefix}"`:o.format==="ends_with"?`Format invàlid: ha d'acabar amb "${o.suffix}"`:o.format==="includes"?`Format invàlid: ha d'incloure "${o.includes}"`:o.format==="regex"?`Format invàlid: ha de coincidir amb el patró ${o.pattern}`:`Format invàlid per a ${i[o.format]??r.format}`}case"not_multiple_of":return`Número invàlid: ha de ser múltiple de ${r.divisor}`;case"unrecognized_keys":return`Clau${r.keys.length>1?"s":""} no reconeguda${r.keys.length>1?"s":""}: ${q(r.keys,", ")}`;case"invalid_key":return`Clau invàlida a ${r.origin}`;case"invalid_union":return"Entrada invàlida";case"invalid_element":return`Element invàlid a ${r.origin}`;default:return"Entrada invàlida"}}};function XR(){return{localeError:YR()}}const QR=()=>{const e={string:{unit:"znaků",verb:"mít"},file:{unit:"bajtů",verb:"mít"},array:{unit:"prvků",verb:"mít"},set:{unit:"prvků",verb:"mít"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"číslo";case"string":return"řetězec";case"boolean":return"boolean";case"bigint":return"bigint";case"function":return"funkce";case"symbol":return"symbol";case"undefined":return"undefined";case"object":{if(Array.isArray(r))return"pole";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"regulární výraz",email:"e-mailová adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"datum a čas ve formátu ISO",date:"datum ve formátu ISO",time:"čas ve formátu ISO",duration:"doba trvání ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"řetězec zakódovaný ve formátu base64",base64url:"řetězec zakódovaný ve formátu base64url",json_string:"řetězec ve formátu JSON",e164:"číslo E.164",jwt:"JWT",template_literal:"vstup"};return r=>{switch(r.code){case"invalid_type":return`Neplatný vstup: očekáváno ${r.expected}, obdrženo ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Neplatný vstup: očekáváno ${ae(r.values[0])}`:`Neplatná možnost: očekávána jedna z hodnot ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Hodnota je příliš velká: ${r.origin??"hodnota"} musí mít ${o}${r.maximum.toString()} ${a.unit??"prvků"}`:`Hodnota je příliš velká: ${r.origin??"hodnota"} musí být ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`Hodnota je příliš malá: ${r.origin??"hodnota"} musí mít ${o}${r.minimum.toString()} ${a.unit??"prvků"}`:`Hodnota je příliš malá: ${r.origin??"hodnota"} musí být ${o}${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`Neplatný řetězec: musí začínat na "${o.prefix}"`:o.format==="ends_with"?`Neplatný řetězec: musí končit na "${o.suffix}"`:o.format==="includes"?`Neplatný řetězec: musí obsahovat "${o.includes}"`:o.format==="regex"?`Neplatný řetězec: musí odpovídat vzoru ${o.pattern}`:`Neplatný formát ${i[o.format]??r.format}`}case"not_multiple_of":return`Neplatné číslo: musí být násobkem ${r.divisor}`;case"unrecognized_keys":return`Neznámé klíče: ${q(r.keys,", ")}`;case"invalid_key":return`Neplatný klíč v ${r.origin}`;case"invalid_union":return"Neplatný vstup";case"invalid_element":return`Neplatná hodnota v ${r.origin}`;default:return"Neplatný vstup"}}};function e1(){return{localeError:QR()}}const t1=()=>{const e={string:{unit:"tegn",verb:"havde"},file:{unit:"bytes",verb:"havde"},array:{unit:"elementer",verb:"indeholdt"},set:{unit:"elementer",verb:"indeholdt"}},t={string:"streng",number:"tal",boolean:"boolean",array:"liste",object:"objekt",set:"sæt",file:"fil"};function n(a){return e[a]??null}function i(a){return t[a]??a}const r=a=>{const s=typeof a;switch(s){case"number":return Number.isNaN(a)?"NaN":"tal";case"object":return Array.isArray(a)?"liste":a===null?"null":Object.getPrototypeOf(a)!==Object.prototype&&a.constructor?a.constructor.name:"objekt"}return s},o={regex:"input",email:"e-mailadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslæt",date:"ISO-dato",time:"ISO-klokkeslæt",duration:"ISO-varighed",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodet streng",base64url:"base64url-kodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"};return a=>{switch(a.code){case"invalid_type":return`Ugyldigt input: forventede ${i(a.expected)}, fik ${i(r(a.input))}`;case"invalid_value":return a.values.length===1?`Ugyldig værdi: forventede ${ae(a.values[0])}`:`Ugyldigt valg: forventede en af følgende ${q(a.values,"|")}`;case"too_big":{const s=a.inclusive?"<=":"<",u=n(a.origin),l=i(a.origin);return u?`For stor: forventede ${l??"value"} ${u.verb} ${s} ${a.maximum.toString()} ${u.unit??"elementer"}`:`For stor: forventede ${l??"value"} havde ${s} ${a.maximum.toString()}`}case"too_small":{const s=a.inclusive?">=":">",u=n(a.origin),l=i(a.origin);return u?`For lille: forventede ${l} ${u.verb} ${s} ${a.minimum.toString()} ${u.unit}`:`For lille: forventede ${l} havde ${s} ${a.minimum.toString()}`}case"invalid_format":{const s=a;return s.format==="starts_with"?`Ugyldig streng: skal starte med "${s.prefix}"`:s.format==="ends_with"?`Ugyldig streng: skal ende med "${s.suffix}"`:s.format==="includes"?`Ugyldig streng: skal indeholde "${s.includes}"`:s.format==="regex"?`Ugyldig streng: skal matche mønsteret ${s.pattern}`:`Ugyldig ${o[s.format]??a.format}`}case"not_multiple_of":return`Ugyldigt tal: skal være deleligt med ${a.divisor}`;case"unrecognized_keys":return`${a.keys.length>1?"Ukendte nøgler":"Ukendt nøgle"}: ${q(a.keys,", ")}`;case"invalid_key":return`Ugyldig nøgle i ${a.origin}`;case"invalid_union":return"Ugyldigt input: matcher ingen af de tilladte typer";case"invalid_element":return`Ugyldig værdi i ${a.origin}`;default:return"Ugyldigt input"}}};function n1(){return{localeError:t1()}}const r1=()=>{const e={string:{unit:"Zeichen",verb:"zu haben"},file:{unit:"Bytes",verb:"zu haben"},array:{unit:"Elemente",verb:"zu haben"},set:{unit:"Elemente",verb:"zu haben"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"Zahl";case"object":{if(Array.isArray(r))return"Array";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"Eingabe",email:"E-Mail-Adresse",url:"URL",emoji:"Emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-Datum und -Uhrzeit",date:"ISO-Datum",time:"ISO-Uhrzeit",duration:"ISO-Dauer",ipv4:"IPv4-Adresse",ipv6:"IPv6-Adresse",cidrv4:"IPv4-Bereich",cidrv6:"IPv6-Bereich",base64:"Base64-codierter String",base64url:"Base64-URL-codierter String",json_string:"JSON-String",e164:"E.164-Nummer",jwt:"JWT",template_literal:"Eingabe"};return r=>{switch(r.code){case"invalid_type":return`Ungültige Eingabe: erwartet ${r.expected}, erhalten ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Ungültige Eingabe: erwartet ${ae(r.values[0])}`:`Ungültige Option: erwartet eine von ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Zu groß: erwartet, dass ${r.origin??"Wert"} ${o}${r.maximum.toString()} ${a.unit??"Elemente"} hat`:`Zu groß: erwartet, dass ${r.origin??"Wert"} ${o}${r.maximum.toString()} ist`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`Zu klein: erwartet, dass ${r.origin} ${o}${r.minimum.toString()} ${a.unit} hat`:`Zu klein: erwartet, dass ${r.origin} ${o}${r.minimum.toString()} ist`}case"invalid_format":{const o=r;return o.format==="starts_with"?`Ungültiger String: muss mit "${o.prefix}" beginnen`:o.format==="ends_with"?`Ungültiger String: muss mit "${o.suffix}" enden`:o.format==="includes"?`Ungültiger String: muss "${o.includes}" enthalten`:o.format==="regex"?`Ungültiger String: muss dem Muster ${o.pattern} entsprechen`:`Ungültig: ${i[o.format]??r.format}`}case"not_multiple_of":return`Ungültige Zahl: muss ein Vielfaches von ${r.divisor} sein`;case"unrecognized_keys":return`${r.keys.length>1?"Unbekannte Schlüssel":"Unbekannter Schlüssel"}: ${q(r.keys,", ")}`;case"invalid_key":return`Ungültiger Schlüssel in ${r.origin}`;case"invalid_union":return"Ungültige Eingabe";case"invalid_element":return`Ungültiger Wert in ${r.origin}`;default:return"Ungültige Eingabe"}}};function i1(){return{localeError:r1()}}const o1=e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return t},a1=()=>{const e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function t(i){return e[i]??null}const n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return i=>{switch(i.code){case"invalid_type":return`Invalid input: expected ${i.expected}, received ${o1(i.input)}`;case"invalid_value":return i.values.length===1?`Invalid input: expected ${ae(i.values[0])}`:`Invalid option: expected one of ${q(i.values,"|")}`;case"too_big":{const r=i.inclusive?"<=":"<",o=t(i.origin);return o?`Too big: expected ${i.origin??"value"} to have ${r}${i.maximum.toString()} ${o.unit??"elements"}`:`Too big: expected ${i.origin??"value"} to be ${r}${i.maximum.toString()}`}case"too_small":{const r=i.inclusive?">=":">",o=t(i.origin);return o?`Too small: expected ${i.origin} to have ${r}${i.minimum.toString()} ${o.unit}`:`Too small: expected ${i.origin} to be ${r}${i.minimum.toString()}`}case"invalid_format":{const r=i;return r.format==="starts_with"?`Invalid string: must start with "${r.prefix}"`:r.format==="ends_with"?`Invalid string: must end with "${r.suffix}"`:r.format==="includes"?`Invalid string: must include "${r.includes}"`:r.format==="regex"?`Invalid string: must match pattern ${r.pattern}`:`Invalid ${n[r.format]??i.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${i.divisor}`;case"unrecognized_keys":return`Unrecognized key${i.keys.length>1?"s":""}: ${q(i.keys,", ")}`;case"invalid_key":return`Invalid key in ${i.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${i.origin}`;default:return"Invalid input"}}};function fx(){return{localeError:a1()}}const s1=e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"nombro";case"object":{if(Array.isArray(e))return"tabelo";if(e===null)return"senvalora";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return t},l1=()=>{const e={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function t(i){return e[i]??null}const n={regex:"enigo",email:"retadreso",url:"URL",emoji:"emoĝio",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datotempo",date:"ISO-dato",time:"ISO-tempo",duration:"ISO-daŭro",ipv4:"IPv4-adreso",ipv6:"IPv6-adreso",cidrv4:"IPv4-rango",cidrv6:"IPv6-rango",base64:"64-ume kodita karaktraro",base64url:"URL-64-ume kodita karaktraro",json_string:"JSON-karaktraro",e164:"E.164-nombro",jwt:"JWT",template_literal:"enigo"};return i=>{switch(i.code){case"invalid_type":return`Nevalida enigo: atendiĝis ${i.expected}, riceviĝis ${s1(i.input)}`;case"invalid_value":return i.values.length===1?`Nevalida enigo: atendiĝis ${ae(i.values[0])}`:`Nevalida opcio: atendiĝis unu el ${q(i.values,"|")}`;case"too_big":{const r=i.inclusive?"<=":"<",o=t(i.origin);return o?`Tro granda: atendiĝis ke ${i.origin??"valoro"} havu ${r}${i.maximum.toString()} ${o.unit??"elementojn"}`:`Tro granda: atendiĝis ke ${i.origin??"valoro"} havu ${r}${i.maximum.toString()}`}case"too_small":{const r=i.inclusive?">=":">",o=t(i.origin);return o?`Tro malgranda: atendiĝis ke ${i.origin} havu ${r}${i.minimum.toString()} ${o.unit}`:`Tro malgranda: atendiĝis ke ${i.origin} estu ${r}${i.minimum.toString()}`}case"invalid_format":{const r=i;return r.format==="starts_with"?`Nevalida karaktraro: devas komenciĝi per "${r.prefix}"`:r.format==="ends_with"?`Nevalida karaktraro: devas finiĝi per "${r.suffix}"`:r.format==="includes"?`Nevalida karaktraro: devas inkluzivi "${r.includes}"`:r.format==="regex"?`Nevalida karaktraro: devas kongrui kun la modelo ${r.pattern}`:`Nevalida ${n[r.format]??i.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${i.divisor}`;case"unrecognized_keys":return`Nekonata${i.keys.length>1?"j":""} ŝlosilo${i.keys.length>1?"j":""}: ${q(i.keys,", ")}`;case"invalid_key":return`Nevalida ŝlosilo en ${i.origin}`;case"invalid_union":return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${i.origin}`;default:return"Nevalida enigo"}}};function u1(){return{localeError:l1()}}const c1=()=>{const e={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}},t={string:"texto",number:"número",boolean:"booleano",array:"arreglo",object:"objeto",set:"conjunto",file:"archivo",date:"fecha",bigint:"número grande",symbol:"símbolo",undefined:"indefinido",null:"nulo",function:"función",map:"mapa",record:"registro",tuple:"tupla",enum:"enumeración",union:"unión",literal:"literal",promise:"promesa",void:"vacío",never:"nunca",unknown:"desconocido",any:"cualquiera"};function n(a){return e[a]??null}function i(a){return t[a]??a}const r=a=>{const s=typeof a;switch(s){case"number":return Number.isNaN(a)?"NaN":"number";case"object":return Array.isArray(a)?"array":a===null?"null":Object.getPrototypeOf(a)!==Object.prototype?a.constructor.name:"object"}return s},o={regex:"entrada",email:"dirección de correo electrónico",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"fecha y hora ISO",date:"fecha ISO",time:"hora ISO",duration:"duración ISO",ipv4:"dirección IPv4",ipv6:"dirección IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"};return a=>{switch(a.code){case"invalid_type":return`Entrada inválida: se esperaba ${i(a.expected)}, recibido ${i(r(a.input))}`;case"invalid_value":return a.values.length===1?`Entrada inválida: se esperaba ${ae(a.values[0])}`:`Opción inválida: se esperaba una de ${q(a.values,"|")}`;case"too_big":{const s=a.inclusive?"<=":"<",u=n(a.origin),l=i(a.origin);return u?`Demasiado grande: se esperaba que ${l??"valor"} tuviera ${s}${a.maximum.toString()} ${u.unit??"elementos"}`:`Demasiado grande: se esperaba que ${l??"valor"} fuera ${s}${a.maximum.toString()}`}case"too_small":{const s=a.inclusive?">=":">",u=n(a.origin),l=i(a.origin);return u?`Demasiado pequeño: se esperaba que ${l} tuviera ${s}${a.minimum.toString()} ${u.unit}`:`Demasiado pequeño: se esperaba que ${l} fuera ${s}${a.minimum.toString()}`}case"invalid_format":{const s=a;return s.format==="starts_with"?`Cadena inválida: debe comenzar con "${s.prefix}"`:s.format==="ends_with"?`Cadena inválida: debe terminar en "${s.suffix}"`:s.format==="includes"?`Cadena inválida: debe incluir "${s.includes}"`:s.format==="regex"?`Cadena inválida: debe coincidir con el patrón ${s.pattern}`:`Inválido ${o[s.format]??a.format}`}case"not_multiple_of":return`Número inválido: debe ser múltiplo de ${a.divisor}`;case"unrecognized_keys":return`Llave${a.keys.length>1?"s":""} desconocida${a.keys.length>1?"s":""}: ${q(a.keys,", ")}`;case"invalid_key":return`Llave inválida en ${i(a.origin)}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido en ${i(a.origin)}`;default:return"Entrada inválida"}}};function d1(){return{localeError:c1()}}const p1=()=>{const e={string:{unit:"کاراکتر",verb:"داشته باشد"},file:{unit:"بایت",verb:"داشته باشد"},array:{unit:"آیتم",verb:"داشته باشد"},set:{unit:"آیتم",verb:"داشته باشد"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"عدد";case"object":{if(Array.isArray(r))return"آرایه";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"ورودی",email:"آدرس ایمیل",url:"URL",emoji:"ایموجی",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاریخ و زمان ایزو",date:"تاریخ ایزو",time:"زمان ایزو",duration:"مدت زمان ایزو",ipv4:"IPv4 آدرس",ipv6:"IPv6 آدرس",cidrv4:"IPv4 دامنه",cidrv6:"IPv6 دامنه",base64:"base64-encoded رشته",base64url:"base64url-encoded رشته",json_string:"JSON رشته",e164:"E.164 عدد",jwt:"JWT",template_literal:"ورودی"};return r=>{switch(r.code){case"invalid_type":return`ورودی نامعتبر: میبایست ${r.expected} میبود، ${n(r.input)} دریافت شد`;case"invalid_value":return r.values.length===1?`ورودی نامعتبر: میبایست ${ae(r.values[0])} میبود`:`گزینه نامعتبر: میبایست یکی از ${q(r.values,"|")} میبود`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`خیلی بزرگ: ${r.origin??"مقدار"} باید ${o}${r.maximum.toString()} ${a.unit??"عنصر"} باشد`:`خیلی بزرگ: ${r.origin??"مقدار"} باید ${o}${r.maximum.toString()} باشد`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`خیلی کوچک: ${r.origin} باید ${o}${r.minimum.toString()} ${a.unit} باشد`:`خیلی کوچک: ${r.origin} باید ${o}${r.minimum.toString()} باشد`}case"invalid_format":{const o=r;return o.format==="starts_with"?`رشته نامعتبر: باید با "${o.prefix}" شروع شود`:o.format==="ends_with"?`رشته نامعتبر: باید با "${o.suffix}" تمام شود`:o.format==="includes"?`رشته نامعتبر: باید شامل "${o.includes}" باشد`:o.format==="regex"?`رشته نامعتبر: باید با الگوی ${o.pattern} مطابقت داشته باشد`:`${i[o.format]??r.format} نامعتبر`}case"not_multiple_of":return`عدد نامعتبر: باید مضرب ${r.divisor} باشد`;case"unrecognized_keys":return`کلید${r.keys.length>1?"های":""} ناشناس: ${q(r.keys,", ")}`;case"invalid_key":return`کلید ناشناس در ${r.origin}`;case"invalid_union":return"ورودی نامعتبر";case"invalid_element":return`مقدار نامعتبر در ${r.origin}`;default:return"ورودی نامعتبر"}}};function f1(){return{localeError:p1()}}const h1=()=>{const e={string:{unit:"merkkiä",subject:"merkkijonon"},file:{unit:"tavua",subject:"tiedoston"},array:{unit:"alkiota",subject:"listan"},set:{unit:"alkiota",subject:"joukon"},number:{unit:"",subject:"luvun"},bigint:{unit:"",subject:"suuren kokonaisluvun"},int:{unit:"",subject:"kokonaisluvun"},date:{unit:"",subject:"päivämäärän"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"number";case"object":{if(Array.isArray(r))return"array";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"säännöllinen lauseke",email:"sähköpostiosoite",url:"URL-osoite",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-aikaleima",date:"ISO-päivämäärä",time:"ISO-aika",duration:"ISO-kesto",ipv4:"IPv4-osoite",ipv6:"IPv6-osoite",cidrv4:"IPv4-alue",cidrv6:"IPv6-alue",base64:"base64-koodattu merkkijono",base64url:"base64url-koodattu merkkijono",json_string:"JSON-merkkijono",e164:"E.164-luku",jwt:"JWT",template_literal:"templaattimerkkijono"};return r=>{switch(r.code){case"invalid_type":return`Virheellinen tyyppi: odotettiin ${r.expected}, oli ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Virheellinen syöte: täytyy olla ${ae(r.values[0])}`:`Virheellinen valinta: täytyy olla yksi seuraavista: ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Liian suuri: ${a.subject} täytyy olla ${o}${r.maximum.toString()} ${a.unit}`.trim():`Liian suuri: arvon täytyy olla ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`Liian pieni: ${a.subject} täytyy olla ${o}${r.minimum.toString()} ${a.unit}`.trim():`Liian pieni: arvon täytyy olla ${o}${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`Virheellinen syöte: täytyy alkaa "${o.prefix}"`:o.format==="ends_with"?`Virheellinen syöte: täytyy loppua "${o.suffix}"`:o.format==="includes"?`Virheellinen syöte: täytyy sisältää "${o.includes}"`:o.format==="regex"?`Virheellinen syöte: täytyy vastata säännöllistä lauseketta ${o.pattern}`:`Virheellinen ${i[o.format]??r.format}`}case"not_multiple_of":return`Virheellinen luku: täytyy olla luvun ${r.divisor} monikerta`;case"unrecognized_keys":return`${r.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${q(r.keys,", ")}`;case"invalid_key":return"Virheellinen avain tietueessa";case"invalid_union":return"Virheellinen unioni";case"invalid_element":return"Virheellinen arvo joukossa";default:return"Virheellinen syöte"}}};function m1(){return{localeError:h1()}}const g1=()=>{const e={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"nombre";case"object":{if(Array.isArray(r))return"tableau";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"entrée",email:"adresse e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date et heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"};return r=>{switch(r.code){case"invalid_type":return`Entrée invalide : ${r.expected} attendu, ${n(r.input)} reçu`;case"invalid_value":return r.values.length===1?`Entrée invalide : ${ae(r.values[0])} attendu`:`Option invalide : une valeur parmi ${q(r.values,"|")} attendue`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Trop grand : ${r.origin??"valeur"} doit ${a.verb} ${o}${r.maximum.toString()} ${a.unit??"élément(s)"}`:`Trop grand : ${r.origin??"valeur"} doit être ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`Trop petit : ${r.origin} doit ${a.verb} ${o}${r.minimum.toString()} ${a.unit}`:`Trop petit : ${r.origin} doit être ${o}${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`Chaîne invalide : doit commencer par "${o.prefix}"`:o.format==="ends_with"?`Chaîne invalide : doit se terminer par "${o.suffix}"`:o.format==="includes"?`Chaîne invalide : doit inclure "${o.includes}"`:o.format==="regex"?`Chaîne invalide : doit correspondre au modèle ${o.pattern}`:`${i[o.format]??r.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${r.divisor}`;case"unrecognized_keys":return`Clé${r.keys.length>1?"s":""} non reconnue${r.keys.length>1?"s":""} : ${q(r.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${r.origin}`;case"invalid_union":return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${r.origin}`;default:return"Entrée invalide"}}};function v1(){return{localeError:g1()}}const y1=()=>{const e={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"number";case"object":{if(Array.isArray(r))return"array";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"entrée",email:"adresse courriel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date-heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"};return r=>{switch(r.code){case"invalid_type":return`Entrée invalide : attendu ${r.expected}, reçu ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Entrée invalide : attendu ${ae(r.values[0])}`:`Option invalide : attendu l'une des valeurs suivantes ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"≤":"<",a=t(r.origin);return a?`Trop grand : attendu que ${r.origin??"la valeur"} ait ${o}${r.maximum.toString()} ${a.unit}`:`Trop grand : attendu que ${r.origin??"la valeur"} soit ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?"≥":">",a=t(r.origin);return a?`Trop petit : attendu que ${r.origin} ait ${o}${r.minimum.toString()} ${a.unit}`:`Trop petit : attendu que ${r.origin} soit ${o}${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`Chaîne invalide : doit commencer par "${o.prefix}"`:o.format==="ends_with"?`Chaîne invalide : doit se terminer par "${o.suffix}"`:o.format==="includes"?`Chaîne invalide : doit inclure "${o.includes}"`:o.format==="regex"?`Chaîne invalide : doit correspondre au motif ${o.pattern}`:`${i[o.format]??r.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${r.divisor}`;case"unrecognized_keys":return`Clé${r.keys.length>1?"s":""} non reconnue${r.keys.length>1?"s":""} : ${q(r.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${r.origin}`;case"invalid_union":return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${r.origin}`;default:return"Entrée invalide"}}};function b1(){return{localeError:y1()}}const _1=()=>{const e={string:{label:"מחרוזת",gender:"f"},number:{label:"מספר",gender:"m"},boolean:{label:"ערך בוליאני",gender:"m"},bigint:{label:"BigInt",gender:"m"},date:{label:"תאריך",gender:"m"},array:{label:"מערך",gender:"m"},object:{label:"אובייקט",gender:"m"},null:{label:"ערך ריק (null)",gender:"m"},undefined:{label:"ערך לא מוגדר (undefined)",gender:"m"},symbol:{label:"סימבול (Symbol)",gender:"m"},function:{label:"פונקציה",gender:"f"},map:{label:"מפה (Map)",gender:"f"},set:{label:"קבוצה (Set)",gender:"f"},file:{label:"קובץ",gender:"m"},promise:{label:"Promise",gender:"m"},NaN:{label:"NaN",gender:"m"},unknown:{label:"ערך לא ידוע",gender:"m"},value:{label:"ערך",gender:"m"}},t={string:{unit:"תווים",shortLabel:"קצר",longLabel:"ארוך"},file:{unit:"בייטים",shortLabel:"קטן",longLabel:"גדול"},array:{unit:"פריטים",shortLabel:"קטן",longLabel:"גדול"},set:{unit:"פריטים",shortLabel:"קטן",longLabel:"גדול"},number:{unit:"",shortLabel:"קטן",longLabel:"גדול"}},n=l=>l?e[l]:void 0,i=l=>{const c=n(l);return c?c.label:l??e.unknown.label},r=l=>`ה${i(l)}`,o=l=>(n(l)?.gender??"m")==="f"?"צריכה להיות":"צריך להיות",a=l=>l?t[l]??null:null,s=l=>{const c=typeof l;switch(c){case"number":return Number.isNaN(l)?"NaN":"number";case"object":return Array.isArray(l)?"array":l===null?"null":Object.getPrototypeOf(l)!==Object.prototype&&l.constructor?l.constructor.name:"object";default:return c}},u={regex:{label:"קלט",gender:"m"},email:{label:"כתובת אימייל",gender:"f"},url:{label:"כתובת רשת",gender:"f"},emoji:{label:"אימוג'י",gender:"m"},uuid:{label:"UUID",gender:"m"},nanoid:{label:"nanoid",gender:"m"},guid:{label:"GUID",gender:"m"},cuid:{label:"cuid",gender:"m"},cuid2:{label:"cuid2",gender:"m"},ulid:{label:"ULID",gender:"m"},xid:{label:"XID",gender:"m"},ksuid:{label:"KSUID",gender:"m"},datetime:{label:"תאריך וזמן ISO",gender:"m"},date:{label:"תאריך ISO",gender:"m"},time:{label:"זמן ISO",gender:"m"},duration:{label:"משך זמן ISO",gender:"m"},ipv4:{label:"כתובת IPv4",gender:"f"},ipv6:{label:"כתובת IPv6",gender:"f"},cidrv4:{label:"טווח IPv4",gender:"m"},cidrv6:{label:"טווח IPv6",gender:"m"},base64:{label:"מחרוזת בבסיס 64",gender:"f"},base64url:{label:"מחרוזת בבסיס 64 לכתובות רשת",gender:"f"},json_string:{label:"מחרוזת JSON",gender:"f"},e164:{label:"מספר E.164",gender:"m"},jwt:{label:"JWT",gender:"m"},ends_with:{label:"קלט",gender:"m"},includes:{label:"קלט",gender:"m"},lowercase:{label:"קלט",gender:"m"},starts_with:{label:"קלט",gender:"m"},uppercase:{label:"קלט",gender:"m"}};return l=>{switch(l.code){case"invalid_type":{const c=l.expected,d=i(c),f=s(l.input),p=e[f]?.label??f;return`קלט לא תקין: צריך להיות ${d}, התקבל ${p}`}case"invalid_value":{if(l.values.length===1)return`ערך לא תקין: הערך חייב להיות ${ae(l.values[0])}`;const c=l.values.map(p=>ae(p));if(l.values.length===2)return`ערך לא תקין: האפשרויות המתאימות הן ${c[0]} או ${c[1]}`;const d=c[c.length-1];return`ערך לא תקין: האפשרויות המתאימות הן ${c.slice(0,-1).join(", ")} או ${d}`}case"too_big":{const c=a(l.origin),d=r(l.origin??"value");if(l.origin==="string")return`${c?.longLabel??"ארוך"} מדי: ${d} צריכה להכיל ${l.maximum.toString()} ${c?.unit??""} ${l.inclusive?"או פחות":"לכל היותר"}`.trim();if(l.origin==="number"){const g=l.inclusive?`קטן או שווה ל-${l.maximum}`:`קטן מ-${l.maximum}`;return`גדול מדי: ${d} צריך להיות ${g}`}if(l.origin==="array"||l.origin==="set"){const g=l.origin==="set"?"צריכה":"צריך",m=l.inclusive?`${l.maximum} ${c?.unit??""} או פחות`:`פחות מ-${l.maximum} ${c?.unit??""}`;return`גדול מדי: ${d} ${g} להכיל ${m}`.trim()}const f=l.inclusive?"<=":"<",p=o(l.origin??"value");return c?.unit?`${c.longLabel} מדי: ${d} ${p} ${f}${l.maximum.toString()} ${c.unit}`:`${c?.longLabel??"גדול"} מדי: ${d} ${p} ${f}${l.maximum.toString()}`}case"too_small":{const c=a(l.origin),d=r(l.origin??"value");if(l.origin==="string")return`${c?.shortLabel??"קצר"} מדי: ${d} צריכה להכיל ${l.minimum.toString()} ${c?.unit??""} ${l.inclusive?"או יותר":"לפחות"}`.trim();if(l.origin==="number"){const g=l.inclusive?`גדול או שווה ל-${l.minimum}`:`גדול מ-${l.minimum}`;return`קטן מדי: ${d} צריך להיות ${g}`}if(l.origin==="array"||l.origin==="set"){const g=l.origin==="set"?"צריכה":"צריך";if(l.minimum===1&&l.inclusive){const y=(l.origin==="set","לפחות פריט אחד");return`קטן מדי: ${d} ${g} להכיל ${y}`}const m=l.inclusive?`${l.minimum} ${c?.unit??""} או יותר`:`יותר מ-${l.minimum} ${c?.unit??""}`;return`קטן מדי: ${d} ${g} להכיל ${m}`.trim()}const f=l.inclusive?">=":">",p=o(l.origin??"value");return c?.unit?`${c.shortLabel} מדי: ${d} ${p} ${f}${l.minimum.toString()} ${c.unit}`:`${c?.shortLabel??"קטן"} מדי: ${d} ${p} ${f}${l.minimum.toString()}`}case"invalid_format":{const c=l;if(c.format==="starts_with")return`המחרוזת חייבת להתחיל ב "${c.prefix}"`;if(c.format==="ends_with")return`המחרוזת חייבת להסתיים ב "${c.suffix}"`;if(c.format==="includes")return`המחרוזת חייבת לכלול "${c.includes}"`;if(c.format==="regex")return`המחרוזת חייבת להתאים לתבנית ${c.pattern}`;const d=u[c.format],f=d?.label??c.format,g=(d?.gender??"m")==="f"?"תקינה":"תקין";return`${f} לא ${g}`}case"not_multiple_of":return`מספר לא תקין: חייב להיות מכפלה של ${l.divisor}`;case"unrecognized_keys":return`מפתח${l.keys.length>1?"ות":""} לא מזוה${l.keys.length>1?"ים":"ה"}: ${q(l.keys,", ")}`;case"invalid_key":return"שדה לא תקין באובייקט";case"invalid_union":return"קלט לא תקין";case"invalid_element":return`ערך לא תקין ב${r(l.origin??"array")}`;default:return"קלט לא תקין"}}};function w1(){return{localeError:_1()}}const x1=()=>{const e={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"szám";case"object":{if(Array.isArray(r))return"tömb";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"bemenet",email:"email cím",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO időbélyeg",date:"ISO dátum",time:"ISO idő",duration:"ISO időintervallum",ipv4:"IPv4 cím",ipv6:"IPv6 cím",cidrv4:"IPv4 tartomány",cidrv6:"IPv6 tartomány",base64:"base64-kódolt string",base64url:"base64url-kódolt string",json_string:"JSON string",e164:"E.164 szám",jwt:"JWT",template_literal:"bemenet"};return r=>{switch(r.code){case"invalid_type":return`Érvénytelen bemenet: a várt érték ${r.expected}, a kapott érték ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Érvénytelen bemenet: a várt érték ${ae(r.values[0])}`:`Érvénytelen opció: valamelyik érték várt ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Túl nagy: ${r.origin??"érték"} mérete túl nagy ${o}${r.maximum.toString()} ${a.unit??"elem"}`:`Túl nagy: a bemeneti érték ${r.origin??"érték"} túl nagy: ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`Túl kicsi: a bemeneti érték ${r.origin} mérete túl kicsi ${o}${r.minimum.toString()} ${a.unit}`:`Túl kicsi: a bemeneti érték ${r.origin} túl kicsi ${o}${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`Érvénytelen string: "${o.prefix}" értékkel kell kezdődnie`:o.format==="ends_with"?`Érvénytelen string: "${o.suffix}" értékkel kell végződnie`:o.format==="includes"?`Érvénytelen string: "${o.includes}" értéket kell tartalmaznia`:o.format==="regex"?`Érvénytelen string: ${o.pattern} mintának kell megfelelnie`:`Érvénytelen ${i[o.format]??r.format}`}case"not_multiple_of":return`Érvénytelen szám: ${r.divisor} többszörösének kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${r.keys.length>1?"s":""}: ${q(r.keys,", ")}`;case"invalid_key":return`Érvénytelen kulcs ${r.origin}`;case"invalid_union":return"Érvénytelen bemenet";case"invalid_element":return`Érvénytelen érték: ${r.origin}`;default:return"Érvénytelen bemenet"}}};function S1(){return{localeError:x1()}}const I1=()=>{const e={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"number";case"object":{if(Array.isArray(r))return"array";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"input",email:"alamat email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tanggal dan waktu format ISO",date:"tanggal format ISO",time:"jam format ISO",duration:"durasi format ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"rentang alamat IPv4",cidrv6:"rentang alamat IPv6",base64:"string dengan enkode base64",base64url:"string dengan enkode base64url",json_string:"string JSON",e164:"angka E.164",jwt:"JWT",template_literal:"input"};return r=>{switch(r.code){case"invalid_type":return`Input tidak valid: diharapkan ${r.expected}, diterima ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Input tidak valid: diharapkan ${ae(r.values[0])}`:`Pilihan tidak valid: diharapkan salah satu dari ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Terlalu besar: diharapkan ${r.origin??"value"} memiliki ${o}${r.maximum.toString()} ${a.unit??"elemen"}`:`Terlalu besar: diharapkan ${r.origin??"value"} menjadi ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`Terlalu kecil: diharapkan ${r.origin} memiliki ${o}${r.minimum.toString()} ${a.unit}`:`Terlalu kecil: diharapkan ${r.origin} menjadi ${o}${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`String tidak valid: harus dimulai dengan "${o.prefix}"`:o.format==="ends_with"?`String tidak valid: harus berakhir dengan "${o.suffix}"`:o.format==="includes"?`String tidak valid: harus menyertakan "${o.includes}"`:o.format==="regex"?`String tidak valid: harus sesuai pola ${o.pattern}`:`${i[o.format]??r.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${r.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${r.keys.length>1?"s":""}: ${q(r.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${r.origin}`;case"invalid_union":return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${r.origin}`;default:return"Input tidak valid"}}};function k1(){return{localeError:I1()}}const E1=e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"númer";case"object":{if(Array.isArray(e))return"fylki";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return t},T1=()=>{const e={string:{unit:"stafi",verb:"að hafa"},file:{unit:"bæti",verb:"að hafa"},array:{unit:"hluti",verb:"að hafa"},set:{unit:"hluti",verb:"að hafa"}};function t(i){return e[i]??null}const n={regex:"gildi",email:"netfang",url:"vefslóð",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dagsetning og tími",date:"ISO dagsetning",time:"ISO tími",duration:"ISO tímalengd",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded strengur",base64url:"base64url-encoded strengur",json_string:"JSON strengur",e164:"E.164 tölugildi",jwt:"JWT",template_literal:"gildi"};return i=>{switch(i.code){case"invalid_type":return`Rangt gildi: Þú slóst inn ${E1(i.input)} þar sem á að vera ${i.expected}`;case"invalid_value":return i.values.length===1?`Rangt gildi: gert ráð fyrir ${ae(i.values[0])}`:`Ógilt val: má vera eitt af eftirfarandi ${q(i.values,"|")}`;case"too_big":{const r=i.inclusive?"<=":"<",o=t(i.origin);return o?`Of stórt: gert er ráð fyrir að ${i.origin??"gildi"} hafi ${r}${i.maximum.toString()} ${o.unit??"hluti"}`:`Of stórt: gert er ráð fyrir að ${i.origin??"gildi"} sé ${r}${i.maximum.toString()}`}case"too_small":{const r=i.inclusive?">=":">",o=t(i.origin);return o?`Of lítið: gert er ráð fyrir að ${i.origin} hafi ${r}${i.minimum.toString()} ${o.unit}`:`Of lítið: gert er ráð fyrir að ${i.origin} sé ${r}${i.minimum.toString()}`}case"invalid_format":{const r=i;return r.format==="starts_with"?`Ógildur strengur: verður að byrja á "${r.prefix}"`:r.format==="ends_with"?`Ógildur strengur: verður að enda á "${r.suffix}"`:r.format==="includes"?`Ógildur strengur: verður að innihalda "${r.includes}"`:r.format==="regex"?`Ógildur strengur: verður að fylgja mynstri ${r.pattern}`:`Rangt ${n[r.format]??i.format}`}case"not_multiple_of":return`Röng tala: verður að vera margfeldi af ${i.divisor}`;case"unrecognized_keys":return`Óþekkt ${i.keys.length>1?"ir lyklar":"ur lykill"}: ${q(i.keys,", ")}`;case"invalid_key":return`Rangur lykill í ${i.origin}`;case"invalid_union":return"Rangt gildi";case"invalid_element":return`Rangt gildi í ${i.origin}`;default:return"Rangt gildi"}}};function $1(){return{localeError:T1()}}const C1=()=>{const e={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"numero";case"object":{if(Array.isArray(r))return"vettore";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"input",email:"indirizzo email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e ora ISO",date:"data ISO",time:"ora ISO",duration:"durata ISO",ipv4:"indirizzo IPv4",ipv6:"indirizzo IPv6",cidrv4:"intervallo IPv4",cidrv6:"intervallo IPv6",base64:"stringa codificata in base64",base64url:"URL codificata in base64",json_string:"stringa JSON",e164:"numero E.164",jwt:"JWT",template_literal:"input"};return r=>{switch(r.code){case"invalid_type":return`Input non valido: atteso ${r.expected}, ricevuto ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Input non valido: atteso ${ae(r.values[0])}`:`Opzione non valida: atteso uno tra ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Troppo grande: ${r.origin??"valore"} deve avere ${o}${r.maximum.toString()} ${a.unit??"elementi"}`:`Troppo grande: ${r.origin??"valore"} deve essere ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`Troppo piccolo: ${r.origin} deve avere ${o}${r.minimum.toString()} ${a.unit}`:`Troppo piccolo: ${r.origin} deve essere ${o}${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`Stringa non valida: deve iniziare con "${o.prefix}"`:o.format==="ends_with"?`Stringa non valida: deve terminare con "${o.suffix}"`:o.format==="includes"?`Stringa non valida: deve includere "${o.includes}"`:o.format==="regex"?`Stringa non valida: deve corrispondere al pattern ${o.pattern}`:`Invalid ${i[o.format]??r.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${r.divisor}`;case"unrecognized_keys":return`Chiav${r.keys.length>1?"i":"e"} non riconosciut${r.keys.length>1?"e":"a"}: ${q(r.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${r.origin}`;case"invalid_union":return"Input non valido";case"invalid_element":return`Valore non valido in ${r.origin}`;default:return"Input non valido"}}};function A1(){return{localeError:C1()}}const P1=()=>{const e={string:{unit:"文字",verb:"である"},file:{unit:"バイト",verb:"である"},array:{unit:"要素",verb:"である"},set:{unit:"要素",verb:"である"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"数値";case"object":{if(Array.isArray(r))return"配列";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"入力値",email:"メールアドレス",url:"URL",emoji:"絵文字",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日時",date:"ISO日付",time:"ISO時刻",duration:"ISO期間",ipv4:"IPv4アドレス",ipv6:"IPv6アドレス",cidrv4:"IPv4範囲",cidrv6:"IPv6範囲",base64:"base64エンコード文字列",base64url:"base64urlエンコード文字列",json_string:"JSON文字列",e164:"E.164番号",jwt:"JWT",template_literal:"入力値"};return r=>{switch(r.code){case"invalid_type":return`無効な入力: ${r.expected}が期待されましたが、${n(r.input)}が入力されました`;case"invalid_value":return r.values.length===1?`無効な入力: ${ae(r.values[0])}が期待されました`:`無効な選択: ${q(r.values,"、")}のいずれかである必要があります`;case"too_big":{const o=r.inclusive?"以下である":"より小さい",a=t(r.origin);return a?`大きすぎる値: ${r.origin??"値"}は${r.maximum.toString()}${a.unit??"要素"}${o}必要があります`:`大きすぎる値: ${r.origin??"値"}は${r.maximum.toString()}${o}必要があります`}case"too_small":{const o=r.inclusive?"以上である":"より大きい",a=t(r.origin);return a?`小さすぎる値: ${r.origin}は${r.minimum.toString()}${a.unit}${o}必要があります`:`小さすぎる値: ${r.origin}は${r.minimum.toString()}${o}必要があります`}case"invalid_format":{const o=r;return o.format==="starts_with"?`無効な文字列: "${o.prefix}"で始まる必要があります`:o.format==="ends_with"?`無効な文字列: "${o.suffix}"で終わる必要があります`:o.format==="includes"?`無効な文字列: "${o.includes}"を含む必要があります`:o.format==="regex"?`無効な文字列: パターン${o.pattern}に一致する必要があります`:`無効な${i[o.format]??r.format}`}case"not_multiple_of":return`無効な数値: ${r.divisor}の倍数である必要があります`;case"unrecognized_keys":return`認識されていないキー${r.keys.length>1?"群":""}: ${q(r.keys,"、")}`;case"invalid_key":return`${r.origin}内の無効なキー`;case"invalid_union":return"無効な入力";case"invalid_element":return`${r.origin}内の無効な値`;default:return"無効な入力"}}};function R1(){return{localeError:P1()}}const O1=e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"რიცხვი";case"object":{if(Array.isArray(e))return"მასივი";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return{string:"სტრინგი",boolean:"ბულეანი",undefined:"undefined",bigint:"bigint",symbol:"symbol",function:"ფუნქცია"}[t]??t},N1=()=>{const e={string:{unit:"სიმბოლო",verb:"უნდა შეიცავდეს"},file:{unit:"ბაიტი",verb:"უნდა შეიცავდეს"},array:{unit:"ელემენტი",verb:"უნდა შეიცავდეს"},set:{unit:"ელემენტი",verb:"უნდა შეიცავდეს"}};function t(i){return e[i]??null}const n={regex:"შეყვანა",email:"ელ-ფოსტის მისამართი",url:"URL",emoji:"ემოჯი",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"თარიღი-დრო",date:"თარიღი",time:"დრო",duration:"ხანგრძლივობა",ipv4:"IPv4 მისამართი",ipv6:"IPv6 მისამართი",cidrv4:"IPv4 დიაპაზონი",cidrv6:"IPv6 დიაპაზონი",base64:"base64-კოდირებული სტრინგი",base64url:"base64url-კოდირებული სტრინგი",json_string:"JSON სტრინგი",e164:"E.164 ნომერი",jwt:"JWT",template_literal:"შეყვანა"};return i=>{switch(i.code){case"invalid_type":return`არასწორი შეყვანა: მოსალოდნელი ${i.expected}, მიღებული ${O1(i.input)}`;case"invalid_value":return i.values.length===1?`არასწორი შეყვანა: მოსალოდნელი ${ae(i.values[0])}`:`არასწორი ვარიანტი: მოსალოდნელია ერთ-ერთი ${q(i.values,"|")}-დან`;case"too_big":{const r=i.inclusive?"<=":"<",o=t(i.origin);return o?`ზედმეტად დიდი: მოსალოდნელი ${i.origin??"მნიშვნელობა"} ${o.verb} ${r}${i.maximum.toString()} ${o.unit}`:`ზედმეტად დიდი: მოსალოდნელი ${i.origin??"მნიშვნელობა"} იყოს ${r}${i.maximum.toString()}`}case"too_small":{const r=i.inclusive?">=":">",o=t(i.origin);return o?`ზედმეტად პატარა: მოსალოდნელი ${i.origin} ${o.verb} ${r}${i.minimum.toString()} ${o.unit}`:`ზედმეტად პატარა: მოსალოდნელი ${i.origin} იყოს ${r}${i.minimum.toString()}`}case"invalid_format":{const r=i;return r.format==="starts_with"?`არასწორი სტრინგი: უნდა იწყებოდეს "${r.prefix}"-ით`:r.format==="ends_with"?`არასწორი სტრინგი: უნდა მთავრდებოდეს "${r.suffix}"-ით`:r.format==="includes"?`არასწორი სტრინგი: უნდა შეიცავდეს "${r.includes}"-ს`:r.format==="regex"?`არასწორი სტრინგი: უნდა შეესაბამებოდეს შაბლონს ${r.pattern}`:`არასწორი ${n[r.format]??i.format}`}case"not_multiple_of":return`არასწორი რიცხვი: უნდა იყოს ${i.divisor}-ის ჯერადი`;case"unrecognized_keys":return`უცნობი გასაღებ${i.keys.length>1?"ები":"ი"}: ${q(i.keys,", ")}`;case"invalid_key":return`არასწორი გასაღები ${i.origin}-ში`;case"invalid_union":return"არასწორი შეყვანა";case"invalid_element":return`არასწორი მნიშვნელობა ${i.origin}-ში`;default:return"არასწორი შეყვანა"}}};function j1(){return{localeError:N1()}}const M1=()=>{const e={string:{unit:"តួអក្សរ",verb:"គួរមាន"},file:{unit:"បៃ",verb:"គួរមាន"},array:{unit:"ធាតុ",verb:"គួរមាន"},set:{unit:"ធាតុ",verb:"គួរមាន"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"មិនមែនជាលេខ (NaN)":"លេខ";case"object":{if(Array.isArray(r))return"អារេ (Array)";if(r===null)return"គ្មានតម្លៃ (null)";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"ទិន្នន័យបញ្ចូល",email:"អាសយដ្ឋានអ៊ីមែល",url:"URL",emoji:"សញ្ញាអារម្មណ៍",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"កាលបរិច្ឆេទ និងម៉ោង ISO",date:"កាលបរិច្ឆេទ ISO",time:"ម៉ោង ISO",duration:"រយៈពេល ISO",ipv4:"អាសយដ្ឋាន IPv4",ipv6:"អាសយដ្ឋាន IPv6",cidrv4:"ដែនអាសយដ្ឋាន IPv4",cidrv6:"ដែនអាសយដ្ឋាន IPv6",base64:"ខ្សែអក្សរអ៊ិកូដ base64",base64url:"ខ្សែអក្សរអ៊ិកូដ base64url",json_string:"ខ្សែអក្សរ JSON",e164:"លេខ E.164",jwt:"JWT",template_literal:"ទិន្នន័យបញ្ចូល"};return r=>{switch(r.code){case"invalid_type":return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${r.expected} ប៉ុន្តែទទួលបាន ${n(r.input)}`;case"invalid_value":return r.values.length===1?`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${ae(r.values[0])}`:`ជម្រើសមិនត្រឹមត្រូវ៖ ត្រូវជាមួយក្នុងចំណោម ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`ធំពេក៖ ត្រូវការ ${r.origin??"តម្លៃ"} ${o} ${r.maximum.toString()} ${a.unit??"ធាតុ"}`:`ធំពេក៖ ត្រូវការ ${r.origin??"តម្លៃ"} ${o} ${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`តូចពេក៖ ត្រូវការ ${r.origin} ${o} ${r.minimum.toString()} ${a.unit}`:`តូចពេក៖ ត្រូវការ ${r.origin} ${o} ${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវចាប់ផ្តើមដោយ "${o.prefix}"`:o.format==="ends_with"?`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវបញ្ចប់ដោយ "${o.suffix}"`:o.format==="includes"?`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវមាន "${o.includes}"`:o.format==="regex"?`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវតែផ្គូផ្គងនឹងទម្រង់ដែលបានកំណត់ ${o.pattern}`:`មិនត្រឹមត្រូវ៖ ${i[o.format]??r.format}`}case"not_multiple_of":return`លេខមិនត្រឹមត្រូវ៖ ត្រូវតែជាពហុគុណនៃ ${r.divisor}`;case"unrecognized_keys":return`រកឃើញសោមិនស្គាល់៖ ${q(r.keys,", ")}`;case"invalid_key":return`សោមិនត្រឹមត្រូវនៅក្នុង ${r.origin}`;case"invalid_union":return"ទិន្នន័យមិនត្រឹមត្រូវ";case"invalid_element":return`ទិន្នន័យមិនត្រឹមត្រូវនៅក្នុង ${r.origin}`;default:return"ទិន្នន័យមិនត្រឹមត្រូវ"}}};function hx(){return{localeError:M1()}}function D1(){return hx()}const z1=()=>{const e={string:{unit:"문자",verb:"to have"},file:{unit:"바이트",verb:"to have"},array:{unit:"개",verb:"to have"},set:{unit:"개",verb:"to have"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"number";case"object":{if(Array.isArray(r))return"array";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"입력",email:"이메일 주소",url:"URL",emoji:"이모지",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 날짜시간",date:"ISO 날짜",time:"ISO 시간",duration:"ISO 기간",ipv4:"IPv4 주소",ipv6:"IPv6 주소",cidrv4:"IPv4 범위",cidrv6:"IPv6 범위",base64:"base64 인코딩 문자열",base64url:"base64url 인코딩 문자열",json_string:"JSON 문자열",e164:"E.164 번호",jwt:"JWT",template_literal:"입력"};return r=>{switch(r.code){case"invalid_type":return`잘못된 입력: 예상 타입은 ${r.expected}, 받은 타입은 ${n(r.input)}입니다`;case"invalid_value":return r.values.length===1?`잘못된 입력: 값은 ${ae(r.values[0])} 이어야 합니다`:`잘못된 옵션: ${q(r.values,"또는 ")} 중 하나여야 합니다`;case"too_big":{const o=r.inclusive?"이하":"미만",a=o==="미만"?"이어야 합니다":"여야 합니다",s=t(r.origin),u=s?.unit??"요소";return s?`${r.origin??"값"}이 너무 큽니다: ${r.maximum.toString()}${u} ${o}${a}`:`${r.origin??"값"}이 너무 큽니다: ${r.maximum.toString()} ${o}${a}`}case"too_small":{const o=r.inclusive?"이상":"초과",a=o==="이상"?"이어야 합니다":"여야 합니다",s=t(r.origin),u=s?.unit??"요소";return s?`${r.origin??"값"}이 너무 작습니다: ${r.minimum.toString()}${u} ${o}${a}`:`${r.origin??"값"}이 너무 작습니다: ${r.minimum.toString()} ${o}${a}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`잘못된 문자열: "${o.prefix}"(으)로 시작해야 합니다`:o.format==="ends_with"?`잘못된 문자열: "${o.suffix}"(으)로 끝나야 합니다`:o.format==="includes"?`잘못된 문자열: "${o.includes}"을(를) 포함해야 합니다`:o.format==="regex"?`잘못된 문자열: 정규식 ${o.pattern} 패턴과 일치해야 합니다`:`잘못된 ${i[o.format]??r.format}`}case"not_multiple_of":return`잘못된 숫자: ${r.divisor}의 배수여야 합니다`;case"unrecognized_keys":return`인식할 수 없는 키: ${q(r.keys,", ")}`;case"invalid_key":return`잘못된 키: ${r.origin}`;case"invalid_union":return"잘못된 입력";case"invalid_element":return`잘못된 값: ${r.origin}`;default:return"잘못된 입력"}}};function U1(){return{localeError:z1()}}const L1=e=>Wi(typeof e,e),Wi=(e,t=void 0)=>{switch(e){case"number":return Number.isNaN(t)?"NaN":"skaičius";case"bigint":return"sveikasis skaičius";case"string":return"eilutė";case"boolean":return"loginė reikšmė";case"undefined":case"void":return"neapibrėžta reikšmė";case"function":return"funkcija";case"symbol":return"simbolis";case"object":return t===void 0?"nežinomas objektas":t===null?"nulinė reikšmė":Array.isArray(t)?"masyvas":Object.getPrototypeOf(t)!==Object.prototype&&t.constructor?t.constructor.name:"objektas";case"null":return"nulinė reikšmė"}return e},Ui=e=>e.charAt(0).toUpperCase()+e.slice(1);function Pm(e){const t=Math.abs(e),n=t%10,i=t%100;return i>=11&&i<=19||n===0?"many":n===1?"one":"few"}const F1=()=>{const e={string:{unit:{one:"simbolis",few:"simboliai",many:"simbolių"},verb:{smaller:{inclusive:"turi būti ne ilgesnė kaip",notInclusive:"turi būti trumpesnė kaip"},bigger:{inclusive:"turi būti ne trumpesnė kaip",notInclusive:"turi būti ilgesnė kaip"}}},file:{unit:{one:"baitas",few:"baitai",many:"baitų"},verb:{smaller:{inclusive:"turi būti ne didesnis kaip",notInclusive:"turi būti mažesnis kaip"},bigger:{inclusive:"turi būti ne mažesnis kaip",notInclusive:"turi būti didesnis kaip"}}},array:{unit:{one:"elementą",few:"elementus",many:"elementų"},verb:{smaller:{inclusive:"turi turėti ne daugiau kaip",notInclusive:"turi turėti mažiau kaip"},bigger:{inclusive:"turi turėti ne mažiau kaip",notInclusive:"turi turėti daugiau kaip"}}},set:{unit:{one:"elementą",few:"elementus",many:"elementų"},verb:{smaller:{inclusive:"turi turėti ne daugiau kaip",notInclusive:"turi turėti mažiau kaip"},bigger:{inclusive:"turi turėti ne mažiau kaip",notInclusive:"turi turėti daugiau kaip"}}}};function t(i,r,o,a){const s=e[i]??null;return s===null?s:{unit:s.unit[r],verb:s.verb[a][o?"inclusive":"notInclusive"]}}const n={regex:"įvestis",email:"el. pašto adresas",url:"URL",emoji:"jaustukas",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO data ir laikas",date:"ISO data",time:"ISO laikas",duration:"ISO trukmė",ipv4:"IPv4 adresas",ipv6:"IPv6 adresas",cidrv4:"IPv4 tinklo prefiksas (CIDR)",cidrv6:"IPv6 tinklo prefiksas (CIDR)",base64:"base64 užkoduota eilutė",base64url:"base64url užkoduota eilutė",json_string:"JSON eilutė",e164:"E.164 numeris",jwt:"JWT",template_literal:"įvestis"};return i=>{switch(i.code){case"invalid_type":return`Gautas tipas ${L1(i.input)}, o tikėtasi - ${Wi(i.expected)}`;case"invalid_value":return i.values.length===1?`Privalo būti ${ae(i.values[0])}`:`Privalo būti vienas iš ${q(i.values,"|")} pasirinkimų`;case"too_big":{const r=Wi(i.origin),o=t(i.origin,Pm(Number(i.maximum)),i.inclusive??!1,"smaller");if(o?.verb)return`${Ui(r??i.origin??"reikšmė")} ${o.verb} ${i.maximum.toString()} ${o.unit??"elementų"}`;const a=i.inclusive?"ne didesnis kaip":"mažesnis kaip";return`${Ui(r??i.origin??"reikšmė")} turi būti ${a} ${i.maximum.toString()} ${o?.unit}`}case"too_small":{const r=Wi(i.origin),o=t(i.origin,Pm(Number(i.minimum)),i.inclusive??!1,"bigger");if(o?.verb)return`${Ui(r??i.origin??"reikšmė")} ${o.verb} ${i.minimum.toString()} ${o.unit??"elementų"}`;const a=i.inclusive?"ne mažesnis kaip":"didesnis kaip";return`${Ui(r??i.origin??"reikšmė")} turi būti ${a} ${i.minimum.toString()} ${o?.unit}`}case"invalid_format":{const r=i;return r.format==="starts_with"?`Eilutė privalo prasidėti "${r.prefix}"`:r.format==="ends_with"?`Eilutė privalo pasibaigti "${r.suffix}"`:r.format==="includes"?`Eilutė privalo įtraukti "${r.includes}"`:r.format==="regex"?`Eilutė privalo atitikti ${r.pattern}`:`Neteisingas ${n[r.format]??i.format}`}case"not_multiple_of":return`Skaičius privalo būti ${i.divisor} kartotinis.`;case"unrecognized_keys":return`Neatpažint${i.keys.length>1?"i":"as"} rakt${i.keys.length>1?"ai":"as"}: ${q(i.keys,", ")}`;case"invalid_key":return"Rastas klaidingas raktas";case"invalid_union":return"Klaidinga įvestis";case"invalid_element":{const r=Wi(i.origin);return`${Ui(r??i.origin??"reikšmė")} turi klaidingą įvestį`}default:return"Klaidinga įvestis"}}};function B1(){return{localeError:F1()}}const Z1=()=>{const e={string:{unit:"знаци",verb:"да имаат"},file:{unit:"бајти",verb:"да имаат"},array:{unit:"ставки",verb:"да имаат"},set:{unit:"ставки",verb:"да имаат"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"број";case"object":{if(Array.isArray(r))return"низа";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"внес",email:"адреса на е-пошта",url:"URL",emoji:"емоџи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO датум и време",date:"ISO датум",time:"ISO време",duration:"ISO времетраење",ipv4:"IPv4 адреса",ipv6:"IPv6 адреса",cidrv4:"IPv4 опсег",cidrv6:"IPv6 опсег",base64:"base64-енкодирана низа",base64url:"base64url-енкодирана низа",json_string:"JSON низа",e164:"E.164 број",jwt:"JWT",template_literal:"внес"};return r=>{switch(r.code){case"invalid_type":return`Грешен внес: се очекува ${r.expected}, примено ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Invalid input: expected ${ae(r.values[0])}`:`Грешана опција: се очекува една ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Премногу голем: се очекува ${r.origin??"вредноста"} да има ${o}${r.maximum.toString()} ${a.unit??"елементи"}`:`Премногу голем: се очекува ${r.origin??"вредноста"} да биде ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`Премногу мал: се очекува ${r.origin} да има ${o}${r.minimum.toString()} ${a.unit}`:`Премногу мал: се очекува ${r.origin} да биде ${o}${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`Неважечка низа: мора да започнува со "${o.prefix}"`:o.format==="ends_with"?`Неважечка низа: мора да завршува со "${o.suffix}"`:o.format==="includes"?`Неважечка низа: мора да вклучува "${o.includes}"`:o.format==="regex"?`Неважечка низа: мора да одгоара на патернот ${o.pattern}`:`Invalid ${i[o.format]??r.format}`}case"not_multiple_of":return`Грешен број: мора да биде делив со ${r.divisor}`;case"unrecognized_keys":return`${r.keys.length>1?"Непрепознаени клучеви":"Непрепознаен клуч"}: ${q(r.keys,", ")}`;case"invalid_key":return`Грешен клуч во ${r.origin}`;case"invalid_union":return"Грешен внес";case"invalid_element":return`Грешна вредност во ${r.origin}`;default:return"Грешен внес"}}};function q1(){return{localeError:Z1()}}const V1=()=>{const e={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"nombor";case"object":{if(Array.isArray(r))return"array";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"input",email:"alamat e-mel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tarikh masa ISO",date:"tarikh ISO",time:"masa ISO",duration:"tempoh ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"julat IPv4",cidrv6:"julat IPv6",base64:"string dikodkan base64",base64url:"string dikodkan base64url",json_string:"string JSON",e164:"nombor E.164",jwt:"JWT",template_literal:"input"};return r=>{switch(r.code){case"invalid_type":return`Input tidak sah: dijangka ${r.expected}, diterima ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Input tidak sah: dijangka ${ae(r.values[0])}`:`Pilihan tidak sah: dijangka salah satu daripada ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Terlalu besar: dijangka ${r.origin??"nilai"} ${a.verb} ${o}${r.maximum.toString()} ${a.unit??"elemen"}`:`Terlalu besar: dijangka ${r.origin??"nilai"} adalah ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`Terlalu kecil: dijangka ${r.origin} ${a.verb} ${o}${r.minimum.toString()} ${a.unit}`:`Terlalu kecil: dijangka ${r.origin} adalah ${o}${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`String tidak sah: mesti bermula dengan "${o.prefix}"`:o.format==="ends_with"?`String tidak sah: mesti berakhir dengan "${o.suffix}"`:o.format==="includes"?`String tidak sah: mesti mengandungi "${o.includes}"`:o.format==="regex"?`String tidak sah: mesti sepadan dengan corak ${o.pattern}`:`${i[o.format]??r.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${r.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${q(r.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${r.origin}`;case"invalid_union":return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${r.origin}`;default:return"Input tidak sah"}}};function H1(){return{localeError:V1()}}const J1=()=>{const e={string:{unit:"tekens",verb:"te hebben"},file:{unit:"bytes",verb:"te hebben"},array:{unit:"elementen",verb:"te hebben"},set:{unit:"elementen",verb:"te hebben"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"getal";case"object":{if(Array.isArray(r))return"array";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"invoer",email:"emailadres",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum en tijd",date:"ISO datum",time:"ISO tijd",duration:"ISO duur",ipv4:"IPv4-adres",ipv6:"IPv6-adres",cidrv4:"IPv4-bereik",cidrv6:"IPv6-bereik",base64:"base64-gecodeerde tekst",base64url:"base64 URL-gecodeerde tekst",json_string:"JSON string",e164:"E.164-nummer",jwt:"JWT",template_literal:"invoer"};return r=>{switch(r.code){case"invalid_type":return`Ongeldige invoer: verwacht ${r.expected}, ontving ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Ongeldige invoer: verwacht ${ae(r.values[0])}`:`Ongeldige optie: verwacht één van ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Te groot: verwacht dat ${r.origin??"waarde"} ${a.verb} ${o}${r.maximum.toString()} ${a.unit??"elementen"}`:`Te groot: verwacht dat ${r.origin??"waarde"} ${o}${r.maximum.toString()} is`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`Te klein: verwacht dat ${r.origin} ${a.verb} ${o}${r.minimum.toString()} ${a.unit}`:`Te klein: verwacht dat ${r.origin} ${o}${r.minimum.toString()} is`}case"invalid_format":{const o=r;return o.format==="starts_with"?`Ongeldige tekst: moet met "${o.prefix}" beginnen`:o.format==="ends_with"?`Ongeldige tekst: moet op "${o.suffix}" eindigen`:o.format==="includes"?`Ongeldige tekst: moet "${o.includes}" bevatten`:o.format==="regex"?`Ongeldige tekst: moet overeenkomen met patroon ${o.pattern}`:`Ongeldig: ${i[o.format]??r.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${r.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${r.keys.length>1?"s":""}: ${q(r.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${r.origin}`;case"invalid_union":return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${r.origin}`;default:return"Ongeldige invoer"}}};function W1(){return{localeError:J1()}}const G1=()=>{const e={string:{unit:"tegn",verb:"å ha"},file:{unit:"bytes",verb:"å ha"},array:{unit:"elementer",verb:"å inneholde"},set:{unit:"elementer",verb:"å inneholde"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"tall";case"object":{if(Array.isArray(r))return"liste";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"input",email:"e-postadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varighet",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkodet streng",base64url:"base64url-enkodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"};return r=>{switch(r.code){case"invalid_type":return`Ugyldig input: forventet ${r.expected}, fikk ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Ugyldig verdi: forventet ${ae(r.values[0])}`:`Ugyldig valg: forventet en av ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`For stor(t): forventet ${r.origin??"value"} til å ha ${o}${r.maximum.toString()} ${a.unit??"elementer"}`:`For stor(t): forventet ${r.origin??"value"} til å ha ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`For lite(n): forventet ${r.origin} til å ha ${o}${r.minimum.toString()} ${a.unit}`:`For lite(n): forventet ${r.origin} til å ha ${o}${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`Ugyldig streng: må starte med "${o.prefix}"`:o.format==="ends_with"?`Ugyldig streng: må ende med "${o.suffix}"`:o.format==="includes"?`Ugyldig streng: må inneholde "${o.includes}"`:o.format==="regex"?`Ugyldig streng: må matche mønsteret ${o.pattern}`:`Ugyldig ${i[o.format]??r.format}`}case"not_multiple_of":return`Ugyldig tall: må være et multiplum av ${r.divisor}`;case"unrecognized_keys":return`${r.keys.length>1?"Ukjente nøkler":"Ukjent nøkkel"}: ${q(r.keys,", ")}`;case"invalid_key":return`Ugyldig nøkkel i ${r.origin}`;case"invalid_union":return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${r.origin}`;default:return"Ugyldig input"}}};function K1(){return{localeError:G1()}}const Y1=()=>{const e={string:{unit:"harf",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"unsur",verb:"olmalıdır"},set:{unit:"unsur",verb:"olmalıdır"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"numara";case"object":{if(Array.isArray(r))return"saf";if(r===null)return"gayb";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"giren",email:"epostagâh",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO hengâmı",date:"ISO tarihi",time:"ISO zamanı",duration:"ISO müddeti",ipv4:"IPv4 nişânı",ipv6:"IPv6 nişânı",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-şifreli metin",base64url:"base64url-şifreli metin",json_string:"JSON metin",e164:"E.164 sayısı",jwt:"JWT",template_literal:"giren"};return r=>{switch(r.code){case"invalid_type":return`Fâsit giren: umulan ${r.expected}, alınan ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Fâsit giren: umulan ${ae(r.values[0])}`:`Fâsit tercih: mûteberler ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Fazla büyük: ${r.origin??"value"}, ${o}${r.maximum.toString()} ${a.unit??"elements"} sahip olmalıydı.`:`Fazla büyük: ${r.origin??"value"}, ${o}${r.maximum.toString()} olmalıydı.`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`Fazla küçük: ${r.origin}, ${o}${r.minimum.toString()} ${a.unit} sahip olmalıydı.`:`Fazla küçük: ${r.origin}, ${o}${r.minimum.toString()} olmalıydı.`}case"invalid_format":{const o=r;return o.format==="starts_with"?`Fâsit metin: "${o.prefix}" ile başlamalı.`:o.format==="ends_with"?`Fâsit metin: "${o.suffix}" ile bitmeli.`:o.format==="includes"?`Fâsit metin: "${o.includes}" ihtivâ etmeli.`:o.format==="regex"?`Fâsit metin: ${o.pattern} nakşına uymalı.`:`Fâsit ${i[o.format]??r.format}`}case"not_multiple_of":return`Fâsit sayı: ${r.divisor} katı olmalıydı.`;case"unrecognized_keys":return`Tanınmayan anahtar ${r.keys.length>1?"s":""}: ${q(r.keys,", ")}`;case"invalid_key":return`${r.origin} için tanınmayan anahtar var.`;case"invalid_union":return"Giren tanınamadı.";case"invalid_element":return`${r.origin} için tanınmayan kıymet var.`;default:return"Kıymet tanınamadı."}}};function X1(){return{localeError:Y1()}}const Q1=()=>{const e={string:{unit:"توکي",verb:"ولري"},file:{unit:"بایټس",verb:"ولري"},array:{unit:"توکي",verb:"ولري"},set:{unit:"توکي",verb:"ولري"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"عدد";case"object":{if(Array.isArray(r))return"ارې";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"ورودي",email:"بریښنالیک",url:"یو آر ال",emoji:"ایموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"نیټه او وخت",date:"نېټه",time:"وخت",duration:"موده",ipv4:"د IPv4 پته",ipv6:"د IPv6 پته",cidrv4:"د IPv4 ساحه",cidrv6:"د IPv6 ساحه",base64:"base64-encoded متن",base64url:"base64url-encoded متن",json_string:"JSON متن",e164:"د E.164 شمېره",jwt:"JWT",template_literal:"ورودي"};return r=>{switch(r.code){case"invalid_type":return`ناسم ورودي: باید ${r.expected} وای, مګر ${n(r.input)} ترلاسه شو`;case"invalid_value":return r.values.length===1?`ناسم ورودي: باید ${ae(r.values[0])} وای`:`ناسم انتخاب: باید یو له ${q(r.values,"|")} څخه وای`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`ډیر لوی: ${r.origin??"ارزښت"} باید ${o}${r.maximum.toString()} ${a.unit??"عنصرونه"} ولري`:`ډیر لوی: ${r.origin??"ارزښت"} باید ${o}${r.maximum.toString()} وي`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`ډیر کوچنی: ${r.origin} باید ${o}${r.minimum.toString()} ${a.unit} ولري`:`ډیر کوچنی: ${r.origin} باید ${o}${r.minimum.toString()} وي`}case"invalid_format":{const o=r;return o.format==="starts_with"?`ناسم متن: باید د "${o.prefix}" سره پیل شي`:o.format==="ends_with"?`ناسم متن: باید د "${o.suffix}" سره پای ته ورسيږي`:o.format==="includes"?`ناسم متن: باید "${o.includes}" ولري`:o.format==="regex"?`ناسم متن: باید د ${o.pattern} سره مطابقت ولري`:`${i[o.format]??r.format} ناسم دی`}case"not_multiple_of":return`ناسم عدد: باید د ${r.divisor} مضرب وي`;case"unrecognized_keys":return`ناسم ${r.keys.length>1?"کلیډونه":"کلیډ"}: ${q(r.keys,", ")}`;case"invalid_key":return`ناسم کلیډ په ${r.origin} کې`;case"invalid_union":return"ناسمه ورودي";case"invalid_element":return`ناسم عنصر په ${r.origin} کې`;default:return"ناسمه ورودي"}}};function eO(){return{localeError:Q1()}}const tO=()=>{const e={string:{unit:"znaków",verb:"mieć"},file:{unit:"bajtów",verb:"mieć"},array:{unit:"elementów",verb:"mieć"},set:{unit:"elementów",verb:"mieć"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"liczba";case"object":{if(Array.isArray(r))return"tablica";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"wyrażenie",email:"adres email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i godzina w formacie ISO",date:"data w formacie ISO",time:"godzina w formacie ISO",duration:"czas trwania ISO",ipv4:"adres IPv4",ipv6:"adres IPv6",cidrv4:"zakres IPv4",cidrv6:"zakres IPv6",base64:"ciąg znaków zakodowany w formacie base64",base64url:"ciąg znaków zakodowany w formacie base64url",json_string:"ciąg znaków w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wejście"};return r=>{switch(r.code){case"invalid_type":return`Nieprawidłowe dane wejściowe: oczekiwano ${r.expected}, otrzymano ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Nieprawidłowe dane wejściowe: oczekiwano ${ae(r.values[0])}`:`Nieprawidłowa opcja: oczekiwano jednej z wartości ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Za duża wartość: oczekiwano, że ${r.origin??"wartość"} będzie mieć ${o}${r.maximum.toString()} ${a.unit??"elementów"}`:`Zbyt duż(y/a/e): oczekiwano, że ${r.origin??"wartość"} będzie wynosić ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`Za mała wartość: oczekiwano, że ${r.origin??"wartość"} będzie mieć ${o}${r.minimum.toString()} ${a.unit??"elementów"}`:`Zbyt mał(y/a/e): oczekiwano, że ${r.origin??"wartość"} będzie wynosić ${o}${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`Nieprawidłowy ciąg znaków: musi zaczynać się od "${o.prefix}"`:o.format==="ends_with"?`Nieprawidłowy ciąg znaków: musi kończyć się na "${o.suffix}"`:o.format==="includes"?`Nieprawidłowy ciąg znaków: musi zawierać "${o.includes}"`:o.format==="regex"?`Nieprawidłowy ciąg znaków: musi odpowiadać wzorcowi ${o.pattern}`:`Nieprawidłow(y/a/e) ${i[o.format]??r.format}`}case"not_multiple_of":return`Nieprawidłowa liczba: musi być wielokrotnością ${r.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${r.keys.length>1?"s":""}: ${q(r.keys,", ")}`;case"invalid_key":return`Nieprawidłowy klucz w ${r.origin}`;case"invalid_union":return"Nieprawidłowe dane wejściowe";case"invalid_element":return`Nieprawidłowa wartość w ${r.origin}`;default:return"Nieprawidłowe dane wejściowe"}}};function nO(){return{localeError:tO()}}const rO=()=>{const e={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"número";case"object":{if(Array.isArray(r))return"array";if(r===null)return"nulo";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"padrão",email:"endereço de e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e hora ISO",date:"data ISO",time:"hora ISO",duration:"duração ISO",ipv4:"endereço IPv4",ipv6:"endereço IPv6",cidrv4:"faixa de IPv4",cidrv6:"faixa de IPv6",base64:"texto codificado em base64",base64url:"URL codificada em base64",json_string:"texto JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"};return r=>{switch(r.code){case"invalid_type":return`Tipo inválido: esperado ${r.expected}, recebido ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Entrada inválida: esperado ${ae(r.values[0])}`:`Opção inválida: esperada uma das ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Muito grande: esperado que ${r.origin??"valor"} tivesse ${o}${r.maximum.toString()} ${a.unit??"elementos"}`:`Muito grande: esperado que ${r.origin??"valor"} fosse ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`Muito pequeno: esperado que ${r.origin} tivesse ${o}${r.minimum.toString()} ${a.unit}`:`Muito pequeno: esperado que ${r.origin} fosse ${o}${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`Texto inválido: deve começar com "${o.prefix}"`:o.format==="ends_with"?`Texto inválido: deve terminar com "${o.suffix}"`:o.format==="includes"?`Texto inválido: deve incluir "${o.includes}"`:o.format==="regex"?`Texto inválido: deve corresponder ao padrão ${o.pattern}`:`${i[o.format]??r.format} inválido`}case"not_multiple_of":return`Número inválido: deve ser múltiplo de ${r.divisor}`;case"unrecognized_keys":return`Chave${r.keys.length>1?"s":""} desconhecida${r.keys.length>1?"s":""}: ${q(r.keys,", ")}`;case"invalid_key":return`Chave inválida em ${r.origin}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido em ${r.origin}`;default:return"Campo inválido"}}};function iO(){return{localeError:rO()}}function Rm(e,t,n,i){const r=Math.abs(e),o=r%10,a=r%100;return a>=11&&a<=19?i:o===1?t:o>=2&&o<=4?n:i}const oO=()=>{const e={string:{unit:{one:"символ",few:"символа",many:"символов"},verb:"иметь"},file:{unit:{one:"байт",few:"байта",many:"байт"},verb:"иметь"},array:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"},set:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"число";case"object":{if(Array.isArray(r))return"массив";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"ввод",email:"email адрес",url:"URL",emoji:"эмодзи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата и время",date:"ISO дата",time:"ISO время",duration:"ISO длительность",ipv4:"IPv4 адрес",ipv6:"IPv6 адрес",cidrv4:"IPv4 диапазон",cidrv6:"IPv6 диапазон",base64:"строка в формате base64",base64url:"строка в формате base64url",json_string:"JSON строка",e164:"номер E.164",jwt:"JWT",template_literal:"ввод"};return r=>{switch(r.code){case"invalid_type":return`Неверный ввод: ожидалось ${r.expected}, получено ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Неверный ввод: ожидалось ${ae(r.values[0])}`:`Неверный вариант: ожидалось одно из ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);if(a){const s=Number(r.maximum),u=Rm(s,a.unit.one,a.unit.few,a.unit.many);return`Слишком большое значение: ожидалось, что ${r.origin??"значение"} будет иметь ${o}${r.maximum.toString()} ${u}`}return`Слишком большое значение: ожидалось, что ${r.origin??"значение"} будет ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);if(a){const s=Number(r.minimum),u=Rm(s,a.unit.one,a.unit.few,a.unit.many);return`Слишком маленькое значение: ожидалось, что ${r.origin} будет иметь ${o}${r.minimum.toString()} ${u}`}return`Слишком маленькое значение: ожидалось, что ${r.origin} будет ${o}${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`Неверная строка: должна начинаться с "${o.prefix}"`:o.format==="ends_with"?`Неверная строка: должна заканчиваться на "${o.suffix}"`:o.format==="includes"?`Неверная строка: должна содержать "${o.includes}"`:o.format==="regex"?`Неверная строка: должна соответствовать шаблону ${o.pattern}`:`Неверный ${i[o.format]??r.format}`}case"not_multiple_of":return`Неверное число: должно быть кратным ${r.divisor}`;case"unrecognized_keys":return`Нераспознанн${r.keys.length>1?"ые":"ый"} ключ${r.keys.length>1?"и":""}: ${q(r.keys,", ")}`;case"invalid_key":return`Неверный ключ в ${r.origin}`;case"invalid_union":return"Неверные входные данные";case"invalid_element":return`Неверное значение в ${r.origin}`;default:return"Неверные входные данные"}}};function aO(){return{localeError:oO()}}const sO=()=>{const e={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"število";case"object":{if(Array.isArray(r))return"tabela";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"vnos",email:"e-poštni naslov",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum in čas",date:"ISO datum",time:"ISO čas",duration:"ISO trajanje",ipv4:"IPv4 naslov",ipv6:"IPv6 naslov",cidrv4:"obseg IPv4",cidrv6:"obseg IPv6",base64:"base64 kodiran niz",base64url:"base64url kodiran niz",json_string:"JSON niz",e164:"E.164 številka",jwt:"JWT",template_literal:"vnos"};return r=>{switch(r.code){case"invalid_type":return`Neveljaven vnos: pričakovano ${r.expected}, prejeto ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Neveljaven vnos: pričakovano ${ae(r.values[0])}`:`Neveljavna možnost: pričakovano eno izmed ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Preveliko: pričakovano, da bo ${r.origin??"vrednost"} imelo ${o}${r.maximum.toString()} ${a.unit??"elementov"}`:`Preveliko: pričakovano, da bo ${r.origin??"vrednost"} ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`Premajhno: pričakovano, da bo ${r.origin} imelo ${o}${r.minimum.toString()} ${a.unit}`:`Premajhno: pričakovano, da bo ${r.origin} ${o}${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`Neveljaven niz: mora se začeti z "${o.prefix}"`:o.format==="ends_with"?`Neveljaven niz: mora se končati z "${o.suffix}"`:o.format==="includes"?`Neveljaven niz: mora vsebovati "${o.includes}"`:o.format==="regex"?`Neveljaven niz: mora ustrezati vzorcu ${o.pattern}`:`Neveljaven ${i[o.format]??r.format}`}case"not_multiple_of":return`Neveljavno število: mora biti večkratnik ${r.divisor}`;case"unrecognized_keys":return`Neprepoznan${r.keys.length>1?"i ključi":" ključ"}: ${q(r.keys,", ")}`;case"invalid_key":return`Neveljaven ključ v ${r.origin}`;case"invalid_union":return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${r.origin}`;default:return"Neveljaven vnos"}}};function lO(){return{localeError:sO()}}const uO=()=>{const e={string:{unit:"tecken",verb:"att ha"},file:{unit:"bytes",verb:"att ha"},array:{unit:"objekt",verb:"att innehålla"},set:{unit:"objekt",verb:"att innehålla"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"antal";case"object":{if(Array.isArray(r))return"lista";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"reguljärt uttryck",email:"e-postadress",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datum och tid",date:"ISO-datum",time:"ISO-tid",duration:"ISO-varaktighet",ipv4:"IPv4-intervall",ipv6:"IPv6-intervall",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodad sträng",base64url:"base64url-kodad sträng",json_string:"JSON-sträng",e164:"E.164-nummer",jwt:"JWT",template_literal:"mall-literal"};return r=>{switch(r.code){case"invalid_type":return`Ogiltig inmatning: förväntat ${r.expected}, fick ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Ogiltig inmatning: förväntat ${ae(r.values[0])}`:`Ogiltigt val: förväntade en av ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`För stor(t): förväntade ${r.origin??"värdet"} att ha ${o}${r.maximum.toString()} ${a.unit??"element"}`:`För stor(t): förväntat ${r.origin??"värdet"} att ha ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`För lite(t): förväntade ${r.origin??"värdet"} att ha ${o}${r.minimum.toString()} ${a.unit}`:`För lite(t): förväntade ${r.origin??"värdet"} att ha ${o}${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`Ogiltig sträng: måste börja med "${o.prefix}"`:o.format==="ends_with"?`Ogiltig sträng: måste sluta med "${o.suffix}"`:o.format==="includes"?`Ogiltig sträng: måste innehålla "${o.includes}"`:o.format==="regex"?`Ogiltig sträng: måste matcha mönstret "${o.pattern}"`:`Ogiltig(t) ${i[o.format]??r.format}`}case"not_multiple_of":return`Ogiltigt tal: måste vara en multipel av ${r.divisor}`;case"unrecognized_keys":return`${r.keys.length>1?"Okända nycklar":"Okänd nyckel"}: ${q(r.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${r.origin??"värdet"}`;case"invalid_union":return"Ogiltig input";case"invalid_element":return`Ogiltigt värde i ${r.origin??"värdet"}`;default:return"Ogiltig input"}}};function cO(){return{localeError:uO()}}const dO=()=>{const e={string:{unit:"எழுத்துக்கள்",verb:"கொண்டிருக்க வேண்டும்"},file:{unit:"பைட்டுகள்",verb:"கொண்டிருக்க வேண்டும்"},array:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"},set:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"எண் அல்லாதது":"எண்";case"object":{if(Array.isArray(r))return"அணி";if(r===null)return"வெறுமை";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"உள்ளீடு",email:"மின்னஞ்சல் முகவரி",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO தேதி நேரம்",date:"ISO தேதி",time:"ISO நேரம்",duration:"ISO கால அளவு",ipv4:"IPv4 முகவரி",ipv6:"IPv6 முகவரி",cidrv4:"IPv4 வரம்பு",cidrv6:"IPv6 வரம்பு",base64:"base64-encoded சரம்",base64url:"base64url-encoded சரம்",json_string:"JSON சரம்",e164:"E.164 எண்",jwt:"JWT",template_literal:"input"};return r=>{switch(r.code){case"invalid_type":return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${r.expected}, பெறப்பட்டது ${n(r.input)}`;case"invalid_value":return r.values.length===1?`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${ae(r.values[0])}`:`தவறான விருப்பம்: எதிர்பார்க்கப்பட்டது ${q(r.values,"|")} இல் ஒன்று`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${r.origin??"மதிப்பு"} ${o}${r.maximum.toString()} ${a.unit??"உறுப்புகள்"} ஆக இருக்க வேண்டும்`:`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${r.origin??"மதிப்பு"} ${o}${r.maximum.toString()} ஆக இருக்க வேண்டும்`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${r.origin} ${o}${r.minimum.toString()} ${a.unit} ஆக இருக்க வேண்டும்`:`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${r.origin} ${o}${r.minimum.toString()} ஆக இருக்க வேண்டும்`}case"invalid_format":{const o=r;return o.format==="starts_with"?`தவறான சரம்: "${o.prefix}" இல் தொடங்க வேண்டும்`:o.format==="ends_with"?`தவறான சரம்: "${o.suffix}" இல் முடிவடைய வேண்டும்`:o.format==="includes"?`தவறான சரம்: "${o.includes}" ஐ உள்ளடக்க வேண்டும்`:o.format==="regex"?`தவறான சரம்: ${o.pattern} முறைபாட்டுடன் பொருந்த வேண்டும்`:`தவறான ${i[o.format]??r.format}`}case"not_multiple_of":return`தவறான எண்: ${r.divisor} இன் பலமாக இருக்க வேண்டும்`;case"unrecognized_keys":return`அடையாளம் தெரியாத விசை${r.keys.length>1?"கள்":""}: ${q(r.keys,", ")}`;case"invalid_key":return`${r.origin} இல் தவறான விசை`;case"invalid_union":return"தவறான உள்ளீடு";case"invalid_element":return`${r.origin} இல் தவறான மதிப்பு`;default:return"தவறான உள்ளீடு"}}};function pO(){return{localeError:dO()}}const fO=()=>{const e={string:{unit:"ตัวอักษร",verb:"ควรมี"},file:{unit:"ไบต์",verb:"ควรมี"},array:{unit:"รายการ",verb:"ควรมี"},set:{unit:"รายการ",verb:"ควรมี"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"ไม่ใช่ตัวเลข (NaN)":"ตัวเลข";case"object":{if(Array.isArray(r))return"อาร์เรย์ (Array)";if(r===null)return"ไม่มีค่า (null)";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"ข้อมูลที่ป้อน",email:"ที่อยู่อีเมล",url:"URL",emoji:"อิโมจิ",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"วันที่เวลาแบบ ISO",date:"วันที่แบบ ISO",time:"เวลาแบบ ISO",duration:"ช่วงเวลาแบบ ISO",ipv4:"ที่อยู่ IPv4",ipv6:"ที่อยู่ IPv6",cidrv4:"ช่วง IP แบบ IPv4",cidrv6:"ช่วง IP แบบ IPv6",base64:"ข้อความแบบ Base64",base64url:"ข้อความแบบ Base64 สำหรับ URL",json_string:"ข้อความแบบ JSON",e164:"เบอร์โทรศัพท์ระหว่างประเทศ (E.164)",jwt:"โทเคน JWT",template_literal:"ข้อมูลที่ป้อน"};return r=>{switch(r.code){case"invalid_type":return`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น ${r.expected} แต่ได้รับ ${n(r.input)}`;case"invalid_value":return r.values.length===1?`ค่าไม่ถูกต้อง: ควรเป็น ${ae(r.values[0])}`:`ตัวเลือกไม่ถูกต้อง: ควรเป็นหนึ่งใน ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"ไม่เกิน":"น้อยกว่า",a=t(r.origin);return a?`เกินกำหนด: ${r.origin??"ค่า"} ควรมี${o} ${r.maximum.toString()} ${a.unit??"รายการ"}`:`เกินกำหนด: ${r.origin??"ค่า"} ควรมี${o} ${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?"อย่างน้อย":"มากกว่า",a=t(r.origin);return a?`น้อยกว่ากำหนด: ${r.origin} ควรมี${o} ${r.minimum.toString()} ${a.unit}`:`น้อยกว่ากำหนด: ${r.origin} ควรมี${o} ${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`รูปแบบไม่ถูกต้อง: ข้อความต้องขึ้นต้นด้วย "${o.prefix}"`:o.format==="ends_with"?`รูปแบบไม่ถูกต้อง: ข้อความต้องลงท้ายด้วย "${o.suffix}"`:o.format==="includes"?`รูปแบบไม่ถูกต้อง: ข้อความต้องมี "${o.includes}" อยู่ในข้อความ`:o.format==="regex"?`รูปแบบไม่ถูกต้อง: ต้องตรงกับรูปแบบที่กำหนด ${o.pattern}`:`รูปแบบไม่ถูกต้อง: ${i[o.format]??r.format}`}case"not_multiple_of":return`ตัวเลขไม่ถูกต้อง: ต้องเป็นจำนวนที่หารด้วย ${r.divisor} ได้ลงตัว`;case"unrecognized_keys":return`พบคีย์ที่ไม่รู้จัก: ${q(r.keys,", ")}`;case"invalid_key":return`คีย์ไม่ถูกต้องใน ${r.origin}`;case"invalid_union":return"ข้อมูลไม่ถูกต้อง: ไม่ตรงกับรูปแบบยูเนียนที่กำหนดไว้";case"invalid_element":return`ข้อมูลไม่ถูกต้องใน ${r.origin}`;default:return"ข้อมูลไม่ถูกต้อง"}}};function hO(){return{localeError:fO()}}const mO=e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return t},gO=()=>{const e={string:{unit:"karakter",verb:"olmalı"},file:{unit:"bayt",verb:"olmalı"},array:{unit:"öğe",verb:"olmalı"},set:{unit:"öğe",verb:"olmalı"}};function t(i){return e[i]??null}const n={regex:"girdi",email:"e-posta adresi",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO tarih ve saat",date:"ISO tarih",time:"ISO saat",duration:"ISO süre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aralığı",cidrv6:"IPv6 aralığı",base64:"base64 ile şifrelenmiş metin",base64url:"base64url ile şifrelenmiş metin",json_string:"JSON dizesi",e164:"E.164 sayısı",jwt:"JWT",template_literal:"Şablon dizesi"};return i=>{switch(i.code){case"invalid_type":return`Geçersiz değer: beklenen ${i.expected}, alınan ${mO(i.input)}`;case"invalid_value":return i.values.length===1?`Geçersiz değer: beklenen ${ae(i.values[0])}`:`Geçersiz seçenek: aşağıdakilerden biri olmalı: ${q(i.values,"|")}`;case"too_big":{const r=i.inclusive?"<=":"<",o=t(i.origin);return o?`Çok büyük: beklenen ${i.origin??"değer"} ${r}${i.maximum.toString()} ${o.unit??"öğe"}`:`Çok büyük: beklenen ${i.origin??"değer"} ${r}${i.maximum.toString()}`}case"too_small":{const r=i.inclusive?">=":">",o=t(i.origin);return o?`Çok küçük: beklenen ${i.origin} ${r}${i.minimum.toString()} ${o.unit}`:`Çok küçük: beklenen ${i.origin} ${r}${i.minimum.toString()}`}case"invalid_format":{const r=i;return r.format==="starts_with"?`Geçersiz metin: "${r.prefix}" ile başlamalı`:r.format==="ends_with"?`Geçersiz metin: "${r.suffix}" ile bitmeli`:r.format==="includes"?`Geçersiz metin: "${r.includes}" içermeli`:r.format==="regex"?`Geçersiz metin: ${r.pattern} desenine uymalı`:`Geçersiz ${n[r.format]??i.format}`}case"not_multiple_of":return`Geçersiz sayı: ${i.divisor} ile tam bölünebilmeli`;case"unrecognized_keys":return`Tanınmayan anahtar${i.keys.length>1?"lar":""}: ${q(i.keys,", ")}`;case"invalid_key":return`${i.origin} içinde geçersiz anahtar`;case"invalid_union":return"Geçersiz değer";case"invalid_element":return`${i.origin} içinde geçersiz değer`;default:return"Geçersiz değer"}}};function vO(){return{localeError:gO()}}const yO=()=>{const e={string:{unit:"символів",verb:"матиме"},file:{unit:"байтів",verb:"матиме"},array:{unit:"елементів",verb:"матиме"},set:{unit:"елементів",verb:"матиме"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"число";case"object":{if(Array.isArray(r))return"масив";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"вхідні дані",email:"адреса електронної пошти",url:"URL",emoji:"емодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"дата та час ISO",date:"дата ISO",time:"час ISO",duration:"тривалість ISO",ipv4:"адреса IPv4",ipv6:"адреса IPv6",cidrv4:"діапазон IPv4",cidrv6:"діапазон IPv6",base64:"рядок у кодуванні base64",base64url:"рядок у кодуванні base64url",json_string:"рядок JSON",e164:"номер E.164",jwt:"JWT",template_literal:"вхідні дані"};return r=>{switch(r.code){case"invalid_type":return`Неправильні вхідні дані: очікується ${r.expected}, отримано ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Неправильні вхідні дані: очікується ${ae(r.values[0])}`:`Неправильна опція: очікується одне з ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Занадто велике: очікується, що ${r.origin??"значення"} ${a.verb} ${o}${r.maximum.toString()} ${a.unit??"елементів"}`:`Занадто велике: очікується, що ${r.origin??"значення"} буде ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`Занадто мале: очікується, що ${r.origin} ${a.verb} ${o}${r.minimum.toString()} ${a.unit}`:`Занадто мале: очікується, що ${r.origin} буде ${o}${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`Неправильний рядок: повинен починатися з "${o.prefix}"`:o.format==="ends_with"?`Неправильний рядок: повинен закінчуватися на "${o.suffix}"`:o.format==="includes"?`Неправильний рядок: повинен містити "${o.includes}"`:o.format==="regex"?`Неправильний рядок: повинен відповідати шаблону ${o.pattern}`:`Неправильний ${i[o.format]??r.format}`}case"not_multiple_of":return`Неправильне число: повинно бути кратним ${r.divisor}`;case"unrecognized_keys":return`Нерозпізнаний ключ${r.keys.length>1?"і":""}: ${q(r.keys,", ")}`;case"invalid_key":return`Неправильний ключ у ${r.origin}`;case"invalid_union":return"Неправильні вхідні дані";case"invalid_element":return`Неправильне значення у ${r.origin}`;default:return"Неправильні вхідні дані"}}};function mx(){return{localeError:yO()}}function bO(){return mx()}const _O=()=>{const e={string:{unit:"حروف",verb:"ہونا"},file:{unit:"بائٹس",verb:"ہونا"},array:{unit:"آئٹمز",verb:"ہونا"},set:{unit:"آئٹمز",verb:"ہونا"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"نمبر";case"object":{if(Array.isArray(r))return"آرے";if(r===null)return"نل";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"ان پٹ",email:"ای میل ایڈریس",url:"یو آر ایل",emoji:"ایموجی",uuid:"یو یو آئی ڈی",uuidv4:"یو یو آئی ڈی وی 4",uuidv6:"یو یو آئی ڈی وی 6",nanoid:"نینو آئی ڈی",guid:"جی یو آئی ڈی",cuid:"سی یو آئی ڈی",cuid2:"سی یو آئی ڈی 2",ulid:"یو ایل آئی ڈی",xid:"ایکس آئی ڈی",ksuid:"کے ایس یو آئی ڈی",datetime:"آئی ایس او ڈیٹ ٹائم",date:"آئی ایس او تاریخ",time:"آئی ایس او وقت",duration:"آئی ایس او مدت",ipv4:"آئی پی وی 4 ایڈریس",ipv6:"آئی پی وی 6 ایڈریس",cidrv4:"آئی پی وی 4 رینج",cidrv6:"آئی پی وی 6 رینج",base64:"بیس 64 ان کوڈڈ سٹرنگ",base64url:"بیس 64 یو آر ایل ان کوڈڈ سٹرنگ",json_string:"جے ایس او این سٹرنگ",e164:"ای 164 نمبر",jwt:"جے ڈبلیو ٹی",template_literal:"ان پٹ"};return r=>{switch(r.code){case"invalid_type":return`غلط ان پٹ: ${r.expected} متوقع تھا، ${n(r.input)} موصول ہوا`;case"invalid_value":return r.values.length===1?`غلط ان پٹ: ${ae(r.values[0])} متوقع تھا`:`غلط آپشن: ${q(r.values,"|")} میں سے ایک متوقع تھا`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`بہت بڑا: ${r.origin??"ویلیو"} کے ${o}${r.maximum.toString()} ${a.unit??"عناصر"} ہونے متوقع تھے`:`بہت بڑا: ${r.origin??"ویلیو"} کا ${o}${r.maximum.toString()} ہونا متوقع تھا`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`بہت چھوٹا: ${r.origin} کے ${o}${r.minimum.toString()} ${a.unit} ہونے متوقع تھے`:`بہت چھوٹا: ${r.origin} کا ${o}${r.minimum.toString()} ہونا متوقع تھا`}case"invalid_format":{const o=r;return o.format==="starts_with"?`غلط سٹرنگ: "${o.prefix}" سے شروع ہونا چاہیے`:o.format==="ends_with"?`غلط سٹرنگ: "${o.suffix}" پر ختم ہونا چاہیے`:o.format==="includes"?`غلط سٹرنگ: "${o.includes}" شامل ہونا چاہیے`:o.format==="regex"?`غلط سٹرنگ: پیٹرن ${o.pattern} سے میچ ہونا چاہیے`:`غلط ${i[o.format]??r.format}`}case"not_multiple_of":return`غلط نمبر: ${r.divisor} کا مضاعف ہونا چاہیے`;case"unrecognized_keys":return`غیر تسلیم شدہ کی${r.keys.length>1?"ز":""}: ${q(r.keys,"، ")}`;case"invalid_key":return`${r.origin} میں غلط کی`;case"invalid_union":return"غلط ان پٹ";case"invalid_element":return`${r.origin} میں غلط ویلیو`;default:return"غلط ان پٹ"}}};function wO(){return{localeError:_O()}}const xO=()=>{const e={string:{unit:"ký tự",verb:"có"},file:{unit:"byte",verb:"có"},array:{unit:"phần tử",verb:"có"},set:{unit:"phần tử",verb:"có"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"số";case"object":{if(Array.isArray(r))return"mảng";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"đầu vào",email:"địa chỉ email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ngày giờ ISO",date:"ngày ISO",time:"giờ ISO",duration:"khoảng thời gian ISO",ipv4:"địa chỉ IPv4",ipv6:"địa chỉ IPv6",cidrv4:"dải IPv4",cidrv6:"dải IPv6",base64:"chuỗi mã hóa base64",base64url:"chuỗi mã hóa base64url",json_string:"chuỗi JSON",e164:"số E.164",jwt:"JWT",template_literal:"đầu vào"};return r=>{switch(r.code){case"invalid_type":return`Đầu vào không hợp lệ: mong đợi ${r.expected}, nhận được ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Đầu vào không hợp lệ: mong đợi ${ae(r.values[0])}`:`Tùy chọn không hợp lệ: mong đợi một trong các giá trị ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Quá lớn: mong đợi ${r.origin??"giá trị"} ${a.verb} ${o}${r.maximum.toString()} ${a.unit??"phần tử"}`:`Quá lớn: mong đợi ${r.origin??"giá trị"} ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`Quá nhỏ: mong đợi ${r.origin} ${a.verb} ${o}${r.minimum.toString()} ${a.unit}`:`Quá nhỏ: mong đợi ${r.origin} ${o}${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`Chuỗi không hợp lệ: phải bắt đầu bằng "${o.prefix}"`:o.format==="ends_with"?`Chuỗi không hợp lệ: phải kết thúc bằng "${o.suffix}"`:o.format==="includes"?`Chuỗi không hợp lệ: phải bao gồm "${o.includes}"`:o.format==="regex"?`Chuỗi không hợp lệ: phải khớp với mẫu ${o.pattern}`:`${i[o.format]??r.format} không hợp lệ`}case"not_multiple_of":return`Số không hợp lệ: phải là bội số của ${r.divisor}`;case"unrecognized_keys":return`Khóa không được nhận dạng: ${q(r.keys,", ")}`;case"invalid_key":return`Khóa không hợp lệ trong ${r.origin}`;case"invalid_union":return"Đầu vào không hợp lệ";case"invalid_element":return`Giá trị không hợp lệ trong ${r.origin}`;default:return"Đầu vào không hợp lệ"}}};function SO(){return{localeError:xO()}}const IO=()=>{const e={string:{unit:"字符",verb:"包含"},file:{unit:"字节",verb:"包含"},array:{unit:"项",verb:"包含"},set:{unit:"项",verb:"包含"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"非数字(NaN)":"数字";case"object":{if(Array.isArray(r))return"数组";if(r===null)return"空值(null)";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"输入",email:"电子邮件",url:"URL",emoji:"表情符号",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日期时间",date:"ISO日期",time:"ISO时间",duration:"ISO时长",ipv4:"IPv4地址",ipv6:"IPv6地址",cidrv4:"IPv4网段",cidrv6:"IPv6网段",base64:"base64编码字符串",base64url:"base64url编码字符串",json_string:"JSON字符串",e164:"E.164号码",jwt:"JWT",template_literal:"输入"};return r=>{switch(r.code){case"invalid_type":return`无效输入:期望 ${r.expected},实际接收 ${n(r.input)}`;case"invalid_value":return r.values.length===1?`无效输入:期望 ${ae(r.values[0])}`:`无效选项:期望以下之一 ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`数值过大:期望 ${r.origin??"值"} ${o}${r.maximum.toString()} ${a.unit??"个元素"}`:`数值过大:期望 ${r.origin??"值"} ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`数值过小:期望 ${r.origin} ${o}${r.minimum.toString()} ${a.unit}`:`数值过小:期望 ${r.origin} ${o}${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`无效字符串:必须以 "${o.prefix}" 开头`:o.format==="ends_with"?`无效字符串:必须以 "${o.suffix}" 结尾`:o.format==="includes"?`无效字符串:必须包含 "${o.includes}"`:o.format==="regex"?`无效字符串:必须满足正则表达式 ${o.pattern}`:`无效${i[o.format]??r.format}`}case"not_multiple_of":return`无效数字:必须是 ${r.divisor} 的倍数`;case"unrecognized_keys":return`出现未知的键(key): ${q(r.keys,", ")}`;case"invalid_key":return`${r.origin} 中的键(key)无效`;case"invalid_union":return"无效输入";case"invalid_element":return`${r.origin} 中包含无效值(value)`;default:return"无效输入"}}};function kO(){return{localeError:IO()}}const EO=()=>{const e={string:{unit:"字元",verb:"擁有"},file:{unit:"位元組",verb:"擁有"},array:{unit:"項目",verb:"擁有"},set:{unit:"項目",verb:"擁有"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"number";case"object":{if(Array.isArray(r))return"array";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"輸入",email:"郵件地址",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 日期時間",date:"ISO 日期",time:"ISO 時間",duration:"ISO 期間",ipv4:"IPv4 位址",ipv6:"IPv6 位址",cidrv4:"IPv4 範圍",cidrv6:"IPv6 範圍",base64:"base64 編碼字串",base64url:"base64url 編碼字串",json_string:"JSON 字串",e164:"E.164 數值",jwt:"JWT",template_literal:"輸入"};return r=>{switch(r.code){case"invalid_type":return`無效的輸入值:預期為 ${r.expected},但收到 ${n(r.input)}`;case"invalid_value":return r.values.length===1?`無效的輸入值:預期為 ${ae(r.values[0])}`:`無效的選項:預期為以下其中之一 ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`數值過大:預期 ${r.origin??"值"} 應為 ${o}${r.maximum.toString()} ${a.unit??"個元素"}`:`數值過大:預期 ${r.origin??"值"} 應為 ${o}${r.maximum.toString()}`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`數值過小:預期 ${r.origin} 應為 ${o}${r.minimum.toString()} ${a.unit}`:`數值過小:預期 ${r.origin} 應為 ${o}${r.minimum.toString()}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`無效的字串:必須以 "${o.prefix}" 開頭`:o.format==="ends_with"?`無效的字串:必須以 "${o.suffix}" 結尾`:o.format==="includes"?`無效的字串:必須包含 "${o.includes}"`:o.format==="regex"?`無效的字串:必須符合格式 ${o.pattern}`:`無效的 ${i[o.format]??r.format}`}case"not_multiple_of":return`無效的數字:必須為 ${r.divisor} 的倍數`;case"unrecognized_keys":return`無法識別的鍵值${r.keys.length>1?"們":""}:${q(r.keys,"、")}`;case"invalid_key":return`${r.origin} 中有無效的鍵值`;case"invalid_union":return"無效的輸入值";case"invalid_element":return`${r.origin} 中有無效的值`;default:return"無效的輸入值"}}};function TO(){return{localeError:EO()}}const $O=()=>{const e={string:{unit:"àmi",verb:"ní"},file:{unit:"bytes",verb:"ní"},array:{unit:"nkan",verb:"ní"},set:{unit:"nkan",verb:"ní"}};function t(r){return e[r]??null}const n=r=>{const o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"nọ́mbà";case"object":{if(Array.isArray(r))return"akopọ";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"ẹ̀rọ ìbáwọlé",email:"àdírẹ́sì ìmẹ́lì",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"àkókò ISO",date:"ọjọ́ ISO",time:"àkókò ISO",duration:"àkókò tó pé ISO",ipv4:"àdírẹ́sì IPv4",ipv6:"àdírẹ́sì IPv6",cidrv4:"àgbègbè IPv4",cidrv6:"àgbègbè IPv6",base64:"ọ̀rọ̀ tí a kọ́ ní base64",base64url:"ọ̀rọ̀ base64url",json_string:"ọ̀rọ̀ JSON",e164:"nọ́mbà E.164",jwt:"JWT",template_literal:"ẹ̀rọ ìbáwọlé"};return r=>{switch(r.code){case"invalid_type":return`Ìbáwọlé aṣìṣe: a ní láti fi ${r.expected}, àmọ̀ a rí ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Ìbáwọlé aṣìṣe: a ní láti fi ${ae(r.values[0])}`:`Àṣàyàn aṣìṣe: yan ọ̀kan lára ${q(r.values,"|")}`;case"too_big":{const o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Tó pọ̀ jù: a ní láti jẹ́ pé ${r.origin??"iye"} ${a.verb} ${o}${r.maximum} ${a.unit}`:`Tó pọ̀ jù: a ní láti jẹ́ ${o}${r.maximum}`}case"too_small":{const o=r.inclusive?">=":">",a=t(r.origin);return a?`Kéré ju: a ní láti jẹ́ pé ${r.origin} ${a.verb} ${o}${r.minimum} ${a.unit}`:`Kéré ju: a ní láti jẹ́ ${o}${r.minimum}`}case"invalid_format":{const o=r;return o.format==="starts_with"?`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bẹ̀rẹ̀ pẹ̀lú "${o.prefix}"`:o.format==="ends_with"?`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ parí pẹ̀lú "${o.suffix}"`:o.format==="includes"?`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ ní "${o.includes}"`:o.format==="regex"?`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bá àpẹẹrẹ mu ${o.pattern}`:`Aṣìṣe: ${i[o.format]??r.format}`}case"not_multiple_of":return`Nọ́mbà aṣìṣe: gbọ́dọ̀ jẹ́ èyà pípín ti ${r.divisor}`;case"unrecognized_keys":return`Bọtìnì àìmọ̀: ${q(r.keys,", ")}`;case"invalid_key":return`Bọtìnì aṣìṣe nínú ${r.origin}`;case"invalid_union":return"Ìbáwọlé aṣìṣe";case"invalid_element":return`Iye aṣìṣe nínú ${r.origin}`;default:return"Ìbáwọlé aṣìṣe"}}};function CO(){return{localeError:$O()}}const gx=Object.freeze(Object.defineProperty({__proto__:null,ar:ZR,az:VR,be:JR,bg:KR,ca:XR,cs:e1,da:n1,de:i1,en:fx,eo:u1,es:d1,fa:f1,fi:m1,fr:v1,frCA:b1,he:w1,hu:S1,id:k1,is:$1,it:A1,ja:R1,ka:j1,kh:D1,km:hx,ko:U1,lt:B1,mk:q1,ms:H1,nl:W1,no:K1,ota:X1,pl:nO,ps:eO,pt:iO,ru:aO,sl:lO,sv:cO,ta:pO,th:hO,tr:vO,ua:bO,uk:mx,ur:wO,vi:SO,yo:CO,zhCN:kO,zhTW:TO},Symbol.toStringTag,{value:"Module"}));var Om;const vx=Symbol("ZodOutput"),yx=Symbol("ZodInput");class bx{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){const i=n[0];if(this._map.set(t,i),i&&typeof i=="object"&&"id"in i){if(this._idmap.has(i.id))throw new Error(`ID ${i.id} already exists in the registry`);this._idmap.set(i.id,t)}return this}clear(){return this._map=new WeakMap,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 i={...this.get(n)??{}};delete i.id;const r={...i,...this._map.get(t)};return Object.keys(r).length?r:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function pp(){return new bx}(Om=globalThis).__zod_globalRegistry??(Om.__zod_globalRegistry=pp());const on=globalThis.__zod_globalRegistry;function _x(e,t){return new e({type:"string",...M(t)})}function wx(e,t){return new e({type:"string",coerce:!0,...M(t)})}function fp(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...M(t)})}function xs(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...M(t)})}function hp(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...M(t)})}function mp(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...M(t)})}function gp(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...M(t)})}function vp(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...M(t)})}function fl(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...M(t)})}function yp(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...M(t)})}function bp(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...M(t)})}function _p(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...M(t)})}function wp(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...M(t)})}function xp(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...M(t)})}function Sp(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...M(t)})}function Ip(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...M(t)})}function kp(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...M(t)})}function Ep(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...M(t)})}function xx(e,t){return new e({type:"string",format:"mac",check:"string_format",abort:!1,...M(t)})}function Tp(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...M(t)})}function $p(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...M(t)})}function Cp(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...M(t)})}function Ap(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...M(t)})}function Pp(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...M(t)})}function Rp(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...M(t)})}const Sx={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function Ix(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...M(t)})}function kx(e,t){return new e({type:"string",format:"date",check:"string_format",...M(t)})}function Ex(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...M(t)})}function Tx(e,t){return new e({type:"string",format:"duration",check:"string_format",...M(t)})}function $x(e,t){return new e({type:"number",checks:[],...M(t)})}function Cx(e,t){return new e({type:"number",coerce:!0,checks:[],...M(t)})}function Ax(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...M(t)})}function Px(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...M(t)})}function Rx(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...M(t)})}function Ox(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...M(t)})}function Nx(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...M(t)})}function jx(e,t){return new e({type:"boolean",...M(t)})}function Mx(e,t){return new e({type:"boolean",coerce:!0,...M(t)})}function Dx(e,t){return new e({type:"bigint",...M(t)})}function zx(e,t){return new e({type:"bigint",coerce:!0,...M(t)})}function Ux(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...M(t)})}function Lx(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...M(t)})}function Fx(e,t){return new e({type:"symbol",...M(t)})}function Bx(e,t){return new e({type:"undefined",...M(t)})}function Zx(e,t){return new e({type:"null",...M(t)})}function qx(e){return new e({type:"any"})}function Vx(e){return new e({type:"unknown"})}function Hx(e,t){return new e({type:"never",...M(t)})}function Jx(e,t){return new e({type:"void",...M(t)})}function Wx(e,t){return new e({type:"date",...M(t)})}function Gx(e,t){return new e({type:"date",coerce:!0,...M(t)})}function Kx(e,t){return new e({type:"nan",...M(t)})}function ar(e,t){return new ip({check:"less_than",...M(t),value:e,inclusive:!1})}function Vt(e,t){return new ip({check:"less_than",...M(t),value:e,inclusive:!0})}function sr(e,t){return new op({check:"greater_than",...M(t),value:e,inclusive:!1})}function bt(e,t){return new op({check:"greater_than",...M(t),value:e,inclusive:!0})}function Op(e){return sr(0,e)}function Np(e){return ar(0,e)}function jp(e){return Vt(0,e)}function Mp(e){return bt(0,e)}function mi(e,t){return new N_({check:"multiple_of",...M(t),value:e})}function Ko(e,t){return new D_({check:"max_size",...M(t),maximum:e})}function gi(e,t){return new z_({check:"min_size",...M(t),minimum:e})}function hl(e,t){return new U_({check:"size_equals",...M(t),size:e})}function Yo(e,t){return new L_({check:"max_length",...M(t),maximum:e})}function Ar(e,t){return new F_({check:"min_length",...M(t),minimum:e})}function Xo(e,t){return new B_({check:"length_equals",...M(t),length:e})}function ml(e,t){return new Z_({check:"string_format",format:"regex",...M(t),pattern:e})}function gl(e){return new q_({check:"string_format",format:"lowercase",...M(e)})}function vl(e){return new V_({check:"string_format",format:"uppercase",...M(e)})}function yl(e,t){return new H_({check:"string_format",format:"includes",...M(t),includes:e})}function bl(e,t){return new J_({check:"string_format",format:"starts_with",...M(t),prefix:e})}function _l(e,t){return new W_({check:"string_format",format:"ends_with",...M(t),suffix:e})}function Dp(e,t,n){return new G_({check:"property",property:e,schema:t,...M(n)})}function wl(e,t){return new K_({check:"mime_type",mime:e,...M(t)})}function Vn(e){return new Y_({check:"overwrite",tx:e})}function xl(e){return Vn(t=>t.normalize(e))}function Sl(){return Vn(e=>e.trim())}function Il(){return Vn(e=>e.toLowerCase())}function kl(){return Vn(e=>e.toUpperCase())}function El(){return Vn(e=>Ab(e))}function Yx(e,t,n){return new e({type:"array",element:t,...M(n)})}function AO(e,t,n){return new e({type:"union",options:t,...M(n)})}function PO(e,t,n){return new e({type:"union",options:t,inclusive:!1,...M(n)})}function RO(e,t,n,i){return new e({type:"union",options:n,discriminator:t,...M(i)})}function OO(e,t,n){return new e({type:"intersection",left:t,right:n})}function NO(e,t,n,i){const r=n instanceof de,o=r?i:n,a=r?n:null;return new e({type:"tuple",items:t,rest:a,...M(o)})}function jO(e,t,n,i){return new e({type:"record",keyType:t,valueType:n,...M(i)})}function MO(e,t,n,i){return new e({type:"map",keyType:t,valueType:n,...M(i)})}function DO(e,t,n){return new e({type:"set",valueType:t,...M(n)})}function zO(e,t,n){const i=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new e({type:"enum",entries:i,...M(n)})}function UO(e,t,n){return new e({type:"enum",entries:t,...M(n)})}function LO(e,t,n){return new e({type:"literal",values:Array.isArray(t)?t:[t],...M(n)})}function Xx(e,t){return new e({type:"file",...M(t)})}function FO(e,t){return new e({type:"transform",transform:t})}function BO(e,t){return new e({type:"optional",innerType:t})}function ZO(e,t){return new e({type:"nullable",innerType:t})}function qO(e,t,n){return new e({type:"default",innerType:t,get defaultValue(){return typeof n=="function"?n():ul(n)}})}function VO(e,t,n){return new e({type:"nonoptional",innerType:t,...M(n)})}function HO(e,t){return new e({type:"success",innerType:t})}function JO(e,t,n){return new e({type:"catch",innerType:t,catchValue:typeof n=="function"?n:()=>n})}function WO(e,t,n){return new e({type:"pipe",in:t,out:n})}function GO(e,t){return new e({type:"readonly",innerType:t})}function KO(e,t,n){return new e({type:"template_literal",parts:t,...M(n)})}function YO(e,t){return new e({type:"lazy",getter:t})}function XO(e,t){return new e({type:"promise",innerType:t})}function Qx(e,t,n){const i=M(n);return i.abort??(i.abort=!0),new e({type:"custom",check:"custom",fn:t,...i})}function eS(e,t,n){return new e({type:"custom",check:"custom",fn:t,...M(n)})}function tS(e){const t=nS(n=>(n.addIssue=i=>{if(typeof i=="string")n.issues.push(fi(i,n.value,t._zod.def));else{const r=i;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=n.value),r.inst??(r.inst=t),r.continue??(r.continue=!t._zod.def.abort),n.issues.push(fi(r))}},e(n.value,n)));return t}function nS(e,t){const n=new Fe({check:"custom",...M(t)});return n._zod.check=e,n}function rS(e){const t=new Fe({check:"describe"});return t._zod.onattach=[n=>{const i=on.get(n)??{};on.add(n,{...i,description:e})}],t._zod.check=()=>{},t}function iS(e){const t=new Fe({check:"meta"});return t._zod.onattach=[n=>{const i=on.get(n)??{};on.add(n,{...i,...e})}],t._zod.check=()=>{},t}function oS(e,t){const n=M(t);let i=n.truthy??["true","1","yes","on","y","enabled"],r=n.falsy??["false","0","no","off","n","disabled"];n.case!=="sensitive"&&(i=i.map(p=>typeof p=="string"?p.toLowerCase():p),r=r.map(p=>typeof p=="string"?p.toLowerCase():p));const o=new Set(i),a=new Set(r),s=e.Codec??dp,u=e.Boolean??lp,l=e.String??Go,c=new l({type:"string",error:n.error}),d=new u({type:"boolean",error:n.error}),f=new s({type:"pipe",in:c,out:d,transform:((p,g)=>{let m=p;return n.case!=="sensitive"&&(m=m.toLowerCase()),o.has(m)?!0:a.has(m)?!1:(g.issues.push({code:"invalid_value",expected:"stringbool",values:[...o,...a],input:g.value,inst:f,continue:!1}),{})}),reverseTransform:((p,g)=>p===!0?i[0]||"true":r[0]||"false"),error:n.error});return f}function Qo(e,t,n,i={}){const r=M(i),o={...M(i),check:"string_format",type:"string",format:t,fn:typeof n=="function"?n:s=>n.test(s),...r};return n instanceof RegExp&&(o.pattern=n),new e(o)}function vi(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??on,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function Re(e,t,n={path:[],schemaPath:[]}){var i;const r=e._zod.def,o=t.seen.get(e);if(o)return o.count++,n.schemaPath.includes(e)&&(o.cycle=n.path),o.schema;const a={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,a);const s=e._zod.toJSONSchema?.();if(s)a.schema=s;else{const c={...n,schemaPath:[...n.schemaPath,e],path:n.path},d=e._zod.parent;if(d)a.ref=d,Re(d,t,c),t.seen.get(d).isParent=!0;else if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,a.schema,c);else{const f=a.schema,p=t.processors[r.type];if(!p)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${r.type}`);p(e,t,f,c)}}const u=t.metadataRegistry.get(e);return u&&Object.assign(a.schema,u),t.io==="input"&&ht(e)&&(delete a.schema.examples,delete a.schema.default),t.io==="input"&&a.schema._prefault&&((i=a.schema).default??(i.default=a.schema._prefault)),delete a.schema._prefault,t.seen.get(e).schema}function yi(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const i=o=>{const a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const c=e.external.registry.get(o[0])?.id,d=e.external.uri??(p=>p);if(c)return{ref:d(c)};const f=o[1].defId??o[1].schema.id??`schema${e.counter++}`;return o[1].defId=f,{defId:f,ref:`${d("__shared")}#/${a}/${f}`}}if(o[1]===n)return{ref:"#"};const u=`#/${a}/`,l=o[1].schema.id??`__schema${e.counter++}`;return{defId:l,ref:u+l}},r=o=>{if(o[1].schema.$ref)return;const a=o[1],{ref:s,defId:u}=i(o);a.def={...a.schema},u&&(a.defId=u);const l=a.schema;for(const c in l)delete l[c];l.$ref=s};if(e.cycles==="throw")for(const o of e.seen.entries()){const a=o[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
|
|
28
|
-
|
|
29
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const o of e.seen.entries()){const a=o[1];if(t===o[0]){r(o);continue}if(e.external){const u=e.external.registry.get(o[0])?.id;if(t!==o[0]&&u){r(o);continue}}if(e.metadataRegistry.get(o[0])?.id){r(o);continue}if(a.cycle){r(o);continue}if(a.count>1&&e.reused==="ref"){r(o);continue}}}function bi(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const i=a=>{const s=e.seen.get(a),u=s.def??s.schema,l={...u};if(s.ref===null)return;const c=s.ref;if(s.ref=null,c){i(c);const d=e.seen.get(c).schema;d.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(d)):(Object.assign(u,d),Object.assign(u,l))}s.isParent||e.override({zodSchema:a,jsonSchema:u,path:s.path??[]})};for(const a of[...e.seen.entries()].reverse())i(a[0]);const r={};if(e.target==="draft-2020-12"?r.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?r.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?r.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const a=e.external.registry.get(t)?.id;if(!a)throw new Error("Schema is missing an `id` property");r.$id=e.external.uri(a)}Object.assign(r,n.def??n.schema);const o=e.external?.defs??{};for(const a of e.seen.entries()){const s=a[1];s.def&&s.defId&&(o[s.defId]=s.def)}e.external||Object.keys(o).length>0&&(e.target==="draft-2020-12"?r.$defs=o:r.definitions=o);try{const a=JSON.parse(JSON.stringify(r));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:co(t,"input"),output:co(t,"output")}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function ht(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const i=e._zod.def;if(i.type==="transform")return!0;if(i.type==="array")return ht(i.element,n);if(i.type==="set")return ht(i.valueType,n);if(i.type==="lazy")return ht(i.getter(),n);if(i.type==="promise"||i.type==="optional"||i.type==="nonoptional"||i.type==="nullable"||i.type==="readonly"||i.type==="default"||i.type==="prefault")return ht(i.innerType,n);if(i.type==="intersection")return ht(i.left,n)||ht(i.right,n);if(i.type==="record"||i.type==="map")return ht(i.keyType,n)||ht(i.valueType,n);if(i.type==="pipe")return ht(i.in,n)||ht(i.out,n);if(i.type==="object"){for(const r in i.shape)if(ht(i.shape[r],n))return!0;return!1}if(i.type==="union"){for(const r of i.options)if(ht(r,n))return!0;return!1}if(i.type==="tuple"){for(const r of i.items)if(ht(r,n))return!0;return!!(i.rest&&ht(i.rest,n))}return!1}const aS=(e,t={})=>n=>{const i=vi({...n,processors:t});return Re(e,i),yi(i,e),bi(i,e)},co=(e,t)=>n=>{const{libraryOptions:i,target:r}=n??{},o=vi({...i??{},target:r,io:t,processors:{}});return Re(e,o),yi(o,e),bi(o,e)},QO={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},sS=(e,t,n,i)=>{const r=n;r.type="string";const{minimum:o,maximum:a,format:s,patterns:u,contentEncoding:l}=e._zod.bag;if(typeof o=="number"&&(r.minLength=o),typeof a=="number"&&(r.maxLength=a),s&&(r.format=QO[s]??s,r.format===""&&delete r.format),l&&(r.contentEncoding=l),u&&u.size>0){const c=[...u];c.length===1?r.pattern=c[0].source:c.length>1&&(r.allOf=[...c.map(d=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},lS=(e,t,n,i)=>{const r=n,{minimum:o,maximum:a,format:s,multipleOf:u,exclusiveMaximum:l,exclusiveMinimum:c}=e._zod.bag;typeof s=="string"&&s.includes("int")?r.type="integer":r.type="number",typeof c=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(r.minimum=c,r.exclusiveMinimum=!0):r.exclusiveMinimum=c),typeof o=="number"&&(r.minimum=o,typeof c=="number"&&t.target!=="draft-04"&&(c>=o?delete r.minimum:delete r.exclusiveMinimum)),typeof l=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(r.maximum=l,r.exclusiveMaximum=!0):r.exclusiveMaximum=l),typeof a=="number"&&(r.maximum=a,typeof l=="number"&&t.target!=="draft-04"&&(l<=a?delete r.maximum:delete r.exclusiveMaximum)),typeof u=="number"&&(r.multipleOf=u)},uS=(e,t,n,i)=>{n.type="boolean"},cS=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},dS=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},pS=(e,t,n,i)=>{t.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},fS=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},hS=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},mS=(e,t,n,i)=>{n.not={}},gS=(e,t,n,i)=>{},vS=(e,t,n,i)=>{},yS=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},bS=(e,t,n,i)=>{const r=e._zod.def,o=Zd(r.entries);o.every(a=>typeof a=="number")&&(n.type="number"),o.every(a=>typeof a=="string")&&(n.type="string"),n.enum=o},_S=(e,t,n,i)=>{const r=e._zod.def,o=[];for(const a of r.values)if(a===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof a=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");o.push(Number(a))}else o.push(a);if(o.length!==0)if(o.length===1){const a=o[0];n.type=a===null?"null":typeof a,t.target==="draft-04"||t.target==="openapi-3.0"?n.enum=[a]:n.const=a}else o.every(a=>typeof a=="number")&&(n.type="number"),o.every(a=>typeof a=="string")&&(n.type="string"),o.every(a=>typeof a=="boolean")&&(n.type="boolean"),o.every(a=>a===null)&&(n.type="null"),n.enum=o},wS=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},xS=(e,t,n,i)=>{const r=n,o=e._zod.pattern;if(!o)throw new Error("Pattern not found in template literal");r.type="string",r.pattern=o.source},SS=(e,t,n,i)=>{const r=n,o={type:"string",format:"binary",contentEncoding:"binary"},{minimum:a,maximum:s,mime:u}=e._zod.bag;a!==void 0&&(o.minLength=a),s!==void 0&&(o.maxLength=s),u?u.length===1?(o.contentMediaType=u[0],Object.assign(r,o)):r.anyOf=u.map(l=>({...o,contentMediaType:l})):Object.assign(r,o)},IS=(e,t,n,i)=>{n.type="boolean"},kS=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},ES=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},TS=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},$S=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},CS=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},AS=(e,t,n,i)=>{const r=n,o=e._zod.def,{minimum:a,maximum:s}=e._zod.bag;typeof a=="number"&&(r.minItems=a),typeof s=="number"&&(r.maxItems=s),r.type="array",r.items=Re(o.element,t,{...i,path:[...i.path,"items"]})},PS=(e,t,n,i)=>{const r=n,o=e._zod.def;r.type="object",r.properties={};const a=o.shape;for(const l in a)r.properties[l]=Re(a[l],t,{...i,path:[...i.path,"properties",l]});const s=new Set(Object.keys(a)),u=new Set([...s].filter(l=>{const c=o.shape[l]._zod;return t.io==="input"?c.optin===void 0:c.optout===void 0}));u.size>0&&(r.required=Array.from(u)),o.catchall?._zod.def.type==="never"?r.additionalProperties=!1:o.catchall?o.catchall&&(r.additionalProperties=Re(o.catchall,t,{...i,path:[...i.path,"additionalProperties"]})):t.io==="output"&&(r.additionalProperties=!1)},zp=(e,t,n,i)=>{const r=e._zod.def,o=r.inclusive===!1,a=r.options.map((s,u)=>Re(s,t,{...i,path:[...i.path,o?"oneOf":"anyOf",u]}));o?n.oneOf=a:n.anyOf=a},RS=(e,t,n,i)=>{const r=e._zod.def,o=Re(r.left,t,{...i,path:[...i.path,"allOf",0]}),a=Re(r.right,t,{...i,path:[...i.path,"allOf",1]}),s=l=>"allOf"in l&&Object.keys(l).length===1,u=[...s(o)?o.allOf:[o],...s(a)?a.allOf:[a]];n.allOf=u},OS=(e,t,n,i)=>{const r=n,o=e._zod.def;r.type="array";const a=t.target==="draft-2020-12"?"prefixItems":"items",s=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",u=o.items.map((f,p)=>Re(f,t,{...i,path:[...i.path,a,p]})),l=o.rest?Re(o.rest,t,{...i,path:[...i.path,s,...t.target==="openapi-3.0"?[o.items.length]:[]]}):null;t.target==="draft-2020-12"?(r.prefixItems=u,l&&(r.items=l)):t.target==="openapi-3.0"?(r.items={anyOf:u},l&&r.items.anyOf.push(l),r.minItems=u.length,l||(r.maxItems=u.length)):(r.items=u,l&&(r.additionalItems=l));const{minimum:c,maximum:d}=e._zod.bag;typeof c=="number"&&(r.minItems=c),typeof d=="number"&&(r.maxItems=d)},NS=(e,t,n,i)=>{const r=n,o=e._zod.def;r.type="object",(t.target==="draft-07"||t.target==="draft-2020-12")&&(r.propertyNames=Re(o.keyType,t,{...i,path:[...i.path,"propertyNames"]})),r.additionalProperties=Re(o.valueType,t,{...i,path:[...i.path,"additionalProperties"]})},jS=(e,t,n,i)=>{const r=e._zod.def,o=Re(r.innerType,t,i),a=t.seen.get(e);t.target==="openapi-3.0"?(a.ref=r.innerType,n.nullable=!0):n.anyOf=[o,{type:"null"}]},MS=(e,t,n,i)=>{const r=e._zod.def;Re(r.innerType,t,i);const o=t.seen.get(e);o.ref=r.innerType},DS=(e,t,n,i)=>{const r=e._zod.def;Re(r.innerType,t,i);const o=t.seen.get(e);o.ref=r.innerType,n.default=JSON.parse(JSON.stringify(r.defaultValue))},zS=(e,t,n,i)=>{const r=e._zod.def;Re(r.innerType,t,i);const o=t.seen.get(e);o.ref=r.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(r.defaultValue)))},US=(e,t,n,i)=>{const r=e._zod.def;Re(r.innerType,t,i);const o=t.seen.get(e);o.ref=r.innerType;let a;try{a=r.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=a},LS=(e,t,n,i)=>{const r=e._zod.def,o=t.io==="input"?r.in._zod.def.type==="transform"?r.out:r.in:r.out;Re(o,t,i);const a=t.seen.get(e);a.ref=o},FS=(e,t,n,i)=>{const r=e._zod.def;Re(r.innerType,t,i);const o=t.seen.get(e);o.ref=r.innerType,n.readOnly=!0},BS=(e,t,n,i)=>{const r=e._zod.def;Re(r.innerType,t,i);const o=t.seen.get(e);o.ref=r.innerType},ZS=(e,t,n,i)=>{const r=e._zod.def;Re(r.innerType,t,i);const o=t.seen.get(e);o.ref=r.innerType},qS=(e,t,n,i)=>{const r=e._zod.innerType;Re(r,t,i);const o=t.seen.get(e);o.ref=r},Bc={string:sS,number:lS,boolean:uS,bigint:cS,symbol:dS,null:pS,undefined:fS,void:hS,never:mS,any:gS,unknown:vS,date:yS,enum:bS,literal:_S,nan:wS,template_literal:xS,file:SS,success:IS,custom:kS,function:ES,transform:TS,map:$S,set:CS,array:AS,object:PS,union:zp,intersection:RS,tuple:OS,record:NS,nullable:jS,nonoptional:MS,default:DS,prefault:zS,catch:US,pipe:LS,readonly:FS,promise:BS,optional:ZS,lazy:qS};function Tl(e,t){if("_idmap"in e){const i=e,r=vi({...t,processors:Bc}),o={};for(const u of i._idmap.entries()){const[l,c]=u;Re(c,r)}const a={},s={registry:i,uri:t?.uri,defs:o};r.external=s;for(const u of i._idmap.entries()){const[l,c]=u;yi(r,c),a[l]=bi(r,c)}if(Object.keys(o).length>0){const u=r.target==="draft-2020-12"?"$defs":"definitions";a.__shared={[u]:o}}return{schemas:a}}const n=vi({...t,processors:Bc});return Re(e,n),yi(n,e),bi(n,e)}class eN{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(t){this.ctx.counter=t}get seen(){return this.ctx.seen}constructor(t){let n=t?.target??"draft-2020-12";n==="draft-4"&&(n="draft-04"),n==="draft-7"&&(n="draft-07"),this.ctx=vi({processors:Bc,target:n,...t?.metadata&&{metadata:t.metadata},...t?.unrepresentable&&{unrepresentable:t.unrepresentable},...t?.override&&{override:t.override},...t?.io&&{io:t.io}})}process(t,n={path:[],schemaPath:[]}){return Re(t,this.ctx,n)}emit(t,n){n&&(n.cycles&&(this.ctx.cycles=n.cycles),n.reused&&(this.ctx.reused=n.reused),n.external&&(this.ctx.external=n.external)),yi(this.ctx,t);const i=bi(this.ctx,t),{"~standard":r,...o}=i;return o}}const tN=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"})),nN=Object.freeze(Object.defineProperty({__proto__:null,$ZodAny:Rw,$ZodArray:Dw,$ZodAsyncError:Er,$ZodBase64:_w,$ZodBase64URL:xw,$ZodBigInt:up,$ZodBigIntFormat:$w,$ZodBoolean:lp,$ZodCIDRv4:yw,$ZodCIDRv6:bw,$ZodCUID:aw,$ZodCUID2:sw,$ZodCatch:ix,$ZodCheck:Fe,$ZodCheckBigIntFormat:M_,$ZodCheckEndsWith:W_,$ZodCheckGreaterThan:op,$ZodCheckIncludes:H_,$ZodCheckLengthEquals:B_,$ZodCheckLessThan:ip,$ZodCheckLowerCase:q_,$ZodCheckMaxLength:L_,$ZodCheckMaxSize:D_,$ZodCheckMimeType:K_,$ZodCheckMinLength:F_,$ZodCheckMinSize:z_,$ZodCheckMultipleOf:N_,$ZodCheckNumberFormat:j_,$ZodCheckOverwrite:Y_,$ZodCheckProperty:G_,$ZodCheckRegex:Z_,$ZodCheckSizeEquals:U_,$ZodCheckStartsWith:J_,$ZodCheckStringFormat:Wo,$ZodCheckUpperCase:V_,$ZodCodec:dp,$ZodCustom:px,$ZodCustomStringFormat:Ew,$ZodDate:Mw,$ZodDefault:ex,$ZodDiscriminatedUnion:Zw,$ZodE164:Sw,$ZodEmail:nw,$ZodEmoji:iw,$ZodEncodeError:sl,$ZodEnum:Ww,$ZodError:Vd,$ZodFile:Kw,$ZodFunction:ux,$ZodGUID:ew,$ZodIPv4:mw,$ZodIPv6:gw,$ZodISODate:pw,$ZodISODateTime:dw,$ZodISODuration:hw,$ZodISOTime:fw,$ZodIntersection:qw,$ZodJWT:kw,$ZodKSUID:cw,$ZodLazy:dx,$ZodLiteral:Gw,$ZodMAC:vw,$ZodMap:Hw,$ZodNaN:ox,$ZodNanoID:ow,$ZodNever:Nw,$ZodNonOptional:nx,$ZodNull:Pw,$ZodNullable:Qw,$ZodNumber:sp,$ZodNumberFormat:Tw,$ZodObject:Lw,$ZodObjectJIT:Fw,$ZodOptional:Xw,$ZodPipe:ax,$ZodPrefault:tx,$ZodPromise:cx,$ZodReadonly:sx,$ZodRealError:Dt,$ZodRecord:Vw,$ZodRegistry:bx,$ZodSet:Jw,$ZodString:Go,$ZodStringFormat:Oe,$ZodSuccess:rx,$ZodSymbol:Cw,$ZodTemplateLiteral:lx,$ZodTransform:Yw,$ZodTuple:cp,$ZodType:de,$ZodULID:lw,$ZodURL:rw,$ZodUUID:tw,$ZodUndefined:Aw,$ZodUnion:pl,$ZodUnknown:Ow,$ZodVoid:jw,$ZodXID:uw,$ZodXor:Bw,$brand:$b,$constructor:P,$input:yx,$output:vx,Doc:X_,JSONSchema:tN,JSONSchemaGenerator:eN,NEVER:Bd,TimePrecision:Sx,_any:qx,_array:Yx,_base64:Cp,_base64url:Ap,_bigint:Dx,_boolean:jx,_catch:JO,_check:nS,_cidrv4:Tp,_cidrv6:$p,_coercedBigint:zx,_coercedBoolean:Mx,_coercedDate:Gx,_coercedNumber:Cx,_coercedString:wx,_cuid:_p,_cuid2:wp,_custom:Qx,_date:Wx,_decode:Gd,_decodeAsync:Yd,_default:qO,_discriminatedUnion:RO,_e164:Pp,_email:fp,_emoji:yp,_encode:Wd,_encodeAsync:Kd,_endsWith:_l,_enum:zO,_file:Xx,_float32:Px,_float64:Rx,_gt:sr,_gte:bt,_guid:xs,_includes:yl,_int:Ax,_int32:Ox,_int64:Ux,_intersection:OO,_ipv4:kp,_ipv6:Ep,_isoDate:kx,_isoDateTime:Ix,_isoDuration:Tx,_isoTime:Ex,_jwt:Rp,_ksuid:Ip,_lazy:YO,_length:Xo,_literal:LO,_lowercase:gl,_lt:ar,_lte:Vt,_mac:xx,_map:MO,_max:Vt,_maxLength:Yo,_maxSize:Ko,_mime:wl,_min:bt,_minLength:Ar,_minSize:gi,_multipleOf:mi,_nan:Kx,_nanoid:bp,_nativeEnum:UO,_negative:Np,_never:Hx,_nonnegative:Mp,_nonoptional:VO,_nonpositive:jp,_normalize:xl,_null:Zx,_nullable:ZO,_number:$x,_optional:BO,_overwrite:Vn,_parse:Bo,_parseAsync:Zo,_pipe:WO,_positive:Op,_promise:XO,_property:Dp,_readonly:GO,_record:jO,_refine:eS,_regex:ml,_safeDecode:Qd,_safeDecodeAsync:tp,_safeEncode:Xd,_safeEncodeAsync:ep,_safeParse:qo,_safeParseAsync:Vo,_set:DO,_size:hl,_slugify:El,_startsWith:bl,_string:_x,_stringFormat:Qo,_stringbool:oS,_success:HO,_superRefine:tS,_symbol:Fx,_templateLiteral:KO,_toLowerCase:Il,_toUpperCase:kl,_transform:FO,_trim:Sl,_tuple:NO,_uint32:Nx,_uint64:Lx,_ulid:xp,_undefined:Bx,_union:AO,_unknown:Vx,_uppercase:vl,_url:fl,_uuid:hp,_uuidv4:mp,_uuidv6:gp,_uuidv7:vp,_void:Jx,_xid:Sp,_xor:PO,clone:Gt,config:st,createStandardJSONSchemaMethod:co,createToJSONSchemaMethod:aS,decode:dR,decodeAsync:fR,describe:rS,encode:cR,encodeAsync:pR,extractDefs:yi,finalize:bi,flattenError:Hd,formatError:Jd,globalConfig:ys,globalRegistry:on,initializeContext:vi,isValidBase64:ap,isValidBase64URL:ww,isValidJWT:Iw,locales:gx,meta:iS,parse:Uc,parseAsync:Lc,prettifyError:Gb,process:Re,regexes:rp,registry:pp,safeDecode:mR,safeDecodeAsync:vR,safeEncode:hR,safeEncodeAsync:gR,safeParse:Kb,safeParseAsync:Yb,toDotPath:Wb,toJSONSchema:Tl,treeifyError:Jb,util:Vb,version:Q_},Symbol.toStringTag,{value:"Module"})),rN=Object.freeze(Object.defineProperty({__proto__:null,endsWith:_l,gt:sr,gte:bt,includes:yl,length:Xo,lowercase:gl,lt:ar,lte:Vt,maxLength:Yo,maxSize:Ko,mime:wl,minLength:Ar,minSize:gi,multipleOf:mi,negative:Np,nonnegative:Mp,nonpositive:jp,normalize:xl,overwrite:Vn,positive:Op,property:Dp,regex:ml,size:hl,slugify:El,startsWith:bl,toLowerCase:Il,toUpperCase:kl,trim:Sl,uppercase:vl},Symbol.toStringTag,{value:"Module"})),Up=P("ZodISODateTime",(e,t)=>{dw.init(e,t),Ne.init(e,t)});function VS(e){return Ix(Up,e)}const Lp=P("ZodISODate",(e,t)=>{pw.init(e,t),Ne.init(e,t)});function HS(e){return kx(Lp,e)}const Fp=P("ZodISOTime",(e,t)=>{fw.init(e,t),Ne.init(e,t)});function JS(e){return Ex(Fp,e)}const Bp=P("ZodISODuration",(e,t)=>{hw.init(e,t),Ne.init(e,t)});function WS(e){return Tx(Bp,e)}const GS=Object.freeze(Object.defineProperty({__proto__:null,ZodISODate:Lp,ZodISODateTime:Up,ZodISODuration:Bp,ZodISOTime:Fp,date:HS,datetime:VS,duration:WS,time:JS},Symbol.toStringTag,{value:"Module"})),KS=(e,t)=>{Vd.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>Jd(e,n)},flatten:{value:n=>Hd(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,bs,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,bs,2)}},isEmpty:{get(){return e.issues.length===0}}})},iN=P("ZodError",KS),zt=P("ZodError",KS,{Parent:Error}),YS=Bo(zt),XS=Zo(zt),QS=qo(zt),$l=Vo(zt),eI=Wd(zt),tI=Gd(zt),nI=Kd(zt),rI=Yd(zt),iI=Xd(zt),oI=Qd(zt),aI=ep(zt),sI=tp(zt),he=P("ZodType",(e,t)=>(de.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:co(e,"input"),output:co(e,"output")}}),e.toJSONSchema=aS(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone(qn(t,{checks:[...t.checks??[],...n.map(i=>typeof i=="function"?{_zod:{check:i,def:{check:"custom"},onattach:[]}}:i)]})),e.clone=(n,i)=>Gt(e,n,i),e.brand=()=>e,e.register=((n,i)=>(n.add(e,i),e)),e.parse=(n,i)=>YS(e,n,i,{callee:e.parse}),e.safeParse=(n,i)=>QS(e,n,i),e.parseAsync=async(n,i)=>XS(e,n,i,{callee:e.parseAsync}),e.safeParseAsync=async(n,i)=>$l(e,n,i),e.spa=e.safeParseAsync,e.encode=(n,i)=>eI(e,n,i),e.decode=(n,i)=>tI(e,n,i),e.encodeAsync=async(n,i)=>nI(e,n,i),e.decodeAsync=async(n,i)=>rI(e,n,i),e.safeEncode=(n,i)=>iI(e,n,i),e.safeDecode=(n,i)=>oI(e,n,i),e.safeEncodeAsync=async(n,i)=>aI(e,n,i),e.safeDecodeAsync=async(n,i)=>sI(e,n,i),e.refine=(n,i)=>e.check(Ef(n,i)),e.superRefine=n=>e.check(Tf(n)),e.overwrite=n=>e.check(Vn(n)),e.optional=()=>pe(e),e.nullable=()=>fo(e),e.nullish=()=>pe(fo(e)),e.nonoptional=n=>mf(e,n),e.array=()=>W(e),e.or=n=>se([e,n]),e.and=n=>tf(e,n),e.transform=n=>ho(e,Yl(n)),e.default=n=>pf(e,n),e.prefault=n=>hf(e,n),e.catch=n=>yf(e,n),e.pipe=n=>ho(e,n),e.readonly=()=>wf(e),e.describe=n=>{const i=e.clone();return on.add(i,{description:n}),i},Object.defineProperty(e,"description",{get(){return on.get(e)?.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return on.get(e);const i=e.clone();return on.add(i,n[0]),i},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),Cl=P("_ZodString",(e,t)=>{Go.init(e,t),he.init(e,t),e._zod.processJSONSchema=(i,r,o)=>sS(e,i,r);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...i)=>e.check(ml(...i)),e.includes=(...i)=>e.check(yl(...i)),e.startsWith=(...i)=>e.check(bl(...i)),e.endsWith=(...i)=>e.check(_l(...i)),e.min=(...i)=>e.check(Ar(...i)),e.max=(...i)=>e.check(Yo(...i)),e.length=(...i)=>e.check(Xo(...i)),e.nonempty=(...i)=>e.check(Ar(1,...i)),e.lowercase=i=>e.check(gl(i)),e.uppercase=i=>e.check(vl(i)),e.trim=()=>e.check(Sl()),e.normalize=(...i)=>e.check(xl(...i)),e.toLowerCase=()=>e.check(Il()),e.toUpperCase=()=>e.check(kl()),e.slugify=()=>e.check(El())}),ea=P("ZodString",(e,t)=>{Go.init(e,t),Cl.init(e,t),e.email=n=>e.check(fp(Al,n)),e.url=n=>e.check(fl(ta,n)),e.jwt=n=>e.check(Rp(Hl,n)),e.emoji=n=>e.check(yp(Pl,n)),e.guid=n=>e.check(xs(po,n)),e.uuid=n=>e.check(hp(xn,n)),e.uuidv4=n=>e.check(mp(xn,n)),e.uuidv6=n=>e.check(gp(xn,n)),e.uuidv7=n=>e.check(vp(xn,n)),e.nanoid=n=>e.check(bp(Rl,n)),e.guid=n=>e.check(xs(po,n)),e.cuid=n=>e.check(_p(Ol,n)),e.cuid2=n=>e.check(wp(Nl,n)),e.ulid=n=>e.check(xp(jl,n)),e.base64=n=>e.check(Cp(Bl,n)),e.base64url=n=>e.check(Ap(ql,n)),e.xid=n=>e.check(Sp(Ml,n)),e.ksuid=n=>e.check(Ip(Dl,n)),e.ipv4=n=>e.check(kp(zl,n)),e.ipv6=n=>e.check(Ep(Ul,n)),e.cidrv4=n=>e.check(Tp(Ll,n)),e.cidrv6=n=>e.check($p(Fl,n)),e.e164=n=>e.check(Pp(Vl,n)),e.datetime=n=>e.check(VS(n)),e.date=n=>e.check(HS(n)),e.time=n=>e.check(JS(n)),e.duration=n=>e.check(WS(n))});function I(e){return _x(ea,e)}const Ne=P("ZodStringFormat",(e,t)=>{Oe.init(e,t),Cl.init(e,t)}),Al=P("ZodEmail",(e,t)=>{nw.init(e,t),Ne.init(e,t)});function lI(e){return fp(Al,e)}const po=P("ZodGUID",(e,t)=>{ew.init(e,t),Ne.init(e,t)});function uI(e){return xs(po,e)}const xn=P("ZodUUID",(e,t)=>{tw.init(e,t),Ne.init(e,t)});function cI(e){return hp(xn,e)}function dI(e){return mp(xn,e)}function pI(e){return gp(xn,e)}function fI(e){return vp(xn,e)}const ta=P("ZodURL",(e,t)=>{rw.init(e,t),Ne.init(e,t)});function hI(e){return fl(ta,e)}function mI(e){return fl(ta,{protocol:/^https?$/,hostname:g_,...M(e)})}const Pl=P("ZodEmoji",(e,t)=>{iw.init(e,t),Ne.init(e,t)});function gI(e){return yp(Pl,e)}const Rl=P("ZodNanoID",(e,t)=>{ow.init(e,t),Ne.init(e,t)});function vI(e){return bp(Rl,e)}const Ol=P("ZodCUID",(e,t)=>{aw.init(e,t),Ne.init(e,t)});function yI(e){return _p(Ol,e)}const Nl=P("ZodCUID2",(e,t)=>{sw.init(e,t),Ne.init(e,t)});function bI(e){return wp(Nl,e)}const jl=P("ZodULID",(e,t)=>{lw.init(e,t),Ne.init(e,t)});function _I(e){return xp(jl,e)}const Ml=P("ZodXID",(e,t)=>{uw.init(e,t),Ne.init(e,t)});function wI(e){return Sp(Ml,e)}const Dl=P("ZodKSUID",(e,t)=>{cw.init(e,t),Ne.init(e,t)});function xI(e){return Ip(Dl,e)}const zl=P("ZodIPv4",(e,t)=>{mw.init(e,t),Ne.init(e,t)});function SI(e){return kp(zl,e)}const Zp=P("ZodMAC",(e,t)=>{vw.init(e,t),Ne.init(e,t)});function II(e){return xx(Zp,e)}const Ul=P("ZodIPv6",(e,t)=>{gw.init(e,t),Ne.init(e,t)});function kI(e){return Ep(Ul,e)}const Ll=P("ZodCIDRv4",(e,t)=>{yw.init(e,t),Ne.init(e,t)});function EI(e){return Tp(Ll,e)}const Fl=P("ZodCIDRv6",(e,t)=>{bw.init(e,t),Ne.init(e,t)});function TI(e){return $p(Fl,e)}const Bl=P("ZodBase64",(e,t)=>{_w.init(e,t),Ne.init(e,t)});function Zl(e){return Cp(Bl,e)}const ql=P("ZodBase64URL",(e,t)=>{xw.init(e,t),Ne.init(e,t)});function $I(e){return Ap(ql,e)}const Vl=P("ZodE164",(e,t)=>{Sw.init(e,t),Ne.init(e,t)});function CI(e){return Pp(Vl,e)}const Hl=P("ZodJWT",(e,t)=>{kw.init(e,t),Ne.init(e,t)});function AI(e){return Rp(Hl,e)}const $i=P("ZodCustomStringFormat",(e,t)=>{Ew.init(e,t),Ne.init(e,t)});function PI(e,t,n={}){return Qo($i,e,t,n)}function RI(e){return Qo($i,"hostname",m_,e)}function OI(e){return Qo($i,"hex",R_,e)}function NI(e,t){const n=t?.enc??"hex",i=`${e}_${n}`,r=rp[i];if(!r)throw new Error(`Unrecognized hash format: ${i}`);return Qo($i,i,r,t)}const na=P("ZodNumber",(e,t)=>{sp.init(e,t),he.init(e,t),e._zod.processJSONSchema=(i,r,o)=>lS(e,i,r),e.gt=(i,r)=>e.check(sr(i,r)),e.gte=(i,r)=>e.check(bt(i,r)),e.min=(i,r)=>e.check(bt(i,r)),e.lt=(i,r)=>e.check(ar(i,r)),e.lte=(i,r)=>e.check(Vt(i,r)),e.max=(i,r)=>e.check(Vt(i,r)),e.int=i=>e.check(Ss(i)),e.safe=i=>e.check(Ss(i)),e.positive=i=>e.check(sr(0,i)),e.nonnegative=i=>e.check(bt(0,i)),e.negative=i=>e.check(ar(0,i)),e.nonpositive=i=>e.check(Vt(0,i)),e.multipleOf=(i,r)=>e.check(mi(i,r)),e.step=(i,r)=>e.check(mi(i,r)),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 te(e){return $x(na,e)}const zr=P("ZodNumberFormat",(e,t)=>{Tw.init(e,t),na.init(e,t)});function Ss(e){return Ax(zr,e)}function jI(e){return Px(zr,e)}function MI(e){return Rx(zr,e)}function DI(e){return Ox(zr,e)}function zI(e){return Nx(zr,e)}const ra=P("ZodBoolean",(e,t)=>{lp.init(e,t),he.init(e,t),e._zod.processJSONSchema=(n,i,r)=>uS(e,n,i)});function Ce(e){return jx(ra,e)}const ia=P("ZodBigInt",(e,t)=>{up.init(e,t),he.init(e,t),e._zod.processJSONSchema=(i,r,o)=>cS(e,i),e.gte=(i,r)=>e.check(bt(i,r)),e.min=(i,r)=>e.check(bt(i,r)),e.gt=(i,r)=>e.check(sr(i,r)),e.gte=(i,r)=>e.check(bt(i,r)),e.min=(i,r)=>e.check(bt(i,r)),e.lt=(i,r)=>e.check(ar(i,r)),e.lte=(i,r)=>e.check(Vt(i,r)),e.max=(i,r)=>e.check(Vt(i,r)),e.positive=i=>e.check(sr(BigInt(0),i)),e.negative=i=>e.check(ar(BigInt(0),i)),e.nonpositive=i=>e.check(Vt(BigInt(0),i)),e.nonnegative=i=>e.check(bt(BigInt(0),i)),e.multipleOf=(i,r)=>e.check(mi(i,r));const n=e._zod.bag;e.minValue=n.minimum??null,e.maxValue=n.maximum??null,e.format=n.format??null});function UI(e){return Dx(ia,e)}const Jl=P("ZodBigIntFormat",(e,t)=>{$w.init(e,t),ia.init(e,t)});function LI(e){return Ux(Jl,e)}function FI(e){return Lx(Jl,e)}const qp=P("ZodSymbol",(e,t)=>{Cw.init(e,t),he.init(e,t),e._zod.processJSONSchema=(n,i,r)=>dS(e,n)});function BI(e){return Fx(qp,e)}const Vp=P("ZodUndefined",(e,t)=>{Aw.init(e,t),he.init(e,t),e._zod.processJSONSchema=(n,i,r)=>fS(e,n)});function ZI(e){return Bx(Vp,e)}const Hp=P("ZodNull",(e,t)=>{Pw.init(e,t),he.init(e,t),e._zod.processJSONSchema=(n,i,r)=>pS(e,n,i)});function oa(e){return Zx(Hp,e)}const Jp=P("ZodAny",(e,t)=>{Rw.init(e,t),he.init(e,t),e._zod.processJSONSchema=(n,i,r)=>gS()});function Ye(){return qx(Jp)}const Wp=P("ZodUnknown",(e,t)=>{Ow.init(e,t),he.init(e,t),e._zod.processJSONSchema=(n,i,r)=>vS()});function Le(){return Vx(Wp)}const Gp=P("ZodNever",(e,t)=>{Nw.init(e,t),he.init(e,t),e._zod.processJSONSchema=(n,i,r)=>mS(e,n,i)});function Wl(e){return Hx(Gp,e)}const Kp=P("ZodVoid",(e,t)=>{jw.init(e,t),he.init(e,t),e._zod.processJSONSchema=(n,i,r)=>hS(e,n)});function qI(e){return Jx(Kp,e)}const Gl=P("ZodDate",(e,t)=>{Mw.init(e,t),he.init(e,t),e._zod.processJSONSchema=(i,r,o)=>yS(e,i),e.min=(i,r)=>e.check(bt(i,r)),e.max=(i,r)=>e.check(Vt(i,r));const n=e._zod.bag;e.minDate=n.minimum?new Date(n.minimum):null,e.maxDate=n.maximum?new Date(n.maximum):null});function VI(e){return Wx(Gl,e)}const Yp=P("ZodArray",(e,t)=>{Dw.init(e,t),he.init(e,t),e._zod.processJSONSchema=(n,i,r)=>AS(e,n,i,r),e.element=t.element,e.min=(n,i)=>e.check(Ar(n,i)),e.nonempty=n=>e.check(Ar(1,n)),e.max=(n,i)=>e.check(Yo(n,i)),e.length=(n,i)=>e.check(Xo(n,i)),e.unwrap=()=>e.element});function W(e,t){return Yx(Yp,e,t)}function HI(e){const t=e._zod.def.shape;return fr(Object.keys(t))}const aa=P("ZodObject",(e,t)=>{Fw.init(e,t),he.init(e,t),e._zod.processJSONSchema=(n,i,r)=>PS(e,n,i,r),ve(e,"shape",()=>t.shape),e.keyof=()=>fr(Object.keys(e._zod.def.shape)),e.catchall=n=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Le()}),e.loose=()=>e.clone({...e._zod.def,catchall:Le()}),e.strict=()=>e.clone({...e._zod.def,catchall:Wl()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=n=>zb(e,n),e.safeExtend=n=>Ub(e,n),e.merge=n=>Lb(e,n),e.pick=n=>Mb(e,n),e.omit=n=>Db(e,n),e.partial=(...n)=>Fb(Xl,e,n[0]),e.required=(...n)=>Bb(Ql,e,n[0])});function O(e,t){const n={type:"object",shape:e??{},...M(t)};return new aa(n)}function ze(e,t){return new aa({type:"object",shape:e,catchall:Wl(),...M(t)})}function tr(e,t){return new aa({type:"object",shape:e,catchall:Le(),...M(t)})}const sa=P("ZodUnion",(e,t)=>{pl.init(e,t),he.init(e,t),e._zod.processJSONSchema=(n,i,r)=>zp(e,n,i,r),e.options=t.options});function se(e,t){return new sa({type:"union",options:e,...M(t)})}const Xp=P("ZodXor",(e,t)=>{sa.init(e,t),Bw.init(e,t),e._zod.processJSONSchema=(n,i,r)=>zp(e,n,i,r),e.options=t.options});function JI(e,t){return new Xp({type:"union",options:e,inclusive:!1,...M(t)})}const Qp=P("ZodDiscriminatedUnion",(e,t)=>{sa.init(e,t),Zw.init(e,t)});function Kl(e,t,n){return new Qp({type:"union",options:t,discriminator:e,...M(n)})}const ef=P("ZodIntersection",(e,t)=>{qw.init(e,t),he.init(e,t),e._zod.processJSONSchema=(n,i,r)=>RS(e,n,i,r)});function tf(e,t){return new ef({type:"intersection",left:e,right:t})}const nf=P("ZodTuple",(e,t)=>{cp.init(e,t),he.init(e,t),e._zod.processJSONSchema=(n,i,r)=>OS(e,n,i,r),e.rest=n=>e.clone({...e._zod.def,rest:n})});function rf(e,t,n){const i=t instanceof de,r=i?n:t,o=i?t:null;return new nf({type:"tuple",items:e,rest:o,...M(r)})}const la=P("ZodRecord",(e,t)=>{Vw.init(e,t),he.init(e,t),e._zod.processJSONSchema=(n,i,r)=>NS(e,n,i,r),e.keyType=t.keyType,e.valueType=t.valueType});function Rt(e,t,n){return new la({type:"record",keyType:e,valueType:t,...M(n)})}function WI(e,t,n){const i=Gt(e);return i._zod.values=void 0,new la({type:"record",keyType:i,valueType:t,...M(n)})}function GI(e,t,n){return new la({type:"record",keyType:e,valueType:t,mode:"loose",...M(n)})}const of=P("ZodMap",(e,t)=>{Hw.init(e,t),he.init(e,t),e._zod.processJSONSchema=(n,i,r)=>$S(e,n),e.keyType=t.keyType,e.valueType=t.valueType});function KI(e,t,n){return new of({type:"map",keyType:e,valueType:t,...M(n)})}const af=P("ZodSet",(e,t)=>{Jw.init(e,t),he.init(e,t),e._zod.processJSONSchema=(n,i,r)=>CS(e,n),e.min=(...n)=>e.check(gi(...n)),e.nonempty=n=>e.check(gi(1,n)),e.max=(...n)=>e.check(Ko(...n)),e.size=(...n)=>e.check(hl(...n))});function YI(e,t){return new af({type:"set",valueType:e,...M(t)})}const _i=P("ZodEnum",(e,t)=>{Ww.init(e,t),he.init(e,t),e._zod.processJSONSchema=(i,r,o)=>bS(e,i,r),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(i,r)=>{const o={};for(const a of i)if(n.has(a))o[a]=t.entries[a];else throw new Error(`Key ${a} not found in enum`);return new _i({...t,checks:[],...M(r),entries:o})},e.exclude=(i,r)=>{const o={...t.entries};for(const a of i)if(n.has(a))delete o[a];else throw new Error(`Key ${a} not found in enum`);return new _i({...t,checks:[],...M(r),entries:o})}});function fr(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(i=>[i,i])):e;return new _i({type:"enum",entries:n,...M(t)})}function XI(e,t){return new _i({type:"enum",entries:e,...M(t)})}const sf=P("ZodLiteral",(e,t)=>{Gw.init(e,t),he.init(e,t),e._zod.processJSONSchema=(n,i,r)=>_S(e,n,i),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 L(e,t){return new sf({type:"literal",values:Array.isArray(e)?e:[e],...M(t)})}const lf=P("ZodFile",(e,t)=>{Kw.init(e,t),he.init(e,t),e._zod.processJSONSchema=(n,i,r)=>SS(e,n,i),e.min=(n,i)=>e.check(gi(n,i)),e.max=(n,i)=>e.check(Ko(n,i)),e.mime=(n,i)=>e.check(wl(Array.isArray(n)?n:[n],i))});function QI(e){return Xx(lf,e)}const uf=P("ZodTransform",(e,t)=>{Yw.init(e,t),he.init(e,t),e._zod.processJSONSchema=(n,i,r)=>TS(e,n),e._zod.parse=(n,i)=>{if(i.direction==="backward")throw new sl(e.constructor.name);n.addIssue=o=>{if(typeof o=="string")n.issues.push(fi(o,n.value,t));else{const a=o;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=n.value),a.inst??(a.inst=e),n.issues.push(fi(a))}};const r=t.transform(n.value,n);return r instanceof Promise?r.then(o=>(n.value=o,n)):(n.value=r,n)}});function Yl(e){return new uf({type:"transform",transform:e})}const Xl=P("ZodOptional",(e,t)=>{Xw.init(e,t),he.init(e,t),e._zod.processJSONSchema=(n,i,r)=>ZS(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function pe(e){return new Xl({type:"optional",innerType:e})}const cf=P("ZodNullable",(e,t)=>{Qw.init(e,t),he.init(e,t),e._zod.processJSONSchema=(n,i,r)=>jS(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function fo(e){return new cf({type:"nullable",innerType:e})}function ek(e){return pe(fo(e))}const df=P("ZodDefault",(e,t)=>{ex.init(e,t),he.init(e,t),e._zod.processJSONSchema=(n,i,r)=>DS(e,n,i,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function pf(e,t){return new df({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():ul(t)}})}const ff=P("ZodPrefault",(e,t)=>{tx.init(e,t),he.init(e,t),e._zod.processJSONSchema=(n,i,r)=>zS(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function hf(e,t){return new ff({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():ul(t)}})}const Ql=P("ZodNonOptional",(e,t)=>{nx.init(e,t),he.init(e,t),e._zod.processJSONSchema=(n,i,r)=>MS(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function mf(e,t){return new Ql({type:"nonoptional",innerType:e,...M(t)})}const gf=P("ZodSuccess",(e,t)=>{rx.init(e,t),he.init(e,t),e._zod.processJSONSchema=(n,i,r)=>IS(e,n,i),e.unwrap=()=>e._zod.def.innerType});function tk(e){return new gf({type:"success",innerType:e})}const vf=P("ZodCatch",(e,t)=>{ix.init(e,t),he.init(e,t),e._zod.processJSONSchema=(n,i,r)=>US(e,n,i,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function yf(e,t){return new vf({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const bf=P("ZodNaN",(e,t)=>{ox.init(e,t),he.init(e,t),e._zod.processJSONSchema=(n,i,r)=>wS(e,n)});function nk(e){return Kx(bf,e)}const eu=P("ZodPipe",(e,t)=>{ax.init(e,t),he.init(e,t),e._zod.processJSONSchema=(n,i,r)=>LS(e,n,i,r),e.in=t.in,e.out=t.out});function ho(e,t){return new eu({type:"pipe",in:e,out:t})}const tu=P("ZodCodec",(e,t)=>{eu.init(e,t),dp.init(e,t)});function rk(e,t,n){return new tu({type:"pipe",in:e,out:t,transform:n.decode,reverseTransform:n.encode})}const _f=P("ZodReadonly",(e,t)=>{sx.init(e,t),he.init(e,t),e._zod.processJSONSchema=(n,i,r)=>FS(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function wf(e){return new _f({type:"readonly",innerType:e})}const xf=P("ZodTemplateLiteral",(e,t)=>{lx.init(e,t),he.init(e,t),e._zod.processJSONSchema=(n,i,r)=>xS(e,n,i)});function ik(e,t){return new xf({type:"template_literal",parts:e,...M(t)})}const Sf=P("ZodLazy",(e,t)=>{dx.init(e,t),he.init(e,t),e._zod.processJSONSchema=(n,i,r)=>qS(e,n,i,r),e.unwrap=()=>e._zod.def.getter()});function ua(e){return new Sf({type:"lazy",getter:e})}const If=P("ZodPromise",(e,t)=>{cx.init(e,t),he.init(e,t),e._zod.processJSONSchema=(n,i,r)=>BS(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function ok(e){return new If({type:"promise",innerType:e})}const kf=P("ZodFunction",(e,t)=>{ux.init(e,t),he.init(e,t),e._zod.processJSONSchema=(n,i,r)=>ES(e,n)});function Is(e){return new kf({type:"function",input:Array.isArray(e?.input)?rf(e?.input):e?.input??W(Le()),output:e?.output??Le()})}const ca=P("ZodCustom",(e,t)=>{px.init(e,t),he.init(e,t),e._zod.processJSONSchema=(n,i,r)=>kS(e,n)});function ak(e){const t=new Fe({check:"custom"});return t._zod.check=e,t}function da(e,t){return Qx(ca,e??(()=>!0),t)}function Ef(e,t={}){return eS(ca,e,t)}function Tf(e){return tS(e)}const sk=rS,lk=iS;function En(e,t={error:`Input not instance of ${e.name}`}){const n=new ca({type:"custom",check:"custom",fn:i=>i instanceof e,abort:!0,...M(t)});return n._zod.bag.Class=e,n}const uk=(...e)=>oS({Codec:tu,Boolean:ra,String:ea},...e);function ck(e){const t=ua(()=>se([I(e),te(),Ce(),oa(),W(t),Rt(I(),t)]));return t}function dk(e,t){return ho(Yl(e),t)}const oN=Object.freeze(Object.defineProperty({__proto__:null,ZodAny:Jp,ZodArray:Yp,ZodBase64:Bl,ZodBase64URL:ql,ZodBigInt:ia,ZodBigIntFormat:Jl,ZodBoolean:ra,ZodCIDRv4:Ll,ZodCIDRv6:Fl,ZodCUID:Ol,ZodCUID2:Nl,ZodCatch:vf,ZodCodec:tu,ZodCustom:ca,ZodCustomStringFormat:$i,ZodDate:Gl,ZodDefault:df,ZodDiscriminatedUnion:Qp,ZodE164:Vl,ZodEmail:Al,ZodEmoji:Pl,ZodEnum:_i,ZodFile:lf,ZodFunction:kf,ZodGUID:po,ZodIPv4:zl,ZodIPv6:Ul,ZodIntersection:ef,ZodJWT:Hl,ZodKSUID:Dl,ZodLazy:Sf,ZodLiteral:sf,ZodMAC:Zp,ZodMap:of,ZodNaN:bf,ZodNanoID:Rl,ZodNever:Gp,ZodNonOptional:Ql,ZodNull:Hp,ZodNullable:cf,ZodNumber:na,ZodNumberFormat:zr,ZodObject:aa,ZodOptional:Xl,ZodPipe:eu,ZodPrefault:ff,ZodPromise:If,ZodReadonly:_f,ZodRecord:la,ZodSet:af,ZodString:ea,ZodStringFormat:Ne,ZodSuccess:gf,ZodSymbol:qp,ZodTemplateLiteral:xf,ZodTransform:uf,ZodTuple:nf,ZodType:he,ZodULID:jl,ZodURL:ta,ZodUUID:xn,ZodUndefined:Vp,ZodUnion:sa,ZodUnknown:Wp,ZodVoid:Kp,ZodXID:Ml,ZodXor:Xp,_ZodString:Cl,_default:pf,_function:Is,any:Ye,array:W,base64:Zl,base64url:$I,bigint:UI,boolean:Ce,catch:yf,check:ak,cidrv4:EI,cidrv6:TI,codec:rk,cuid:yI,cuid2:bI,custom:da,date:VI,describe:sk,discriminatedUnion:Kl,e164:CI,email:lI,emoji:gI,enum:fr,file:QI,float32:jI,float64:MI,function:Is,guid:uI,hash:NI,hex:OI,hostname:RI,httpUrl:mI,instanceof:En,int:Ss,int32:DI,int64:LI,intersection:tf,ipv4:SI,ipv6:kI,json:ck,jwt:AI,keyof:HI,ksuid:xI,lazy:ua,literal:L,looseObject:tr,looseRecord:GI,mac:II,map:KI,meta:lk,nan:nk,nanoid:vI,nativeEnum:XI,never:Wl,nonoptional:mf,null:oa,nullable:fo,nullish:ek,number:te,object:O,optional:pe,partialRecord:WI,pipe:ho,prefault:hf,preprocess:dk,promise:ok,readonly:wf,record:Rt,refine:Ef,set:YI,strictObject:ze,string:I,stringFormat:PI,stringbool:uk,success:tk,superRefine:Tf,symbol:BI,templateLiteral:ik,transform:Yl,tuple:rf,uint32:zI,uint64:FI,ulid:_I,undefined:ZI,union:se,unknown:Le,url:hI,uuid:cI,uuidv4:dI,uuidv6:pI,uuidv7:fI,void:qI,xid:wI,xor:JI},Symbol.toStringTag,{value:"Module"})),pk={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function aN(e){st({customError:e})}function sN(){return st().customError}var Zc;Zc||(Zc={});const K={...oN,...rN,iso:GS};function lN(e,t){const n=e.$schema;return n==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":n==="http://json-schema.org/draft-07/schema#"?"draft-7":n==="http://json-schema.org/draft-04/schema#"?"draft-4":t??"draft-2020-12"}function uN(e,t){if(!e.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");const n=e.slice(1).split("/").filter(Boolean);if(n.length===0)return t.rootSchema;const i=t.version==="draft-2020-12"?"$defs":"definitions";if(n[0]===i){const r=n[1];if(!r||!t.defs[r])throw new Error(`Reference not found: ${e}`);return t.defs[r]}throw new Error(`Reference not found: ${e}`)}function fk(e,t){if(e.not!==void 0){if(typeof e.not=="object"&&Object.keys(e.not).length===0)return K.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(e.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(e.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(e.if!==void 0||e.then!==void 0||e.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(e.dependentSchemas!==void 0||e.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(e.$ref){const r=e.$ref;if(t.refs.has(r))return t.refs.get(r);if(t.processing.has(r))return K.lazy(()=>{if(!t.refs.has(r))throw new Error(`Circular reference not resolved: ${r}`);return t.refs.get(r)});t.processing.add(r);const o=uN(r,t),a=ot(o,t);return t.refs.set(r,a),t.processing.delete(r),a}if(e.enum!==void 0){const r=e.enum;if(t.version==="openapi-3.0"&&e.nullable===!0&&r.length===1&&r[0]===null)return K.null();if(r.length===0)return K.never();if(r.length===1)return K.literal(r[0]);if(r.every(a=>typeof a=="string"))return K.enum(r);const o=r.map(a=>K.literal(a));return o.length<2?o[0]:K.union([o[0],o[1],...o.slice(2)])}if(e.const!==void 0)return K.literal(e.const);const n=e.type;if(Array.isArray(n)){const r=n.map(o=>{const a={...e,type:o};return fk(a,t)});return r.length===0?K.never():r.length===1?r[0]:K.union(r)}if(!n)return K.any();let i;switch(n){case"string":{let r=K.string();if(e.format){const o=e.format;o==="email"?r=r.check(K.email()):o==="uri"||o==="uri-reference"?r=r.check(K.url()):o==="uuid"||o==="guid"?r=r.check(K.uuid()):o==="date-time"?r=r.check(K.iso.datetime()):o==="date"?r=r.check(K.iso.date()):o==="time"?r=r.check(K.iso.time()):o==="duration"?r=r.check(K.iso.duration()):o==="ipv4"?r=r.check(K.ipv4()):o==="ipv6"?r=r.check(K.ipv6()):o==="mac"?r=r.check(K.mac()):o==="cidr"?r=r.check(K.cidrv4()):o==="cidr-v6"?r=r.check(K.cidrv6()):o==="base64"?r=r.check(K.base64()):o==="base64url"?r=r.check(K.base64url()):o==="e164"?r=r.check(K.e164()):o==="jwt"?r=r.check(K.jwt()):o==="emoji"?r=r.check(K.emoji()):o==="nanoid"?r=r.check(K.nanoid()):o==="cuid"?r=r.check(K.cuid()):o==="cuid2"?r=r.check(K.cuid2()):o==="ulid"?r=r.check(K.ulid()):o==="xid"?r=r.check(K.xid()):o==="ksuid"&&(r=r.check(K.ksuid()))}typeof e.minLength=="number"&&(r=r.min(e.minLength)),typeof e.maxLength=="number"&&(r=r.max(e.maxLength)),e.pattern&&(r=r.regex(new RegExp(e.pattern))),i=r;break}case"number":case"integer":{let r=n==="integer"?K.number().int():K.number();typeof e.minimum=="number"&&(r=r.min(e.minimum)),typeof e.maximum=="number"&&(r=r.max(e.maximum)),typeof e.exclusiveMinimum=="number"?r=r.gt(e.exclusiveMinimum):e.exclusiveMinimum===!0&&typeof e.minimum=="number"&&(r=r.gt(e.minimum)),typeof e.exclusiveMaximum=="number"?r=r.lt(e.exclusiveMaximum):e.exclusiveMaximum===!0&&typeof e.maximum=="number"&&(r=r.lt(e.maximum)),typeof e.multipleOf=="number"&&(r=r.multipleOf(e.multipleOf)),i=r;break}case"boolean":{i=K.boolean();break}case"null":{i=K.null();break}case"object":{const r={},o=e.properties||{},a=new Set(e.required||[]);for(const[u,l]of Object.entries(o)){const c=ot(l,t);r[u]=a.has(u)?c:c.optional()}if(e.propertyNames){const u=ot(e.propertyNames,t),l=e.additionalProperties&&typeof e.additionalProperties=="object"?ot(e.additionalProperties,t):K.any();if(Object.keys(r).length===0){i=K.record(u,l);break}const c=K.object(r).passthrough(),d=K.looseRecord(u,l);i=K.intersection(c,d);break}if(e.patternProperties){const u=e.patternProperties,l=Object.keys(u),c=[];for(const f of l){const p=ot(u[f],t),g=K.string().regex(new RegExp(f));c.push(K.looseRecord(g,p))}const d=[];if(Object.keys(r).length>0&&d.push(K.object(r).passthrough()),d.push(...c),d.length===0)i=K.object({}).passthrough();else if(d.length===1)i=d[0];else{let f=K.intersection(d[0],d[1]);for(let p=2;p<d.length;p++)f=K.intersection(f,d[p]);i=f}break}const s=K.object(r);e.additionalProperties===!1?i=s.strict():typeof e.additionalProperties=="object"?i=s.catchall(ot(e.additionalProperties,t)):i=s.passthrough();break}case"array":{const r=e.prefixItems,o=e.items;if(r&&Array.isArray(r)){const a=r.map(u=>ot(u,t)),s=o&&typeof o=="object"&&!Array.isArray(o)?ot(o,t):void 0;s?i=K.tuple(a).rest(s):i=K.tuple(a),typeof e.minItems=="number"&&(i=i.check(K.minLength(e.minItems))),typeof e.maxItems=="number"&&(i=i.check(K.maxLength(e.maxItems)))}else if(Array.isArray(o)){const a=o.map(u=>ot(u,t)),s=e.additionalItems&&typeof e.additionalItems=="object"?ot(e.additionalItems,t):void 0;s?i=K.tuple(a).rest(s):i=K.tuple(a),typeof e.minItems=="number"&&(i=i.check(K.minLength(e.minItems))),typeof e.maxItems=="number"&&(i=i.check(K.maxLength(e.maxItems)))}else if(o!==void 0){const a=ot(o,t);let s=K.array(a);typeof e.minItems=="number"&&(s=s.min(e.minItems)),typeof e.maxItems=="number"&&(s=s.max(e.maxItems)),i=s}else i=K.array(K.any());break}default:throw new Error(`Unsupported type: ${n}`)}return e.description&&(i=i.describe(e.description)),e.default!==void 0&&(i=i.default(e.default)),i}function ot(e,t){if(typeof e=="boolean")return e?K.any():K.never();let n=fk(e,t);const i=e.type||e.enum!==void 0||e.const!==void 0;if(e.anyOf&&Array.isArray(e.anyOf)){const r=e.anyOf.map(a=>ot(a,t)),o=K.union(r);n=i?K.intersection(n,o):o}if(e.oneOf&&Array.isArray(e.oneOf)){const r=e.oneOf.map(a=>ot(a,t)),o=K.xor(r);n=i?K.intersection(n,o):o}if(e.allOf&&Array.isArray(e.allOf))if(e.allOf.length===0)n=i?n:K.any();else{let r=i?n:ot(e.allOf[0],t);const o=i?0:1;for(let a=o;a<e.allOf.length;a++)r=K.intersection(r,ot(e.allOf[a],t));n=r}return e.nullable===!0&&t.version==="openapi-3.0"&&(n=K.nullable(n)),e.readOnly===!0&&(n=K.readonly(n)),n}function cN(e,t){if(typeof e=="boolean")return e?K.any():K.never();const n=lN(e,t?.defaultTarget),i=e.$defs||e.definitions||{};return ot(e,{version:n,defs:i,refs:new Map,processing:new Set,rootSchema:e})}function dN(e){return wx(ea,e)}function pN(e){return Cx(na,e)}function fN(e){return Mx(ra,e)}function hN(e){return zx(ia,e)}function mN(e){return Gx(Gl,e)}const gN=Object.freeze(Object.defineProperty({__proto__:null,bigint:hN,boolean:fN,date:mN,number:pN,string:dN},Symbol.toStringTag,{value:"Module"}));st(fx());const ks=Object.freeze(Object.defineProperty({__proto__:null,$brand:$b,$input:yx,$output:vx,NEVER:Bd,TimePrecision:Sx,ZodAny:Jp,ZodArray:Yp,ZodBase64:Bl,ZodBase64URL:ql,ZodBigInt:ia,ZodBigIntFormat:Jl,ZodBoolean:ra,ZodCIDRv4:Ll,ZodCIDRv6:Fl,ZodCUID:Ol,ZodCUID2:Nl,ZodCatch:vf,ZodCodec:tu,ZodCustom:ca,ZodCustomStringFormat:$i,ZodDate:Gl,ZodDefault:df,ZodDiscriminatedUnion:Qp,ZodE164:Vl,ZodEmail:Al,ZodEmoji:Pl,ZodEnum:_i,ZodError:iN,ZodFile:lf,get ZodFirstPartyTypeKind(){return Zc},ZodFunction:kf,ZodGUID:po,ZodIPv4:zl,ZodIPv6:Ul,ZodISODate:Lp,ZodISODateTime:Up,ZodISODuration:Bp,ZodISOTime:Fp,ZodIntersection:ef,ZodIssueCode:pk,ZodJWT:Hl,ZodKSUID:Dl,ZodLazy:Sf,ZodLiteral:sf,ZodMAC:Zp,ZodMap:of,ZodNaN:bf,ZodNanoID:Rl,ZodNever:Gp,ZodNonOptional:Ql,ZodNull:Hp,ZodNullable:cf,ZodNumber:na,ZodNumberFormat:zr,ZodObject:aa,ZodOptional:Xl,ZodPipe:eu,ZodPrefault:ff,ZodPromise:If,ZodReadonly:_f,ZodRealError:zt,ZodRecord:la,ZodSet:af,ZodString:ea,ZodStringFormat:Ne,ZodSuccess:gf,ZodSymbol:qp,ZodTemplateLiteral:xf,ZodTransform:uf,ZodTuple:nf,ZodType:he,ZodULID:jl,ZodURL:ta,ZodUUID:xn,ZodUndefined:Vp,ZodUnion:sa,ZodUnknown:Wp,ZodVoid:Kp,ZodXID:Ml,ZodXor:Xp,_ZodString:Cl,_default:pf,_function:Is,any:Ye,array:W,base64:Zl,base64url:$I,bigint:UI,boolean:Ce,catch:yf,check:ak,cidrv4:EI,cidrv6:TI,clone:Gt,codec:rk,coerce:gN,config:st,core:nN,cuid:yI,cuid2:bI,custom:da,date:VI,decode:tI,decodeAsync:rI,describe:sk,discriminatedUnion:Kl,e164:CI,email:lI,emoji:gI,encode:eI,encodeAsync:nI,endsWith:_l,enum:fr,file:QI,flattenError:Hd,float32:jI,float64:MI,formatError:Jd,fromJSONSchema:cN,function:Is,getErrorMap:sN,globalRegistry:on,gt:sr,gte:bt,guid:uI,hash:NI,hex:OI,hostname:RI,httpUrl:mI,includes:yl,instanceof:En,int:Ss,int32:DI,int64:LI,intersection:tf,ipv4:SI,ipv6:kI,iso:GS,json:ck,jwt:AI,keyof:HI,ksuid:xI,lazy:ua,length:Xo,literal:L,locales:gx,looseObject:tr,looseRecord:GI,lowercase:gl,lt:ar,lte:Vt,mac:II,map:KI,maxLength:Yo,maxSize:Ko,meta:lk,mime:wl,minLength:Ar,minSize:gi,multipleOf:mi,nan:nk,nanoid:vI,nativeEnum:XI,negative:Np,never:Wl,nonnegative:Mp,nonoptional:mf,nonpositive:jp,normalize:xl,null:oa,nullable:fo,nullish:ek,number:te,object:O,optional:pe,overwrite:Vn,parse:YS,parseAsync:XS,partialRecord:WI,pipe:ho,positive:Op,prefault:hf,preprocess:dk,prettifyError:Gb,promise:ok,property:Dp,readonly:wf,record:Rt,refine:Ef,regex:ml,regexes:rp,registry:pp,safeDecode:oI,safeDecodeAsync:sI,safeEncode:iI,safeEncodeAsync:aI,safeParse:QS,safeParseAsync:$l,set:YI,setErrorMap:aN,size:hl,slugify:El,startsWith:bl,strictObject:ze,string:I,stringFormat:PI,stringbool:uk,success:tk,superRefine:Tf,symbol:BI,templateLiteral:ik,toJSONSchema:Tl,toLowerCase:Il,toUpperCase:kl,transform:Yl,treeifyError:Jb,trim:Sl,tuple:rf,uint32:zI,uint64:FI,ulid:_I,undefined:ZI,union:se,unknown:Le,uppercase:vl,url:hI,util:Vb,uuid:cI,uuidv4:dI,uuidv6:pI,uuidv7:fI,void:qI,xid:wI,xor:JI},Symbol.toStringTag,{value:"Module"}));var mo;(function(e){e.assertEqual=r=>{};function t(r){}e.assertIs=t;function n(r){throw new Error}e.assertNever=n,e.arrayToEnum=r=>{const o={};for(const a of r)o[a]=a;return o},e.getValidEnumValues=r=>{const o=e.objectKeys(r).filter(s=>typeof r[r[s]]!="number"),a={};for(const s of o)a[s]=r[s];return e.objectValues(a)},e.objectValues=r=>e.objectKeys(r).map(function(o){return r[o]}),e.objectKeys=typeof Object.keys=="function"?r=>Object.keys(r):r=>{const o=[];for(const a in r)Object.prototype.hasOwnProperty.call(r,a)&&o.push(a);return o},e.find=(r,o)=>{for(const a of r)if(o(a))return a},e.isInteger=typeof Number.isInteger=="function"?r=>Number.isInteger(r):r=>typeof r=="number"&&Number.isFinite(r)&&Math.floor(r)===r;function i(r,o=" | "){return r.map(a=>typeof a=="string"?`'${a}'`:a).join(o)}e.joinValues=i,e.jsonStringifyReplacer=(r,o)=>typeof o=="bigint"?o.toString():o})(mo||(mo={}));var Nm;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Nm||(Nm={}));mo.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]);mo.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 Es extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=i=>{this.issues=[...this.issues,i]},this.addIssues=(i=[])=>{this.issues=[...this.issues,...i]};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(o){return o.message},i={_errors:[]},r=o=>{for(const a of o.issues)if(a.code==="invalid_union")a.unionErrors.map(r);else if(a.code==="invalid_return_type")r(a.returnTypeError);else if(a.code==="invalid_arguments")r(a.argumentsError);else if(a.path.length===0)i._errors.push(n(a));else{let s=i,u=0;for(;u<a.path.length;){const l=a.path[u];u===a.path.length-1?(s[l]=s[l]||{_errors:[]},s[l]._errors.push(n(a))):s[l]=s[l]||{_errors:[]},s=s[l],u++}}};return r(this),i}static assert(t){if(!(t instanceof Es))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,mo.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){const n=Object.create(null),i=[];for(const r of this.issues)if(r.path.length>0){const o=r.path[0];n[o]=n[o]||[],n[o].push(t(r))}else i.push(t(r));return{formErrors:i,fieldErrors:n}}get formErrors(){return this.flatten()}}Es.create=e=>new Es(e);var jm;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(jm||(jm={}));var H;(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"})(H||(H={}));var vN=({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:i="-"}={})=>{const r=()=>{const o=n.length,a=new Array(t);for(let s=0;s<t;s++)a[s]=n[Math.random()*o|0];return a.join("")};if(e==null)return r;if(n.includes(i))throw new al({argument:"separator",message:`The separator "${i}" must not be part of the alphabet "${n}".`});return()=>`${e}${i}${r()}`};vN();function hk(e=globalThis){var t,n,i;return e.window?"runtime/browser":(t=e.navigator)!=null&&t.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(i=(n=e.process)==null?void 0:n.versions)!=null&&i.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function yN(e){if(e==null)return{};const t={};if(e instanceof Headers)e.forEach((n,i)=>{t[i.toLowerCase()]=n});else{Array.isArray(e)||(e=Object.entries(e));for(const[n,i]of e)i!=null&&(t[n.toLowerCase()]=i)}return t}function mk(e,...t){const n=new Headers(yN(e)),i=n.get("user-agent")||"";return n.set("user-agent",[i,...t].filter(Boolean).join(" ")),Object.fromEntries(n.entries())}var bN=Symbol.for("vercel.ai.validator");function _N(e){return{...e,type:"dynamic"}}new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");var wN=Symbol.for("vercel.ai.schema");function xN(e,{validate:t}={}){return{[wN]:!0,_type:void 0,[bN]:!0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}let $f;$f=globalThis.crypto;async function SN(e){return(await $f).getRandomValues(new Uint8Array(e))}async function IN(e){const t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";let n="";const i=await SN(e);for(let r=0;r<e;r++){const o=i[r]%t.length;n+=t[o]}return n}async function kN(e){return await IN(e)}async function EN(e){const t=await(await $f).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function TN(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;const t=await kN(e),n=await EN(t);return{code_verifier:t,code_challenge:n}}var $N="AI_MCPClientError",gk=`vercel.ai.error.${$N}`,CN=Symbol.for(gk),Mm,Dm,ke=class extends(Dm=ce,Mm=CN,Dm){constructor({name:e="MCPClientError",message:t,cause:n,data:i,code:r}){super({name:e,message:t,cause:n}),this[Mm]=!0,this.data=i,this.code=r}static isInstance(e){return ce.hasMarker(e,gk)}},Ci="2025-06-18",AN=[Ci,"2025-03-26","2024-11-05"],PN=tr({name:I(),version:I()}),nu=tr({_meta:pe(O({}).loose())}),Fn=nu,vk=O({method:I(),params:pe(nu)}),yk=O({applyDefaults:pe(Ce())}).loose(),RN=tr({experimental:pe(O({}).loose()),logging:pe(O({}).loose()),prompts:pe(tr({listChanged:pe(Ce())})),resources:pe(tr({subscribe:pe(Ce()),listChanged:pe(Ce())})),tools:pe(tr({listChanged:pe(Ce())})),elicitation:pe(yk)});O({elicitation:pe(yk)}).loose();var ON=Fn.extend({protocolVersion:I(),capabilities:RN,serverInfo:PN,instructions:pe(I())}),Cf=Fn.extend({nextCursor:pe(I())}),NN=O({name:I(),description:pe(I()),inputSchema:O({type:L("object"),properties:pe(O({}).loose())}).loose()}).loose(),jN=Cf.extend({tools:W(NN)}),bk=O({type:L("text"),text:I()}).loose(),_k=O({type:L("image"),data:Zl(),mimeType:I()}).loose(),MN=O({uri:I(),name:I(),title:pe(I()),description:pe(I()),mimeType:pe(I()),size:pe(te())}).loose(),DN=Cf.extend({resources:W(MN)}),wk=O({uri:I(),name:pe(I()),title:pe(I()),mimeType:pe(I())}).loose(),xk=wk.extend({text:I()}),Sk=wk.extend({blob:Zl()}),Ik=O({type:L("resource"),resource:se([xk,Sk])}).loose(),zN=Fn.extend({content:W(se([bk,_k,Ik])),isError:Ce().default(!1).optional()}).or(Fn.extend({toolResult:Le()})),UN=O({uriTemplate:I(),name:I(),title:pe(I()),description:pe(I()),mimeType:pe(I())}).loose(),LN=Fn.extend({resourceTemplates:W(UN)}),FN=Fn.extend({contents:W(se([xk,Sk]))}),BN=O({name:I(),description:pe(I()),required:pe(Ce())}).loose(),ZN=O({name:I(),title:pe(I()),description:pe(I()),arguments:pe(W(BN))}).loose(),qN=Cf.extend({prompts:W(ZN)}),VN=O({role:se([L("user"),L("assistant")]),content:se([bk,_k,Ik])}).loose(),HN=Fn.extend({description:pe(I()),messages:W(VN)}),JN=nu.extend({message:I(),requestedSchema:Le()}),zm=vk.extend({method:L("elicitation/create"),params:JN}),WN=Fn.extend({action:se([L("accept"),L("decline"),L("cancel")]),content:pe(Rt(I(),Le()))}),ru="2.0",GN=O({jsonrpc:L(ru),id:se([I(),te().int()])}).merge(vk).strict(),KN=O({jsonrpc:L(ru),id:se([I(),te().int()]),result:Fn}).strict(),YN=O({jsonrpc:L(ru),id:se([I(),te().int()]),error:O({code:te().int(),message:I(),data:pe(Le())})}).strict(),XN=O({jsonrpc:L(ru)}).merge(O({method:I(),params:pe(nu)})).strict(),Gi=se([GN,XN,KN,YN]),kk=typeof __PACKAGE_VERSION__<"u"?__PACKAGE_VERSION__:"0.0.0-test",Ek=O({access_token:I(),id_token:I().optional(),token_type:I(),expires_in:te().optional(),scope:I().optional(),refresh_token:I().optional()}).strip(),_t=I().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:pk.custom,message:"URL must be parseable",fatal:!0}),Bd}).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"}),QN=O({resource:I().url(),authorization_servers:W(_t).optional(),jwks_uri:I().url().optional(),scopes_supported:W(I()).optional(),bearer_methods_supported:W(I()).optional(),resource_signing_alg_values_supported:W(I()).optional(),resource_name:I().optional(),resource_documentation:I().optional(),resource_policy_uri:I().url().optional(),resource_tos_uri:I().url().optional(),tls_client_certificate_bound_access_tokens:Ce().optional(),authorization_details_types_supported:W(I()).optional(),dpop_signing_alg_values_supported:W(I()).optional(),dpop_bound_access_tokens_required:Ce().optional()}).passthrough(),Tk=O({issuer:I(),authorization_endpoint:_t,token_endpoint:_t,registration_endpoint:_t.optional(),scopes_supported:W(I()).optional(),response_types_supported:W(I()),grant_types_supported:W(I()).optional(),code_challenge_methods_supported:W(I()),token_endpoint_auth_methods_supported:W(I()).optional(),token_endpoint_auth_signing_alg_values_supported:W(I()).optional()}).passthrough(),ej=O({issuer:I(),authorization_endpoint:_t,token_endpoint:_t,userinfo_endpoint:_t.optional(),jwks_uri:_t,registration_endpoint:_t.optional(),scopes_supported:W(I()).optional(),response_types_supported:W(I()),grant_types_supported:W(I()).optional(),subject_types_supported:W(I()),id_token_signing_alg_values_supported:W(I()),claims_supported:W(I()).optional(),token_endpoint_auth_methods_supported:W(I()).optional()}).passthrough(),tj=ej.merge(Tk.pick({code_challenge_methods_supported:!0})),nj=O({client_id:I(),client_secret:I().optional(),client_id_issued_at:te().optional(),client_secret_expires_at:te().optional()}).strip(),rj=O({redirect_uris:W(_t),token_endpoint_auth_method:I().optional(),grant_types:W(I()).optional(),response_types:W(I()).optional(),client_name:I().optional(),client_uri:_t.optional(),logo_uri:_t.optional(),scope:I().optional(),contacts:W(I()).optional(),tos_uri:_t.optional(),policy_uri:I().optional(),jwks_uri:_t.optional(),jwks:Ye().optional(),software_id:I().optional(),software_version:I().optional(),software_statement:I().optional()}).strip(),ij=O({error:I(),error_description:I().optional(),error_uri:I().optional()}),oj=rj.merge(nj),aj="AI_MCPClientOAuthError",$k=`vercel.ai.error.${aj}`,sj=Symbol.for($k),Um,Lm,pa=class extends(Lm=ce,Um=sj,Lm){constructor({name:e="MCPClientOAuthError",message:t,cause:n}){super({name:e,message:t,cause:n}),this[Um]=!0}static isInstance(e){return ce.hasMarker(e,$k)}},wi=class extends pa{};wi.errorCode="server_error";var Ts=class extends pa{};Ts.errorCode="invalid_client";var $s=class extends pa{};$s.errorCode="invalid_grant";var Cs=class extends pa{};Cs.errorCode="unauthorized_client";var lj={[wi.errorCode]:wi,[Ts.errorCode]:Ts,[$s.errorCode]:$s,[Cs.errorCode]:Cs};function uj(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function cj({requestedResource:e,configuredResource:t}){const n=typeof e=="string"?new URL(e):new URL(e.href),i=typeof t=="string"?new URL(t):new URL(t.href);if(n.origin!==i.origin||n.pathname.length<i.pathname.length)return!1;const r=n.pathname.endsWith("/")?n.pathname:n.pathname+"/",o=i.pathname.endsWith("/")?i.pathname:i.pathname+"/";return r.startsWith(o)}var As=class extends Error{constructor(e="Unauthorized"){super(e),this.name="UnauthorizedError"}};function Ps(e){var t;const n=(t=e.headers.get("www-authenticate"))!=null?t:e.headers.get("WWW-Authenticate");if(!n)return;const[i,r]=n.split(" ");if(i.toLowerCase()!=="bearer"||!r)return;const o=/resource_metadata="([^"]*)"/,a=n.match(o);if(a)try{return new URL(a[1])}catch{return}}function dj(e,t="",n={}){return t.endsWith("/")&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Af(e,t,n=fetch){try{return await n(e,{headers:t})}catch(i){if(i instanceof TypeError)return t?Af(e,void 0,n):void 0;throw i}}async function Fm(e,t,n=fetch){return await Af(e,{"MCP-Protocol-Version":t},n)}function pj(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function fj(e,t,n,i){var r,o;const a=new URL(e),s=(r=i?.protocolVersion)!=null?r:Ci;let u;if(i?.metadataUrl)u=new URL(i.metadataUrl);else{const c=dj(t,a.pathname);u=new URL(c,(o=i?.metadataServerUrl)!=null?o:a),u.search=a.search}let l=await Fm(u,s,n);if(!i?.metadataUrl&&pj(l,a.pathname)){const c=new URL(`/.well-known/${t}`,a);l=await Fm(c,s,n)}return l}async function hj(e,t,n=fetch){const i=await fj(e,"oauth-protected-resource",n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!i||i.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!i.ok)throw new Error(`HTTP ${i.status} trying to load well-known OAuth protected resource metadata.`);return QN.parse(await i.json())}function mj(e){const t=typeof e=="string"?new URL(e):e,n=t.pathname!=="/",i=[];if(!n)return i.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),i.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),i;let r=t.pathname;return r.endsWith("/")&&(r=r.slice(0,-1)),i.push({url:new URL(`/.well-known/oauth-authorization-server${r}`,t.origin),type:"oauth"}),i.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),i.push({url:new URL(`/.well-known/openid-configuration${r}`,t.origin),type:"oidc"}),i.push({url:new URL(`${r}/.well-known/openid-configuration`,t.origin),type:"oidc"}),i}async function gj(e,{fetchFn:t=fetch,protocolVersion:n=Ci}={}){var i;const r={"MCP-Protocol-Version":n},o=mj(e);for(const{url:a,type:s}of o){const u=await Af(a,r,t);if(u){if(!u.ok){if(u.status>=400&&u.status<500)continue;throw new Error(`HTTP ${u.status} trying to load ${s==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`)}if(s==="oauth")return Tk.parse(await u.json());{const l=tj.parse(await u.json());if(!((i=l.code_challenge_methods_supported)!=null&&i.includes("S256")))throw new Error(`Incompatible OIDC provider at ${a}: does not support S256 code challenge method required by MCP specification`);return l}}}}async function vj(e,{metadata:t,clientInformation:n,redirectUrl:i,scope:r,state:o,resource:a}){const s="code",u="S256";let l;if(t){if(l=new URL(t.authorization_endpoint),!t.response_types_supported.includes(s))throw new Error(`Incompatible auth server: does not support response type ${s}`);if(!t.code_challenge_methods_supported||!t.code_challenge_methods_supported.includes(u))throw new Error(`Incompatible auth server: does not support code challenge method ${u}`)}else l=new URL("/authorize",e);const c=await TN(),d=c.code_verifier,f=c.code_challenge;return l.searchParams.set("response_type",s),l.searchParams.set("client_id",n.client_id),l.searchParams.set("code_challenge",f),l.searchParams.set("code_challenge_method",u),l.searchParams.set("redirect_uri",String(i)),o&&l.searchParams.set("state",o),r&&l.searchParams.set("scope",r),r?.includes("offline_access")&&l.searchParams.append("prompt","consent"),a&&l.searchParams.set("resource",a.href),{authorizationUrl:l,codeVerifier:d}}function Ck(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 Ak(e,t,n,i){const{client_id:r,client_secret:o}=t;switch(e){case"client_secret_basic":yj(r,o,n);return;case"client_secret_post":bj(r,o,i);return;case"none":_j(r,i);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function yj(e,t,n){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const i=btoa(`${e}:${t}`);n.set("Authorization",`Basic ${i}`)}function bj(e,t,n){n.set("client_id",e),t&&n.set("client_secret",t)}function _j(e,t){t.set("client_id",e)}async function Pf(e){const t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{const i=ij.parse(JSON.parse(n)),{error:r,error_description:o,error_uri:a}=i,s=lj[r]||wi;return new s({message:o||"",cause:a})}catch(i){const r=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${i}. Raw body: ${n}`;return new wi({message:r})}}async function wj(e,{metadata:t,clientInformation:n,authorizationCode:i,codeVerifier:r,redirectUri:o,resource:a,addClientAuthentication:s,fetchFn:u}){var l;const c="authorization_code",d=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e);if(t?.grant_types_supported&&!t.grant_types_supported.includes(c))throw new Error(`Incompatible auth server: does not support grant type ${c}`);const f=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),p=new URLSearchParams({grant_type:c,code:i,code_verifier:r,redirect_uri:String(o)});if(s)s(f,p,e,t);else{const m=(l=t?.token_endpoint_auth_methods_supported)!=null?l:[],y=Ck(n,m);Ak(y,n,f,p)}a&&p.set("resource",a.href);const g=await(u??fetch)(d,{method:"POST",headers:f,body:p});if(!g.ok)throw await Pf(g);return Ek.parse(await g.json())}async function xj(e,{metadata:t,clientInformation:n,refreshToken:i,resource:r,addClientAuthentication:o,fetchFn:a}){var s;const u="refresh_token";let l;if(t){if(l=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(u))throw new Error(`Incompatible auth server: does not support grant type ${u}`)}else l=new URL("/token",e);const c=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),d=new URLSearchParams({grant_type:u,refresh_token:i});if(o)o(c,d,e,t);else{const p=(s=t?.token_endpoint_auth_methods_supported)!=null?s:[],g=Ck(n,p);Ak(g,n,c,d)}r&&d.set("resource",r.href);const f=await(a??fetch)(l,{method:"POST",headers:c,body:d});if(!f.ok)throw await Pf(f);return Ek.parse({refresh_token:i,...await f.json()})}async function Sj(e,{metadata:t,clientMetadata:n,fetchFn:i}){let r;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");r=new URL(t.registration_endpoint)}else r=new URL("/register",e);const o=await(i??fetch)(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok)throw await Pf(o);return oj.parse(await o.json())}async function Rs(e,t){var n,i;try{return await zu(e,t)}catch(r){if(r instanceof Ts||r instanceof Cs)return await((n=e.invalidateCredentials)==null?void 0:n.call(e,"all")),await zu(e,t);if(r instanceof $s)return await((i=e.invalidateCredentials)==null?void 0:i.call(e,"tokens")),await zu(e,t);throw r}}async function Ij(e,t,n){const i=uj(e);if(t.validateResourceURL)return await t.validateResourceURL(i,n?.resource);if(n){if(!cj({requestedResource:i,configuredResource:n.resource}))throw new Error(`Protected resource ${n.resource} does not match expected ${i} (or origin)`);return new URL(n.resource)}}async function zu(e,{serverUrl:t,authorizationCode:n,scope:i,resourceMetadataUrl:r,fetchFn:o}){let a,s;try{a=await hj(t,{resourceMetadataUrl:r},o),a.authorization_servers&&a.authorization_servers.length>0&&(s=a.authorization_servers[0])}catch{}s||(s=t);const u=await Ij(t,e,a),l=await gj(s,{fetchFn:o});let c=await Promise.resolve(e.clientInformation());if(!c){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 m=await Sj(s,{metadata:l,clientMetadata:e.clientMetadata,fetchFn:o});await e.saveClientInformation(m),c=m}if(n!==void 0){const m=await e.codeVerifier(),y=await wj(s,{metadata:l,clientInformation:c,authorizationCode:n,codeVerifier:m,redirectUri:e.redirectUrl,resource:u,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(y),"AUTHORIZED"}const d=await e.tokens();if(d?.refresh_token)try{const m=await xj(s,{metadata:l,clientInformation:c,refreshToken:d.refresh_token,resource:u,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(m),"AUTHORIZED"}catch(m){if(!(!(m instanceof pa)||m instanceof wi))throw m}const f=e.state?await e.state():void 0,{authorizationUrl:p,codeVerifier:g}=await vj(s,{metadata:l,clientInformation:c,state:f,redirectUrl:e.redirectUrl,scope:i||e.clientMetadata.scope,resource:u});return await e.saveCodeVerifier(g),await e.redirectToAuthorization(p),"REDIRECT"}var kj=class{constructor({url:e,headers:t,authProvider:n}){this.connected=!1,this.url=new URL(e),this.headers=t,this.authProvider=n}async commonHeaders(e){const t={...this.headers,...e,"mcp-protocol-version":Ci};if(this.authProvider){const n=await this.authProvider.tokens();n?.access_token&&(t.Authorization=`Bearer ${n.access_token}`)}return mk(t,`ai-sdk/${kk}`,hk())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;const n=async(i=!1)=>{var r,o,a,s,u;try{const l=await this.commonHeaders({Accept:"text/event-stream"}),c=await fetch(this.url.href,{headers:l,signal:(r=this.abortController)==null?void 0:r.signal});if(c.status===401&&this.authProvider&&!i){this.resourceMetadataUrl=Ps(c);try{if(await Rs(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const m=new As;return(o=this.onerror)==null||o.call(this,m),t(m)}}catch(g){return(a=this.onerror)==null||a.call(this,g),t(g)}return n(!0)}if(!c.ok||!c.body){let g=`MCP SSE Transport Error: ${c.status} ${c.statusText}`;c.status===405&&(g+=". This server does not support SSE transport. Try using `http` transport instead");const m=new ke({message:g});return(s=this.onerror)==null||s.call(this,m),t(m)}const f=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new uo).getReader(),p=async()=>{var g,m,y;try{for(;;){const{done:v,value:_}=await f.read();if(v){if(this.connected)throw this.connected=!1,new ke({message:"MCP SSE Transport Error: Connection closed unexpectedly"});return}const{event:x,data:b}=_;if(x==="endpoint"){if(this.endpoint=new URL(b,this.url),this.endpoint.origin!==this.url.origin)throw new ke({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${this.endpoint.origin}`});this.connected=!0,e()}else if(x==="message")try{const C=Gi.parse(JSON.parse(b));(g=this.onmessage)==null||g.call(this,C)}catch(C){const E=new ke({message:"MCP SSE Transport Error: Failed to parse message",cause:C});(m=this.onerror)==null||m.call(this,E)}}}catch(v){if(v instanceof Error&&v.name==="AbortError")return;(y=this.onerror)==null||y.call(this,v),t(v)}};this.sseConnection={close:()=>f.cancel()},p()}catch(l){if(l instanceof Error&&l.name==="AbortError")return;(u=this.onerror)==null||u.call(this,l),t(l)}};n()})}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){if(!this.endpoint||!this.connected)throw new ke({message:"MCP SSE Transport Error: Not connected"});const t=this.endpoint,n=async(i=!1)=>{var r,o,a,s,u;try{const c={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json"}),body:JSON.stringify(e),signal:(r=this.abortController)==null?void 0:r.signal},d=await fetch(t,c);if(d.status===401&&this.authProvider&&!i){this.resourceMetadataUrl=Ps(d);try{if(await Rs(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const p=new As;(o=this.onerror)==null||o.call(this,p);return}}catch(f){(a=this.onerror)==null||a.call(this,f);return}return n(!0)}if(!d.ok){const f=await d.text().catch(()=>null),p=new ke({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${d.status}): ${f}`});(s=this.onerror)==null||s.call(this,p);return}}catch(l){(u=this.onerror)==null||u.call(this,l);return}};await n()}},Ej=class{constructor({url:e,headers:t,authProvider:n}){this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(e),this.headers=t,this.authProvider=n}async commonHeaders(e){const t={...this.headers,...e,"mcp-protocol-version":Ci};if(this.sessionId&&(t["mcp-session-id"]=this.sessionId),this.authProvider){const n=await this.authProvider.tokens();n?.access_token&&(t.Authorization=`Bearer ${n.access_token}`)}return mk(t,`ai-sdk/${kk}`,hk())}async start(){if(this.abortController)throw new ke({message:"MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically."});this.abortController=new AbortController,this.openInboundSse()}async close(){var e,t,n;(e=this.inboundSseConnection)==null||e.close();try{if(this.sessionId&&this.abortController&&!this.abortController.signal.aborted){const i=await this.commonHeaders({});await fetch(this.url,{method:"DELETE",headers:i,signal:this.abortController.signal}).catch(()=>{})}}catch{}(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e){const t=async(n=!1)=>{var i,r,o,a,s,u,l;try{const d={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),body:JSON.stringify(e),signal:(i=this.abortController)==null?void 0:i.signal},f=await fetch(this.url,d),p=f.headers.get("mcp-session-id");if(p&&(this.sessionId=p),f.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=Ps(f);try{if(await Rs(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED")throw new As}catch(y){throw(r=this.onerror)==null||r.call(this,y),y}return t(!0)}if(f.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!f.ok){const y=await f.text().catch(()=>null);let v=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${f.status}): ${y}`;f.status===404&&(v+=". This server does not support HTTP transport. Try using `sse` transport instead");const _=new ke({message:v});throw(o=this.onerror)==null||o.call(this,_),_}const g=f.headers.get("content-type")||"";if(g.includes("application/json")){const y=await f.json(),v=Array.isArray(y)?y.map(_=>Gi.parse(_)):[Gi.parse(y)];for(const _ of v)(a=this.onmessage)==null||a.call(this,_);return}if(g.includes("text/event-stream")){if(!f.body){const x=new ke({message:"MCP HTTP Transport Error: text/event-stream response without body"});throw(s=this.onerror)==null||s.call(this,x),x}const v=f.body.pipeThrough(new TextDecoderStream).pipeThrough(new uo).getReader();(async()=>{var x,b,C;try{for(;;){const{done:E,value:$}=await v.read();if(E)return;const{event:A,data:j}=$;if(A==="message")try{const F=Gi.parse(JSON.parse(j));(x=this.onmessage)==null||x.call(this,F)}catch(F){const z=new ke({message:"MCP HTTP Transport Error: Failed to parse message",cause:F});(b=this.onerror)==null||b.call(this,z)}}}catch(E){if(E instanceof Error&&E.name==="AbortError")return;(C=this.onerror)==null||C.call(this,E)}})();return}const m=new ke({message:`MCP HTTP Transport Error: Unexpected content type: ${g}`});throw(u=this.onerror)==null||u.call(this,m),m}catch(c){throw(l=this.onerror)==null||l.call(this,c),c}};await t()}getNextReconnectionDelay(e){const{initialReconnectionDelay:t,reconnectionDelayGrowFactor:n,maxReconnectionDelay:i}=this.reconnectionOptions;return Math.min(t*Math.pow(n,e),i)}scheduleInboundSseReconnection(){var e;const{maxRetries:t}=this.reconnectionOptions;if(t>0&&this.inboundReconnectAttempts>=t){(e=this.onerror)==null||e.call(this,new ke({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${t}) exceeded.`}));return}const n=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(async()=>{var i;(i=this.abortController)!=null&&i.signal.aborted||await this.openInboundSse(!1,this.lastInboundEventId)},n)}async openInboundSse(e=!1,t){var n,i,r,o,a,s;try{const u=await this.commonHeaders({Accept:"text/event-stream"});t&&(u["last-event-id"]=t);const l=await fetch(this.url.href,{method:"GET",headers:u,signal:(n=this.abortController)==null?void 0:n.signal}),c=l.headers.get("mcp-session-id");if(c&&(this.sessionId=c),l.status===401&&this.authProvider&&!e){this.resourceMetadataUrl=Ps(l);try{if(await Rs(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const m=new As;(i=this.onerror)==null||i.call(this,m);return}}catch(g){(r=this.onerror)==null||r.call(this,g);return}return this.openInboundSse(!0,t)}if(l.status===405)return;if(!l.ok||!l.body){const g=new ke({message:`MCP HTTP Transport Error: GET SSE failed: ${l.status} ${l.statusText}`});(o=this.onerror)==null||o.call(this,g);return}const f=l.body.pipeThrough(new TextDecoderStream).pipeThrough(new uo).getReader(),p=async()=>{var g,m,y,v;try{for(;;){const{done:_,value:x}=await f.read();if(_)return;const{event:b,data:C,id:E}=x;if(E&&(this.lastInboundEventId=E),b==="message")try{const $=Gi.parse(JSON.parse(C));(g=this.onmessage)==null||g.call(this,$)}catch($){const A=new ke({message:"MCP HTTP Transport Error: Failed to parse message",cause:$});(m=this.onerror)==null||m.call(this,A)}}}catch(_){if(_ instanceof Error&&_.name==="AbortError")return;(y=this.onerror)==null||y.call(this,_),(v=this.abortController)!=null&&v.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>f.cancel()},this.inboundReconnectAttempts=0,p()}catch(u){if(u instanceof Error&&u.name==="AbortError")return;(a=this.onerror)==null||a.call(this,u),(s=this.abortController)!=null&&s.signal.aborted||this.scheduleInboundSseReconnection()}}};function Tj(e){switch(e.type){case"sse":return new kj(e);case"http":return new Ej(e);default:throw new ke({message:"Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface."})}}function $j(e){return"start"in e&&typeof e.start=="function"&&"send"in e&&typeof e.send=="function"&&"close"in e&&typeof e.close=="function"}var Cj="1.0.0";async function Aj(e){const t=new Pj(e);return await t.init(),t}var Pj=class{constructor({transport:e,name:t="ai-sdk-mcp-client",version:n=Cj,onUncaughtError:i,capabilities:r}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this.isClosed=!0,this.onUncaughtError=i,this.clientCapabilities=r??{},$j(e)?this.transport=e:this.transport=Tj(e),this.transport.onclose=()=>this.onClose(),this.transport.onerror=o=>this.onError(o),this.transport.onmessage=o=>{if("method"in o){"id"in o?this.onRequestMessage(o):this.onError(new ke({message:"Unsupported message type"}));return}this.onResponse(o)},this.clientInfo={name:t,version:n}}async init(){try{await this.transport.start(),this.isClosed=!1;const e=await this.request({request:{method:"initialize",params:{protocolVersion:Ci,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:ON});if(e===void 0)throw new ke({message:"Server sent invalid initialize result"});if(!AN.includes(e.protocolVersion))throw new ke({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 ke({message:"Server does not support tools"});break;case"resources/list":case"resources/read":case"resources/templates/list":if(!this.serverCapabilities.resources)throw new ke({message:"Server does not support resources"});break;case"prompts/list":case"prompts/get":if(!this.serverCapabilities.prompts)throw new ke({message:"Server does not support prompts"});break;default:throw new ke({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:n}){return new Promise((i,r)=>{if(this.isClosed)return r(new ke({message:"Attempted to send a request from a closed client"}));this.assertCapability(e.method);const o=n?.signal;o?.throwIfAborted();const a=this.requestMessageId++,s={...e,jsonrpc:"2.0",id:a},u=()=>{this.responseHandlers.delete(a)};this.responseHandlers.set(a,l=>{if(o?.aborted)return r(new ke({message:"Request was aborted",cause:o.reason}));if(l instanceof Error)return r(l);try{const c=t.parse(l.result);i(c)}catch(c){const d=new ke({message:"Failed to parse server response",cause:c});r(d)}}),this.transport.send(s).catch(l=>{u(),r(l)})})}async listTools({params:e,options:t}={}){try{return this.request({request:{method:"tools/list",params:e},resultSchema:jN,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:zN,options:{signal:n?.abortSignal}})}catch(i){throw i}}async listResourcesInternal({params:e,options:t}={}){try{return this.request({request:{method:"resources/list",params:e},resultSchema:DN,options:t})}catch(n){throw n}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:"resources/read",params:{uri:e}},resultSchema:FN,options:t})}catch(n){throw n}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:"resources/templates/list"},resultSchema:LN,options:e})}catch(t){throw t}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:"prompts/list",params:e},resultSchema:qN,options:t})}catch(n){throw n}}async getPromptInternal({name:e,args:t,options:n}){try{return this.request({request:{method:"prompts/get",params:{name:e,arguments:t}},resultSchema:HN,options:n})}catch(i){throw i}}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 i=await this.listTools();for(const{name:r,description:o,inputSchema:a}of i.tools){if(e!=="automatic"&&!(r in e))continue;const s=this,u=async(c,d)=>{var f;return(f=d?.abortSignal)==null||f.throwIfAborted(),s.callTool({name:r,args:c,options:d})},l=e==="automatic"?_N({description:o,inputSchema:xN({...a,properties:(t=a.properties)!=null?t:{},additionalProperties:!1}),execute:u}):{description:o,inputSchema:e[r].inputSchema,execute:u};n[r]=l}return n}catch(i){throw i}}listResources({params:e,options:t}={}){return this.listResourcesInternal({params:e,options:t})}readResource({uri:e,options:t}){return this.readResourceInternal({uri:e,options:t})}listResourceTemplates({options:e}={}){return this.listResourceTemplatesInternal({options:e})}listPrompts({params:e,options:t}={}){return this.listPromptsInternal({params:e,options:t})}getPrompt({name:e,arguments:t,options:n}){return this.getPromptInternal({name:e,args:t,options:n})}onElicitationRequest(e,t){if(e!==zm)throw new ke({message:"Unsupported request schema. Only ElicitationRequestSchema is supported."});this.elicitationRequestHandler=t}async onRequestMessage(e){try{if(e.method!=="elicitation/create"){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32601,message:`Unsupported request method: ${e.method}`}});return}if(!this.elicitationRequestHandler){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32601,message:"No elicitation handler registered on client"}});return}const t=zm.safeParse({method:e.method,params:e.params});if(!t.success){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32602,message:`Invalid elicitation request: ${t.error.message}`,data:t.error.issues}});return}try{const n=await this.elicitationRequestHandler(t.data),i=WN.parse(n);await this.transport.send({jsonrpc:"2.0",id:e.id,result:i})}catch(n){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32603,message:n instanceof Error?n.message:"Failed to handle elicitation request"}}),this.onError(n)}}catch(t){this.onError(t)}}onClose(){if(this.isClosed)return;this.isClosed=!0;const e=new ke({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 ke({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),n("result"in e?e:new ke({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}},fa=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Rj={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},Oj=class{#e=Rj;#t=!1;setTimeoutProvider(e){process.env.NODE_ENV!=="production"&&this.#t&&e!==this.#e&&console.error("[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.",{previous:this.#e,provider:e}),this.#e=e,process.env.NODE_ENV!=="production"&&(this.#t=!1)}setTimeout(e,t){return process.env.NODE_ENV!=="production"&&(this.#t=!0),this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return process.env.NODE_ENV!=="production"&&(this.#t=!0),this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}},Sr=new Oj;function Nj(e){setTimeout(e,0)}var Pr=typeof window>"u"||"Deno"in globalThis;function yt(){}function jj(e,t){return typeof e=="function"?e(t):e}function qc(e){return typeof e=="number"&&e>=0&&e!==1/0}function Pk(e,t){return Math.max(e+(t||0)-Date.now(),0)}function rr(e,t){return typeof e=="function"?e(t):e}function Zt(e,t){return typeof e=="function"?e(t):e}function Bm(e,t){const{type:n="all",exact:i,fetchStatus:r,predicate:o,queryKey:a,stale:s}=e;if(a){if(i){if(t.queryHash!==Rf(a,t.options))return!1}else if(!vo(t.queryKey,a))return!1}if(n!=="all"){const u=t.isActive();if(n==="active"&&!u||n==="inactive"&&u)return!1}return!(typeof s=="boolean"&&t.isStale()!==s||r&&r!==t.state.fetchStatus||o&&!o(t))}function Zm(e,t){const{exact:n,status:i,predicate:r,mutationKey:o}=e;if(o){if(!t.options.mutationKey)return!1;if(n){if(go(t.options.mutationKey)!==go(o))return!1}else if(!vo(t.options.mutationKey,o))return!1}return!(i&&t.state.status!==i||r&&!r(t))}function Rf(e,t){return(t?.queryKeyHashFn||go)(e)}function go(e){return JSON.stringify(e,(t,n)=>Jc(n)?Object.keys(n).sort().reduce((i,r)=>(i[r]=n[r],i),{}):n)}function vo(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>vo(e[n],t[n])):!1}var Mj=Object.prototype.hasOwnProperty;function Vc(e,t){if(e===t)return e;const n=qm(e)&&qm(t);if(!n&&!(Jc(e)&&Jc(t)))return t;const r=(n?e:Object.keys(e)).length,o=n?t:Object.keys(t),a=o.length,s=n?new Array(a):{};let u=0;for(let l=0;l<a;l++){const c=n?l:o[l],d=e[c],f=t[c];if(d===f){s[c]=d,(n?l<r:Mj.call(e,c))&&u++;continue}if(d===null||f===null||typeof d!="object"||typeof f!="object"){s[c]=f;continue}const p=Vc(d,f);s[c]=p,p===d&&u++}return r===a&&u===r?e:s}function Hc(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(e[n]!==t[n])return!1;return!0}function qm(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Jc(e){if(!Vm(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!Vm(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Vm(e){return Object.prototype.toString.call(e)==="[object Object]"}function Dj(e){return new Promise(t=>{Sr.setTimeout(t,e)})}function Wc(e,t,n){if(typeof n.structuralSharing=="function")return n.structuralSharing(e,t);if(n.structuralSharing!==!1){if(process.env.NODE_ENV!=="production")try{return Vc(e,t)}catch(i){throw console.error(`Structural sharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${n.queryHash}]: ${i}`),i}return Vc(e,t)}return t}function zj(e,t,n=0){const i=[...e,t];return n&&i.length>n?i.slice(1):i}function Uj(e,t,n=0){const i=[t,...e];return n&&i.length>n?i.slice(0,-1):i}var Os=Symbol();function Rk(e,t){return process.env.NODE_ENV!=="production"&&e.queryFn===Os&&console.error(`Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${e.queryHash}'`),!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Os?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Lj(e,t){return typeof e=="function"?e(...t):!!e}var Fj=class extends fa{#e;#t;#n;constructor(){super(),this.#n=e=>{if(!Pr&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}},Of=new Fj;function Gc(){let e,t;const n=new Promise((r,o)=>{e=r,t=o});n.status="pending",n.catch(()=>{});function i(r){Object.assign(n,r),delete n.resolve,delete n.reject}return n.resolve=r=>{i({status:"fulfilled",value:r}),e(r)},n.reject=r=>{i({status:"rejected",reason:r}),t(r)},n}var Bj=Nj;function Zj(){let e=[],t=0,n=s=>{s()},i=s=>{s()},r=Bj;const o=s=>{t?e.push(s):r(()=>{n(s)})},a=()=>{const s=e;e=[],s.length&&r(()=>{i(()=>{s.forEach(u=>{n(u)})})})};return{batch:s=>{let u;t++;try{u=s()}finally{t--,t||a()}return u},batchCalls:s=>(...u)=>{o(()=>{s(...u)})},schedule:o,setNotifyFunction:s=>{n=s},setBatchNotifyFunction:s=>{i=s},setScheduler:s=>{r=s}}}var nt=Zj(),qj=class extends fa{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(!Pr&&window.addEventListener){const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(n=>{n(e)}))}isOnline(){return this.#e}},Ns=new qj;function Vj(e){return Math.min(1e3*2**e,3e4)}function Ok(e){return(e??"online")==="online"?Ns.isOnline():!0}var Kc=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Nk(e){let t=!1,n=0,i;const r=Gc(),o=()=>r.status!=="pending",a=m=>{if(!o()){const y=new Kc(m);f(y),e.onCancel?.(y)}},s=()=>{t=!0},u=()=>{t=!1},l=()=>Of.isFocused()&&(e.networkMode==="always"||Ns.isOnline())&&e.canRun(),c=()=>Ok(e.networkMode)&&e.canRun(),d=m=>{o()||(i?.(),r.resolve(m))},f=m=>{o()||(i?.(),r.reject(m))},p=()=>new Promise(m=>{i=y=>{(o()||l())&&m(y)},e.onPause?.()}).then(()=>{i=void 0,o()||e.onContinue?.()}),g=()=>{if(o())return;let m;const y=n===0?e.initialPromise:void 0;try{m=y??e.fn()}catch(v){m=Promise.reject(v)}Promise.resolve(m).then(d).catch(v=>{if(o())return;const _=e.retry??(Pr?0:3),x=e.retryDelay??Vj,b=typeof x=="function"?x(n,v):x,C=_===!0||typeof _=="number"&&n<_||typeof _=="function"&&_(n,v);if(t||!C){f(v);return}n++,e.onFail?.(n,v),Dj(b).then(()=>l()?void 0:p()).then(()=>{t?f(v):g()})})};return{promise:r,status:()=>r.status,cancel:a,continue:()=>(i?.(),r),cancelRetry:s,continueRetry:u,canStart:c,start:()=>(c()?g():p().then(g),r)}}var jk=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),qc(this.gcTime)&&(this.#e=Sr.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Pr?1/0:300*1e3))}clearGcTimeout(){this.#e&&(Sr.clearTimeout(this.#e),this.#e=void 0)}},Hj=class extends jk{#e;#t;#n;#i;#r;#s;#a;constructor(e){super(),this.#a=!1,this.#s=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#i=e.client,this.#n=this.#i.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#e=Jm(this.options),this.state=e.state??this.#e,this.scheduleGc()}get meta(){return this.options.meta}get promise(){return this.#r?.promise}setOptions(e){if(this.options={...this.#s,...e},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const t=Jm(this.options);t.data!==void 0&&(this.setState(Hm(t.data,t.dataUpdatedAt)),this.#e=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#n.remove(this)}setData(e,t){const n=Wc(this.state.data,e,this.options);return this.#o({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e,t){this.#o({type:"setState",state:e,setStateOptions:t})}cancel(e){const t=this.#r?.promise;return this.#r?.cancel(e),t?t.then(yt).catch(yt):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#e)}isActive(){return this.observers.some(e=>Zt(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Os||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>rr(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!Pk(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#r?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#r?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#r&&(this.#a?this.#r.cancel({revert:!0}):this.#r.cancelRetry()),this.scheduleGc()),this.#n.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#o({type:"invalidate"})}async fetch(e,t){if(this.state.fetchStatus!=="idle"&&this.#r?.status()!=="rejected"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#r)return this.#r.continueRetry(),this.#r.promise}if(e&&this.setOptions(e),!this.options.queryFn){const s=this.observers.find(u=>u.options.queryFn);s&&this.setOptions(s.options)}process.env.NODE_ENV!=="production"&&(Array.isArray(this.options.queryKey)||console.error("As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']"));const n=new AbortController,i=s=>{Object.defineProperty(s,"signal",{enumerable:!0,get:()=>(this.#a=!0,n.signal)})},r=()=>{const s=Rk(this.options,t),l=(()=>{const c={client:this.#i,queryKey:this.queryKey,meta:this.meta};return i(c),c})();return this.#a=!1,this.options.persister?this.options.persister(s,l,this):s(l)},a=(()=>{const s={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:r};return i(s),s})();this.options.behavior?.onFetch(a,this),this.#t=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#o({type:"fetch",meta:a.fetchOptions?.meta}),this.#r=Nk({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:s=>{s instanceof Kc&&s.revert&&this.setState({...this.#t,fetchStatus:"idle"}),n.abort()},onFail:(s,u)=>{this.#o({type:"failed",failureCount:s,error:u})},onPause:()=>{this.#o({type:"pause"})},onContinue:()=>{this.#o({type:"continue"})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0});try{const s=await this.#r.start();if(s===void 0)throw process.env.NODE_ENV!=="production"&&console.error(`Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`),new Error(`${this.queryHash} data is undefined`);return this.setData(s),this.#n.config.onSuccess?.(s,this),this.#n.config.onSettled?.(s,this.state.error,this),s}catch(s){if(s instanceof Kc){if(s.silent)return this.#r.promise;if(s.revert){if(this.state.data===void 0)throw s;return this.state.data}}throw this.#o({type:"error",error:s}),this.#n.config.onError?.(s,this),this.#n.config.onSettled?.(this.state.data,s,this),s}finally{this.scheduleGc()}}#o(e){const t=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...Mk(n.data,this.options),fetchMeta:e.meta??null};case"success":const i={...n,...Hm(e.data,e.dataUpdatedAt),dataUpdateCount:n.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#t=e.manual?i:void 0,i;case"error":const r=e.error;return{...n,error:r,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:"idle",status:"error"};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),nt.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#n.notify({query:this,type:"updated",action:e})})}};function Mk(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Ok(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Hm(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Jm(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,i=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?i??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var Jj=class extends fa{constructor(e,t){super(),this.options=t,this.#e=e,this.#o=null,this.#a=Gc(),this.bindMethods(),this.setOptions(t)}#e;#t=void 0;#n=void 0;#i=void 0;#r;#s;#a;#o;#m;#p;#f;#u;#c;#l;#h=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),Wm(this.#t,this.options)?this.#d():this.updateResult(),this.#b())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Yc(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Yc(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#_(),this.#w(),this.#t.removeObserver(this)}setOptions(e){const t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Zt(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#x(),this.#t.setOptions(this.options),t._defaulted&&!Hc(this.options,t)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const i=this.hasListeners();i&&Gm(this.#t,n,this.options,t)&&this.#d(),this.updateResult(),i&&(this.#t!==n||Zt(this.options.enabled,this.#t)!==Zt(t.enabled,this.#t)||rr(this.options.staleTime,this.#t)!==rr(t.staleTime,this.#t))&&this.#g();const r=this.#v();i&&(this.#t!==n||Zt(this.options.enabled,this.#t)!==Zt(t.enabled,this.#t)||r!==this.#l)&&this.#y(r)}getOptimisticResult(e){const t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return Gj(this,n)&&(this.#i=n,this.#s=this.options,this.#r=this.#t.state),n}getCurrentResult(){return this.#i}trackResult(e,t){return new Proxy(e,{get:(n,i)=>(this.trackProp(i),t?.(i),i==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#a.status==="pending"&&this.#a.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(n,i))})}trackProp(e){this.#h.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#d({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#i))}#d(e){this.#x();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(yt)),t}#g(){this.#_();const e=rr(this.options.staleTime,this.#t);if(Pr||this.#i.isStale||!qc(e))return;const n=Pk(this.#i.dataUpdatedAt,e)+1;this.#u=Sr.setTimeout(()=>{this.#i.isStale||this.updateResult()},n)}#v(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#y(e){this.#w(),this.#l=e,!(Pr||Zt(this.options.enabled,this.#t)===!1||!qc(this.#l)||this.#l===0)&&(this.#c=Sr.setInterval(()=>{(this.options.refetchIntervalInBackground||Of.isFocused())&&this.#d()},this.#l))}#b(){this.#g(),this.#y(this.#v())}#_(){this.#u&&(Sr.clearTimeout(this.#u),this.#u=void 0)}#w(){this.#c&&(Sr.clearInterval(this.#c),this.#c=void 0)}createResult(e,t){const n=this.#t,i=this.options,r=this.#i,o=this.#r,a=this.#s,u=e!==n?e.state:this.#n,{state:l}=e;let c={...l},d=!1,f;if(t._optimisticResults){const A=this.hasListeners(),j=!A&&Wm(e,t),F=A&&Gm(e,n,t,i);(j||F)&&(c={...c,...Mk(l.data,e.options)}),t._optimisticResults==="isRestoring"&&(c.fetchStatus="idle")}let{error:p,errorUpdatedAt:g,status:m}=c;f=c.data;let y=!1;if(t.placeholderData!==void 0&&f===void 0&&m==="pending"){let A;r?.isPlaceholderData&&t.placeholderData===a?.placeholderData?(A=r.data,y=!0):A=typeof t.placeholderData=="function"?t.placeholderData(this.#f?.state.data,this.#f):t.placeholderData,A!==void 0&&(m="success",f=Wc(r?.data,A,t),d=!0)}if(t.select&&f!==void 0&&!y)if(r&&f===o?.data&&t.select===this.#m)f=this.#p;else try{this.#m=t.select,f=t.select(f),f=Wc(r?.data,f,t),this.#p=f,this.#o=null}catch(A){this.#o=A}this.#o&&(p=this.#o,f=this.#p,g=Date.now(),m="error");const v=c.fetchStatus==="fetching",_=m==="pending",x=m==="error",b=_&&v,C=f!==void 0,$={status:m,fetchStatus:c.fetchStatus,isPending:_,isSuccess:m==="success",isError:x,isInitialLoading:b,isLoading:b,data:f,dataUpdatedAt:c.dataUpdatedAt,error:p,errorUpdatedAt:g,failureCount:c.fetchFailureCount,failureReason:c.fetchFailureReason,errorUpdateCount:c.errorUpdateCount,isFetched:c.dataUpdateCount>0||c.errorUpdateCount>0,isFetchedAfterMount:c.dataUpdateCount>u.dataUpdateCount||c.errorUpdateCount>u.errorUpdateCount,isFetching:v,isRefetching:v&&!_,isLoadingError:x&&!C,isPaused:c.fetchStatus==="paused",isPlaceholderData:d,isRefetchError:x&&C,isStale:Nf(e,t),refetch:this.refetch,promise:this.#a,isEnabled:Zt(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const A=z=>{$.status==="error"?z.reject($.error):$.data!==void 0&&z.resolve($.data)},j=()=>{const z=this.#a=$.promise=Gc();A(z)},F=this.#a;switch(F.status){case"pending":e.queryHash===n.queryHash&&A(F);break;case"fulfilled":($.status==="error"||$.data!==F.value)&&j();break;case"rejected":($.status!=="error"||$.error!==F.reason)&&j();break}}return $}updateResult(){const e=this.#i,t=this.createResult(this.#t,this.options);if(this.#r=this.#t.state,this.#s=this.options,this.#r.data!==void 0&&(this.#f=this.#t),Hc(t,e))return;this.#i=t;const n=()=>{if(!e)return!0;const{notifyOnChangeProps:i}=this.options,r=typeof i=="function"?i():i;if(r==="all"||!r&&!this.#h.size)return!0;const o=new Set(r??this.#h);return this.options.throwOnError&&o.add("error"),Object.keys(this.#i).some(a=>{const s=a;return this.#i[s]!==e[s]&&o.has(s)})};this.#S({listeners:n()})}#x(){const e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;const t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#b()}#S(e){nt.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#i)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function Wj(e,t){return Zt(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function Wm(e,t){return Wj(e,t)||e.state.data!==void 0&&Yc(e,t,t.refetchOnMount)}function Yc(e,t,n){if(Zt(t.enabled,e)!==!1&&rr(t.staleTime,e)!=="static"){const i=typeof n=="function"?n(e):n;return i==="always"||i!==!1&&Nf(e,t)}return!1}function Gm(e,t,n,i){return(e!==t||Zt(i.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Nf(e,n)}function Nf(e,t){return Zt(t.enabled,e)!==!1&&e.isStaleByTime(rr(t.staleTime,e))}function Gj(e,t){return!Hc(e.getCurrentResult(),t)}function Km(e){return{onFetch:(t,n)=>{const i=t.options,r=t.fetchOptions?.meta?.fetchMore?.direction,o=t.state.data?.pages||[],a=t.state.data?.pageParams||[];let s={pages:[],pageParams:[]},u=0;const l=async()=>{let c=!1;const d=g=>{Object.defineProperty(g,"signal",{enumerable:!0,get:()=>(t.signal.aborted?c=!0:t.signal.addEventListener("abort",()=>{c=!0}),t.signal)})},f=Rk(t.options,t.fetchOptions),p=async(g,m,y)=>{if(c)return Promise.reject();if(m==null&&g.pages.length)return Promise.resolve(g);const _=(()=>{const E={client:t.client,queryKey:t.queryKey,pageParam:m,direction:y?"backward":"forward",meta:t.options.meta};return d(E),E})(),x=await f(_),{maxPages:b}=t.options,C=y?Uj:zj;return{pages:C(g.pages,x,b),pageParams:C(g.pageParams,m,b)}};if(r&&o.length){const g=r==="backward",m=g?Kj:Ym,y={pages:o,pageParams:a},v=m(i,y);s=await p(y,v,g)}else{const g=e??o.length;do{const m=u===0?a[0]??i.initialPageParam:Ym(i,s);if(u>0&&m==null)break;s=await p(s,m),u++}while(u<g)}return s};t.options.persister?t.fetchFn=()=>t.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=l}}}function Ym(e,{pages:t,pageParams:n}){const i=t.length-1;return t.length>0?e.getNextPageParam(t[i],t,n[i],n):void 0}function Kj(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var Yj=class extends jk{#e;#t;#n;#i;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||Xj(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#n.remove(this))}continue(){return this.#i?.continue()??this.execute(this.state.variables)}async execute(e){const t=()=>{this.#r({type:"continue"})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#i=Nk({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(new Error("No mutationFn found")),onFail:(o,a)=>{this.#r({type:"failed",failureCount:o,error:a})},onPause:()=>{this.#r({type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)});const i=this.state.status==="pending",r=!this.#i.canStart();try{if(i)t();else{this.#r({type:"pending",variables:e,isPaused:r}),await this.#n.config.onMutate?.(e,this,n);const a=await this.options.onMutate?.(e,n);a!==this.state.context&&this.#r({type:"pending",context:a,variables:e,isPaused:r})}const o=await this.#i.start();return await this.#n.config.onSuccess?.(o,e,this.state.context,this,n),await this.options.onSuccess?.(o,e,this.state.context,n),await this.#n.config.onSettled?.(o,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(o,null,e,this.state.context,n),this.#r({type:"success",data:o}),o}catch(o){try{throw await this.#n.config.onError?.(o,e,this.state.context,this,n),await this.options.onError?.(o,e,this.state.context,n),await this.#n.config.onSettled?.(void 0,o,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(void 0,o,e,this.state.context,n),o}finally{this.#r({type:"error",error:o})}}finally{this.#n.runNext(this)}}#r(e){const t=n=>{switch(e.type){case"failed":return{...n,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...n,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:e.error,failureCount:n.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),nt.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:"updated",action:e})})}};function Xj(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Qj=class extends fa{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}#e;#t;#n;build(e,t,n){const i=new Yj({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(i),i}add(e){this.#e.add(e);const t=za(e);if(typeof t=="string"){const n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#e.delete(e)){const t=za(e);if(typeof t=="string"){const n=this.#t.get(t);if(n)if(n.length>1){const i=n.indexOf(e);i!==-1&&n.splice(i,1)}else n[0]===e&&this.#t.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=za(e);if(typeof t=="string"){const i=this.#t.get(t)?.find(r=>r.state.status==="pending");return!i||i===e}else return!0}runNext(e){const t=za(e);return typeof t=="string"?this.#t.get(t)?.find(i=>i!==e&&i.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){nt.batch(()=>{this.#e.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){const t={exact:!0,...e};return this.getAll().find(n=>Zm(t,n))}findAll(e={}){return this.getAll().filter(t=>Zm(e,t))}notify(e){nt.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return nt.batch(()=>Promise.all(e.map(t=>t.continue().catch(yt))))}};function za(e){return e.options.scope?.id}var eM=class extends fa{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,n){const i=t.queryKey,r=t.queryHash??Rf(i,t);let o=this.get(r);return o||(o=new Hj({client:e,queryKey:i,queryHash:r,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(i)}),this.add(o)),o}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){nt.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(n=>Bm(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>Bm(e,n)):t}notify(e){nt.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){nt.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){nt.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},tM=class{#e;#t;#n;#i;#r;#s;#a;#o;constructor(e={}){this.#e=e.queryCache||new eM,this.#t=e.mutationCache||new Qj,this.#n=e.defaultOptions||{},this.#i=new Map,this.#r=new Map,this.#s=0}mount(){this.#s++,this.#s===1&&(this.#a=Of.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#o=Ns.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#s--,this.#s===0&&(this.#a?.(),this.#a=void 0,this.#o?.(),this.#o=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#t.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#e.build(this,t),i=n.state.data;return i===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(rr(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(i))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:t,state:n})=>{const i=n.data;return[t,i]})}setQueryData(e,t,n){const i=this.defaultQueryOptions({queryKey:e}),o=this.#e.get(i.queryHash)?.state.data,a=jj(t,o);if(a!==void 0)return this.#e.build(this,i).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return nt.batch(()=>this.#e.findAll(e).map(({queryKey:i})=>[i,this.setQueryData(i,t,n)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){const t=this.#e;nt.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#e;return nt.batch(()=>(n.findAll(e).forEach(i=>{i.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},i=nt.batch(()=>this.#e.findAll(e).map(r=>r.cancel(n)));return Promise.all(i).then(yt).catch(yt)}invalidateQueries(e,t={}){return nt.batch(()=>(this.#e.findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},i=nt.batch(()=>this.#e.findAll(e).filter(r=>!r.isDisabled()&&!r.isStatic()).map(r=>{let o=r.fetch(void 0,n);return n.throwOnError||(o=o.catch(yt)),r.state.fetchStatus==="paused"?Promise.resolve():o}));return Promise.all(i).then(yt)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#e.build(this,t);return n.isStaleByTime(rr(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(yt).catch(yt)}fetchInfiniteQuery(e){return e.behavior=Km(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(yt).catch(yt)}ensureInfiniteQueryData(e){return e.behavior=Km(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Ns.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#i.set(go(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#i.values()],n={};return t.forEach(i=>{vo(e,i.queryKey)&&Object.assign(n,i.defaultOptions)}),n}setMutationDefaults(e,t){this.#r.set(go(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#r.values()],n={};return t.forEach(i=>{vo(e,i.mutationKey)&&Object.assign(n,i.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Rf(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===Os&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},Dk=w.createContext(void 0),zk=e=>{const t=w.useContext(Dk);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},nM=({client:e,children:t})=>(w.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),h.jsx(Dk.Provider,{value:e,children:t})),Uk=w.createContext(!1),rM=()=>w.useContext(Uk);Uk.Provider;function iM(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var oM=w.createContext(iM()),aM=()=>w.useContext(oM),sM=(e,t)=>{(e.suspense||e.throwOnError||e.experimental_prefetchInRender)&&(t.isReset()||(e.retryOnMount=!1))},lM=e=>{w.useEffect(()=>{e.clearReset()},[e])},uM=({result:e,errorResetBoundary:t,throwOnError:n,query:i,suspense:r})=>e.isError&&!t.isReset()&&!e.isFetching&&i&&(r&&e.data===void 0||Lj(n,[e.error,i])),cM=e=>{if(e.suspense){const n=r=>r==="static"?r:Math.max(r??1e3,1e3),i=e.staleTime;e.staleTime=typeof i=="function"?(...r)=>n(i(...r)):n(i),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},dM=(e,t)=>e.isLoading&&e.isFetching&&!t,pM=(e,t)=>e?.suspense&&t.isPending,Xm=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function fM(e,t,n){if(process.env.NODE_ENV!=="production"&&(typeof e!="object"||Array.isArray(e)))throw new Error('Bad argument type. Starting with v5, only the "Object" form is allowed when calling query related functions. Please use the error stack to find the culprit call. More info here: https://tanstack.com/query/latest/docs/react/guides/migrating-to-v5#supports-a-single-signature-one-object');const i=rM(),r=aM(),o=zk(),a=o.defaultQueryOptions(e);o.getDefaultOptions().queries?._experimental_beforeQuery?.(a),process.env.NODE_ENV!=="production"&&(a.queryFn||console.error(`[${a.queryHash}]: No queryFn was passed as an option, and no default queryFn was found. The queryFn parameter is only optional when using a default queryFn. More info here: https://tanstack.com/query/latest/docs/framework/react/guides/default-query-function`)),a._optimisticResults=i?"isRestoring":"optimistic",cM(a),sM(a,r),lM(r);const s=!o.getQueryCache().get(a.queryHash),[u]=w.useState(()=>new t(o,a)),l=u.getOptimisticResult(a),c=!i&&e.subscribed!==!1;if(w.useSyncExternalStore(w.useCallback(d=>{const f=c?u.subscribe(nt.batchCalls(d)):yt;return u.updateResult(),f},[u,c]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),w.useEffect(()=>{u.setOptions(a)},[a,u]),pM(a,l))throw Xm(a,u,r);if(uM({result:l,errorResetBoundary:r,throwOnError:a.throwOnError,query:o.getQueryCache().get(a.queryHash),suspense:a.suspense}))throw l.error;return o.getDefaultOptions().queries?._experimental_afterQuery?.(a,l),a.experimental_prefetchInRender&&!Pr&&dM(l,i)&&(s?Xm(a,u,r):o.getQueryCache().get(a.queryHash)?.promise)?.catch(yt).finally(()=>{u.updateResult()}),a.notifyOnChangeProps?l:u.trackResult(l)}function Lk(e,t){return fM(e,Jj)}function hM({auth:e,mcp:t,environment:n}){const i=Object.entries(e.headers??{}).map((o,a)=>`${o}:${a}`);return Lk({queryKey:["mcpTools",t,...i],queryFn:async()=>(R.assert(!e.isLoading,"No auth found"),R.assert(t,"No MCP URL found"),await(await Aj({name:"gram-elements-mcp-client",transport:{type:"http",url:t,headers:{...mM(n??{}),...e.headers}}})).tools()),enabled:!e.isLoading&&!!t,staleTime:1/0,gcTime:1/0})}const Qm="MCP-";function mM(e){return typeof e!="object"||e===null?{}:Object.entries(e).reduce((t,[n,i])=>{const r=n.replace(/_/g,"-"),o=r.startsWith(Qm)?r:`${Qm}${r}`;return t[o]=i,t},{})}const Fk=()=>{const e=k.useContext(R.ToolApprovalContext);if(!e)throw new Error("useToolApproval must be used within a ToolApprovalProvider");return e};function gM(e){return(e.api?.url||""||"https://app.getgram.ai").replace(/\/+$/,"")}const jf=["anthropic/claude-sonnet-4.5","anthropic/claude-haiku-4.5","anthropic/claude-sonnet-4","anthropic/claude-opus-4.5","openai/gpt-4o","openai/gpt-4o-mini","openai/gpt-5.1-codex","openai/gpt-5","openai/gpt-5.1","openai/gpt-4.1","anthropic/claude-3.7-sonnet","anthropic/claude-opus-4","google/gemini-2.5-pro-preview","google/gemini-3-pro-preview","moonshotai/kimi-k2","mistralai/mistral-medium-3","mistralai/mistral-medium-3.1","mistralai/codestral-2501"],vM=e=>Array.from(e).map(n=>n.getModelContext()).sort((n,i)=>(i.priority??0)-(n.priority??0)).reduce((n,i)=>{if(i.system&&(n.system?n.system+=`
|
|
30
|
-
|
|
31
|
-
${i.system}`:n.system=i.system),i.tools)for(const[r,o]of Object.entries(i.tools)){const a=n.tools?.[r];if(a&&a!==o)throw new Error(`You tried to define a tool with the name ${r}, but it already exists.`);n.tools||(n.tools={}),n.tools[r]=o}return i.config&&(n.config={...n.config,...i.config}),i.callSettings&&(n.callSettings={...n.callSettings,...i.callSettings}),n},{});class Mf{_providers=new Set;getModelContext(){return vM(this._providers)}registerModelContextProvider(t){this._providers.add(t);const n=t.subscribe?.(()=>{this.notifySubscribers()});return this.notifySubscribers(),()=>{this._providers.delete(t),n?.(),this.notifySubscribers()}}_subscribers=new Set;notifySubscribers(){for(const t of this._subscribers)t()}subscribe(t){return this._subscribers.add(t),()=>this._subscribers.delete(t)}}class Df{_contextProvider=new Mf;registerModelContextProvider(t){return this._contextProvider.registerModelContextProvider(t)}getModelContextProvider(){return this._contextProvider}}class iu{_subscribers=new Set;subscribe(t){return this._subscribers.add(t),()=>this._subscribers.delete(t)}waitForUpdate(){return new Promise(t=>{const n=this.subscribe(()=>{n(),t()})})}_notifySubscribers(){const t=[];for(const n of this._subscribers)try{n()}catch(i){t.push(i)}if(t.length>0)throw t.length===1?t[0]:new AggregateError(t)}}const yM=e=>e.status.type==="complete";class Bk extends iu{isEditing=!0;get attachmentAccept(){return this.getAttachmentAdapter()?.accept??"*"}_attachments=[];get attachments(){return this._attachments}setAttachments(t){this._attachments=t,this._notifySubscribers()}get isEmpty(){return!this.text.trim()&&!this.attachments.length}_text="";get text(){return this._text}_role="user";get role(){return this._role}_runConfig={};get runConfig(){return this._runConfig}setText(t){this._text!==t&&(this._text=t,this._notifySubscribers())}setRole(t){this._role!==t&&(this._role=t,this._notifySubscribers())}setRunConfig(t){this._runConfig!==t&&(this._runConfig=t,this._notifySubscribers())}_emptyTextAndAttachments(){this._attachments=[],this._text="",this._notifySubscribers()}async _onClearAttachments(){const t=this.getAttachmentAdapter();t&&await Promise.all(this._attachments.map(n=>t.remove(n)))}async reset(){if(this._attachments.length===0&&this._text===""&&this._role==="user"&&Object.keys(this._runConfig).length===0)return;this._role="user",this._runConfig={};const t=this._onClearAttachments();this._emptyTextAndAttachments(),await t}async clearAttachments(){const t=this._onClearAttachments();this.setAttachments([]),await t}async send(){const t=this.getAttachmentAdapter(),n=t&&this.attachments.length>0?Promise.all(this.attachments.map(async o=>yM(o)?o:await t.send(o))):[],i=this.text;this._emptyTextAndAttachments();const r={createdAt:new Date,role:this.role,content:i?[{type:"text",text:i}]:[],attachments:await n,runConfig:this.runConfig,metadata:{custom:{}}};this.handleSend(r),this._notifyEventSubscribers("send")}cancel(){this.handleCancel()}async addAttachment(t){const n=this.getAttachmentAdapter();if(!n)throw new Error("Attachments are not supported");const i=o=>{const a=this._attachments.findIndex(s=>s.id===o.id);a!==-1?this._attachments=[...this._attachments.slice(0,a),o,...this._attachments.slice(a+1)]:this._attachments=[...this._attachments,o],this._notifySubscribers()},r=n.add({file:t});if(Symbol.asyncIterator in r)for await(const o of r)i(o);else i(await r);this._notifyEventSubscribers("attachment-add"),this._notifySubscribers()}async removeAttachment(t){const n=this.getAttachmentAdapter();if(!n)throw new Error("Attachments are not supported");const i=this._attachments.findIndex(o=>o.id===t);if(i===-1)throw new Error("Attachment not found");const r=this._attachments[i];await n.remove(r),this._attachments=[...this._attachments.slice(0,i),...this._attachments.slice(i+1)],this._notifySubscribers()}_eventSubscribers=new Map;_notifyEventSubscribers(t){const n=this._eventSubscribers.get(t);if(n)for(const i of n)i()}unstable_on(t,n){const i=this._eventSubscribers.get(t);return i?i.add(n):this._eventSubscribers.set(t,new Set([n])),()=>{const r=this._eventSubscribers.get(t);r&&r.delete(n)}}}class Zk extends Bk{runtime;_canCancel=!1;get canCancel(){return this._canCancel}get attachments(){return super.attachments}getAttachmentAdapter(){return this.runtime.adapters?.attachments}constructor(t){super(),this.runtime=t,this.connect()}connect(){return this.runtime.subscribe(()=>{this.canCancel!==this.runtime.capabilities.cancel&&(this._canCancel=this.runtime.capabilities.cancel,this._notifySubscribers())})}async handleSend(t){this.runtime.append({...t,parentId:this.runtime.messages.at(-1)?.id??null,sourceId:null})}async handleCancel(){this.runtime.cancelRun()}}let qk=(e,t=21)=>(n=t)=>{let i="",r=n|0;for(;r--;)i+=e[Math.random()*e.length|0];return i};const ha=qk("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7),bM="__optimistic__",_M=()=>`${bM}${ha()}`,Ai=Symbol("autoStatus"),wM=Object.freeze(Object.assign({type:"running"},{[Ai]:!0})),xM=Object.freeze(Object.assign({type:"complete",reason:"unknown"},{[Ai]:!0})),SM=Object.freeze(Object.assign({type:"requires-action",reason:"tool-calls"},{[Ai]:!0})),IM=Object.freeze(Object.assign({type:"requires-action",reason:"interrupt"},{[Ai]:!0})),Vk=e=>e[Ai]===!0,ma=(e,t,n,i,r)=>e&&r?Object.assign({type:"incomplete",reason:"error",error:r},{[Ai]:!0}):e&&t?wM:n?IM:i?SM:xM;function ga(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var yr={exports:{}},eg;function kM(){if(eg)return yr.exports;eg=1;const e=typeof Buffer<"u",t=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,n=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function i(s,u,l){l==null&&u!==null&&typeof u=="object"&&(l=u,u=void 0),e&&Buffer.isBuffer(s)&&(s=s.toString()),s&&s.charCodeAt(0)===65279&&(s=s.slice(1));const c=JSON.parse(s,u);if(c===null||typeof c!="object")return c;const d=l&&l.protoAction||"error",f=l&&l.constructorAction||"error";if(d==="ignore"&&f==="ignore")return c;if(d!=="ignore"&&f!=="ignore"){if(t.test(s)===!1&&n.test(s)===!1)return c}else if(d!=="ignore"&&f==="ignore"){if(t.test(s)===!1)return c}else if(n.test(s)===!1)return c;return r(c,{protoAction:d,constructorAction:f,safe:l&&l.safe})}function r(s,{protoAction:u="error",constructorAction:l="error",safe:c}={}){let d=[s];for(;d.length;){const f=d;d=[];for(const p of f){if(u!=="ignore"&&Object.prototype.hasOwnProperty.call(p,"__proto__")){if(c===!0)return null;if(u==="error")throw new SyntaxError("Object contains forbidden prototype property");delete p.__proto__}if(l!=="ignore"&&Object.prototype.hasOwnProperty.call(p,"constructor")&&p.constructor!==null&&typeof p.constructor=="object"&&Object.prototype.hasOwnProperty.call(p.constructor,"prototype")){if(c===!0)return null;if(l==="error")throw new SyntaxError("Object contains forbidden prototype property");delete p.constructor}for(const g in p){const m=p[g];m&&typeof m=="object"&&d.push(m)}}}return s}function o(s,u,l){const{stackTraceLimit:c}=Error;Error.stackTraceLimit=0;try{return i(s,u,l)}finally{Error.stackTraceLimit=c}}function a(s,u){const{stackTraceLimit:l}=Error;Error.stackTraceLimit=0;try{return i(s,u,{safe:!0})}catch{return}finally{Error.stackTraceLimit=l}}return yr.exports=o,yr.exports.default=o,yr.exports.parse=o,yr.exports.safeParse=a,yr.exports.scan=r,yr.exports}var EM=kM();const Xc=ga(EM);function TM(e){const t=["ROOT"];let n=-1,i=null;const r=[];let o;function a(){o!==void 0&&(r.push(JSON.parse(`"${o}"`)),o=void 0)}function s(d,f,p){switch(d){case'"':{n=f,t.pop(),t.push(p),t.push("INSIDE_STRING"),a();break}case"f":case"t":case"n":{n=f,i=f,t.pop(),t.push(p),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(p),t.push("INSIDE_NUMBER"),a();break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=f,t.pop(),t.push(p),t.push("INSIDE_NUMBER"),a();break}case"{":{n=f,t.pop(),t.push(p),t.push("INSIDE_OBJECT_START"),a();break}case"[":{n=f,t.pop(),t.push(p),t.push("INSIDE_ARRAY_START"),a();break}}}function u(d,f){switch(d){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=f,t.pop(),o=r.pop();break}}}function l(d,f){switch(d){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA"),o=(Number(o)+1).toString();break}case"]":{n=f,t.pop(),o=r.pop();break}}}for(let d=0;d<e.length;d++){const f=e[d];switch(t[t.length-1]){case"ROOT":s(f,d,"FINISH");break;case"INSIDE_OBJECT_START":{switch(f){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY"),o="";break}case"}":{n=d,t.pop(),o=r.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(f){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY"),o="";break}}break}case"INSIDE_OBJECT_KEY":{switch(f){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}case"\\":{t.push("INSIDE_STRING_ESCAPE"),o+=f;break}default:{o+=f;break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(f){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{s(f,d,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{u(f,d);break}case"INSIDE_STRING":{switch(f){case'"':{t.pop(),n=d,o=r.pop();break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=d}break}case"INSIDE_ARRAY_START":{switch(f){case"]":{n=d,t.pop(),o=r.pop();break}default:{n=d,o="0",s(f,d,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(f){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA"),o=(Number(o)+1).toString();break}case"]":{n=d,t.pop(),o=r.pop();break}default:{n=d;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{s(f,d,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),t[t.length-1]==="INSIDE_STRING"?n=d:t[t.length-1]==="INSIDE_OBJECT_KEY"&&(o+=f);break}case"INSIDE_NUMBER":{switch(f){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=d;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),o=r.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&l(f,d),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&u(f,d);break}case"}":{t.pop(),o=r.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&u(f,d);break}case"]":{t.pop(),o=r.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&l(f,d);break}default:{t.pop(),o=r.pop();break}}break}case"INSIDE_LITERAL":{const g=e.substring(i,d+1);!"false".startsWith(g)&&!"true".startsWith(g)&&!"null".startsWith(g)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?u(f,d):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&l(f,d)):n=d;break}}}let c=e.slice(0,n+1);for(let d=t.length-1;d>=0;d--)switch(t[d]){case"INSIDE_STRING":{c+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{c+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{c+="]";break}case"INSIDE_LITERAL":{const p=e.substring(i,e.length);"true".startsWith(p)?c+="true".slice(p.length):"false".startsWith(p)?c+="false".slice(p.length):"null".startsWith(p)&&(c+="null".slice(p.length))}}return[c,r]}const os=Symbol("aui.parse-partial-json-object.meta"),$M=e=>e?.[os],js=e=>{if(e.length===0)return{[os]:{state:"partial",partialPath:[]}};try{const t=Xc.parse(e);if(typeof t!="object"||t===null)throw new Error("argsText is expected to be an object");return t[os]={state:"complete",partialPath:[]},t}catch{try{const[t,n]=TM(e),i=Xc.parse(t);if(typeof i!="object"||i===null)throw new Error("argsText is expected to be an object");return i[os]={state:"partial",partialPath:n},i}catch{return}}},Hk=(e,t,n)=>{if(typeof e!="object"||e===null)return t.state;if(t.state==="complete")return"complete";if(n.length===0)return t.state;const[i,...r]=n;if(!Object.prototype.hasOwnProperty.call(e,i))return"partial";const[o,...a]=t.partialPath;if(i!==o)return"complete";const s=e[i];return Hk(s,{state:"partial",partialPath:a},r)},xi=(e,t)=>{const n=$M(e);if(!n)throw new Error("unable to determine object state");return Hk(e,n,t.map(String))};async function*CM(){const e=this.getReader();try{for(;;){const{done:t,value:n}=await e.read();if(t)break;yield n}}finally{e.releaseLock()}}function Uu(e){return e[Symbol.asyncIterator]??=CM,e}const Qc={toResponse(e,t){return new Response(Qc.toByteStream(e,t),{headers:t.headers??{}})},fromResponse(e,t){return Qc.fromByteStream(e.body,t)},toByteStream(e,t){return e.pipeThrough(t)},fromByteStream(e,t){return e.pipeThrough(t)}},zf=function(){let e,t;const n=new Promise((i,r)=>{e=i,t=r});if(!e||!t)throw new Error("Failed to create promise");return{promise:n,resolve:e,reject:t}},AM=()=>{const e=[];let t=!1,n,i;const r=a=>{a.promise||(a.promise=a.reader.read().then(({done:s,value:u})=>{a.promise=void 0,s?(e.splice(e.indexOf(a),1),t&&e.length===0&&n.close()):n.enqueue(u),i?.resolve(),i=void 0}).catch(s=>{console.error(s),e.forEach(u=>{u.reader.cancel()}),e.length=0,n.error(s),i?.reject(s),i=void 0}))};return{readable:new ReadableStream({start(a){n=a},pull(){return i=zf(),e.forEach(a=>{r(a)}),i.promise},cancel(){e.forEach(a=>{a.reader.cancel()}),e.length=0}}),isSealed(){return t},seal(){t=!0,e.length===0&&n.close()},addStream(a){if(t)throw new Error("Cannot add streams after the run callback has settled.");const s={reader:a.getReader()};e.push(s),r(s)},enqueue(a){this.addStream(new ReadableStream({start(s){s.enqueue(a),s.close()}}))}}};class tg{_controller;_isClosed=!1;constructor(t){this._controller=t}append(t){return this._controller.enqueue({type:"text-delta",path:[],textDelta:t}),this}close(){this._isClosed||(this._isClosed=!0,this._controller.enqueue({type:"part-finish",path:[]}),this._controller.close())}}const Jk=e=>new ReadableStream({start(t){return e.start?.(new tg(t))},pull(t){return e.pull?.(new tg(t))},cancel(t){return e.cancel?.(t)}}),ng=()=>{let e;return[Jk({start(n){e=n}}),e]};class rg{_controller;_isClosed=!1;_mergeTask;constructor(t){this._controller=t;const n=Jk({start:r=>{this._argsTextController=r}});let i=!1;this._mergeTask=n.pipeTo(new WritableStream({write:r=>{switch(r.type){case"text-delta":i=!0,this._controller.enqueue(r);break;case"part-finish":i||this._controller.enqueue({type:"text-delta",textDelta:"{}",path:[]}),this._controller.enqueue({type:"tool-call-args-text-finish",path:[]});break;default:throw new Error(`Unexpected chunk type: ${r.type}`)}}}))}get argsText(){return this._argsTextController}_argsTextController;async setResponse(t){this._argsTextController.close(),await Promise.resolve(),this._controller.enqueue({type:"result",path:[],...t.artifact!==void 0?{artifact:t.artifact}:{},result:t.result,isError:t.isError??!1})}async close(){this._isClosed||(this._isClosed=!0,this._argsTextController.close(),await this._mergeTask,this._controller.enqueue({type:"part-finish",path:[]}),this._controller.close())}}const PM=e=>new ReadableStream({start(t){return e.start?.(new rg(t))},pull(t){return e.pull?.(new rg(t))},cancel(t){return e.cancel?.(t)}}),RM=()=>{let e;return[PM({start(n){e=n}}),e]};class Wk{value=-1;up(){return++this.value}}class OM extends TransformStream{constructor(t){super({transform(n,i){i.enqueue({...n,path:[t,...n.path]})}})}}class fY extends TransformStream{constructor(t){super({transform(n,i){const{path:[r,...o]}=n;if(t!==r)throw new Error(`Path mismatch: expected ${t}, got ${r}`);i.enqueue({...n,path:o})}})}}class NM extends TransformStream{constructor(t){const n=new Wk,i=new Map;super({transform(r,o){r.type==="part-start"&&r.path.length===0&&i.set(n.up(),t.up());const[a,...s]=r.path;if(a===void 0){o.enqueue(r);return}const u=i.get(a);if(u===void 0)throw new Error("Path not found");o.enqueue({...r,path:[u,...s]})}})}}class Gk extends TransformStream{constructor(t){super();const n=t(super.readable);Object.defineProperty(this,"readable",{value:n,writable:!1})}}class Kk extends TransformStream{constructor(){const t=[];super({transform(n,i){if(n.type==="part-start"){if(n.path.length!==0){i.error(new Error("Nested parts are not supported"));return}t.push(n.part),i.enqueue(n);return}if(n.type==="text-delta"||n.type==="result"||n.type==="part-finish"||n.type==="tool-call-args-text-finish"){if(n.path.length!==1){i.error(new Error(`${n.type} chunks must have a path of length 1`));return}const r=n.path[0];if(r<0||r>=t.length){i.error(new Error(`Invalid path index: ${r}`));return}const o=t[r];i.enqueue({...n,meta:o});return}i.enqueue(n)}})}}const Yk=qk("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7);class Uf{_state;_parentId;constructor(t){this._state=t||{merger:AM(),contentCounter:new Wk}}get __internal_isClosed(){return this._state.merger.isSealed()}__internal_getReadable(){return this._state.merger.readable}__internal_subscribeToClose(t){this._state.closeSubscriber=t}_addPart(t,n){this._state.append&&(this._state.append.controller.close(),this._state.append=void 0),this.enqueue({type:"part-start",part:t,path:[]}),this._state.merger.addStream(n.pipeThrough(new OM(this._state.contentCounter.value)))}merge(t){this._state.merger.addStream(t.pipeThrough(new NM(this._state.contentCounter)))}appendText(t){this._state.append?.kind!=="text"&&(this._state.append={kind:"text",controller:this.addTextPart()}),this._state.append.controller.append(t)}appendReasoning(t){this._state.append?.kind!=="reasoning"&&(this._state.append={kind:"reasoning",controller:this.addReasoningPart()}),this._state.append.controller.append(t)}addTextPart(){const[t,n]=ng();return this._addPart({type:"text"},t),n}addReasoningPart(){const[t,n]=ng();return this._addPart({type:"reasoning"},t),n}addToolCallPart(t){const n=typeof t=="string"?{toolName:t}:t,i=n.toolName,r=n.toolCallId??Yk(),[o,a]=RM();return this._addPart({type:"tool-call",toolName:i,toolCallId:r,...this._parentId&&{parentId:this._parentId}},o),n.argsText!==void 0&&(a.argsText.append(n.argsText),a.argsText.close()),n.args!==void 0&&(a.argsText.append(JSON.stringify(n.args)),a.argsText.close()),n.response!==void 0&&a.setResponse(n.response),a}appendSource(t){this._addPart({...t,...this._parentId&&{parentId:this._parentId}},new ReadableStream({start(n){n.enqueue({type:"part-finish",path:[]}),n.close()}}))}appendFile(t){this._addPart(t,new ReadableStream({start(n){n.enqueue({type:"part-finish",path:[]}),n.close()}}))}enqueue(t){this._state.merger.enqueue(t),t.type==="part-start"&&t.path.length===0&&this._state.contentCounter.up()}withParentId(t){const n=new Uf(this._state);return n._parentId=t,n}close(){this._state.append?.controller?.close(),this._state.merger.seal(),this._state.closeSubscriber?.()}}function jM(e){const t=new Uf;return(async()=>{try{await e(t)}catch(i){throw t.__internal_isClosed||t.enqueue({type:"error",path:[],error:String(i)}),i}finally{t.__internal_isClosed||t.close()}})(),t.__internal_getReadable()}function Xk(){const{resolve:e,promise:t}=zf();let n;return[jM(r=>(n=r,n.__internal_subscribeToClose(e),t)),n]}class MM extends TransformStream{constructor(t,n,i){const[r,o]=Xk();let a;super({start(s){return a=r.pipeTo(new WritableStream({write(u){s.enqueue(u)},abort(u){s.error(u)},close(){s.terminate()}})).catch(u=>{s.error(u)}),t.start?.(o)},transform(s){return t.transform?.(s,o)},async flush(){await t.flush?.(o),o.close(),await a}},n,i)}}const Ur=(e,t,n)=>{const{role:i,id:r,createdAt:o,attachments:a,status:s,metadata:u}=e,l={id:r??t,createdAt:o??new Date},c=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content,d=({image:f,...p})=>f.match(/^data:image\/(png|jpeg|jpg|gif|webp);base64,(.*)$/)?{...p,image:f}:(console.warn("Invalid image data format detected"),null);if(i!=="user"&&a?.length)throw new Error("attachments are only supported for user messages");if(i!=="assistant"&&s)throw new Error("status is only supported for assistant messages");if(i!=="assistant"&&u?.steps)throw new Error("metadata.steps is only supported for assistant messages");switch(i){case"assistant":return{...l,role:i,content:c.map(f=>{const p=f.type;switch(p){case"text":case"reasoning":return f.text.trim().length===0?null:f;case"file":case"source":return f;case"image":return d(f);case"data":return f;case"tool-call":{const{parentId:g,messages:m,...y}=f,v={...y,toolCallId:f.toolCallId??`tool-${ha()}`,...g!==void 0&&{parentId:g},...m!==void 0&&{messages:m}};return f.args?{...v,args:f.args,argsText:f.argsText??JSON.stringify(f.args)}:{...v,args:js(f.argsText??"")??{},argsText:f.argsText??""}}default:{const g=p;throw new Error(`Unsupported assistant message part type: ${g}`)}}}).filter(f=>!!f),status:s??n,metadata:{unstable_state:u?.unstable_state??null,unstable_annotations:u?.unstable_annotations??[],unstable_data:u?.unstable_data??[],custom:u?.custom??{},steps:u?.steps??[],...u?.submittedFeedback&&{submittedFeedback:u.submittedFeedback}}};case"user":return{...l,role:i,content:c.map(f=>{const p=f.type;switch(p){case"text":case"image":case"audio":case"file":return f;default:{const g=p;throw new Error(`Unsupported user message part type: ${g}`)}}}),attachments:a??[],metadata:{custom:u?.custom??{}}};case"system":if(c.length!==1||c[0].type!=="text")throw new Error("System messages must have exactly one text message part.");return{...l,role:i,content:c,metadata:{custom:u?.custom??{}}};default:{const f=i;throw new Error(`Unknown message role: ${f}`)}}},Lf={fromArray:e=>{const t=e.map(n=>Ur(n,ha(),ma(!1,!1,!1,!1,void 0)));return{messages:t.map((n,i)=>({parentId:i>0?t[i-1].id:null,message:n}))}}},as=e=>e.next?as(e.next):"current"in e?e:null;class DM{func;_value=null;constructor(t){this.func=t}get value(){return this._value===null&&(this._value=this.func()),this._value}dirty(){this._value=null}}let Ff=class{messages=new Map;head=null;root={children:[],next:null};updateLevels(t,n){t.level=n;for(const i of t.children){const r=this.messages.get(i);r&&this.updateLevels(r,n+1)}}performOp(t,n,i){const r=n.prev??this.root,o=t??this.root;if(!(i==="relink"&&r===o)){if(i!=="link"&&(r.children=r.children.filter(a=>a!==n.current.id),r.next===n)){const a=r.children.at(-1),s=a?this.messages.get(a):null;if(s===void 0)throw new Error("MessageRepository(performOp/cut): Fallback sibling message not found. This is likely an internal bug in assistant-ui.");r.next=s}if(i!=="cut"){for(let s=t;s;s=s.prev)if(s.current.id===n.current.id)throw new Error("MessageRepository(performOp/link): A message with the same id already exists in the parent tree. This error occurs if the same message id is found multiple times. This is likely an internal bug in assistant-ui.");o.children=[...o.children,n.current.id],(as(n)===this.head||o.next===null)&&(o.next=n),n.prev=t;const a=t?t.level+1:0;this.updateLevels(n,a)}}}_messages=new DM(()=>{const t=new Array((this.head?.level??-1)+1);for(let n=this.head;n;n=n.prev)t[n.level]=n.current;return t});get headId(){return this.head?.current.id??null}getMessages(t){if(t===void 0||t===this.head?.current.id)return this._messages.value;const n=this.messages.get(t);if(!n)throw new Error("MessageRepository(getMessages): Head message not found. This is likely an internal bug in assistant-ui.");const i=new Array(n.level+1);for(let r=n;r;r=r.prev)i[r.level]=r.current;return i}addOrUpdateMessage(t,n){const i=this.messages.get(n.id),r=t?this.messages.get(t):null;if(r===void 0)throw new Error("MessageRepository(addOrUpdateMessage): Parent message not found. This is likely an internal bug in assistant-ui.");if(i){i.current=n,this.performOp(r,i,"relink"),this._messages.dirty();return}const o={prev:r,current:n,next:null,children:[],level:r?r.level+1:0};this.messages.set(n.id,o),this.performOp(r,o,"link"),this.head===r&&(this.head=o),this._messages.dirty()}getMessage(t){const n=this.messages.get(t);if(!n)throw new Error("MessageRepository(updateMessage): Message not found. This is likely an internal bug in assistant-ui.");return{parentId:n.prev?.current.id??null,message:n.current,index:n.level}}appendOptimisticMessage(t,n){let i;do i=_M();while(this.messages.has(i));return this.addOrUpdateMessage(t,Ur(n,i,{type:"running"})),i}deleteMessage(t,n){const i=this.messages.get(t);if(!i)throw new Error("MessageRepository(deleteMessage): Message not found. This is likely an internal bug in assistant-ui.");const r=n===void 0?i.prev:n===null?null:this.messages.get(n);if(r===void 0)throw new Error("MessageRepository(deleteMessage): Replacement not found. This is likely an internal bug in assistant-ui.");for(const o of i.children){const a=this.messages.get(o);if(!a)throw new Error("MessageRepository(deleteMessage): Child message not found. This is likely an internal bug in assistant-ui.");this.performOp(r,a,"relink")}this.performOp(null,i,"cut"),this.messages.delete(t),this.head===i&&(this.head=as(r??this.root)),this._messages.dirty()}getBranches(t){const n=this.messages.get(t);if(!n)throw new Error("MessageRepository(getBranches): Message not found. This is likely an internal bug in assistant-ui.");const{children:i}=n.prev??this.root;return i}switchToBranch(t){const n=this.messages.get(t);if(!n)throw new Error("MessageRepository(switchToBranch): Branch not found. This is likely an internal bug in assistant-ui.");const i=n.prev??this.root;i.next=n,this.head=as(n),this._messages.dirty()}resetHead(t){if(t===null){this.clear();return}const n=this.messages.get(t);if(!n)throw new Error("MessageRepository(resetHead): Branch not found. This is likely an internal bug in assistant-ui.");if(n.children.length>0){const i=r=>{for(const o of r.children){const a=this.messages.get(o);a&&(i(a),this.messages.delete(o))}};i(n),n.children=[],n.next=null}this.head=n;for(let i=n;i;i=i.prev)i.prev&&(i.prev.next=i);this._messages.dirty()}clear(){this.messages.clear(),this.head=null,this.root={children:[],next:null},this._messages.dirty()}export(){const t=[];for(const[,n]of this.messages)t.push({message:n.current,parentId:n.prev?.current.id??null});return{headId:this.head?.current.id??null,messages:t}}import({headId:t,messages:n}){for(const{message:i,parentId:r}of n)this.addOrUpdateMessage(r,i);this.resetHead(t??n.at(-1)?.message.id??null)}};class ou{_subscriptions=new Set;_connection;get isConnected(){return!!this._connection}notifySubscribers(){for(const t of this._subscriptions)t()}_updateConnection(){if(this._subscriptions.size>0){if(this._connection)return;this._connection=this._connect()}else this._connection?.(),this._connection=void 0}subscribe(t){return this._subscriptions.add(t),this._updateConnection(),()=>{this._subscriptions.delete(t),this._updateConnection()}}}const un=Symbol("skip-update");class Bf extends ou{binding;get path(){return this.binding.path}constructor(t){super(),this.binding=t}_previousStateDirty=!0;_previousState;getState=()=>{if(!this.isConnected||this._previousStateDirty){const t=this.binding.getState();t!==un&&(this._previousState=t),this._previousStateDirty=!1}if(this._previousState===void 0)throw new Error("Entry not available in the store");return this._previousState};_connect(){const t=()=>{this._previousStateDirty=!0,this.notifySubscribers()};return this.binding.subscribe(t)}}class Ua{_core;_threadListBinding;get path(){return this._core.path}constructor(t,n){this._core=t,this._threadListBinding=n,this.__internal_bindMethods()}__internal_bindMethods(){this.switchTo=this.switchTo.bind(this),this.rename=this.rename.bind(this),this.archive=this.archive.bind(this),this.unarchive=this.unarchive.bind(this),this.delete=this.delete.bind(this),this.initialize=this.initialize.bind(this),this.generateTitle=this.generateTitle.bind(this),this.subscribe=this.subscribe.bind(this),this.unstable_on=this.unstable_on.bind(this),this.getState=this.getState.bind(this),this.detach=this.detach.bind(this)}getState(){return this._core.getState()}switchTo(){const t=this._core.getState();return this._threadListBinding.switchToThread(t.id)}rename(t){const n=this._core.getState();return this._threadListBinding.rename(n.id,t)}archive(){const t=this._core.getState();return this._threadListBinding.archive(t.id)}unarchive(){const t=this._core.getState();return this._threadListBinding.unarchive(t.id)}delete(){const t=this._core.getState();return this._threadListBinding.delete(t.id)}initialize(){const t=this._core.getState();return this._threadListBinding.initialize(t.id)}generateTitle(){const t=this._core.getState();return this._threadListBinding.generateTitle(t.id)}unstable_on(t,n){let i=this._core.getState().isMain,r=this._core.getState().id;return this.subscribe(()=>{const o=this._core.getState(),a=o.isMain,s=o.id;i===a&&r===s||(i=a,r=s,!(t==="switched-to"&&!a)&&(t==="switched-away"&&a||n()))})}subscribe(t){return this._core.subscribe(t)}detach(){const t=this._core.getState();this._threadListBinding.detach(t.id)}__internal_getRuntime(){return this}}function zM(e,t){if(e===void 0&&t===void 0)return!0;if(e===void 0||t===void 0)return!1;for(const n of Object.keys(e)){const i=e[n],r=t[n];if(!Object.is(i,r))return!1}return!0}class an extends ou{binding;get path(){return this.binding.path}constructor(t){super(),this.binding=t;const n=t.getState();if(n===un)throw new Error("Entry not available in the store");this._previousState=n}_previousState;getState=()=>(this.isConnected||this._syncState(),this._previousState);_syncState(){const t=this.binding.getState();return t===un||zM(t,this._previousState)?!1:(this._previousState=t,!0)}_connect(){const t=()=>{this._syncState()&&this.notifySubscribers()};return this.binding.subscribe(t)}}const Ct=Symbol("innerMessage"),Lu=Symbol("innerMessages"),UM=e=>e[Ct],LM=[],Tr=e=>{const t="messages"in e?e.messages:e,n=t[Lu]||t[Ct];return n?Array.isArray(n)?n:(t[Lu]=[n],t[Lu]):LM},yo=e=>e.content.filter(n=>n.type==="text").map(n=>n.text).join(`
|
|
32
|
-
|
|
33
|
-
`);class Qk{_core;get path(){return this._core.path}constructor(t){this._core=t,this.__internal_bindMethods()}__internal_bindMethods(){this.getState=this.getState.bind(this),this.remove=this.remove.bind(this),this.subscribe=this.subscribe.bind(this)}getState(){return this._core.getState()}subscribe(t){return this._core.subscribe(t)}}class eE extends Qk{_composerApi;constructor(t,n){super(t),this._composerApi=n}remove(){const t=this._composerApi.getState();if(!t)throw new Error("Composer is not available");return t.removeAttachment(this.getState().id)}}class FM extends eE{get source(){return"thread-composer"}}class BM extends eE{get source(){return"edit-composer"}}class ZM extends Qk{get source(){return"message"}constructor(t){super(t)}remove(){throw new Error("Message attachments cannot be removed")}}class tE extends ou{config;constructor(t){super(),this.config=t}getState(){return this.config.binding.getState()}outerSubscribe(t){return this.config.binding.subscribe(t)}_connect(){const t=()=>{this.notifySubscribers()};let n=this.config.binding.getState(),i=n?.unstable_on(this.config.event,t);const r=()=>{const a=this.config.binding.getState();a!==n&&(n=a,i?.(),i=this.config.binding.getState()?.unstable_on(this.config.event,t))},o=this.outerSubscribe(r);return()=>{o?.(),i?.()}}}const nE=Object.freeze([]),rE=Object.freeze({}),qM=e=>Object.freeze({type:"thread",isEditing:e?.isEditing??!1,canCancel:e?.canCancel??!1,isEmpty:e?.isEmpty??!0,attachments:e?.attachments??nE,text:e?.text??"",role:e?.role??"user",runConfig:e?.runConfig??rE,attachmentAccept:e?.attachmentAccept??"",value:e?.text??""}),VM=e=>Object.freeze({type:"edit",isEditing:e?.isEditing??!1,canCancel:e?.canCancel??!1,isEmpty:e?.isEmpty??!0,text:e?.text??"",role:e?.role??"user",attachments:e?.attachments??nE,runConfig:e?.runConfig??rE,attachmentAccept:e?.attachmentAccept??"",value:e?.text??""});class iE{_core;get path(){return this._core.path}constructor(t){this._core=t}__internal_bindMethods(){this.setText=this.setText.bind(this),this.setRunConfig=this.setRunConfig.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.addAttachment=this.addAttachment.bind(this),this.reset=this.reset.bind(this),this.clearAttachments=this.clearAttachments.bind(this),this.send=this.send.bind(this),this.cancel=this.cancel.bind(this),this.setRole=this.setRole.bind(this),this.getAttachmentByIndex=this.getAttachmentByIndex.bind(this),this.unstable_on=this.unstable_on.bind(this)}setText(t){const n=this._core.getState();if(!n)throw new Error("Composer is not available");n.setText(t)}setRunConfig(t){const n=this._core.getState();if(!n)throw new Error("Composer is not available");n.setRunConfig(t)}addAttachment(t){const n=this._core.getState();if(!n)throw new Error("Composer is not available");return n.addAttachment(t)}reset(){const t=this._core.getState();if(!t)throw new Error("Composer is not available");return t.reset()}clearAttachments(){const t=this._core.getState();if(!t)throw new Error("Composer is not available");return t.clearAttachments()}send(){const t=this._core.getState();if(!t)throw new Error("Composer is not available");t.send()}cancel(){const t=this._core.getState();if(!t)throw new Error("Composer is not available");t.cancel()}setRole(t){const n=this._core.getState();if(!n)throw new Error("Composer is not available");n.setRole(t)}subscribe(t){return this._core.subscribe(t)}_eventSubscriptionSubjects=new Map;unstable_on(t,n){let i=this._eventSubscriptionSubjects.get(t);return i||(i=new tE({event:t,binding:this._core}),this._eventSubscriptionSubjects.set(t,i)),i.subscribe(n)}}class HM extends iE{get path(){return this._core.path}get type(){return"thread"}_getState;constructor(t){const n=new Bf({path:t.path,getState:()=>qM(t.getState()),subscribe:i=>t.subscribe(i)});super({path:t.path,getState:()=>t.getState(),subscribe:i=>n.subscribe(i)}),this._getState=n.getState.bind(n),this.__internal_bindMethods()}getState(){return this._getState()}getAttachmentByIndex(t){return new FM(new an({path:{...this.path,attachmentSource:"thread-composer",attachmentSelector:{type:"index",index:t},ref:`${this.path.ref}${this.path.ref}.attachments[${t}]`},getState:()=>{const i=this.getState().attachments[t];return i?{...i,source:"thread-composer"}:un},subscribe:n=>this._core.subscribe(n)}),this._core)}}class JM extends iE{_beginEdit;get path(){return this._core.path}get type(){return"edit"}_getState;constructor(t,n){const i=new Bf({path:t.path,getState:()=>VM(t.getState()),subscribe:r=>t.subscribe(r)});super({path:t.path,getState:()=>t.getState(),subscribe:r=>i.subscribe(r)}),this._beginEdit=n,this._getState=i.getState.bind(i),this.__internal_bindMethods()}__internal_bindMethods(){super.__internal_bindMethods(),this.beginEdit=this.beginEdit.bind(this)}getState(){return this._getState()}beginEdit(){this._beginEdit()}getAttachmentByIndex(t){return new BM(new an({path:{...this.path,attachmentSource:"edit-composer",attachmentSelector:{type:"index",index:t},ref:`${this.path.ref}${this.path.ref}.attachments[${t}]`},getState:()=>{const i=this.getState().attachments[t];return i?{...i,source:"edit-composer"}:un},subscribe:n=>this._core.subscribe(n)}),this._core)}}class Qi{_state;constructor(t=null){this._state=t}get state(){return this._state}append(t){this._state=t.reduce((n,i)=>Qi.apply(n,i),this._state)}static apply(t,n){const i=n.type;switch(i){case"set":return Qi.updatePath(t,n.path,()=>n.value);case"append-text":return Qi.updatePath(t,n.path,r=>{if(typeof r!="string")throw new Error(`Expected string at path [${n.path.join(", ")}]`);return r+n.value});default:{const r=i;throw new Error(`Invalid operation type: ${r}`)}}}static updatePath(t,n,i){if(n.length===0)return i(t);if(t??={},typeof t!="object")throw new Error(`Invalid path: [${n.join(", ")}]`);const[r,...o]=n;if(Array.isArray(t)){const s=Number(r);if(Number.isNaN(s))throw new Error(`Expected array index at [${n.join(", ")}]`);if(s>t.length||s<0)throw new Error("Insert array index out of bounds");const u=[...t];return u[s]=this.updatePath(u[s],o,i),u}const a={...t};return a[r]=this.updatePath(a[r],o,i),a}}const WM=({unstable_state:e=null}={})=>({role:"assistant",status:{type:"running"},parts:[],get content(){return this.parts},metadata:{unstable_state:e,unstable_data:[],unstable_annotations:[],steps:[],custom:{}}}),au=(e,t,n)=>{if(e.parts.length===0)throw new Error("No parts available to update.");if(t.path.length!==1)throw new Error("Nested paths are not supported yet.");const i=t.path[0],r=n(e.parts[i]);return{...e,parts:[...e.parts.slice(0,i),r,...e.parts.slice(i+1)],get content(){return this.parts}}},GM=(e,t)=>{const n=t.part;if(n.type==="text"||n.type==="reasoning"){const i={type:n.type,text:"",status:{type:"running"},...n.parentId&&{parentId:n.parentId}};return{...e,parts:[...e.parts,i],get content(){return this.parts}}}else if(n.type==="tool-call"){const i={type:"tool-call",state:"partial-call",status:{type:"running",isArgsComplete:!1},toolCallId:n.toolCallId,toolName:n.toolName,argsText:"",args:{},...n.parentId&&{parentId:n.parentId}};return{...e,parts:[...e.parts,i],get content(){return this.parts}}}else if(n.type==="source"){const i={type:"source",sourceType:n.sourceType,id:n.id,url:n.url,...n.title?{title:n.title}:void 0,...n.parentId&&{parentId:n.parentId}};return{...e,parts:[...e.parts,i],get content(){return this.parts}}}else if(n.type==="file"){const i={type:"file",mimeType:n.mimeType,data:n.data};return{...e,parts:[...e.parts,i],get content(){return this.parts}}}else throw new Error(`Unsupported part type: ${n.type}`)},KM=(e,t)=>au(e,t,n=>{if(n.type!=="tool-call")throw new Error("Last is not a tool call");return n.state!=="partial-call"?n:{...n,state:"call"}}),YM=(e,t)=>au(e,t,n=>({...n,status:{type:"complete",reason:"unknown"}})),XM=(e,t)=>au(e,t,n=>{if(n.type==="text"||n.type==="reasoning")return{...n,text:n.text+t.textDelta};if(n.type==="tool-call"){const i=n.argsText+t.textDelta,r=js(i)??n.args;return{...n,argsText:i,args:r}}else throw new Error("text-delta received but part is neither text nor tool-call")}),QM=(e,t)=>au(e,t,n=>{if(n.type==="tool-call")return{...n,state:"result",...t.artifact!==void 0?{artifact:t.artifact}:{},result:t.result,isError:t.isError??!1,status:{type:"complete",reason:"stop"}};throw new Error("Result chunk received but part is not a tool-call")}),ig=(e,t)=>{if(e.status?.type==="incomplete"&&e.status?.reason==="error")return e;const n=eD(t);return{...e,status:n}},eD=e=>e.finishReason==="tool-calls"?{type:"requires-action",reason:"tool-calls"}:e.finishReason==="stop"||e.finishReason==="unknown"?{type:"complete",reason:e.finishReason}:{type:"incomplete",reason:e.finishReason},tD=(e,t)=>({...e,metadata:{...e.metadata,unstable_annotations:[...e.metadata.unstable_annotations,...t.annotations]}}),nD=(e,t)=>({...e,metadata:{...e.metadata,unstable_data:[...e.metadata.unstable_data,...t.data]}}),rD=(e,t)=>({...e,metadata:{...e.metadata,steps:[...e.metadata.steps,{state:"started",messageId:t.messageId}]}}),iD=(e,t)=>{const n=e.metadata.steps.slice(),i=n.length-1;return n.length>0&&n[i]?.state==="started"?n[i]={...n[i],state:"finished",finishReason:t.finishReason,usage:t.usage,isContinued:t.isContinued}:n.push({state:"finished",messageId:Yk(),finishReason:t.finishReason,usage:t.usage,isContinued:t.isContinued}),{...e,metadata:{...e.metadata,steps:n}}},oD=(e,t)=>({...e,status:{type:"incomplete",reason:"error",error:t.error}}),aD=(e,t)=>{const n=new Qi(e.metadata.unstable_state);return n.append(t.operations),{...e,metadata:{...e.metadata,unstable_state:n.state}}},sD=e=>{let t=!1;return()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}};class lD extends TransformStream{constructor({initialMessage:t,throttle:n,onError:i}={}){let r=t??WM(),o;const a=n?sD(()=>{o?.enqueue(r)}):()=>{o?.enqueue(r)};super({start(s){o=s},transform(s){const u=s.type;switch(u){case"part-start":r=GM(r,s);break;case"tool-call-args-text-finish":r=KM(r,s);break;case"part-finish":r=YM(r,s);break;case"text-delta":r=XM(r,s);break;case"result":r=QM(r,s);break;case"message-finish":r=ig(r,s);break;case"annotations":r=tD(r,s);break;case"data":r=nD(r,s);break;case"step-start":r=rD(r,s);break;case"step-finish":r=iD(r,s);break;case"error":r=oD(r,s),i?.(s.error);break;case"update-state":r=aD(r,s);break;default:{const l=u;throw new Error(`Unsupported chunk type: ${l}`)}}a()},flush(s){if(r.status?.type==="running"){const u=r.parts?.some(l=>l.type==="tool-call"&&(l.state==="call"||l.state==="partial-call")&&l.result===void 0)??!1;r=ig(r,{finishReason:u?"tool-calls":"unknown"}),s.enqueue(r)}}})}}class uD extends Gk{constructor(){super(t=>{const n=new MM({transform(i,r){r.appendText(i)}});return t.pipeThrough(new TextDecoderStream).pipeThrough(n)})}}class eo{readable;constructor(t){this.readable=t,this.readable=t}static fromAssistantStream(t){return new eo(t.pipeThrough(new lD))}async unstable_result(){let t;for await(const n of this)t=n;return t||{role:"assistant",status:{type:"complete",reason:"unknown"},parts:[],content:[],metadata:{unstable_state:null,unstable_data:[],unstable_annotations:[],steps:[],custom:{}}}}[Symbol.asyncIterator](){const t=this.readable.getReader();return{async next(){const{done:n,value:i}=await t.read();return n?{done:!0,value:void 0}:{done:!1,value:i}}}}tee(){const[t,n]=this.readable.tee();return[new eo(t),new eo(n)]}}const og=Symbol.for("aui.tool-response");class ln{get[og](){return!0}artifact;result;isError;constructor(t){t.artifact!==void 0&&(this.artifact=t.artifact),this.result=t.result,this.isError=t.isError??!1}static[Symbol.hasInstance](t){return typeof t=="object"&&t!==null&&og in t}static toResponse(t){return t instanceof ln?t:new ln({result:t===void 0?"<no result>":t})}}function cD(e,t,n){try{const i=e();if(typeof i=="object"&&i!==null&&"then"in i)return i.then(t,n);t(i)}catch(i){n(i)}}function va(e,t){let n=e;for(const i of t){if(n==null)return;n=n[i]}return n}class dD{resolve;reject;disposed=!1;fieldPath;constructor(t,n,i){this.resolve=t,this.reject=n,this.fieldPath=i}update(t){if(!this.disposed)try{if(xi(t,this.fieldPath)==="complete"){const n=va(t,this.fieldPath);n!==void 0&&(this.resolve(n),this.dispose())}}catch(n){this.reject(n),this.dispose()}}dispose(){this.disposed=!0}}class ag{controller;disposed=!1;fieldPath;constructor(t,n){this.controller=t,this.fieldPath=n}update(t){if(!this.disposed)try{const n=va(t,this.fieldPath);n!==void 0&&this.controller.enqueue(n),xi(t,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(n){this.controller.error(n),this.dispose()}}dispose(){this.disposed=!0}}class sg{controller;disposed=!1;fieldPath;lastValue=void 0;constructor(t,n){this.controller=t,this.fieldPath=n}update(t){if(!this.disposed)try{const n=va(t,this.fieldPath);if(n!==void 0&&typeof n=="string"){const i=n.substring(this.lastValue?.length||0);this.lastValue=n,this.controller.enqueue(i)}xi(t,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(n){this.controller.error(n),this.dispose()}}dispose(){this.disposed=!0}}class lg{controller;disposed=!1;fieldPath;processedIndexes=new Set;constructor(t,n){this.controller=t,this.fieldPath=n}update(t){if(!this.disposed)try{const n=va(t,this.fieldPath);if(!Array.isArray(n))return;for(let i=0;i<n.length;i++)if(!this.processedIndexes.has(i)){const r=[...this.fieldPath,i];xi(t,r)==="complete"&&(this.controller.enqueue(n[i]),this.processedIndexes.add(i))}xi(t,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(n){this.controller.error(n),this.dispose()}}dispose(){this.disposed=!0}}class pD{argTextDeltas;handles=new Set;args=js("");constructor(t){this.argTextDeltas=t,this.processStream()}async processStream(){try{let t="";const n=this.argTextDeltas.getReader();for(;;){const{value:i,done:r}=await n.read();if(r)break;t+=i;const o=js(t);if(o!==void 0){this.args=o;for(const a of this.handles)a.update(o)}}}catch(t){console.error("Error processing argument stream:",t);for(const n of this.handles)n.dispose()}}get(...t){return new Promise((n,i)=>{const r=new dD(n,i,t);if(this.args&&xi(this.args,t)==="complete"){const o=va(this.args,t);if(o!==void 0){n(o);return}}this.handles.add(r),r.update(this.args)})}streamValues(...t){const n=t,i=new ReadableStream({start:r=>{const o=new ag(r,n);this.handles.add(o),o.update(this.args)},cancel:()=>{for(const r of this.handles)if(r instanceof ag){r.dispose(),this.handles.delete(r);break}}});return Uu(i)}streamText(...t){const n=t,i=new ReadableStream({start:r=>{const o=new sg(r,n);this.handles.add(o),o.update(this.args)},cancel:()=>{for(const r of this.handles)if(r instanceof sg){r.dispose(),this.handles.delete(r);break}}});return Uu(i)}forEach(...t){const n=t,i=new ReadableStream({start:r=>{const o=new lg(r,n);this.handles.add(o),o.update(this.args)},cancel:()=>{for(const r of this.handles)if(r instanceof lg){r.dispose(),this.handles.delete(r);break}}});return Uu(i)}}class fD{promise;constructor(t){this.promise=t}get(){return this.promise}}class hD{args;response;writable;resolve;argsText="";constructor(){const t=new TransformStream;this.writable=t.writable,this.args=new pD(t.readable);const{promise:n,resolve:i}=zf();this.resolve=i,this.response=new fD(n)}async appendArgsTextDelta(t){const n=this.writable.getWriter();try{await n.write(t)}catch(i){console.warn(i)}finally{n.releaseLock()}this.argsText+=t}setResponse(t){this.resolve(t)}result={get:async()=>(await this.response.get()).result}}class mD extends Gk{constructor(t){const n=new Map,i=new Map;super(r=>{const o=new TransformStream({transform(a,s){switch((a.type!=="part-finish"||a.meta.type!=="tool-call")&&s.enqueue(a),a.type){case"part-start":if(a.part.type==="tool-call"){const l=new hD;i.set(a.part.toolCallId,l),t.streamCall({reader:l,toolCallId:a.part.toolCallId,toolName:a.part.toolName})}break;case"text-delta":{if(a.meta.type==="tool-call"){const l=a.meta.toolCallId,c=i.get(l);if(!c)throw new Error("No controller found for tool call");c.appendArgsTextDelta(a.textDelta)}break}case"result":{if(a.meta.type!=="tool-call")break;const{toolCallId:l}=a.meta,c=i.get(l);if(!c)throw new Error("No controller found for tool call");c.setResponse(new ln({result:a.result,artifact:a.artifact,isError:a.isError}));break}case"tool-call-args-text-finish":{if(a.meta.type!=="tool-call")break;const{toolCallId:l,toolName:c}=a.meta,d=i.get(l);if(!d)throw new Error("No controller found for tool call");let f=!1;const p=cD(()=>{let g;try{g=Xc.parse(d.argsText)}catch(y){throw new Error(`Function parameter parsing failed. ${JSON.stringify(y.message)}`)}const m=t.execute({toolCallId:l,toolName:c,args:g});return m!==void 0&&(f=!0,t.onExecutionStart?.(l,c)),m},g=>{if(f&&t.onExecutionEnd?.(l,c),g===void 0)return;const m=new ln({artifact:g.artifact,result:g.result,isError:g.isError});d.setResponse(m),s.enqueue({type:"result",path:a.path,...m})},g=>{f&&t.onExecutionEnd?.(l,c);const m=new ln({result:String(g),isError:!0});d.setResponse(m),s.enqueue({type:"result",path:a.path,...m})});p&&n.set(l,p);break}case"part-finish":{if(a.meta.type!=="tool-call")break;const{toolCallId:l}=a.meta,c=n.get(l);c?c.then(()=>{n.delete(l),i.delete(l),s.enqueue(a)}):s.enqueue(a)}}},async flush(){await Promise.all(n.values())}});return r.pipeThrough(new Kk).pipeThrough(o)})}}const gD=e=>typeof e=="object"&&e!==null&&"~standard"in e&&e["~standard"].version===1;function vD(e,t,n,i){const r=e?.[n.toolName];return!r||!r.execute?void 0:(async a=>{if(t.aborted)return new ln({result:"Tool execution was cancelled.",isError:!0});let s=a;if(gD(r.parameters)){let c=r.parameters["~standard"].validate(n.args);c instanceof Promise&&(c=await c),c.issues&&(s=r.experimental_onSchemaValidationError??(()=>{throw new Error(`Function parameter validation failed. ${JSON.stringify(c.issues)}`)}))}const u=new Promise(c=>{const d=()=>{queueMicrotask(()=>{queueMicrotask(()=>{c(new ln({result:"Tool execution was cancelled.",isError:!0}))})})};t.aborted?d():t.addEventListener("abort",d,{once:!0})}),l=(async()=>{const c=await s(n.args,{toolCallId:n.toolCallId,abortSignal:t,human:d=>i(n.toolCallId,d)});return ln.toResponse(c)})();return Promise.race([l,u])})(r.execute)}function yD(e,t,n,i,r){e?.[i.toolName]?.streamCall?.(n,{toolCallId:i.toolCallId,abortSignal:t,human:o=>r(i.toolCallId,o)})}function bD(e,t,n,i){const r=typeof e=="function"?e:()=>e,o=typeof t=="function"?t:()=>t;return new mD({execute:a=>vD(r(),o(),a,n),streamCall:({reader:a,...s})=>yD(r(),o(),a,s,n),onExecutionStart:i?.onExecutionStart,onExecutionEnd:i?.onExecutionEnd})}class ug{contentBinding;messageApi;threadApi;get path(){return this.contentBinding.path}constructor(t,n,i){this.contentBinding=t,this.messageApi=n,this.threadApi=i,this.__internal_bindMethods()}__internal_bindMethods(){this.addToolResult=this.addToolResult.bind(this),this.resumeToolCall=this.resumeToolCall.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this)}getState(){return this.contentBinding.getState()}addToolResult(t){const n=this.contentBinding.getState();if(!n)throw new Error("Message part is not available");if(n.type!=="tool-call")throw new Error("Tried to add tool result to non-tool message part");if(!this.messageApi)throw new Error("Message API is not available. This is likely a bug in assistant-ui.");if(!this.threadApi)throw new Error("Thread API is not available");const i=this.messageApi.getState();if(!i)throw new Error("Message is not available");const r=n.toolName,o=n.toolCallId,a=ln.toResponse(t);this.threadApi.getState().addToolResult({messageId:i.id,toolName:r,toolCallId:o,result:a.result,artifact:a.artifact,isError:a.isError})}resumeToolCall(t){const n=this.contentBinding.getState();if(!n)throw new Error("Message part is not available");if(n.type!=="tool-call")throw new Error("Tried to resume tool call on non-tool message part");if(!this.threadApi)throw new Error("Thread API is not available");const i=n.toolCallId;this.threadApi.getState().resumeToolCall({toolCallId:i,payload:t})}subscribe(t){return this.contentBinding.subscribe(t)}}class Ms extends ou{binding;get path(){return this.binding.path}constructor(t){super(),this.binding=t}getState(){return this.binding.getState()}outerSubscribe(t){return this.binding.subscribe(t)}_connect(){const t=()=>{this.notifySubscribers()};let n=this.binding.getState(),i=n?.subscribe(t);const r=()=>{const a=this.binding.getState();a!==n&&(n=a,i?.(),i=this.binding.getState()?.subscribe(t),t())},o=this.outerSubscribe(r);return()=>{o?.(),i?.()}}}const La=Object.freeze({type:"complete"}),_D=(e,t,n)=>{if(e.role!=="assistant")return La;if(n.type==="tool-call")return n.result?La:e.status;const i=t===Math.max(0,e.content.length-1);return e.status.type==="requires-action"?La:i?e.status:La},cg=(e,t)=>{const n=e.content[t];if(!n)return un;const i=_D(e,t,n);return Object.freeze({...n,[Ct]:n[Ct],status:i})};class wD{_core;_threadBinding;get path(){return this._core.path}constructor(t,n){this._core=t,this._threadBinding=n,this.composer=new JM(new Ms({path:{...this.path,ref:`${this.path.ref}${this.path.ref}.composer`,composerSource:"edit"},getState:this._getEditComposerRuntimeCore,subscribe:i=>this._threadBinding.subscribe(i)}),()=>this._threadBinding.getState().beginEdit(this._core.getState().id)),this.__internal_bindMethods()}__internal_bindMethods(){this.reload=this.reload.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.getMessagePartByIndex=this.getMessagePartByIndex.bind(this),this.getMessagePartByToolCallId=this.getMessagePartByToolCallId.bind(this),this.getAttachmentByIndex=this.getAttachmentByIndex.bind(this),this.unstable_getCopyText=this.unstable_getCopyText.bind(this),this.speak=this.speak.bind(this),this.stopSpeaking=this.stopSpeaking.bind(this),this.submitFeedback=this.submitFeedback.bind(this),this.switchToBranch=this.switchToBranch.bind(this)}composer;_getEditComposerRuntimeCore=()=>this._threadBinding.getState().getEditComposer(this._core.getState().id);getState(){return this._core.getState()}reload(t={}){const n=this._getEditComposerRuntimeCore(),i=n??this._threadBinding.getState().composer,r=n??i,{runConfig:o=r.runConfig}=t,a=this._core.getState();if(a.role!=="assistant")throw new Error("Can only reload assistant messages");this._threadBinding.getState().startRun({parentId:a.parentId,sourceId:a.id,runConfig:o})}speak(){const t=this._core.getState();return this._threadBinding.getState().speak(t.id)}stopSpeaking(){const t=this._core.getState();if(this._threadBinding.getState().speech?.messageId===t.id)this._threadBinding.getState().stopSpeaking();else throw new Error("Message is not being spoken")}submitFeedback({type:t}){const n=this._core.getState();this._threadBinding.getState().submitFeedback({messageId:n.id,type:t})}switchToBranch({position:t,branchId:n}){const i=this._core.getState();if(n&&t)throw new Error("May not specify both branchId and position");if(!n&&!t)throw new Error("Must specify either branchId or position");const o=this._threadBinding.getState().getBranches(i.id);let a=n;if(t==="previous"?a=o[i.branchNumber-2]:t==="next"&&(a=o[i.branchNumber]),!a)throw new Error("Branch not found");this._threadBinding.getState().switchToBranch(a)}unstable_getCopyText(){return yo(this.getState())}subscribe(t){return this._core.subscribe(t)}getMessagePartByIndex(t){if(t<0)throw new Error("Message part index must be >= 0");return new ug(new an({path:{...this.path,ref:`${this.path.ref}${this.path.ref}.content[${t}]`,messagePartSelector:{type:"index",index:t}},getState:()=>cg(this.getState(),t),subscribe:n=>this._core.subscribe(n)}),this._core,this._threadBinding)}getMessagePartByToolCallId(t){return new ug(new an({path:{...this.path,ref:this.path.ref+`${this.path.ref}.content[toolCallId=${JSON.stringify(t)}]`,messagePartSelector:{type:"toolCallId",toolCallId:t}},getState:()=>{const n=this._core.getState(),i=n.content.findIndex(r=>r.type==="tool-call"&&r.toolCallId===t);return i===-1?un:cg(n,i)},subscribe:n=>this._core.subscribe(n)}),this._core,this._threadBinding)}getAttachmentByIndex(t){return new ZM(new an({path:{...this.path,ref:`${this.path.ref}${this.path.ref}.attachments[${t}]`,attachmentSource:"message",attachmentSelector:{type:"index",index:t}},getState:()=>{const i=this.getState().attachments?.[t];return i?{...i,source:"message"}:un},subscribe:n=>this._core.subscribe(n)}))}}const xD=e=>({parentId:e.parentId??null,sourceId:e.sourceId??null,runConfig:e.runConfig??{},...e.stream?{stream:e.stream}:{}}),SD=e=>({parentId:e.parentId??null,sourceId:e.sourceId??null,runConfig:e.runConfig??{}}),ID=(e,t)=>typeof t=="string"?{createdAt:new Date,parentId:e.at(-1)?.id??null,sourceId:null,runConfig:{},role:"user",content:[{type:"text",text:t}],attachments:[],metadata:{custom:{}}}:{createdAt:t.createdAt??new Date,parentId:t.parentId??e.at(-1)?.id??null,sourceId:t.sourceId??null,role:t.role??"user",content:t.content,attachments:t.attachments??[],metadata:t.metadata??{custom:{}},runConfig:t.runConfig??{},startRun:t.startRun},kD=(e,t)=>{const n=e.messages.at(-1);return Object.freeze({threadId:t.id,metadata:t,capabilities:e.capabilities,isDisabled:e.isDisabled,isLoading:e.isLoading,isRunning:n?.role!=="assistant"?!1:n.status.type==="running",messages:e.messages,state:e.state,suggestions:e.suggestions,extras:e.extras,speech:e.speech})};class oE{get path(){return this._threadBinding.path}get __internal_threadBinding(){return this._threadBinding}_threadBinding;constructor(t,n){const i=new an({path:t.path,getState:()=>kD(t.getState(),n.getState()),subscribe:r=>{const o=t.subscribe(r),a=n.subscribe(r);return()=>{o(),a()}}});this._threadBinding={path:t.path,getState:()=>t.getState(),getStateState:()=>i.getState(),outerSubscribe:r=>t.outerSubscribe(r),subscribe:r=>t.subscribe(r)},this.composer=new HM(new Ms({path:{...this.path,ref:`${this.path.ref}${this.path.ref}.composer`,composerSource:"thread"},getState:()=>this._threadBinding.getState().composer,subscribe:r=>this._threadBinding.subscribe(r)})),this.__internal_bindMethods()}__internal_bindMethods(){this.append=this.append.bind(this),this.unstable_resumeRun=this.unstable_resumeRun.bind(this),this.unstable_loadExternalState=this.unstable_loadExternalState.bind(this),this.startRun=this.startRun.bind(this),this.cancelRun=this.cancelRun.bind(this),this.stopSpeaking=this.stopSpeaking.bind(this),this.export=this.export.bind(this),this.import=this.import.bind(this),this.reset=this.reset.bind(this),this.getMessageByIndex=this.getMessageByIndex.bind(this),this.getMessageById=this.getMessageById.bind(this),this.subscribe=this.subscribe.bind(this),this.unstable_on=this.unstable_on.bind(this),this.getModelContext=this.getModelContext.bind(this),this.getModelConfig=this.getModelConfig.bind(this),this.getState=this.getState.bind(this)}composer;getState(){return this._threadBinding.getStateState()}append(t){this._threadBinding.getState().append(ID(this._threadBinding.getState().messages,t))}subscribe(t){return this._threadBinding.subscribe(t)}getModelContext(){return this._threadBinding.getState().getModelContext()}getModelConfig(){return this.getModelContext()}startRun(t){const n=t===null||typeof t=="string"?{parentId:t}:t;return this._threadBinding.getState().startRun(SD(n))}unstable_resumeRun(t){return this._threadBinding.getState().resumeRun(xD(t))}unstable_loadExternalState(t){this._threadBinding.getState().unstable_loadExternalState(t)}cancelRun(){this._threadBinding.getState().cancelRun()}stopSpeaking(){return this._threadBinding.getState().stopSpeaking()}export(){return this._threadBinding.getState().export()}import(t){this._threadBinding.getState().import(t)}reset(t){this._threadBinding.getState().reset(t)}getMessageByIndex(t){if(t<0)throw new Error("Message index must be >= 0");return this._getMessageRuntime({...this.path,ref:`${this.path.ref}${this.path.ref}.messages[${t}]`,messageSelector:{type:"index",index:t}},()=>{const n=this._threadBinding.getState().messages,i=n[t];if(i)return{message:i,parentId:n[t-1]?.id??null,index:t}})}getMessageById(t){return this._getMessageRuntime({...this.path,ref:this.path.ref+`${this.path.ref}.messages[messageId=${JSON.stringify(t)}]`,messageSelector:{type:"messageId",messageId:t}},()=>this._threadBinding.getState().getMessageById(t))}_getMessageRuntime(t,n){return new wD(new an({path:t,getState:()=>{const{message:i,parentId:r,index:o}=n()??{},{messages:a,speech:s}=this._threadBinding.getState();if(!i||r===void 0||o===void 0)return un;const l=this._threadBinding.getState().getBranches(i.id),c=i.metadata.submittedFeedback;return{...i,[Ct]:i[Ct],index:o,isLast:a.at(-1)?.id===i.id,parentId:r,branchNumber:l.indexOf(i.id)+1,branchCount:l.length,speech:s?.messageId===i.id?s:void 0,submittedFeedback:c}},subscribe:i=>this._threadBinding.subscribe(i)}),this._threadBinding)}_eventSubscriptionSubjects=new Map;unstable_on(t,n){let i=this._eventSubscriptionSubjects.get(t);return i||(i=new tE({event:t,binding:this._threadBinding}),this._eventSubscriptionSubjects.set(t,i)),i.subscribe(n)}}const ED=e=>({mainThreadId:e.mainThreadId,newThread:e.newThreadId,threads:e.threadIds,archivedThreads:e.archivedThreadIds,isLoading:e.isLoading,threadItems:e.threadData}),Fa=(e,t)=>{if(t===void 0)return un;const n=e.getItemById(t);return n?{id:n.id,threadId:n.id,remoteId:n.remoteId,externalId:n.externalId,title:n.title,status:n.status,isMain:n.id===e.mainThreadId}:un};class TD{_core;_runtimeFactory;_getState;constructor(t,n=oE){this._core=t,this._runtimeFactory=n;const i=new Bf({path:{},getState:()=>ED(t),subscribe:r=>t.subscribe(r)});this._getState=i.getState.bind(i),this._mainThreadListItemRuntime=new Ua(new an({path:{ref:"threadItems[main]",threadSelector:{type:"main"}},getState:()=>Fa(this._core,this._core.mainThreadId),subscribe:r=>this._core.subscribe(r)}),this._core),this.main=new n(new Ms({path:{ref:"threads.main",threadSelector:{type:"main"}},getState:()=>t.getMainThreadRuntimeCore(),subscribe:r=>t.subscribe(r)}),this._mainThreadListItemRuntime),this.__internal_bindMethods()}__internal_bindMethods(){this.switchToThread=this.switchToThread.bind(this),this.switchToNewThread=this.switchToNewThread.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.getById=this.getById.bind(this),this.getItemById=this.getItemById.bind(this),this.getItemByIndex=this.getItemByIndex.bind(this),this.getArchivedItemByIndex=this.getArchivedItemByIndex.bind(this)}switchToThread(t){return this._core.switchToThread(t)}switchToNewThread(){return this._core.switchToNewThread()}getState(){return this._getState()}subscribe(t){return this._core.subscribe(t)}_mainThreadListItemRuntime;main;get mainItem(){return this._mainThreadListItemRuntime}getById(t){return new this._runtimeFactory(new Ms({path:{ref:`threads[threadId=${JSON.stringify(t)}]`,threadSelector:{type:"threadId",threadId:t}},getState:()=>this._core.getThreadRuntimeCore(t),subscribe:n=>this._core.subscribe(n)}),this.mainItem)}getItemByIndex(t){return new Ua(new an({path:{ref:`threadItems[${t}]`,threadSelector:{type:"index",index:t}},getState:()=>Fa(this._core,this._core.threadIds[t]),subscribe:n=>this._core.subscribe(n)}),this._core)}getArchivedItemByIndex(t){return new Ua(new an({path:{ref:`archivedThreadItems[${t}]`,threadSelector:{type:"archiveIndex",index:t}},getState:()=>Fa(this._core,this._core.archivedThreadIds[t]),subscribe:n=>this._core.subscribe(n)}),this._core)}getItemById(t){return new Ua(new an({path:{ref:`threadItems[threadId=${t}]`,threadSelector:{type:"threadId",threadId:t}},getState:()=>Fa(this._core,t),subscribe:n=>this._core.subscribe(n)}),this._core)}}const $D=e=>e.startsWith("image/")?"image":e.startsWith("text/")?"document":"file";class CD{cloud;accept="*";constructor(t){this.cloud=t}uploadedUrls=new Map;async*add({file:t}){const n=crypto.randomUUID(),i=$D(t.type);let r={id:n,type:i,name:t.name,contentType:t.type,file:t,status:{type:"running",reason:"uploading",progress:0}};yield r;try{const{signedUrl:o,publicUrl:a}=await this.cloud.files.generatePresignedUploadUrl({filename:t.name});await fetch(o,{method:"PUT",body:t,headers:{"Content-Type":t.type},mode:"cors"}),this.uploadedUrls.set(n,a),r={...r,status:{type:"requires-action",reason:"composer-send"}},yield r}catch{r={...r,status:{type:"incomplete",reason:"error"}},yield r}}async remove(t){this.uploadedUrls.delete(t.id)}async send(t){const n=this.uploadedUrls.get(t.id);if(!n)throw new Error("Attachment not uploaded");this.uploadedUrls.delete(t.id);let i;return t.type==="image"?i=[{type:"image",image:n,filename:t.name}]:i=[{type:"file",data:n,mimeType:t.contentType,filename:t.name}],{...t,status:{type:"complete"},content:i}}}const ed=k.createContext(null),Zf=({adapters:e,children:t})=>{const n=k.useContext(ed);return h.jsx(ed.Provider,{value:{...n,...e},children:t})},aE=()=>k.useContext(ed),br=Object.freeze([]),Ir="DEFAULT_THREAD_ID",AD=Object.freeze([Ir]),sE=Object.freeze({id:Ir,remoteId:void 0,externalId:void 0,status:"regular"}),PD=Promise.resolve(),dg=Object.freeze({[Ir]:sE});class RD{adapter;threadFactory;_mainThreadId=Ir;_threads=AD;_archivedThreads=br;_threadData=dg;get isLoading(){return this.adapter.isLoading??!1}get newThreadId(){}get threadIds(){return this._threads}get archivedThreadIds(){return this._archivedThreads}get threadData(){return this._threadData}getLoadThreadsPromise(){return PD}_mainThread;get mainThreadId(){return this._mainThreadId}constructor(t={},n){this.adapter=t,this.threadFactory=n,this._mainThread=this.threadFactory(),this.__internal_setAdapter(t,!0)}getMainThreadRuntimeCore(){return this._mainThread}getThreadRuntimeCore(){throw new Error("Method not implemented.")}getItemById(t){for(const n of this.adapter.threads??[])if(n.id===t)return n;for(const n of this.adapter.archivedThreads??[])if(n.id===t)return n;if(t===Ir)return sE}__internal_setAdapter(t,n=!1){const i=this.adapter;this.adapter=t;const r=t.threadId??Ir,o=t.threads??br,a=t.archivedThreads??br,s=i.threadId??Ir,u=i.threads??br,l=i.archivedThreads??br;!n&&s===r&&u===o&&l===a||(this._threadData={...dg,...Object.fromEntries(t.threads?.map(c=>[c.id,{...c,remoteId:c.remoteId,externalId:c.externalId,status:"regular"}])??[]),...Object.fromEntries(t.archivedThreads?.map(c=>[c.id,{...c,remoteId:c.remoteId,externalId:c.externalId,status:"archived"}])??[])},u!==o&&(this._threads=this.adapter.threads?.map(c=>c.id)??br),l!==a&&(this._archivedThreads=this.adapter.archivedThreads?.map(c=>c.id)??br),s!==r&&(this._mainThreadId=r,this._mainThread=this.threadFactory()),this._notifySubscribers())}async switchToThread(t){if(this._mainThreadId===t)return;const n=this.adapter.onSwitchToThread;if(!n)throw new Error("External store adapter does not support switching to thread");n(t)}async switchToNewThread(){const t=this.adapter.onSwitchToNewThread;if(!t)throw new Error("External store adapter does not support switching to new thread");t()}async rename(t,n){const i=this.adapter.onRename;if(!i)throw new Error("External store adapter does not support renaming");i(t,n)}async detach(){}async archive(t){const n=this.adapter.onArchive;if(!n)throw new Error("External store adapter does not support archiving");n(t)}async unarchive(t){const n=this.adapter.onUnarchive;if(!n)throw new Error("External store adapter does not support unarchiving");n(t)}async delete(t){const n=this.adapter.onDelete;if(!n)throw new Error("External store adapter does not support deleting");n(t)}initialize(t){return Promise.resolve({remoteId:t,externalId:void 0})}generateTitle(){throw new Error("Method not implemented.")}_subscriptions=new Set;subscribe(t){return this._subscriptions.add(t),()=>this._subscriptions.delete(t)}_notifySubscribers(){for(const t of this._subscriptions)t()}}class td{cache=new WeakMap;convertMessages(t,n){return t.map((i,r)=>{const o=this.cache.get(i),a=n(o,i,r);return this.cache.set(i,a),a})}}class OD extends Bk{runtime;endEditCallback;get canCancel(){return!0}getAttachmentAdapter(){return this.runtime.adapters?.attachments}_nonTextParts;_previousText;_parentId;_sourceId;constructor(t,n,{parentId:i,message:r}){super(),this.runtime=t,this.endEditCallback=n,this._parentId=i,this._sourceId=r.id,this._previousText=yo(r),this.setText(this._previousText),this.setRole(r.role),this.setAttachments(r.attachments??[]),this._nonTextParts=r.content.filter(o=>o.type!=="text"),this.setRunConfig({...t.composer.runConfig})}async handleSend(t){yo(t)!==this._previousText&&this.runtime.append({...t,content:[...t.content,...this._nonTextParts],parentId:this._parentId,sourceId:this._sourceId}),this.handleCancel()}handleCancel(){this.endEditCallback(),this._notifySubscribers()}}class ND{_contextProvider;_subscriptions=new Set;_isInitialized=!1;repository=new Ff;get messages(){return this.repository.getMessages()}get state(){let t;for(const n of this.messages)if(n.role==="assistant"){t=n;break}return t?.metadata.unstable_state??null}composer=new Zk(this);constructor(t){this._contextProvider=t}getModelContext(){return this._contextProvider.getModelContext()}_editComposers=new Map;getEditComposer(t){return this._editComposers.get(t)}beginEdit(t){if(this._editComposers.has(t))throw new Error("Edit already in progress");this._editComposers.set(t,new OD(this,()=>this._editComposers.delete(t),this.repository.getMessage(t))),this._notifySubscribers()}getMessageById(t){try{return this.repository.getMessage(t)}catch{return}}getBranches(t){return this.repository.getBranches(t)}switchToBranch(t){this.repository.switchToBranch(t),this._notifySubscribers()}_notifySubscribers(){for(const t of this._subscriptions)t()}_notifyEventSubscribers(t){const n=this._eventSubscribers.get(t);if(n)for(const i of n)i()}subscribe(t){return this._subscriptions.add(t),()=>this._subscriptions.delete(t)}submitFeedback({messageId:t,type:n}){const i=this.adapters?.feedback;if(!i)throw new Error("Feedback adapter not configured");const{message:r,parentId:o}=this.repository.getMessage(t);if(i.submit({message:r,type:n}),r.role==="assistant"){const a={...r,metadata:{...r.metadata,submittedFeedback:{type:n}}};this.repository.addOrUpdateMessage(o,a)}this._notifySubscribers()}_stopSpeaking;speech;speak(t){const n=this.adapters?.speech;if(!n)throw new Error("Speech adapter not configured");const{message:i}=this.repository.getMessage(t);this._stopSpeaking?.();const r=n.speak(yo(i)),o=r.subscribe(()=>{r.status.type==="ended"?(this._stopSpeaking=void 0,this.speech=void 0):this.speech={messageId:t,status:r.status},this._notifySubscribers()});this.speech={messageId:t,status:r.status},this._notifySubscribers(),this._stopSpeaking=()=>{r.cancel(),o(),this.speech=void 0,this._stopSpeaking=void 0}}stopSpeaking(){if(!this._stopSpeaking)throw new Error("No message is being spoken");this._stopSpeaking(),this._notifySubscribers()}ensureInitialized(){this._isInitialized||(this._isInitialized=!0,this._notifyEventSubscribers("initialize"))}export(){return this.repository.export()}import(t){this.ensureInitialized(),this.repository.clear(),this.repository.import(t),this._notifySubscribers()}reset(t){this.import(Lf.fromArray(t??[]))}_eventSubscribers=new Map;unstable_on(t,n){if(t==="model-context-update")return this._contextProvider.subscribe?.(n)??(()=>{});const i=this._eventSubscribers.get(t);return i?i.add(n):this._eventSubscribers.set(t,new Set([n])),()=>{this._eventSubscribers.get(t).delete(n)}}}const jD=Object.freeze([]),MD=(e,t)=>e&&t[t.length-1]?.role!=="assistant";class DD extends ND{_assistantOptimisticId=null;_capabilities={switchToBranch:!1,switchBranchDuringRun:!1,edit:!1,reload:!1,cancel:!1,unstable_copy:!1,speech:!1,attachments:!1,feedback:!1};get capabilities(){return this._capabilities}_messages;isDisabled;get isLoading(){return this._store.isLoading??!1}get messages(){return this._messages}get state(){return this._store.state??super.state}get adapters(){return this._store.adapters}suggestions=[];extras=void 0;_converter=new td;_store;beginEdit(t){if(!this._store.onEdit)throw new Error("Runtime does not support editing.");super.beginEdit(t)}constructor(t,n){super(t),this.__internal_setAdapter(n)}__internal_setAdapter(t){if(this._store===t)return;const n=t.isRunning??!1;this.isDisabled=t.isDisabled??!1;const i=this._store;this._store=t,this.extras=t.extras,this.suggestions=t.suggestions??jD,this._capabilities={switchToBranch:this._store.setMessages!==void 0,switchBranchDuringRun:!1,edit:this._store.onEdit!==void 0,reload:this._store.onReload!==void 0,cancel:this._store.onCancel!==void 0,speech:this._store.adapters?.speech!==void 0,unstable_copy:this._store.unstable_capabilities?.copy!==!1,attachments:!!this._store.adapters?.attachments,feedback:!!this._store.adapters?.feedback};let r;if(t.messageRepository){if(i&&i.isRunning===t.isRunning&&i.messageRepository===t.messageRepository){this._notifySubscribers();return}this.repository.clear(),this._assistantOptimisticId=null,this.repository.import(t.messageRepository),r=this.repository.getMessages()}else if(t.messages){if(i){if(i.convertMessage!==t.convertMessage)this._converter=new td;else if(i.isRunning===t.isRunning&&i.messages===t.messages){this._notifySubscribers();return}}r=t.convertMessage?this._converter.convertMessages(t.messages,(o,a,s)=>{if(!t.convertMessage)return a;const u=s===t.messages.length-1,l=ma(u,n,!1,!1,void 0);if(o&&(o.role!=="assistant"||!Vk(o.status)||o.status===l))return o;const c=t.convertMessage(a,s),d=Ur(c,s.toString(),l);return d[Ct]=a,d}):t.messages;for(let o=0;o<r.length;o++){const a=r[o],s=r[o-1];this.repository.addOrUpdateMessage(s?.id??null,a)}}else throw new Error("ExternalStoreAdapter must provide either 'messages' or 'messageRepository'");r.length>0&&this.ensureInitialized(),(i?.isRunning??!1)!==(t.isRunning??!1)&&(t.isRunning?this._notifyEventSubscribers("run-start"):this._notifyEventSubscribers("run-end")),this._assistantOptimisticId&&(this.repository.deleteMessage(this._assistantOptimisticId),this._assistantOptimisticId=null),MD(n,r)&&(this._assistantOptimisticId=this.repository.appendOptimisticMessage(r.at(-1)?.id??null,{role:"assistant",content:[]})),this.repository.resetHead(this._assistantOptimisticId??r.at(-1)?.id??null),this._messages=this.repository.getMessages(),this._notifySubscribers()}switchToBranch(t){if(!this._store.setMessages)throw new Error("Runtime does not support switching branches.");this._store.isRunning||(this.repository.switchToBranch(t),this.updateMessages(this.repository.getMessages()))}async append(t){if(t.parentId!==(this.messages.at(-1)?.id??null)){if(!this._store.onEdit)throw new Error("Runtime does not support editing messages.");await this._store.onEdit(t)}else await this._store.onNew(t)}async startRun(t){if(!this._store.onReload)throw new Error("Runtime does not support reloading messages.");await this._store.onReload(t.parentId,t)}async resumeRun(t){if(!this._store.onResume)throw new Error("Runtime does not support resuming runs.");await this._store.onResume(t)}unstable_loadExternalState(t){if(!this._store.onLoadExternalState)throw new Error("Runtime does not support importing states.");this._store.onLoadExternalState(t)}cancelRun(){if(!this._store.onCancel)throw new Error("Runtime does not support cancelling runs.");this._store.onCancel(),this._assistantOptimisticId&&(this.repository.deleteMessage(this._assistantOptimisticId),this._assistantOptimisticId=null);let t=this.repository.getMessages();const n=t[t.length-1];n?.role==="user"&&n.id===t.at(-1)?.id?(this.repository.deleteMessage(n.id),this.composer.text.trim()||this.composer.setText(yo(n)),t=this.repository.getMessages()):this._notifySubscribers(),setTimeout(()=>{this.updateMessages(t)},0)}addToolResult(t){if(!this._store.onAddToolResult&&!this._store.onAddToolResult)throw new Error("Runtime does not support tool results.");this._store.onAddToolResult?.(t)}resumeToolCall(t){if(!this._store.onResumeToolCall)throw new Error("Runtime does not support resuming tool calls.");this._store.onResumeToolCall(t)}reset(t){const n=new Ff;n.import(Lf.fromArray(t??[])),this.updateMessages(n.getMessages())}import(t){this._assistantOptimisticId=null,super.import(t),this._store.onImport&&this._store.onImport(this.repository.getMessages())}updateMessages=t=>{this._store.convertMessage!==void 0?this._store.setMessages?.(t.flatMap(UM).filter(i=>i!=null)):this._store.setMessages?.(t)}}const pg=e=>e.adapters?.threadList??{};class zD extends Df{threads;constructor(t){super(),this.threads=new RD(pg(t),()=>new DD(this._contextProvider,t))}setAdapter(t){this.threads.__internal_setAdapter(pg(t)),this.threads.getMainThreadRuntimeCore().__internal_setAdapter(t)}}const UD=e=>{const[t]=k.useState(()=>new zD(e));k.useEffect(()=>{t.setAdapter(e)});const{modelContext:n}=aE()??{};return k.useEffect(()=>{if(n)return t.registerModelContextProvider(n)},[n,t]),k.useMemo(()=>new Wf(t),[t])},LD=e=>{try{return JSON.parse(e),!0}catch{return!1}};function lE({state:e,getTools:t,onResult:n,setToolStatuses:i}){const r=k.useRef({}),o=k.useRef(new Map),a=k.useRef(new AbortController),s=k.useRef(0),u=k.useRef([]),[l]=k.useState(()=>{const[p,g]=Xk(),m=bD(t,()=>a.current?.signal??new AbortController().signal,(y,v)=>new Promise((_,x)=>{const b=o.current.get(y);b&&b.reject(new Error("Human input request was superseded by a new request")),o.current.set(y,{resolve:_,reject:x}),i(C=>({...C,[y]:{type:"interrupt",payload:{type:"human",payload:v}}}))}),{onExecutionStart:y=>{s.current++,i(v=>({...v,[y]:{type:"executing"}}))},onExecutionEnd:y=>{s.current--,i(v=>{const _={...v};return delete _[y],_}),s.current===0&&(u.current.forEach(v=>v()),u.current=[])}});return p.pipeThrough(m).pipeThrough(new Kk).pipeTo(new WritableStream({write(y){if(y.type==="result"){if(r.current[y.meta.toolCallId]?.hasResult)return;n({type:"add-tool-result",toolCallId:y.meta.toolCallId,toolName:y.meta.toolName,result:y.result,isError:y.isError,...y.artifact&&{artifact:y.artifact}})}}})),g}),c=k.useRef(new Set),d=k.useRef(!0);k.useEffect(()=>{const p=g=>{g.forEach(m=>{m.content.forEach(y=>{if(y.type==="tool-call"){if(d.current)c.current.add(y.toolCallId);else{if(c.current.has(y.toolCallId))return;let v=r.current[y.toolCallId];if(v||(v={argsText:"",hasResult:!1,argsComplete:!1,controller:l.addToolCallPart({toolName:y.toolName,toolCallId:y.toolCallId})},r.current[y.toolCallId]=v),y.argsText!==v.argsText)if(v.argsComplete)process.env.NODE_ENV!=="production"&&console.warn("argsText updated after controller was closed:",{previous:v.argsText,next:y.argsText});else{if(!y.argsText.startsWith(v.argsText))throw new Error(`Tool call argsText can only be appended, not updated: ${y.argsText} does not start with ${v.argsText}`);const _=y.argsText.slice(v.argsText.length);v.controller.argsText.append(_);const x=LD(y.argsText);x&&v.controller.argsText.close(),r.current[y.toolCallId]={argsText:y.argsText,hasResult:v.hasResult,argsComplete:x,controller:v.controller}}y.result!==void 0&&!v.hasResult&&(v.controller.setResponse(new ln({result:y.result,artifact:y.artifact,isError:y.isError})),v.controller.close(),r.current[y.toolCallId]={hasResult:!0,argsComplete:!0,argsText:v.argsText,controller:v.controller})}y.messages&&p(y.messages)}})})};p(e.messages),d.current&&(d.current=!1)},[e,l,n]);const f=()=>(o.current.forEach(({reject:p})=>{p(new Error("Tool execution aborted"))}),o.current.clear(),a.current.abort(),a.current=new AbortController,s.current===0?Promise.resolve():new Promise(p=>{u.current.push(p)}));return{reset:()=>{f(),d.current=!0},abort:f,resume:(p,g)=>{const m=o.current.get(p);if(m)o.current.delete(p),i(y=>({...y,[p]:{type:"executing"}})),m.resolve(g);else throw new Error(`Tool call ${p} is not waiting for human input`)}}}class FD{list(){return Promise.resolve({threads:[]})}rename(){return Promise.resolve()}archive(){return Promise.resolve()}unarchive(){return Promise.resolve()}delete(){return Promise.resolve()}initialize(t){return Promise.resolve({remoteId:t,externalId:void 0})}generateTitle(){return Promise.resolve(new ReadableStream)}fetch(t){return Promise.reject(new Error("Thread not found"))}}function BD(e,t){e.commitTasks.forEach(n=>{const i=n.cellIndex,r=t.cells[i];if(r.type!=="effect")throw new Error("Cannot find effect cell");let o=!0;if(r.deps!==void 0&&n.deps!==void 0&&(o=r.deps.length!==n.deps.length||r.deps.some((a,s)=>!Object.is(a,n.deps[s]))),o){if(r.mounted){if(typeof r.deps!=typeof n.deps)throw new Error("tapEffect called with and without dependencies across re-renders");try{r.mounted&&r.cleanup&&r.cleanup()}finally{r.mounted=!1}}const a=n.effect();if(a!==void 0&&typeof a!="function")throw new Error(`An effect function must either return a cleanup function or nothing. Received: ${typeof a}`);r.mounted=!0,r.cleanup=typeof a=="function"?a:void 0,r.deps=n.deps}})}function ZD(e){let t=null;for(let n=e.cells.length-1;n>=0;n--){const i=e.cells[n];if(i?.type==="effect"&&i.mounted&&i.cleanup)try{i.cleanup()}catch(r){t==null&&(t=r)}finally{i.mounted=!1}}if(t!=null)throw t}let to=null;function qD(e,t){e.currentIndex=0;const n=to;to=e;try{if(t(),e.isFirstRender=!1,e.cells.length!==e.currentIndex)throw new Error(`Rendered ${e.currentIndex} hooks but expected ${e.cells.length}. Hooks must be called in the exact same order in every render.`)}finally{to=n}}function qf(){if(!to)throw new Error("No resource fiber available");return to}function uE(e,t){const n=e[cE];if(!n)throw new Error("ResourceElement.type is not a valid Resource");return n(t)}const cE=Symbol("fnSymbol");function su(e,t){return{resource:e,scheduleRerender:t,cells:[],currentIndex:0,renderContext:void 0,isFirstRender:!0,isMounted:!1,isNeverMounted:!0}}function bo(e){e.isMounted=!1,ZD(e)}function _o(e,t){const n={commitTasks:[],props:t,state:void 0};return qD(e,()=>{e.renderContext=n;try{n.state=uE(e.resource,t)}finally{e.renderContext=void 0}}),n}function wo(e,t){e.isMounted=!0,e.isNeverMounted=!1,BD(t,e)}const VD=globalThis.__ASSISTANT_UI_DISABLE_LAYOUT_EFFECT__===!0,fg=VD?k.useEffect:k.useLayoutEffect;function Vf(e){const[,t]=k.useState({}),n=k.useMemo(()=>su(e.type,()=>t({})),[e.type]),i=_o(n,e.props);return fg(()=>()=>bo(n),[n]),fg(()=>{wo(n,i)}),i.state}const Pi=e=>typeof e=="string"?{scope:e.split(".")[0],event:e}:{scope:e.scope,event:e.event},$r=(e,t,n)=>t===e;let Jr;const Fu=()=>{if(Jr)return Jr;const e=()=>({apis:new Map,nextId:0,listeners:new Set});if(typeof window>"u")return Jr=e(),Jr;const t=window.__ASSISTANT_UI_DEVTOOLS_HOOK__;if(t)return Jr=t,t;const n=e();return window.__ASSISTANT_UI_DEVTOOLS_HOOK__=n,Jr=n,n};class wr{static MAX_EVENT_LOGS_PER_API=200;static register(t){const n=Fu();for(const s of n.apis.values())if(s.api===t)return()=>{};const i=n.nextId++,r={api:t,logs:[]},o=t.on?.("*",s=>{const u=n.apis.get(i);u&&(u.logs.push({time:new Date,event:s.event,data:s.payload}),u.logs.length>wr.MAX_EVENT_LOGS_PER_API&&(u.logs=u.logs.slice(-200)),wr.notifyListeners(i))}),a=t.subscribe?.(()=>{wr.notifyListeners(i)});return n.apis.set(i,r),wr.notifyListeners(i),()=>{const s=Fu();s.apis.get(i)&&(o?.(),a?.(),s.apis.delete(i),wr.notifyListeners(i))}}static notifyListeners(t){Fu().listeners.forEach(i=>i(t))}}function Ze(e){const t=n=>({type:t,props:n});return t[cE]=e,t}const HD=e=>{if(e.renderContext)throw new Error("Resource updated during render");if(e.isMounted)e.scheduleRerender();else if(e.isNeverMounted)throw new Error("Resource updated before mount")};function JD(e){const t=qf(),n=t.currentIndex++;if(!t.isFirstRender&&n>=t.cells.length)throw new Error("Rendered more hooks than during the previous render. Hooks must be called in the exact same order in every render.");if(!t.cells[n]){const o={type:"state",value:typeof e=="function"?e():e,set:a=>{const s=o.value,u=typeof a=="function"?a(s):a;Object.is(s,u)||(o.value=u,HD(t))}};t.cells[n]=o}const i=t.cells[n];if(i.type!=="state")throw new Error("Hook order changed between renders");return i}function Tn(e){const t=JD(e);return[t.value,t.set]}function WD(){const e=qf(),t=e.currentIndex++;if(!e.isFirstRender&&t>=e.cells.length)throw new Error("Rendered more hooks than during the previous render. Hooks must be called in the exact same order in every render.");if(!e.cells[t]){const i={type:"effect",mounted:!1};e.cells[t]=i}if(e.cells[t].type!=="effect")throw new Error("Hook order changed between renders");return t}function gt(e,t){const n=qf(),i=WD();n.renderContext.commitTasks.push({effect:e,deps:t,cellIndex:i})}function Si(e){const[t]=Tn(()=>({current:e}));return t}const GD=(e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!Object.is(e[n],t[n]))return!1;return!0},Ie=(e,t)=>{const n=Si();return n.current||(n.current={value:e(),deps:t}),GD(n.current.deps,t)||(n.current.value=e(),n.current.deps=t),n.current.value},KD=(e,t)=>Ie(()=>e,t);function no(e,t){const[n,i]=Tn({}),r=Ie(()=>su(e.type,()=>i({})),[e.type]),o=t?Ie(()=>e.props,t):e.props,a=Ie(()=>_o(r,o),[r,o,n]);return gt(()=>()=>bo(r),[r]),gt(()=>{wo(r,a)},[r,a]),a.state}function An(e){return uE(e.type,e.props)}function dE(e,t,n){const[i,r]=Tn(0),o=KD(()=>r(l=>l+1),[]),[a]=Tn(()=>new Map),s=Ie(()=>t,n),u=Ie(()=>{const l={remove:[],add:[],commit:[],return:{}};for(const c in e){const d=e[c],f=s(d,c);let p=a.get(c);(!p||p.resource!==f.type)&&(p&&l.remove.push(c),p=su(f.type,o),l.add.push([c,p]));const g=_o(p,f.props);l.commit.push([c,g]),l.return[c]=g.state}if(a.size>l.commit.length-l.add.length+l.remove.length)for(const c of a.keys())c in e||l.remove.push(c);return l},[e,s,i]);return gt(()=>()=>{for(const l of a.keys())bo(a.get(l)),a.delete(l)},[]),gt(()=>{for(const l of u.remove)bo(a.get(l)),a.delete(l);for(const[l,c]of u.add)a.set(l,c);for(const[l,c]of u.commit)wo(a.get(l),c)},[u]),u.return}const YD=50;let Sn={schedulers:new Set([]),isScheduled:!1};class XD{_task;_isDirty=!1;constructor(t){this._task=t}get isDirty(){return this._isDirty}markDirty(){this._isDirty=!0,Sn.schedulers.add(this),QD()}runTask(){this._isDirty=!1,this._task()}}const QD=()=>{Sn.isScheduled||(Sn.isScheduled=!0,queueMicrotask(pE))},pE=()=>{try{const e=[];let t=0;for(const n of Sn.schedulers)if(Sn.schedulers.delete(n),!!n.isDirty){if(t++,t>YD)throw new Error("Maximum update depth exceeded. This can happen when a resource repeatedly calls setState inside tapEffect.");try{n.runTask()}catch(i){e.push(i)}}if(e.length>0)throw e.length===1?e[0]:new AggregateError(e,"Errors occurred during flushSync")}finally{Sn.schedulers.clear(),Sn.isScheduled=!1}},nd=e=>{const t=Sn;Sn={schedulers:new Set([]),isScheduled:!0};try{const n=e();return pE(),n}finally{Sn=t}},ez=Ze(e=>{const[,t]=Tn(e.element),n=no(e.element),i=Si(new Set).current,r=Si(n);return gt(()=>{n!==r.current&&(r.current=n,i.forEach(a=>a()))}),Ie(()=>({getState:()=>r.current,subscribe:a=>(i.add(a),()=>i.delete(a)),render:a=>{const s=e.element!==a;e.element=a,e.onRender(s)&&t(a)},unmount:e.onUnmount}),[])}),tz=(e,{mount:t=!0}={})=>{let n=t,i;const r={element:e,onRender:s=>n?s:(n=!0,nd(()=>{s&&(i=_o(a,r)),!o.isDirty&&wo(a,i)}),!1),onUnmount:()=>{if(!n)throw new Error("Resource not mounted");n=!1,bo(a)}},o=new XD(()=>{i=_o(a,r),!(o.isDirty||!n)&&wo(a,i)}),a=su(ez,()=>o.markDirty());return nd(()=>{o.markDirty()}),i.state},ro=Symbol("tap.Context"),fE=e=>({[ro]:e}),hE=(e,t,n)=>{const i=e[ro];e[ro]=t;try{return n()}finally{e[ro]=i}},mE=e=>e[ro],nz=e=>{const t=_e();k.useEffect(()=>{if(e.render)return t.tools().setToolUI(e.toolName,e.render)},[t,e.toolName,e.render]),k.useEffect(()=>{const{toolName:n,render:i,...r}=e,o={tools:{[n]:r}};return t.modelContext().register({getModelContext:()=>o})},[t,e])},rz=e=>{const t=()=>(nz(e),null);return t.unstable_tool=e,t};function hg(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Hf(...e){return t=>{let n=!1;const i=e.map(r=>{const o=hg(r,t);return!n&&typeof o=="function"&&(n=!0),o});if(n)return()=>{for(let r=0;r<i.length;r++){const o=i[r];typeof o=="function"?o():hg(e[r],null)}}}}function Qe(...e){return w.useCallback(Hf(...e),e)}const gE=Ze(e=>{const t=Ie(()=>tz(e,{mount:!1}),[e.type]);return gt(()=>{t.render(e)}),t});class iz{ref;constructor(t){this.ref=t}get(t,n){return this.ref.current[n]}ownKeys(){return Object.keys(this.ref.current)}has(t,n){return n in this.ref.current}getOwnPropertyDescriptor(t,n){return Object.getOwnPropertyDescriptor(this.ref.current,n)}set(){return!1}setPrototypeOf(){return!1}defineProperty(){return!1}deleteProperty(){return!1}preventExtensions(){return!1}}const pn=(e,t)=>{const n=Si(e);gt(()=>{n.current=e});const i=Ie(()=>new Proxy({},new iz(n)),[]),r=t?.key,o=e.getState();return Ie(()=>({key:r,state:o,api:i}),[o,r])},lr=Ze(e=>{const t=Si(e.get);return gt(()=>{t.current=e.get}),Ie(()=>at({source:e.source,query:e.query,get:()=>t.current()}),[e.source,JSON.stringify(e.query)])}),oz=Ze(e=>{const t=no(e.scopeElement);return Ie(()=>[e.fieldName,t],[e.fieldName,t])}),az=Ze(e=>{const{on:t,subscribe:n,...i}=e,r=Si({on:t,subscribe:n});gt(()=>{r.current={on:t,subscribe:n}});const o=dE(i,(a,s)=>oz({fieldName:s,scopeElement:a}),[]);return Ie(()=>{const a=Object.fromEntries(Object.values(o)),{on:s,subscribe:u}=r.current;return s&&(a.on=(l,c)=>s(l,c)),u&&(a.subscribe=l=>u(l)),a},[o])}),vE=fE(null),sz=(e,t)=>hE(vE,e,t),yE=()=>{const e=mE(vE);if(!e)throw new Error("Model context is not available in this context");return e},lz=Ze(({toolkit:e})=>{const[t,n]=Tn(()=>({tools:{}})),i=yE();gt(()=>{if(!e)return;const o=[];for(const[u,l]of Object.entries(e))l.render&&o.push(r(u,l.render));const a=Object.entries(e).reduce((u,[l,c])=>{const{render:d,...f}=c;return u[l]=f,u},{}),s={getModelContext:()=>({tools:a})};return o.push(i.register(s)),()=>{o.forEach(u=>u())}},[e,i]);const r=(o,a)=>(n(s=>({...s,tools:{...s.tools,[o]:[...s.tools[o]??[],a]}})),()=>{n(s=>({...s,tools:{...s.tools,[o]:s.tools[o]?.filter(u=>u!==a)??[]}}))});return pn({getState:()=>t,setToolUI:r})}),uz=Ze(()=>Ie(()=>{const t=new Map;return{on:(n,i)=>{t.has(n)||t.set(n,new Set);const r=t.get(n);return r.add(i),()=>{r.delete(i),r.size===0&&t.delete(n)}},emit:(n,i)=>{const r=t.get(n),o=t.get("*");!r&&!o||queueMicrotask(()=>{if(r)for(const a of r)a(i);if(o)for(const a of o)a({event:n,payload:i})})}}},[])),bE=fE(null),cz=(e,t)=>hE(bE,e,t),Jf=()=>{const e=mE(bE);if(!e)throw new Error("Events context is not available");return e},dz=Ze(()=>{const[e]=Tn(()=>({})),t=new Mf;return pn({getState:()=>e,getModelContext:()=>t.getModelContext(),subscribe:n=>t.subscribe(n),register:n=>t.registerModelContextProvider(n)})}),pz=Ze(({threads:e,modelContext:t,tools:n})=>{const i=An(uz()),{threads:r,tools:o,modelContext:a}=cz(i,()=>{const u=no(t??dz(),[t]);return sz(u.api,()=>({modelContext:u,tools:no(n??lz({}),[n]),threads:no(e,[e])}))}),s=Ie(()=>({threads:r.state,tools:o.state,modelContext:a.state}),[r.state,o.state,a.state]);return pn({getState:()=>s,threads:r.api,tools:o.api,modelContext:a.api,on:i.on})}),fz=e=>{const t=()=>e.getState().api.threads.item("main");return{threads:at({source:"root",query:{},get:()=>e.getState().api.threads}),tools:at({source:"root",query:{},get:()=>e.getState().api.tools}),modelContext:at({source:"root",query:{},get:()=>e.getState().api.modelContext}),thread:at({source:"threads",query:{type:"main"},get:()=>e.getState().api.threads.thread("main")}),threadListItem:at({source:"threads",query:{type:"main"},get:()=>t()}),composer:at({source:"thread",query:{},get:()=>e.getState().api.threads.thread("main").composer}),on(n,i){const{event:r,scope:o}=Pi(n);if(o==="*")return e.getState().api.on(r,i);if($r("thread",o)||$r("thread-list-item",o)||$r("composer",o))return e.getState().api.on(r,a=>{a.threadId===t().getState().id&&i(a)});throw new Error(`Event scope is not available in this component: ${o}`)},subscribe:e.subscribe}},hz=e=>{const t=lu(),n=Vf(gE(pz(e))),i=k.useMemo(()=>fz(n),[n]);return k.useMemo(()=>wE(t,i),[t,i])},at=e=>{const t=e.get;return t.source=e.source,t.query=e.query,t},Ds=()=>()=>{},_E=k.createContext({threads:at({source:null,query:{},get:()=>{throw new Error("Threads is only available inside <AssistantProvider />")}}),tools:at({source:null,query:{},get:()=>{throw new Error("Tools is only available inside <AssistantProvider />")}}),modelContext:at({source:null,query:{},get:()=>{throw new Error("ModelContext is only available inside <AssistantProvider />")}}),threadListItem:at({source:null,query:{},get:()=>{throw new Error("ThreadListItem is only available inside <AssistantProvider />")}}),thread:at({source:null,query:{},get:()=>{throw new Error("Thread is only available inside <AssistantProvider />")}}),composer:at({source:null,query:{},get:()=>{throw new Error("Composer is only available inside <AssistantProvider />")}}),message:at({source:null,query:{},get:()=>{throw new Error("Message is only available inside <ThreadPrimitive.Messages />")}}),part:at({source:null,query:{},get:()=>{throw new Error("Part is only available inside <MessagePrimitive.Parts />")}}),attachment:at({source:null,query:{},get:()=>{throw new Error("Attachment is only available inside <MessagePrimitive.Attachments /> or <ComposerPrimitive.Attachments />")}}),subscribe:Ds,on:e=>{const{scope:t}=Pi(e);throw new Error(`Event scope is not available in this component: ${t}`)}}),lu=()=>k.useContext(_E),Lr=e=>{const t=lu(),n=Vf(az(e));return k.useMemo(()=>wE(t,n),[t,n])},mz=e=>hz(e);function _e(e){return e?mz(e):lu()}const gz=(e,t)=>e===Ds?t:t===Ds?e:(...n)=>{const i=e(...n),r=t(...n);return()=>{i(),r()}},wE=(e,t)=>{const n=t.subscribe;return{...e,...t,subscribe:gz(e.subscribe,n??Ds)}},hr=({api:e,children:t,devToolsVisible:n=!0})=>(k.useEffect(()=>{if(!(!n||!e.subscribe))return wr.register(e)},[e,n]),h.jsx(_E.Provider,{value:e,children:t}));class mg{#e;constructor(t){this.#e=t}get threads(){return this.#e.threads().getState()}get tools(){return this.#e.tools().getState()}get threadListItem(){return this.#e.threadListItem().getState()}get thread(){return this.#e.thread().getState()}get composer(){return this.#e.composer().getState()}get message(){return this.#e.message().getState()}get part(){return this.#e.part().getState()}get attachment(){return this.#e.attachment().getState()}}const ee=e=>{const t=_e(),n=k.useMemo(()=>new mg(t),[t]),i=k.useSyncExternalStore(t.subscribe,()=>e(n),()=>e(n));if(k.useDebugValue(i),i instanceof mg)throw new Error("You tried to return the entire AssistantState. This is not supported due to technical limitations.");return i},Bu=(e,t)=>{const n=_e(),i=k.useRef(t);k.useEffect(()=>{i.current=t});const{scope:r,event:o}=Pi(e);k.useEffect(()=>n.on({scope:r,event:o},a=>i.current(a)),[n,r,o])};function vz(e,t){function n(i){const r=k.useContext(e);if(!i?.optional&&!r)throw new Error(`This component must be used within ${t}.`);return r}return n}function xE(e,t){function n(r){const o=e(r);return o?o[t]:null}function i(r){let o=!1,a;typeof r=="function"?a=r:r&&typeof r=="object"&&(o=!!r.optional,a=r.selector);const s=n({optional:o});return s?a?s(a):s():null}return{[t]:i,[`${t}Store`]:n}}const SE=k.createContext(null),yz=vz(SE,"ThreadPrimitive.Viewport"),{useThreadViewport:xo,useThreadViewportStore:uu}=xE(yz,"useThreadViewport"),IE=e=>{const t={role:"assistant",content:[]};for(const n of e)if(n.role==="tool"){const i=t.content.findIndex(r=>r.type==="tool-call"&&r.toolCallId===n.toolCallId);if(i!==-1){const r=t.content[i];if(n.toolName!==void 0&&r.toolName!==n.toolName)throw new Error(`Tool call name ${n.toolCallId} ${n.toolName} does not match existing tool call ${r.toolName}`);t.content[i]={...r,[Ct]:[...r[Ct]??[],n],result:n.result,artifact:n.artifact,isError:n.isError,messages:n.messages}}else throw new Error(`Tool call ${n.toolCallId} ${n.toolName} not found in assistant message`)}else{const i=n.role,r=(typeof n.content=="string"?[{type:"text",text:n.content}]:n.content).map(o=>({...o,[Ct]:[n]}));switch(i){case"system":case"user":return{...n,content:r};case"assistant":t.content.length===0&&(t.id=n.id,t.createdAt??=n.createdAt,t.status??=n.status,n.attachments&&(t.attachments=[...t.attachments??[],...n.attachments]),n.metadata&&(t.metadata??={},n.metadata.unstable_state&&(t.metadata.unstable_state=n.metadata.unstable_state),n.metadata.unstable_annotations&&(t.metadata.unstable_annotations=[...t.metadata.unstable_annotations??[],...n.metadata.unstable_annotations]),n.metadata.unstable_data&&(t.metadata.unstable_data=[...t.metadata.unstable_data??[],...n.metadata.unstable_data]),n.metadata.steps&&(t.metadata.steps=[...t.metadata.steps??[],...n.metadata.steps]),n.metadata.custom&&(t.metadata.custom={...t.metadata.custom??{},...n.metadata.custom}),n.metadata.submittedFeedback&&(t.metadata.submittedFeedback=n.metadata.submittedFeedback))),t.content.push(...r);break;default:{const o=i;throw new Error(`Unknown message role: ${o}`)}}}return t},kE=(e,t)=>{const n=[];let i=!1,r=!1,o=[],a=[];const s=()=>{a.length&&n.push({inputs:o,outputs:a}),o=[],a=[],i=!1,r=!1};for(const u of e)for(const l of u.outputs)(r&&l.role!=="tool"||!i||l.role==="user"||l.role==="system")&&s(),i=l.role==="assistant"||l.role==="tool",o.at(-1)!==u.input&&o.push(u.input),a.push(l),l.role==="assistant"&&(l.convertConfig?.joinStrategy==="none"||t==="none")&&(r=!0);return s(),n},bz=(e,t,n,i)=>{const r=[];for(const a of e){const s=t(a,i),u=Array.isArray(s)?s:[s],l={input:a,outputs:u};r.push(l)}const o=kE(r);return o.map((a,s)=>{const u=s===o.length-1,l=IE(a.outputs),c=typeof l.content=="object"&&l.content.some(g=>g.type==="tool-call"&&g.result===void 0),d=typeof l.content=="object"&&l.content.some(g=>g.type==="tool-call"&&g.result===void 0),f=ma(u,n,c,d,u?i.error:void 0),p=Ur(l,s.toString(),f);return p[Ct]=a.inputs,p})},_z=({callback:e,messages:t,isRunning:n,joinStrategy:i,metadata:r})=>{const o=k.useMemo(()=>({metadata:r??{},callback:e,callbackCache:new WeakMap,chunkCache:new WeakMap,converterCache:new td}),[e,r]);return k.useMemo(()=>{const a=[];for(const l of t){let c=o.callbackCache.get(l);if(!c){const d=o.callback(l,o.metadata),f=Array.isArray(d)?d:[d];c={input:l,outputs:f},o.callbackCache.set(l,c)}a.push(c)}const s=kE(a,i).map(l=>{const c=l.outputs[0];if(!c)return l;const d=o.chunkCache.get(c);return d&&gg(d.outputs,l.outputs)?d:(o.chunkCache.set(c,l),l)}),u=o.converterCache.convertMessages(s,(l,c,d)=>{const f=d===s.length-1,p=IE(c.outputs),g=typeof p.content=="object"&&p.content.some(_=>_.type==="tool-call"&&_.result===void 0),m=typeof p.content=="object"&&p.content.some(_=>_.type==="tool-call"&&_.result===void 0),y=ma(f,n,g,m,f?o.metadata.error:void 0);if(l&&(l.role!=="assistant"||!Vk(l.status)||l.status===y)){const _=Tr(l);if(gg(_,c.inputs))return l}const v=Ur(p,d.toString(),y);return v[Ct]=c.inputs,v});return u[Ct]=t,u},[o,t,n,i])},gg=(e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0},Fr=e=>{const[,t]=Tn(e.getState);return gt(()=>(t(e.getState()),e.subscribe(()=>{t(e.getState())})),[e]),e.getState()},wz=Ze(({runtime:e})=>{const t=Fr(e),n=Jf();return gt(()=>{const i=[],r=["switched-to","switched-away"];for(const o of r){const a=e.unstable_on(o,()=>{n.emit(`thread-list-item.${o}`,{threadId:e.getState().id})});i.push(a)}return()=>{for(const o of i)o()}},[e,n]),pn({getState:()=>t,switchTo:e.switchTo,rename:e.rename,archive:e.archive,unarchive:e.unarchive,delete:e.delete,generateTitle:e.generateTitle,initialize:e.initialize,detach:e.detach,__internal_getRuntime:()=>e},{key:t.id})}),So=e=>{const t=Ie(()=>Object.fromEntries(e),[e]),n=dE(t,o=>o,[]),i=Ie(()=>Object.keys(n),[n]);return{state:Ie(()=>{const o=new Array(i.length);for(let a=0;a<i.length;a++)o[a]=n[i[a]].state;return o},[i,n]),api:o=>{const a="index"in o?n[i[o.index]]?.api:n[o.key]?.api;if(!a)throw new Error(`tapLookupResources: Resource not found for lookup: ${JSON.stringify(o)}`);return a}}},EE=Ze(({runtime:e})=>{const t=Fr(e);return pn({getState:()=>t,remove:e.remove,__internal_getRuntime:()=>e},{key:t.id})}),xz=Ze(({runtime:e,index:t})=>{const n=Ie(()=>e.getAttachmentByIndex(t),[e,t]);return An(EE({runtime:n}))}),TE=Ze(({threadIdRef:e,messageIdRef:t,runtime:n})=>{const i=Fr(n),r=Jf();gt(()=>{const s=[],u=["send","attachment-add"];for(const l of u){const c=n.unstable_on(l,()=>{r.emit(`composer.${l}`,{threadId:e.current,...t&&{messageId:t.current}})});s.push(c)}return()=>{for(const l of s)l()}},[n,r,e,t]);const o=So(i.attachments.map((s,u)=>[s.id,xz({runtime:n,index:u})])),a=Ie(()=>({text:i.text,role:i.role,attachments:o.state,runConfig:i.runConfig,isEditing:i.isEditing,canCancel:i.canCancel,attachmentAccept:i.attachmentAccept,isEmpty:i.isEmpty,type:i.type??"thread"}),[i,o.state]);return pn({getState:()=>a,setText:n.setText,setRole:n.setRole,setRunConfig:n.setRunConfig,addAttachment:n.addAttachment,reset:n.reset,clearAttachments:n.clearAttachments,send:n.send,cancel:n.cancel,beginEdit:n.beginEdit??(()=>{throw new Error("beginEdit is not supported in this runtime")}),attachment:s=>"id"in s?o.api({key:s.id}):o.api(s),__internal_getRuntime:()=>n})}),Sz=Ze(({runtime:e})=>{const t=Fr(e);return pn({getState:()=>t,addToolResult:i=>e.addToolResult(i),resumeToolCall:i=>e.resumeToolCall(i),__internal_getRuntime:()=>e},{key:t.type==="tool-call"?`toolCallId-${t.toolCallId}`:void 0})}),Iz=Ze(({runtime:e,index:t})=>{const n=Ie(()=>e.getAttachmentByIndex(t),[e,t]);return An(EE({runtime:n}))}),kz=Ze(({runtime:e,index:t})=>{const n=Ie(()=>e.getMessagePartByIndex(t),[e,t]);return An(Sz({runtime:n}))}),Ez=Ze(({runtime:e,threadIdRef:t})=>{const n=Fr(e),[i,r]=Tn(!1),[o,a]=Tn(!1),s=Ie(()=>({get current(){return e.getState().id}}),[e]),u=An(TE({runtime:e.composer,threadIdRef:t,messageIdRef:s})),l=So(n.content.map((f,p)=>["toolCallId"in f&&f.toolCallId!=null?`toolCallId-${f.toolCallId}`:`index-${p}`,kz({runtime:e,index:p})])),c=So(n.attachments?.map((f,p)=>[f.id,Iz({runtime:e,index:p})])??[]),d=Ie(()=>({...n,parts:l.state,composer:u.state,isCopied:i,isHovering:o}),[n,l.state,u.state,i,o]);return pn({getState:()=>d,composer:u.api,reload:f=>e.reload(f),speak:()=>e.speak(),stopSpeaking:()=>e.stopSpeaking(),submitFeedback:f=>e.submitFeedback(f),switchToBranch:f=>e.switchToBranch(f),getCopyText:()=>e.unstable_getCopyText(),part:f=>"index"in f?l.api({index:f.index}):l.api({key:`toolCallId-${f.toolCallId}`}),attachment:f=>"id"in f?c.api({key:f.id}):c.api(f),setIsCopied:r,setIsHovering:a,__internal_getRuntime:()=>e},{key:n.id})}),Tz=Ze(({runtime:e,id:t,threadIdRef:n})=>{const i=Ie(()=>e.getMessageById(t),[e,t]);return An(Ez({runtime:i,threadIdRef:n}))}),$z=Ze(({runtime:e})=>{const t=Fr(e),n=Jf();gt(()=>{const s=[],u=["run-start","run-end","initialize","model-context-update"];for(const l of u){const c=e.unstable_on(l,()=>{const d=e.getState()?.threadId||"unknown";n.emit(`thread.${l}`,{threadId:d})});s.push(c)}return()=>{for(const l of s)l()}},[e]);const i=Ie(()=>({get current(){return e.getState().threadId}}),[e]),r=An(TE({runtime:e.composer,threadIdRef:i})),o=So(t.messages.map(s=>[s.id,Tz({runtime:e,id:s.id,threadIdRef:i})])),a=Ie(()=>({isEmpty:o.state.length===0&&!t.isLoading,isDisabled:t.isDisabled,isLoading:t.isLoading,isRunning:t.isRunning,capabilities:t.capabilities,state:t.state,suggestions:t.suggestions,extras:t.extras,speech:t.speech,composer:r.state,messages:o.state}),[t,o,r.state]);return pn({getState:()=>a,composer:r.api,append:e.append,startRun:e.startRun,unstable_resumeRun:e.unstable_resumeRun,cancelRun:e.cancelRun,getModelContext:e.getModelContext,export:e.export,import:e.import,reset:e.reset,stopSpeaking:e.stopSpeaking,startVoice:async()=>{throw new Error("startVoice is not supported in this runtime")},stopVoice:async()=>{throw new Error("stopVoice is not supported in this runtime")},message:s=>"id"in s?o.api({key:s.id}):o.api(s),__internal_getRuntime:()=>e})}),Cz=Ze(({runtime:e,id:t})=>{const n=Ie(()=>e.getItemById(t),[e,t]);return An(wz({runtime:n}))}),Az=Ze(({runtime:e,__internal_assistantRuntime:t})=>{const n=Fr(e),i=An($z({runtime:e.main})),r=So(Object.keys(n.threadItems).map(a=>[a,Cz({runtime:e,id:a})])),o=Ie(()=>({mainThreadId:n.mainThreadId,newThreadId:n.newThread??null,isLoading:n.isLoading,threadIds:n.threads,archivedThreadIds:n.archivedThreads,threadItems:r.state,main:i.state}),[n,r.state,i.state]);return pn({getState:()=>o,thread:()=>i.api,item:a=>{if(a==="main")return r.api({key:o.mainThreadId});if("id"in a)return r.api({key:a.id});const{index:s,archived:u=!1}=a,l=u?o.archivedThreadIds[s]:o.threadIds[s];return r.api({key:l})},switchToThread:a=>{e.switchToThread(a)},switchToNewThread:()=>{e.switchToNewThread()},__internal_getAssistantRuntime:()=>t})}),Pz=Ze(e=>{const t=yE();return gt(()=>e.registerModelContextProvider(t),[e,t]),An(Az({runtime:e.threads,__internal_assistantRuntime:e}))}),Zu=e=>{const t=new Map,n=()=>{let i=0;for(const r of t.values())i+=r;e(i)};return{register:()=>{const i=Symbol();return t.set(i,0),{setHeight:r=>{t.get(i)!==r&&(t.set(i,r),n())},unregister:()=>{t.delete(i),n()}}}}},Rz=(e={})=>{const t=new Set,n=Zu(a=>{o.setState({height:{...o.getState().height,viewport:a}})}),i=Zu(a=>{o.setState({height:{...o.getState().height,inset:a}})}),r=Zu(a=>{o.setState({height:{...o.getState().height,userMessage:a}})}),o=ci.create(()=>({isAtBottom:!0,scrollToBottom:({behavior:a="auto"}={})=>{for(const s of t)s({behavior:a})},onScrollToBottom:a=>(t.add(a),()=>{t.delete(a)}),turnAnchor:e.turnAnchor??"bottom",height:{viewport:0,inset:0,userMessage:0},registerViewport:n.register,registerContentInset:i.register,registerUserMessageHeight:r.register}));return o},Io=e=>e,Oz=e=>{const t=uu({optional:!0}),[n]=k.useState(()=>Rz(e));return k.useEffect(()=>t?.getState().onScrollToBottom(()=>{n.getState().scrollToBottom()}),[t,n]),k.useEffect(()=>{if(t)return n.subscribe(i=>{t.getState().isAtBottom!==i.isAtBottom&&Io(t).setState({isAtBottom:i.isAtBottom})})},[n,t]),k.useEffect(()=>{const i={turnAnchor:e.turnAnchor??"bottom"};n.getState().turnAnchor!==i.turnAnchor&&Io(n).setState(i)},[n,e.turnAnchor]),n},$E=({children:e,options:t={}})=>{const n=Oz(t),[i]=k.useState(()=>({useThreadViewport:n}));return h.jsx(SE.Provider,{value:i,children:e})},Nz=e=>e._core?.RenderComponent,jz=({children:e,runtime:t})=>{const n=_e({threads:Pz(t)}),i=Nz(t);return h.jsxs(hr,{api:n,children:[i&&h.jsx(i,{}),h.jsx($E,{children:e})]})},CE=k.memo(jz),Mz=({index:e,archived:t,children:n})=>{const i=_e(),r=Lr({threadListItem:lr({source:"threads",query:{type:"index",index:e,archived:t},get:()=>i.threads().item({index:e,archived:t})}),on(o,a){const s=()=>i.threads().item({index:e,archived:t}),{event:u,scope:l}=Pi(o);return $r("thread-list-item",l)?i.on({scope:"*",event:u},c=>{c.threadId===s().getState().id&&a(c)}):i.on(o,a)}});return h.jsx(hr,{api:r,children:n})},Dz=({id:e,children:t})=>{const n=_e(),i=Lr({threadListItem:lr({source:"threads",query:{type:"id",id:e},get:()=>n.threads().item({id:e})}),on(r,o){const a=()=>n.threads().item({id:e}),{event:s,scope:u}=Pi(r);return $r("thread-list-item",u)?n.on({scope:"*",event:s},l=>{l.threadId===a().getState().id&&o(l)}):n.on(r,o)}});return h.jsx(hr,{api:i,children:t})},zz=({index:e,children:t})=>{const n=_e(),i=Lr({message:lr({source:"thread",query:{type:"index",index:e},get:()=>n.thread().message({index:e})}),composer:lr({source:"message",query:{},get:()=>n.thread().message({index:e}).composer}),on(r,o){const a=()=>n.thread().message({index:e}),{event:s,scope:u}=Pi(r);return!$r("composer",u)&&!$r("message",u)?n.on(r,o):n.on({scope:"thread",event:s},l=>{l.messageId===a().getState().id&&o(l)})}});return h.jsx(hr,{api:i,children:t})},Uz=({index:e,children:t})=>{const n=_e(),i=Lr({part:lr({source:"message",query:{type:"index",index:e},get:()=>n.message().part({index:e})})});return h.jsx(hr,{api:i,children:t})},Lz=({index:e,children:t})=>{const n=_e(),i=Lr({attachment:lr({source:"message",query:{type:"index",index:e},get:()=>n.message().attachment({index:e})})});return h.jsx(hr,{api:i,children:t})},Fz=({index:e,children:t})=>{const n=_e(),i=Lr({attachment:lr({source:"composer",query:{type:"index",index:e},get:()=>n.composer().attachment({index:e})})});return h.jsx(hr,{api:i,children:t})},Bz=Ze(({text:e,isRunning:t})=>{const n=Ie(()=>({type:"text",text:e,status:t?{type:"running"}:{type:"complete"}}),[e,t]);return pn({getState:()=>n,addToolResult:()=>{throw new Error("Not supported")},resumeToolCall:()=>{throw new Error("Not supported")}})}),Zz=({text:e,isRunning:t=!1,children:n})=>{const i=Vf(gE(Bz({text:e,isRunning:t}))),r=Lr({part:lr({source:"root",query:{},get:()=>i.getState().api}),subscribe:i.subscribe});return h.jsx(hr,{api:r,children:n})},qz=e=>{const t={useThreadMessages:({messages:n,isRunning:i,joinStrategy:r,metadata:o})=>_z({callback:e,messages:n,isRunning:i,joinStrategy:r,metadata:o}),toThreadMessages:(n,i=!1,r={})=>bz(n,e,i,r),toOriginalMessages:n=>{const i=Tr(n);if(i.length===0)throw new Error("No original messages found");return i},toOriginalMessage:n=>t.toOriginalMessages(n)[0],useOriginalMessage:()=>t.useOriginalMessages()[0],useOriginalMessages:()=>{const n=_e(),i=ee(a=>{if(n.part.source)return Tr(a.part)}),r=ee(({message:a})=>Tr(a)),o=i??r;if(o.length===0)throw new Error("No original messages found");return o}};return t},vg=e=>{try{const n=e.split(".")[1];if(!n)throw new Error("Invalid JWT format");let i=n.replace(/-/g,"+").replace(/_/g,"/");for(;i.length%4!==0;)i+="=";const r=atob(i),a=JSON.parse(r).exp;if(!a||typeof a!="number")throw new Error('JWT does not contain a valid "exp" field');return a*1e3}catch(t){throw new Error(`Unable to determine the token expiry: ${t}`)}};class AE{strategy="jwt";cachedToken=null;tokenExpiry=null;#e;constructor(t){this.#e=t}async getAuthHeaders(){const t=Date.now();if(this.cachedToken&&this.tokenExpiry&&this.tokenExpiry-t>30*1e3)return{Authorization:`Bearer ${this.cachedToken}`};const n=await this.#e();return n?(this.cachedToken=n,this.tokenExpiry=vg(n),{Authorization:`Bearer ${n}`}):!1}readAuthHeaders(t){const n=t.get("Authorization");if(!n)return;const[i,r]=n.split(" ");if(i!=="Bearer"||!r)throw new Error("Invalid auth header received");this.cachedToken=r,this.tokenExpiry=vg(r)}}class Vz{strategy="api-key";#e;#t;#n;constructor(t,n,i){this.#e=t,this.#t=n,this.#n=i}async getAuthHeaders(){return{Authorization:`Bearer ${this.#e}`,"Aui-User-Id":this.#t,"Aui-Workspace-Id":this.#n}}readAuthHeaders(){}}const Ba="aui:refresh_token";class Hz{strategy="anon";baseUrl;jwtStrategy;constructor(t){this.baseUrl=t,this.jwtStrategy=new AE(async()=>{const n=Date.now(),i=localStorage.getItem(Ba),r=i?JSON.parse(i):void 0;if(r)if(new Date(r.expires_at).getTime()-n>30*1e3){const c=await fetch(`${this.baseUrl}/v1/auth/tokens/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refresh_token:r.token})});if(c.ok){const d=await c.json(),{access_token:f,refresh_token:p}=d;return p&&localStorage.setItem(Ba,JSON.stringify(p)),f}}else localStorage.removeItem(Ba);const o=await fetch(`${this.baseUrl}/v1/auth/tokens/anonymous`,{method:"POST"});if(!o.ok)return null;const a=await o.json(),{access_token:s,refresh_token:u}=a;return!s||!u?null:(localStorage.setItem(Ba,JSON.stringify(u)),s)})}async getAuthHeaders(){return this.jwtStrategy.getAuthHeaders()}readAuthHeaders(t){this.jwtStrategy.readAuthHeaders(t)}}class Jz extends Error{constructor(t){super(t),this.name="APIError"}}class Wz{_auth;_baseUrl;constructor(t){if("authToken"in t)this._baseUrl=t.baseUrl,this._auth=new AE(t.authToken);else if("apiKey"in t)this._baseUrl="https://backend.assistant-api.com",this._auth=new Vz(t.apiKey,t.userId,t.workspaceId);else if("anonymous"in t)this._baseUrl=t.baseUrl,this._auth=new Hz(t.baseUrl);else throw new Error("Invalid configuration: Must provide authToken, apiKey, or anonymous configuration")}async initializeAuth(){return!!this._auth.getAuthHeaders()}async makeRawRequest(t,n={}){const i=await this._auth.getAuthHeaders();if(!i)throw new Error("Authorization failed");const r={...i,...n.headers,"Content-Type":"application/json"},o=new URLSearchParams;if(n.query)for(const[u,l]of Object.entries(n.query))l!==!1&&(l===!0?o.set(u,"true"):o.set(u,l.toString()));const a=new URL(`${this._baseUrl}/v1${t}`);a.search=o.toString();const s=await fetch(a,{method:n.method??"GET",headers:r,body:n.body?JSON.stringify(n.body):null});if(this._auth.readAuthHeaders(s.headers),!s.ok){const u=await s.text();try{const l=JSON.parse(u);throw new Jz(l.message)}catch{throw new Error(`Request failed with status ${s.status}, ${u}`)}}return s}async makeRequest(t,n={}){return(await this.makeRawRequest(t,n)).json()}}class Gz{cloud;constructor(t){this.cloud=t}async create(){return this.cloud.makeRequest("/auth/tokens",{method:"POST"})}}class Kz{cloud;constructor(t){this.cloud=t}__internal_getAssistantOptions(t){return{api:`${this.cloud._baseUrl}/v1/runs/stream`,headers:async()=>{const n=await this.cloud._auth.getAuthHeaders();if(!n)throw new Error("Authorization failed");return{...n,Accept:"text/plain"}},body:{assistant_id:t,response_format:"vercel-ai-data-stream/v1",thread_id:"unstable_todo"}}}async stream(t){const n=await this.cloud.makeRawRequest("/runs/stream",{method:"POST",headers:{Accept:"text/plain"},body:t});return Qc.fromResponse(n,new uD)}}class Yz{cloud;constructor(t){this.cloud=t}async list(t,n){return this.cloud.makeRequest(`/threads/${encodeURIComponent(t)}/messages`,{query:n})}async create(t,n){return this.cloud.makeRequest(`/threads/${encodeURIComponent(t)}/messages`,{method:"POST",body:n})}}class Xz{cloud;messages;constructor(t){this.cloud=t,this.messages=new Yz(t)}async list(t){return this.cloud.makeRequest("/threads",{query:t})}async get(t){return this.cloud.makeRequest(`/threads/${encodeURIComponent(t)}`)}async create(t){return this.cloud.makeRequest("/threads",{method:"POST",body:t})}async update(t,n){return this.cloud.makeRequest(`/threads/${encodeURIComponent(t)}`,{method:"PUT",body:n})}async delete(t){return this.cloud.makeRequest(`/threads/${encodeURIComponent(t)}`,{method:"DELETE"})}}class Qz{cloud;constructor(t){this.cloud=t}async pdfToImages(t){return this.cloud.makeRequest("/files/pdf-to-images",{method:"POST",body:t})}async generatePresignedUploadUrl(t){return this.cloud.makeRequest("/files/attachments/generate-presigned-upload-url",{method:"POST",body:t})}}class e4{threads;auth;runs;files;constructor(t){const n=new Wz(t);this.threads=new Xz(n),this.auth={tokens:new Gz(n)},this.runs=new Kz(n),this.files=new Qz(n)}}function rd(e,t=0){return t>100?!1:e===null||typeof e=="string"||typeof e=="boolean"?!0:typeof e=="number"?!Number.isNaN(e)&&Number.isFinite(e):Array.isArray(e)?e.every(n=>rd(n,t+1)):typeof e=="object"?Object.entries(e).every(([n,i])=>typeof n=="string"&&rd(i,t+1)):!1}const t4=e=>({role:e.role,content:e.content.map(t=>{const n=t.type;switch(n){case"text":return{type:"text",text:t.text};case"reasoning":return{type:"reasoning",text:t.text};case"source":return{type:"source",sourceType:t.sourceType,id:t.id,url:t.url,...t.title?{title:t.title}:void 0};case"tool-call":return rd(t.result)||console.warn(`tool-call result is not JSON! ${JSON.stringify(t)}`),{type:"tool-call",toolCallId:t.toolCallId,toolName:t.toolName,...JSON.stringify(t.args)===t.argsText?{args:t.args}:{argsText:t.argsText},...t.result?{result:t.result}:{},...t.isError?{isError:!0}:{}};default:{const i=n;throw new Error(`Message part type not supported by aui/v0: ${i}`)}}}),metadata:e.metadata,...e.status?{status:e.status?.type==="running"?{type:"incomplete",reason:"cancelled"}:e.status}:void 0}),n4=e=>{const t=e.content,n=Ur({id:e.id,createdAt:e.created_at,...t},e.id,{type:"complete",reason:"unknown"});return{parentId:e.parent_id,message:n}},qu=new WeakMap;class r4{parent;formatAdapter;constructor(t,n){this.parent=t,this.formatAdapter=n}async append(t){const n=this.formatAdapter.encode(t),i=this.formatAdapter.getId(t.message);return this.parent._appendWithFormat(t.parentId,i,this.formatAdapter.format,n)}async load(){return this.parent._loadWithFormat(this.formatAdapter.format,t=>this.formatAdapter.decode(t))}}class i4{cloudRef;store;constructor(t,n){this.cloudRef=t,this.store=n}get _getIdForLocalId(){return qu.has(this.store.threadListItem())||qu.set(this.store.threadListItem(),{}),qu.get(this.store.threadListItem())}withFormat(t){return new r4(this,t)}async append({parentId:t,message:n}){const{remoteId:i}=await this.store.threadListItem().initialize(),r=this.cloudRef.current.threads.messages.create(i,{parent_id:t?await this._getIdForLocalId[t]??t:null,format:"aui/v0",content:t4(n)}).then(({message_id:o})=>(this._getIdForLocalId[n.id]=o,o));return this._getIdForLocalId[n.id]=r,r.then(()=>{})}async load(){const t=this.store.threadListItem().getState().remoteId;if(!t)return{messages:[]};const{messages:n}=await this.cloudRef.current.threads.messages.list(t,{format:"aui/v0"});return{messages:n.filter(r=>r.format==="aui/v0").map(n4).reverse()}}async _appendWithFormat(t,n,i,r){const{remoteId:o}=await this.store.threadListItem().initialize(),a=this.cloudRef.current.threads.messages.create(o,{parent_id:t?await this._getIdForLocalId[t]??t:null,format:i,content:r}).then(({message_id:s})=>(this._getIdForLocalId[n]=s,s));return this._getIdForLocalId[n]=a,a.then(()=>{})}async _loadWithFormat(t,n){const i=this.store.threadListItem().getState().remoteId;if(!i)return{messages:[]};const{messages:r}=await this.cloudRef.current.threads.messages.list(i,{format:t});return{messages:r.filter(o=>o.format===t).map(o=>n({id:o.id,parent_id:o.parent_id,format:o.format,content:o.content})).reverse()}}}const o4=e=>{const t=_e(),[n]=k.useState(()=>new i4(e,t));return n},yg=typeof process<"u"&&process?.env?.NEXT_PUBLIC_ASSISTANT_BASE_URL,Vu=yg?new e4({baseUrl:yg,anonymous:!0}):void 0,a4=e=>{const t=k.useRef(e);k.useEffect(()=>{t.current=e},[e]);const n=k.useCallback(function({children:o}){const a=o4({get current(){return t.current.cloud??Vu}}),s=t.current.cloud??Vu,u=k.useMemo(()=>new CD(s),[s]),l=k.useMemo(()=>({history:a,attachments:u}),[a,u]);return h.jsx(Zf,{adapters:l,children:o})},[]),i=e.cloud??Vu;return i?{list:async()=>{const{threads:r}=await i.threads.list();return{threads:r.map(o=>({status:o.is_archived?"archived":"regular",remoteId:o.id,title:o.title,externalId:o.external_id??void 0}))}},initialize:async()=>{const o=await(e.create?.()??Promise.resolve()),a=o?o.externalId:void 0,{thread_id:s}=await i.threads.create({last_message_at:new Date,external_id:a});return{externalId:a,remoteId:s}},rename:async(r,o)=>i.threads.update(r,{title:o}),archive:async r=>i.threads.update(r,{is_archived:!0}),unarchive:async r=>i.threads.update(r,{is_archived:!1}),delete:async r=>(await e.delete?.(r),i.threads.delete(r)),generateTitle:async(r,o)=>i.runs.stream({thread_id:r,assistant_id:"system/thread_title",messages:o}),fetch:async r=>{const o=await i.threads.get(r);return{status:o.is_archived?"archived":"regular",remoteId:o.id,title:o.title,externalId:o.external_id??void 0}},unstable_Provider:n}:new FD};class Wf{_core;threads;get threadList(){return this.threads}_thread;constructor(t){this._core=t,this.threads=new TD(t.threads),this._thread=this.threads.main,this.__internal_bindMethods()}__internal_bindMethods(){this.switchToNewThread=this.switchToNewThread.bind(this),this.switchToThread=this.switchToThread.bind(this),this.registerModelContextProvider=this.registerModelContextProvider.bind(this),this.registerModelConfigProvider=this.registerModelConfigProvider.bind(this),this.reset=this.reset.bind(this)}get thread(){return this._thread}switchToNewThread(){return this._core.threads.switchToNewThread()}switchToThread(t){return this._core.threads.switchToThread(t)}registerModelContextProvider(t){return this._core.registerModelContextProvider(t)}registerModelConfigProvider(t){return this.registerModelContextProvider(t)}reset({initialMessages:t}={}){return this._core.threads.getMainThreadRuntimeCore().import(Lf.fromArray(t??[]))}}const s4=e=>{const{cloud:t,initialMessages:n,maxSteps:i,adapters:r,unstable_humanToolNames:o,...a}=e;return{localRuntimeOptions:{cloud:t,initialMessages:n,maxSteps:i,adapters:r,unstable_humanToolNames:o},otherOptions:a}};function Ot(e){const t=w.useRef(e);return w.useEffect(()=>{t.current=e}),w.useMemo(()=>(...n)=>t.current?.(...n),[])}const PE=k.createContext(null),l4=e=>({useSmoothStatus:ci.create(()=>e)}),u4=({children:e})=>{const t=RE({optional:!0}),n=_e(),[i]=k.useState(()=>l4(n.part().getState().status));return t?e:h.jsx(PE.Provider,{value:i,children:e})},c4=e=>{const t=k.forwardRef((n,i)=>h.jsx(u4,{children:h.jsx(e,{...n,ref:i})}));return t.displayName=e.displayName,t};function RE(e){const t=k.useContext(PE);if(!e?.optional&&!t)throw new Error("This component must be used within a SmoothContextProvider.");return t}const{useSmoothStatus:d4,useSmoothStatusStore:p4}=xE(RE,"useSmoothStatus");class f4{currentText;setText;animationFrameId=null;lastUpdateTime=Date.now();targetText="";constructor(t,n){this.currentText=t,this.setText=n}start(){this.animationFrameId===null&&(this.lastUpdateTime=Date.now(),this.animate())}stop(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}animate=()=>{const t=Date.now();let i=t-this.lastUpdateTime;const r=this.targetText.length-this.currentText.length,o=Math.min(5,250/r);let a=0;for(;i>=o&&a<r;)a++,i-=o;a!==r?this.animationFrameId=requestAnimationFrame(this.animate):this.animationFrameId=null,a!==0&&(this.currentText=this.targetText.slice(0,this.currentText.length+a),this.lastUpdateTime=t-i,this.setText(this.currentText))}}const Hu=Object.freeze({type:"running"}),OE=(e,t=!1)=>{const{text:n}=e,i=ee(({message:c})=>c.id),r=k.useRef(i),[o,a]=k.useState(n),s=p4({optional:!0}),u=Ot(c=>{if(a(c),s){const d=o!==c||e.status.type==="running"?Hu:e.status;Io(s).setState(d,!0)}});k.useEffect(()=>{if(s){const c=t&&(o!==n||e.status.type==="running")?Hu:e.status;Io(s).setState(c,!0)}},[s,t,n,o,e.status]);const[l]=k.useState(new f4(n,u));return k.useEffect(()=>{if(!t){l.stop();return}if(r.current!==i||!n.startsWith(l.targetText)){r.current=i,u(n),l.currentText=n,l.targetText=n,l.stop();return}l.targetText=n,l.start()},[u,l,i,t,n]),k.useEffect(()=>()=>{l.stop()},[l]),k.useMemo(()=>t?{type:"text",text:o,status:n===o?e.status:Hu}:e,[t,o,e,n])},NE=Object.freeze(Object.defineProperty({__proto__:null,AssistantRuntimeImpl:Wf,BaseAssistantRuntimeCore:Df,CompositeContextProvider:Mf,DefaultThreadComposerRuntimeCore:Zk,MessageRepository:Ff,ThreadRuntimeImpl:oE,fromThreadMessageLike:Ur,generateId:ha,getAutoStatus:ma,splitLocalRuntimeOptions:s4,useSmooth:OE,useSmoothStatus:d4,useToolInvocations:lE,withSmoothContextProvider:c4},Symbol.toStringTag,{value:"Module"}));class h4 extends iu{useRuntimeHook;instances=new Map;useAliveThreadsKeysChanged=ci.create(()=>({}));constructor(t){super(),this.useRuntimeHook=ci.create(()=>({useRuntime:t}))}startThreadRuntime(t){return this.instances.has(t)||(this.instances.set(t,{}),this.useAliveThreadsKeysChanged.setState({},!0)),new Promise((n,i)=>{const r=()=>{const a=this.instances.get(t);if(!a)o(),i(new Error("Thread was deleted before runtime was started"));else if(a.runtime)o(),n(a.runtime);else return},o=this.subscribe(r);r()})}getThreadRuntimeCore(t){const n=this.instances.get(t);if(n)return n.runtime}stopThreadRuntime(t){this.instances.delete(t),this.useAliveThreadsKeysChanged.setState({},!0)}setRuntimeHook(t){this.useRuntimeHook.getState().useRuntime!==t&&this.useRuntimeHook.setState({useRuntime:t},!0)}_InnerActiveThreadProvider=({threadId:t})=>{const{useRuntime:n}=this.useRuntimeHook(),i=n(),r=i.thread.__internal_threadBinding,o=k.useCallback(()=>{const u=this.instances.get(t);if(!u)throw new Error("Thread not found. This is a bug in assistant-ui.");u.runtime=r.getState(),this._notifySubscribers()},[t,r]),a=k.useRef(!1);a.current||o(),k.useEffect(()=>(a.current=!0,o(),r.outerSubscribe(o)),[r,o]);const s=_e();return k.useEffect(()=>i.threads.main.unstable_on("initialize",()=>{if(s.threadListItem().getState().status==="new"){s.threadListItem().initialize();const l=i.thread.unstable_on("run-end",()=>{l(),s.threadListItem().generateTitle()})}}),[i,s]),null};_OuterActiveThreadProvider=k.memo(({threadId:t,provider:n})=>h.jsx(Dz,{id:t,children:h.jsx(n,{children:h.jsx(this._InnerActiveThreadProvider,{threadId:t})})}));__internal_RenderThreadRuntimes=({provider:t})=>(this.useAliveThreadsKeysChanged(),Array.from(this.instances.keys()).map(n=>h.jsx(this._OuterActiveThreadProvider,{threadId:n,provider:t},n)))}const Je=new Error("This is the empty thread, a placeholder for the main thread. You cannot perform any actions on this thread instance. This error is probably because you tried to call a thread method in your render function. Call the method inside a `useEffect` hook instead."),m4={getMessageById(){},getBranches(){return[]},switchToBranch(){throw Je},append(){throw Je},startRun(){throw Je},resumeRun(){throw Je},cancelRun(){throw Je},addToolResult(){throw Je},resumeToolCall(){throw Je},speak(){throw Je},stopSpeaking(){throw Je},submitFeedback(){throw Je},getModelContext(){return{}},unstable_loadExternalState(){throw Je},composer:{attachments:[],attachmentAccept:"*",async addAttachment(){throw Je},async removeAttachment(){throw Je},isEditing:!0,canCancel:!1,isEmpty:!0,text:"",setText(){throw Je},role:"user",setRole(){throw Je},runConfig:{},setRunConfig(){throw Je},async reset(){},async clearAttachments(){},send(){throw Je},cancel(){},subscribe(){return()=>{}},unstable_on(){return()=>{}}},getEditComposer(){},beginEdit(){throw Je},speech:void 0,capabilities:{switchToBranch:!1,switchBranchDuringRun:!1,edit:!1,reload:!1,cancel:!1,unstable_copy:!1,speech:!1,attachments:!1,feedback:!1},isDisabled:!1,isLoading:!1,messages:[],state:null,suggestions:[],extras:void 0,subscribe(){return()=>{}},import(){throw Je},export(){return{messages:[]}},reset(){throw Je},unstable_on(){return()=>{}}},bg=(e,t,n)=>n.reduce((i,r)=>r?.(i,t)??i,e);class g4 extends iu{_pendingTransforms=[];_baseValue;_cachedValue;constructor(t){super(),this._baseValue=t,this._cachedValue=t}_updateState(){this._cachedValue=this._pendingTransforms.reduce((t,n)=>bg(t,n.task,[n.loading,n.optimistic]),this._baseValue),this._notifySubscribers()}get baseValue(){return this._baseValue}get value(){return this._cachedValue}update(t){this._baseValue=t,this._updateState()}async optimisticUpdate(t){const n=t.execute(),i={...t,task:n};try{this._pendingTransforms.push(i),this._updateState();const r=await n;return this._baseValue=bg(this._baseValue,r,[t.optimistic,t.then]),r}finally{const r=this._pendingTransforms.indexOf(i);r>-1&&this._pendingTransforms.splice(r,1),this._updateState()}}}const ss=(e,t)=>{const n=e.threadIdMap[t];if(n!==void 0)return e.threadData[n]},Za=(e,t,n)=>{const i=ss(e,t);if(!i)return e;const{id:r,remoteId:o,status:a}=i;if(a===n)return e;const s={...e};switch(a){case"new":s.newThreadId=void 0;break;case"regular":s.threadIds=s.threadIds.filter(u=>u!==r);break;case"archived":s.archivedThreadIds=s.archivedThreadIds.filter(u=>u!==r);break;default:{const u=a;throw new Error(`Unsupported state: ${u}`)}}switch(n){case"regular":s.threadIds=[r,...s.threadIds];break;case"archived":s.archivedThreadIds=[r,...s.archivedThreadIds];break;case"deleted":s.threadData=Object.fromEntries(Object.entries(s.threadData).filter(([u])=>u!==r)),s.threadIdMap=Object.fromEntries(Object.entries(s.threadIdMap).filter(([u])=>u!==r&&u!==o));break;default:{const u=n;throw new Error(`Unsupported state: ${u}`)}}return n!=="deleted"&&(s.threadData={...s.threadData,[r]:{...i,status:n}}),s};class v4 extends iu{contextProvider;_options;_hookManager;_loadThreadsPromise;_mainThreadId;_state=new g4({isLoading:!1,newThreadId:void 0,threadIds:[],archivedThreadIds:[],threadIdMap:{},threadData:{}});get threadData(){return this._state.value.threadData}getLoadThreadsPromise(){return this._loadThreadsPromise||(this._loadThreadsPromise=this._state.optimisticUpdate({execute:()=>this._options.adapter.list(),loading:t=>({...t,isLoading:!0}),then:(t,n)=>{const i=[],r=[],o={},a={};for(const s of n.threads){switch(s.status){case"regular":i.push(s.remoteId);break;case"archived":r.push(s.remoteId);break;default:{const l=s.status;throw new Error(`Unsupported state: ${l}`)}}const u=s.remoteId;o[s.remoteId]=u,a[u]={id:s.remoteId,remoteId:s.remoteId,externalId:s.externalId,status:s.status,title:s.title,initializeTask:Promise.resolve({remoteId:s.remoteId,externalId:s.externalId})}}return{...t,threadIds:i,archivedThreadIds:r,threadIdMap:{...t.threadIdMap,...o},threadData:{...t.threadData,...a}}}}).then(()=>{})),this._loadThreadsPromise}constructor(t,n){super(),this.contextProvider=n,this._state.subscribe(()=>this._notifySubscribers()),this._hookManager=new h4(t.runtimeHook),this.useProvider=ci.create(()=>({Provider:t.adapter.unstable_Provider??k.Fragment})),this.__internal_setOptions(t),this.switchToNewThread()}useProvider;__internal_setOptions(t){if(this._options===t)return;this._options=t;const n=t.adapter.unstable_Provider??k.Fragment;n!==this.useProvider.getState().Provider&&this.useProvider.setState({Provider:n},!0),this._hookManager.setRuntimeHook(t.runtimeHook)}__internal_load(){this.getLoadThreadsPromise()}get isLoading(){return this._state.value.isLoading}get threadIds(){return this._state.value.threadIds}get archivedThreadIds(){return this._state.value.archivedThreadIds}get newThreadId(){return this._state.value.newThreadId}get mainThreadId(){return this._mainThreadId}getMainThreadRuntimeCore(){const t=this._hookManager.getThreadRuntimeCore(this._mainThreadId);return t||m4}getThreadRuntimeCore(t){const n=this.getItemById(t);if(!n)throw new Error("Thread not found");const i=this._hookManager.getThreadRuntimeCore(n.id);if(!i)throw new Error("Thread not found");return i}getItemById(t){return ss(this._state.value,t)}async switchToThread(t){let n=this.getItemById(t);if(!n){const r=await this._options.adapter.fetch(t),o=this._state.value,a=r.remoteId,s={...o.threadData,[a]:{id:a,initializeTask:Promise.resolve({remoteId:r.remoteId,externalId:r.externalId}),remoteId:r.remoteId,externalId:r.externalId,status:r.status,title:r.title}},u={...o.threadIdMap,[r.remoteId]:a},l=r.status==="regular"?[...o.threadIds,r.remoteId]:o.threadIds,c=r.status==="archived"?[...o.archivedThreadIds,r.remoteId]:o.archivedThreadIds;this._state.update({...o,threadIds:l,archivedThreadIds:c,threadIdMap:u,threadData:s}),n=this.getItemById(t)}if(!n)throw new Error("Thread not found");if(this._mainThreadId===n.id)return;const i=this._hookManager.startThreadRuntime(n.id);this.mainThreadId!==void 0?await i:i.then(()=>this._notifySubscribers()),n.status==="archived"&&await this.unarchive(n.id),this._mainThreadId=n.id,this._notifySubscribers()}async switchToNewThread(){for(;this._state.baseValue.newThreadId!==void 0&&this._state.value.newThreadId===void 0;)await this._state.waitForUpdate();const t=this._state.value;let n=this._state.value.newThreadId;if(n===void 0){do n=`__LOCALID_${ha()}`;while(t.threadIdMap[n]);const i=n;this._state.update({...t,newThreadId:n,threadIdMap:{...t.threadIdMap,[n]:i},threadData:{...t.threadData,[i]:{status:"new",id:n,remoteId:void 0,externalId:void 0,title:void 0}}})}return this.switchToThread(n)}initialize=async t=>{if(this._state.value.newThreadId!==t){const n=this.getItemById(t);if(!n)throw new Error("Thread not found");if(n.status==="new")throw new Error("Unexpected new state");return n.initializeTask}return this._state.optimisticUpdate({execute:()=>this._options.adapter.initialize(t),optimistic:n=>Za(n,t,"regular"),loading:(n,i)=>{const r=t;return{...n,threadData:{...n.threadData,[r]:{...n.threadData[r],initializeTask:i}}}},then:(n,{remoteId:i,externalId:r})=>{const o=ss(n,t);if(!o)return n;const a=t;return{...n,threadIdMap:{...n.threadIdMap,[i]:a},threadData:{...n.threadData,[a]:{...o,initializeTask:Promise.resolve({remoteId:i,externalId:r}),remoteId:i,externalId:r}}}}})};generateTitle=async t=>{const n=this.getItemById(t);if(!n)throw new Error("Thread not found");if(n.status==="new")throw new Error("Thread is not yet initialized");const{remoteId:i}=await n.initializeTask,r=this._hookManager.getThreadRuntimeCore(n.id);if(!r)return;const o=r.messages,a=await this._options.adapter.generateTitle(i,o),s=eo.fromAssistantStream(a);for await(const u of s){const l=u.parts.filter(d=>d.type==="text")[0]?.text,c=this._state.baseValue;this._state.update({...c,threadData:{...c.threadData,[n.id]:{...n,title:l}}})}};rename(t,n){const i=this.getItemById(t);if(!i)throw new Error("Thread not found");if(i.status==="new")throw new Error("Thread is not yet initialized");return this._state.optimisticUpdate({execute:async()=>{const{remoteId:r}=await i.initializeTask;return this._options.adapter.rename(r,n)},optimistic:r=>{const o=ss(r,t);return o?{...r,threadData:{...r.threadData,[o.id]:{...o,title:n}}}:r}})}async _ensureThreadIsNotMain(t){if(t===this.newThreadId)throw new Error("Cannot ensure new thread is not main");t===this._mainThreadId&&await this.switchToNewThread()}async archive(t){const n=this.getItemById(t);if(!n)throw new Error("Thread not found");if(n.status!=="regular")throw new Error("Thread is not yet initialized or already archived");return this._state.optimisticUpdate({execute:async()=>{await this._ensureThreadIsNotMain(n.id);const{remoteId:i}=await n.initializeTask;return this._options.adapter.archive(i)},optimistic:i=>Za(i,n.id,"archived")})}unarchive(t){const n=this.getItemById(t);if(!n)throw new Error("Thread not found");if(n.status!=="archived")throw new Error("Thread is not archived");return this._state.optimisticUpdate({execute:async()=>{try{const{remoteId:i}=await n.initializeTask;return await this._options.adapter.unarchive(i)}catch(i){throw await this._ensureThreadIsNotMain(n.id),i}},optimistic:i=>Za(i,n.id,"regular")})}async delete(t){const n=this.getItemById(t);if(!n)throw new Error("Thread not found");if(n.status!=="regular"&&n.status!=="archived")throw new Error("Thread is not yet initialized");return this._state.optimisticUpdate({execute:async()=>{await this._ensureThreadIsNotMain(n.id);const{remoteId:i}=await n.initializeTask;return await this._options.adapter.delete(i)},optimistic:i=>Za(i,n.id,"deleted")})}async detach(t){const n=this.getItemById(t);if(!n)throw new Error("Thread not found");if(n.status!=="regular"&&n.status!=="archived")throw new Error("Thread is not yet initialized");await this._ensureThreadIsNotMain(n.id),this._hookManager.stopThreadRuntime(n.id)}useBoundIds=ci.create(()=>[]);__internal_RenderComponent=()=>{const t=k.useId();k.useEffect(()=>(this.useBoundIds.setState(o=>[...o,t],!0),()=>{this.useBoundIds.setState(o=>o.filter(a=>a!==t),!0)}),[t]);const n=this.useBoundIds(),{Provider:i}=this.useProvider(),r={modelContext:this.contextProvider};return(n.length===0||n[0]===t)&&h.jsx(Zf,{adapters:r,children:h.jsx(this._hookManager.__internal_RenderThreadRuntimes,{provider:i})})}}class y4 extends Df{threads;constructor(t){super(),this.threads=new v4(t,this._contextProvider)}get RenderComponent(){return this.threads.__internal_RenderComponent}}const b4=e=>{const[t]=k.useState(()=>new y4(e));return k.useEffect(()=>{t.threads.__internal_setOptions(e),t.threads.__internal_load()},[t,e]),k.useMemo(()=>new Wf(t),[t])},jE=e=>{if(lu().threadListItem.source!==null){if(!e.allowNesting)throw new Error("useRemoteThreadListRuntime cannot be nested inside another RemoteThreadListRuntime. Set allowNesting: true to allow nesting (the inner runtime will become a no-op).");return e.runtimeHook()}return b4(e)};var _4=Symbol.for("react.lazy"),zs=w[" use ".trim().toString()];function w4(e){return typeof e=="object"&&e!==null&&"then"in e}function ME(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===_4&&"_payload"in e&&w4(e._payload)}function DE(e){const t=x4(e),n=w.forwardRef((i,r)=>{let{children:o,...a}=i;ME(o)&&typeof zs=="function"&&(o=zs(o._payload));const s=w.Children.toArray(o),u=s.find(k4);if(u){const l=u.props.children,c=s.map(d=>d===u?w.Children.count(l)>1?w.Children.only(null):w.isValidElement(l)?l.props.children:null:d);return h.jsx(t,{...a,ref:r,children:w.isValidElement(l)?w.cloneElement(l,void 0,c):null})}return h.jsx(t,{...a,ref:r,children:o})});return n.displayName=`${e}.Slot`,n}var Gf=DE("Slot");function x4(e){const t=w.forwardRef((n,i)=>{let{children:r,...o}=n;if(ME(r)&&typeof zs=="function"&&(r=zs(r._payload)),w.isValidElement(r)){const a=T4(r),s=E4(o,r.props);return r.type!==w.Fragment&&(s.ref=i?Hf(i,a):a),w.cloneElement(r,s)}return w.Children.count(r)>1?w.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var zE=Symbol("radix.slottable");function S4(e){const t=({children:n})=>h.jsx(h.Fragment,{children:n});return t.displayName=`${e}.Slottable`,t.__radixId=zE,t}var I4=S4("Slottable");function k4(e){return w.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===zE}function E4(e,t){const n={...t};for(const i in t){const r=e[i],o=t[i];/^on[A-Z]/.test(i)?r&&o?n[i]=(...s)=>{const u=o(...s);return r(...s),u}:r&&(n[i]=r):i==="style"?n[i]={...r,...o}:i==="className"&&(n[i]=[r,o].filter(Boolean).join(" "))}return{...e,...n}}function T4(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var $4=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],et=$4.reduce((e,t)=>{const n=DE(`Primitive.${t}`),i=w.forwardRef((r,o)=>{const{asChild:a,...s}=r,u=a?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),h.jsx(u,{...s,ref:o})});return i.displayName=`Primitive.${t}`,{...e,[t]:i}},{}),Dn;(function(e){e.Hidden="hidden",e.Floating="floating",e.Normal="normal"})(Dn||(Dn={}));const C4=({hideWhenRunning:e,autohide:t,autohideFloat:n})=>ee(({thread:i,message:r})=>e&&i.isRunning?Dn.Hidden:t==="always"||t==="not-last"&&!r.isLast?r.isHovering?n==="always"||n==="single-branch"&&r.branchCount<=1?Dn.Floating:Dn.Normal:Dn.Hidden:Dn.Normal),Kf=k.forwardRef(({hideWhenRunning:e,autohide:t,autohideFloat:n,...i},r)=>{const o=C4({hideWhenRunning:e,autohide:t,autohideFloat:n});return o===Dn.Hidden?null:h.jsx(et.div,{...o===Dn.Floating?{"data-floating":"true"}:null,...i,ref:r})});Kf.displayName="ActionBarPrimitive.Root";function Pe(e,t,{checkForDefaultPrevented:n=!0}={}){return function(r){if(e?.(r),n===!1||!r.defaultPrevented)return t?.(r)}}const A4=({copiedDuration:e=3e3}={})=>{const t=_e(),n=ee(({message:a})=>(a.role!=="assistant"||a.status?.type!=="running")&&a.parts.some(s=>s.type==="text"&&s.text.length>0)),i=ee(({composer:a})=>a.isEditing),r=ee(({composer:a})=>a.text),o=k.useCallback(()=>{const a=i?r:t.message().getCopyText();a&&navigator.clipboard.writeText(a).then(()=>{t.message().setIsCopied(!0),setTimeout(()=>t.message().setIsCopied(!1),e)})},[t,i,r,e]);return n?o:null},UE=k.forwardRef(({copiedDuration:e,onClick:t,disabled:n,...i},r)=>{const o=ee(({message:s})=>s.isCopied),a=A4({copiedDuration:e});return h.jsx(et.button,{type:"button",...o?{"data-copied":"true"}:{},...i,ref:r,disabled:n||!a,onClick:Pe(t,()=>{a?.()})})});UE.displayName="ActionBarPrimitive.Copy";const fn=(e,t,n=[])=>{const i=k.forwardRef((r,o)=>{const a={},s={};Object.keys(r).forEach(l=>{n.includes(l)?a[l]=r[l]:s[l]=r[l]});const u=t(a)??void 0;return h.jsx(et.button,{type:"button",...s,ref:o,disabled:s.disabled||!u,onClick:Pe(s.onClick,u)})});return i.displayName=e,i},P4=()=>{const e=_e(),t=ee(i=>i.thread.isRunning||i.thread.isDisabled||i.message.role!=="assistant"),n=k.useCallback(()=>{e.message().reload()},[e]);return t?null:n},R4=fn("ActionBarPrimitive.Reload",P4),O4=()=>{const e=_e(),t=ee(({composer:i})=>i.isEditing),n=k.useCallback(()=>{e.composer().beginEdit()},[e]);return t?null:n},N4=fn("ActionBarPrimitive.Edit",O4);function LE(e,t=globalThis?.document){const n=Ot(e);w.useEffect(()=>{const i=r=>{r.key==="Escape"&&n(r)};return t.addEventListener("keydown",i,{capture:!0}),()=>t.removeEventListener("keydown",i,{capture:!0})},[n,t])}function j4(e,t){const n=w.createContext(t),i=o=>{const{children:a,...s}=o,u=w.useMemo(()=>s,Object.values(s));return h.jsx(n.Provider,{value:u,children:a})};i.displayName=e+"Provider";function r(o){const a=w.useContext(n);if(a)return a;if(t!==void 0)return t;throw new Error(`\`${o}\` must be used within \`${e}\``)}return[i,r]}function ya(e,t=[]){let n=[];function i(o,a){const s=w.createContext(a),u=n.length;n=[...n,a];const l=d=>{const{scope:f,children:p,...g}=d,m=f?.[e]?.[u]||s,y=w.useMemo(()=>g,Object.values(g));return h.jsx(m.Provider,{value:y,children:p})};l.displayName=o+"Provider";function c(d,f){const p=f?.[e]?.[u]||s,g=w.useContext(p);if(g)return g;if(a!==void 0)return a;throw new Error(`\`${d}\` must be used within \`${o}\``)}return[l,c]}const r=()=>{const o=n.map(a=>w.createContext(a));return function(s){const u=s?.[e]||o;return w.useMemo(()=>({[`__scope${e}`]:{...s,[e]:u}}),[s,u])}};return r.scopeName=e,[i,M4(r,...t)]}function M4(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const i=e.map(r=>({useScope:r(),scopeName:r.scopeName}));return function(o){const a=i.reduce((s,{useScope:u,scopeName:l})=>{const d=u(o)[`__scope${l}`];return{...s,...d}},{});return w.useMemo(()=>({[`__scope${t.scopeName}`]:a}),[a])}};return n.scopeName=t.scopeName,n}function Yf(e){const t=D4(e),n=w.forwardRef((i,r)=>{const{children:o,...a}=i,s=w.Children.toArray(o),u=s.find(U4);if(u){const l=u.props.children,c=s.map(d=>d===u?w.Children.count(l)>1?w.Children.only(null):w.isValidElement(l)?l.props.children:null:d);return h.jsx(t,{...a,ref:r,children:w.isValidElement(l)?w.cloneElement(l,void 0,c):null})}return h.jsx(t,{...a,ref:r,children:o})});return n.displayName=`${e}.Slot`,n}function D4(e){const t=w.forwardRef((n,i)=>{const{children:r,...o}=n;if(w.isValidElement(r)){const a=F4(r),s=L4(o,r.props);return r.type!==w.Fragment&&(s.ref=i?Hf(i,a):a),w.cloneElement(r,s)}return w.Children.count(r)>1?w.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var FE=Symbol("radix.slottable");function z4(e){const t=({children:n})=>h.jsx(h.Fragment,{children:n});return t.displayName=`${e}.Slottable`,t.__radixId=FE,t}function U4(e){return w.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===FE}function L4(e,t){const n={...t};for(const i in t){const r=e[i],o=t[i];/^on[A-Z]/.test(i)?r&&o?n[i]=(...s)=>{const u=o(...s);return r(...s),u}:r&&(n[i]=r):i==="style"?n[i]={...r,...o}:i==="className"&&(n[i]=[r,o].filter(Boolean).join(" "))}return{...e,...n}}function F4(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var B4=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Xe=B4.reduce((e,t)=>{const n=Yf(`Primitive.${t}`),i=w.forwardRef((r,o)=>{const{asChild:a,...s}=r,u=a?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),h.jsx(u,{...s,ref:o})});return i.displayName=`Primitive.${t}`,{...e,[t]:i}},{});function Z4(e,t){e&&nb.flushSync(()=>e.dispatchEvent(t))}var q4="DismissableLayer",id="dismissableLayer.update",V4="dismissableLayer.pointerDownOutside",H4="dismissableLayer.focusOutside",_g,BE=w.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),cu=w.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:i,onPointerDownOutside:r,onFocusOutside:o,onInteractOutside:a,onDismiss:s,...u}=e,l=w.useContext(BE),[c,d]=w.useState(null),f=c?.ownerDocument??globalThis?.document,[,p]=w.useState({}),g=Qe(t,$=>d($)),m=Array.from(l.layers),[y]=[...l.layersWithOutsidePointerEventsDisabled].slice(-1),v=m.indexOf(y),_=c?m.indexOf(c):-1,x=l.layersWithOutsidePointerEventsDisabled.size>0,b=_>=v,C=G4($=>{const A=$.target,j=[...l.branches].some(F=>F.contains(A));!b||j||(r?.($),a?.($),$.defaultPrevented||s?.())},f),E=K4($=>{const A=$.target;[...l.branches].some(F=>F.contains(A))||(o?.($),a?.($),$.defaultPrevented||s?.())},f);return LE($=>{_===l.layers.size-1&&(i?.($),!$.defaultPrevented&&s&&($.preventDefault(),s()))},f),w.useEffect(()=>{if(c)return n&&(l.layersWithOutsidePointerEventsDisabled.size===0&&(_g=f.body.style.pointerEvents,f.body.style.pointerEvents="none"),l.layersWithOutsidePointerEventsDisabled.add(c)),l.layers.add(c),wg(),()=>{n&&l.layersWithOutsidePointerEventsDisabled.size===1&&(f.body.style.pointerEvents=_g)}},[c,f,n,l]),w.useEffect(()=>()=>{c&&(l.layers.delete(c),l.layersWithOutsidePointerEventsDisabled.delete(c),wg())},[c,l]),w.useEffect(()=>{const $=()=>p({});return document.addEventListener(id,$),()=>document.removeEventListener(id,$)},[]),h.jsx(Xe.div,{...u,ref:g,style:{pointerEvents:x?b?"auto":"none":void 0,...e.style},onFocusCapture:Pe(e.onFocusCapture,E.onFocusCapture),onBlurCapture:Pe(e.onBlurCapture,E.onBlurCapture),onPointerDownCapture:Pe(e.onPointerDownCapture,C.onPointerDownCapture)})});cu.displayName=q4;var J4="DismissableLayerBranch",W4=w.forwardRef((e,t)=>{const n=w.useContext(BE),i=w.useRef(null),r=Qe(t,i);return w.useEffect(()=>{const o=i.current;if(o)return n.branches.add(o),()=>{n.branches.delete(o)}},[n.branches]),h.jsx(Xe.div,{...e,ref:r})});W4.displayName=J4;function G4(e,t=globalThis?.document){const n=Ot(e),i=w.useRef(!1),r=w.useRef(()=>{});return w.useEffect(()=>{const o=s=>{if(s.target&&!i.current){let u=function(){ZE(V4,n,l,{discrete:!0})};const l={originalEvent:s};s.pointerType==="touch"?(t.removeEventListener("click",r.current),r.current=u,t.addEventListener("click",r.current,{once:!0})):u()}else t.removeEventListener("click",r.current);i.current=!1},a=window.setTimeout(()=>{t.addEventListener("pointerdown",o)},0);return()=>{window.clearTimeout(a),t.removeEventListener("pointerdown",o),t.removeEventListener("click",r.current)}},[t,n]),{onPointerDownCapture:()=>i.current=!0}}function K4(e,t=globalThis?.document){const n=Ot(e),i=w.useRef(!1);return w.useEffect(()=>{const r=o=>{o.target&&!i.current&&ZE(H4,n,{originalEvent:o},{discrete:!1})};return t.addEventListener("focusin",r),()=>t.removeEventListener("focusin",r)},[t,n]),{onFocusCapture:()=>i.current=!0,onBlurCapture:()=>i.current=!1}}function wg(){const e=new CustomEvent(id);document.dispatchEvent(e)}function ZE(e,t,n,{discrete:i}){const r=n.originalEvent.target,o=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&r.addEventListener(e,t,{once:!0}),i?Z4(r,o):r.dispatchEvent(o)}var Ju=0;function qE(){w.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??xg()),document.body.insertAdjacentElement("beforeend",e[1]??xg()),Ju++,()=>{Ju===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),Ju--}},[])}function xg(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var Wu="focusScope.autoFocusOnMount",Gu="focusScope.autoFocusOnUnmount",Sg={bubbles:!1,cancelable:!0},Y4="FocusScope",Xf=w.forwardRef((e,t)=>{const{loop:n=!1,trapped:i=!1,onMountAutoFocus:r,onUnmountAutoFocus:o,...a}=e,[s,u]=w.useState(null),l=Ot(r),c=Ot(o),d=w.useRef(null),f=Qe(t,m=>u(m)),p=w.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;w.useEffect(()=>{if(i){let m=function(x){if(p.paused||!s)return;const b=x.target;s.contains(b)?d.current=b:Xn(d.current,{select:!0})},y=function(x){if(p.paused||!s)return;const b=x.relatedTarget;b!==null&&(s.contains(b)||Xn(d.current,{select:!0}))},v=function(x){if(document.activeElement===document.body)for(const C of x)C.removedNodes.length>0&&Xn(s)};document.addEventListener("focusin",m),document.addEventListener("focusout",y);const _=new MutationObserver(v);return s&&_.observe(s,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",m),document.removeEventListener("focusout",y),_.disconnect()}}},[i,s,p.paused]),w.useEffect(()=>{if(s){kg.add(p);const m=document.activeElement;if(!s.contains(m)){const v=new CustomEvent(Wu,Sg);s.addEventListener(Wu,l),s.dispatchEvent(v),v.defaultPrevented||(X4(rU(VE(s)),{select:!0}),document.activeElement===m&&Xn(s))}return()=>{s.removeEventListener(Wu,l),setTimeout(()=>{const v=new CustomEvent(Gu,Sg);s.addEventListener(Gu,c),s.dispatchEvent(v),v.defaultPrevented||Xn(m??document.body,{select:!0}),s.removeEventListener(Gu,c),kg.remove(p)},0)}}},[s,l,c,p]);const g=w.useCallback(m=>{if(!n&&!i||p.paused)return;const y=m.key==="Tab"&&!m.altKey&&!m.ctrlKey&&!m.metaKey,v=document.activeElement;if(y&&v){const _=m.currentTarget,[x,b]=Q4(_);x&&b?!m.shiftKey&&v===b?(m.preventDefault(),n&&Xn(x,{select:!0})):m.shiftKey&&v===x&&(m.preventDefault(),n&&Xn(b,{select:!0})):v===_&&m.preventDefault()}},[n,i,p.paused]);return h.jsx(Xe.div,{tabIndex:-1,...a,ref:f,onKeyDown:g})});Xf.displayName=Y4;function X4(e,{select:t=!1}={}){const n=document.activeElement;for(const i of e)if(Xn(i,{select:t}),document.activeElement!==n)return}function Q4(e){const t=VE(e),n=Ig(t,e),i=Ig(t.reverse(),e);return[n,i]}function VE(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:i=>{const r=i.tagName==="INPUT"&&i.type==="hidden";return i.disabled||i.hidden||r?NodeFilter.FILTER_SKIP:i.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function Ig(e,t){for(const n of e)if(!eU(n,{upTo:t}))return n}function eU(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function tU(e){return e instanceof HTMLInputElement&&"select"in e}function Xn(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&tU(e)&&t&&e.select()}}var kg=nU();function nU(){let e=[];return{add(t){const n=e[0];t!==n&&n?.pause(),e=Eg(e,t),e.unshift(t)},remove(t){e=Eg(e,t),e[0]?.resume()}}}function Eg(e,t){const n=[...e],i=n.indexOf(t);return i!==-1&&n.splice(i,1),n}function rU(e){return e.filter(t=>t.tagName!=="A")}var Jt=globalThis?.document?w.useLayoutEffect:()=>{},iU=w[" useId ".trim().toString()]||(()=>{}),oU=0;function ri(e){const[t,n]=w.useState(iU());return Jt(()=>{n(i=>i??String(oU++))},[e]),t?`radix-${t}`:""}const aU=["top","right","bottom","left"],ur=Math.min,Tt=Math.max,Us=Math.round,qa=Math.floor,kn=e=>({x:e,y:e}),sU={left:"right",right:"left",bottom:"top",top:"bottom"},lU={start:"end",end:"start"};function od(e,t,n){return Tt(e,ur(t,n))}function Bn(e,t){return typeof e=="function"?e(t):e}function Zn(e){return e.split("-")[0]}function Ri(e){return e.split("-")[1]}function Qf(e){return e==="x"?"y":"x"}function eh(e){return e==="y"?"height":"width"}const uU=new Set(["top","bottom"]);function In(e){return uU.has(Zn(e))?"y":"x"}function th(e){return Qf(In(e))}function cU(e,t,n){n===void 0&&(n=!1);const i=Ri(e),r=th(e),o=eh(r);let a=r==="x"?i===(n?"end":"start")?"right":"left":i==="start"?"bottom":"top";return t.reference[o]>t.floating[o]&&(a=Ls(a)),[a,Ls(a)]}function dU(e){const t=Ls(e);return[ad(e),t,ad(t)]}function ad(e){return e.replace(/start|end/g,t=>lU[t])}const Tg=["left","right"],$g=["right","left"],pU=["top","bottom"],fU=["bottom","top"];function hU(e,t,n){switch(e){case"top":case"bottom":return n?t?$g:Tg:t?Tg:$g;case"left":case"right":return t?pU:fU;default:return[]}}function mU(e,t,n,i){const r=Ri(e);let o=hU(Zn(e),n==="start",i);return r&&(o=o.map(a=>a+"-"+r),t&&(o=o.concat(o.map(ad)))),o}function Ls(e){return e.replace(/left|right|bottom|top/g,t=>sU[t])}function gU(e){return{top:0,right:0,bottom:0,left:0,...e}}function HE(e){return typeof e!="number"?gU(e):{top:e,right:e,bottom:e,left:e}}function Fs(e){const{x:t,y:n,width:i,height:r}=e;return{width:i,height:r,top:n,left:t,right:t+i,bottom:n+r,x:t,y:n}}function Cg(e,t,n){let{reference:i,floating:r}=e;const o=In(t),a=th(t),s=eh(a),u=Zn(t),l=o==="y",c=i.x+i.width/2-r.width/2,d=i.y+i.height/2-r.height/2,f=i[s]/2-r[s]/2;let p;switch(u){case"top":p={x:c,y:i.y-r.height};break;case"bottom":p={x:c,y:i.y+i.height};break;case"right":p={x:i.x+i.width,y:d};break;case"left":p={x:i.x-r.width,y:d};break;default:p={x:i.x,y:i.y}}switch(Ri(t)){case"start":p[a]-=f*(n&&l?-1:1);break;case"end":p[a]+=f*(n&&l?-1:1);break}return p}const vU=async(e,t,n)=>{const{placement:i="bottom",strategy:r="absolute",middleware:o=[],platform:a}=n,s=o.filter(Boolean),u=await(a.isRTL==null?void 0:a.isRTL(t));let l=await a.getElementRects({reference:e,floating:t,strategy:r}),{x:c,y:d}=Cg(l,i,u),f=i,p={},g=0;for(let m=0;m<s.length;m++){const{name:y,fn:v}=s[m],{x:_,y:x,data:b,reset:C}=await v({x:c,y:d,initialPlacement:i,placement:f,strategy:r,middlewareData:p,rects:l,platform:a,elements:{reference:e,floating:t}});c=_??c,d=x??d,p={...p,[y]:{...p[y],...b}},C&&g<=50&&(g++,typeof C=="object"&&(C.placement&&(f=C.placement),C.rects&&(l=C.rects===!0?await a.getElementRects({reference:e,floating:t,strategy:r}):C.rects),{x:c,y:d}=Cg(l,f,u)),m=-1)}return{x:c,y:d,placement:f,strategy:r,middlewareData:p}};async function ko(e,t){var n;t===void 0&&(t={});const{x:i,y:r,platform:o,rects:a,elements:s,strategy:u}=e,{boundary:l="clippingAncestors",rootBoundary:c="viewport",elementContext:d="floating",altBoundary:f=!1,padding:p=0}=Bn(t,e),g=HE(p),y=s[f?d==="floating"?"reference":"floating":d],v=Fs(await o.getClippingRect({element:(n=await(o.isElement==null?void 0:o.isElement(y)))==null||n?y:y.contextElement||await(o.getDocumentElement==null?void 0:o.getDocumentElement(s.floating)),boundary:l,rootBoundary:c,strategy:u})),_=d==="floating"?{x:i,y:r,width:a.floating.width,height:a.floating.height}:a.reference,x=await(o.getOffsetParent==null?void 0:o.getOffsetParent(s.floating)),b=await(o.isElement==null?void 0:o.isElement(x))?await(o.getScale==null?void 0:o.getScale(x))||{x:1,y:1}:{x:1,y:1},C=Fs(o.convertOffsetParentRelativeRectToViewportRelativeRect?await o.convertOffsetParentRelativeRectToViewportRelativeRect({elements:s,rect:_,offsetParent:x,strategy:u}):_);return{top:(v.top-C.top+g.top)/b.y,bottom:(C.bottom-v.bottom+g.bottom)/b.y,left:(v.left-C.left+g.left)/b.x,right:(C.right-v.right+g.right)/b.x}}const yU=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:i,placement:r,rects:o,platform:a,elements:s,middlewareData:u}=t,{element:l,padding:c=0}=Bn(e,t)||{};if(l==null)return{};const d=HE(c),f={x:n,y:i},p=th(r),g=eh(p),m=await a.getDimensions(l),y=p==="y",v=y?"top":"left",_=y?"bottom":"right",x=y?"clientHeight":"clientWidth",b=o.reference[g]+o.reference[p]-f[p]-o.floating[g],C=f[p]-o.reference[p],E=await(a.getOffsetParent==null?void 0:a.getOffsetParent(l));let $=E?E[x]:0;(!$||!await(a.isElement==null?void 0:a.isElement(E)))&&($=s.floating[x]||o.floating[g]);const A=b/2-C/2,j=$/2-m[g]/2-1,F=ur(d[v],j),z=ur(d[_],j),J=F,G=$-m[g]-z,D=$/2-m[g]/2+A,U=od(J,D,G),X=!u.arrow&&Ri(r)!=null&&D!==U&&o.reference[g]/2-(D<J?F:z)-m[g]/2<0,re=X?D<J?D-J:D-G:0;return{[p]:f[p]+re,data:{[p]:U,centerOffset:D-U-re,...X&&{alignmentOffset:re}},reset:X}}}),bU=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,i;const{placement:r,middlewareData:o,rects:a,initialPlacement:s,platform:u,elements:l}=t,{mainAxis:c=!0,crossAxis:d=!0,fallbackPlacements:f,fallbackStrategy:p="bestFit",fallbackAxisSideDirection:g="none",flipAlignment:m=!0,...y}=Bn(e,t);if((n=o.arrow)!=null&&n.alignmentOffset)return{};const v=Zn(r),_=In(s),x=Zn(s)===s,b=await(u.isRTL==null?void 0:u.isRTL(l.floating)),C=f||(x||!m?[Ls(s)]:dU(s)),E=g!=="none";!f&&E&&C.push(...mU(s,m,g,b));const $=[s,...C],A=await ko(t,y),j=[];let F=((i=o.flip)==null?void 0:i.overflows)||[];if(c&&j.push(A[v]),d){const D=cU(r,a,b);j.push(A[D[0]],A[D[1]])}if(F=[...F,{placement:r,overflows:j}],!j.every(D=>D<=0)){var z,J;const D=(((z=o.flip)==null?void 0:z.index)||0)+1,U=$[D];if(U&&(!(d==="alignment"?_!==In(U):!1)||F.every(Q=>In(Q.placement)===_?Q.overflows[0]>0:!0)))return{data:{index:D,overflows:F},reset:{placement:U}};let X=(J=F.filter(re=>re.overflows[0]<=0).sort((re,Q)=>re.overflows[1]-Q.overflows[1])[0])==null?void 0:J.placement;if(!X)switch(p){case"bestFit":{var G;const re=(G=F.filter(Q=>{if(E){const me=In(Q.placement);return me===_||me==="y"}return!0}).map(Q=>[Q.placement,Q.overflows.filter(me=>me>0).reduce((me,S)=>me+S,0)]).sort((Q,me)=>Q[1]-me[1])[0])==null?void 0:G[0];re&&(X=re);break}case"initialPlacement":X=s;break}if(r!==X)return{reset:{placement:X}}}return{}}}};function Ag(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function Pg(e){return aU.some(t=>e[t]>=0)}const _U=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:i="referenceHidden",...r}=Bn(e,t);switch(i){case"referenceHidden":{const o=await ko(t,{...r,elementContext:"reference"}),a=Ag(o,n.reference);return{data:{referenceHiddenOffsets:a,referenceHidden:Pg(a)}}}case"escaped":{const o=await ko(t,{...r,altBoundary:!0}),a=Ag(o,n.floating);return{data:{escapedOffsets:a,escaped:Pg(a)}}}default:return{}}}}},JE=new Set(["left","top"]);async function wU(e,t){const{placement:n,platform:i,elements:r}=e,o=await(i.isRTL==null?void 0:i.isRTL(r.floating)),a=Zn(n),s=Ri(n),u=In(n)==="y",l=JE.has(a)?-1:1,c=o&&u?-1:1,d=Bn(t,e);let{mainAxis:f,crossAxis:p,alignmentAxis:g}=typeof d=="number"?{mainAxis:d,crossAxis:0,alignmentAxis:null}:{mainAxis:d.mainAxis||0,crossAxis:d.crossAxis||0,alignmentAxis:d.alignmentAxis};return s&&typeof g=="number"&&(p=s==="end"?g*-1:g),u?{x:p*c,y:f*l}:{x:f*l,y:p*c}}const xU=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,i;const{x:r,y:o,placement:a,middlewareData:s}=t,u=await wU(t,e);return a===((n=s.offset)==null?void 0:n.placement)&&(i=s.arrow)!=null&&i.alignmentOffset?{}:{x:r+u.x,y:o+u.y,data:{...u,placement:a}}}}},SU=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:i,placement:r}=t,{mainAxis:o=!0,crossAxis:a=!1,limiter:s={fn:y=>{let{x:v,y:_}=y;return{x:v,y:_}}},...u}=Bn(e,t),l={x:n,y:i},c=await ko(t,u),d=In(Zn(r)),f=Qf(d);let p=l[f],g=l[d];if(o){const y=f==="y"?"top":"left",v=f==="y"?"bottom":"right",_=p+c[y],x=p-c[v];p=od(_,p,x)}if(a){const y=d==="y"?"top":"left",v=d==="y"?"bottom":"right",_=g+c[y],x=g-c[v];g=od(_,g,x)}const m=s.fn({...t,[f]:p,[d]:g});return{...m,data:{x:m.x-n,y:m.y-i,enabled:{[f]:o,[d]:a}}}}}},IU=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:i,placement:r,rects:o,middlewareData:a}=t,{offset:s=0,mainAxis:u=!0,crossAxis:l=!0}=Bn(e,t),c={x:n,y:i},d=In(r),f=Qf(d);let p=c[f],g=c[d];const m=Bn(s,t),y=typeof m=="number"?{mainAxis:m,crossAxis:0}:{mainAxis:0,crossAxis:0,...m};if(u){const x=f==="y"?"height":"width",b=o.reference[f]-o.floating[x]+y.mainAxis,C=o.reference[f]+o.reference[x]-y.mainAxis;p<b?p=b:p>C&&(p=C)}if(l){var v,_;const x=f==="y"?"width":"height",b=JE.has(Zn(r)),C=o.reference[d]-o.floating[x]+(b&&((v=a.offset)==null?void 0:v[d])||0)+(b?0:y.crossAxis),E=o.reference[d]+o.reference[x]+(b?0:((_=a.offset)==null?void 0:_[d])||0)-(b?y.crossAxis:0);g<C?g=C:g>E&&(g=E)}return{[f]:p,[d]:g}}}},kU=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var n,i;const{placement:r,rects:o,platform:a,elements:s}=t,{apply:u=()=>{},...l}=Bn(e,t),c=await ko(t,l),d=Zn(r),f=Ri(r),p=In(r)==="y",{width:g,height:m}=o.floating;let y,v;d==="top"||d==="bottom"?(y=d,v=f===(await(a.isRTL==null?void 0:a.isRTL(s.floating))?"start":"end")?"left":"right"):(v=d,y=f==="end"?"top":"bottom");const _=m-c.top-c.bottom,x=g-c.left-c.right,b=ur(m-c[y],_),C=ur(g-c[v],x),E=!t.middlewareData.shift;let $=b,A=C;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(A=x),(i=t.middlewareData.shift)!=null&&i.enabled.y&&($=_),E&&!f){const F=Tt(c.left,0),z=Tt(c.right,0),J=Tt(c.top,0),G=Tt(c.bottom,0);p?A=g-2*(F!==0||z!==0?F+z:Tt(c.left,c.right)):$=m-2*(J!==0||G!==0?J+G:Tt(c.top,c.bottom))}await u({...t,availableWidth:A,availableHeight:$});const j=await a.getDimensions(s.floating);return g!==j.width||m!==j.height?{reset:{rects:!0}}:{}}}};function du(){return typeof window<"u"}function Oi(e){return WE(e)?(e.nodeName||"").toLowerCase():"#document"}function At(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Pn(e){var t;return(t=(WE(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function WE(e){return du()?e instanceof Node||e instanceof At(e).Node:!1}function cn(e){return du()?e instanceof Element||e instanceof At(e).Element:!1}function $n(e){return du()?e instanceof HTMLElement||e instanceof At(e).HTMLElement:!1}function Rg(e){return!du()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof At(e).ShadowRoot}const EU=new Set(["inline","contents"]);function ba(e){const{overflow:t,overflowX:n,overflowY:i,display:r}=dn(e);return/auto|scroll|overlay|hidden|clip/.test(t+i+n)&&!EU.has(r)}const TU=new Set(["table","td","th"]);function $U(e){return TU.has(Oi(e))}const CU=[":popover-open",":modal"];function pu(e){return CU.some(t=>{try{return e.matches(t)}catch{return!1}})}const AU=["transform","translate","scale","rotate","perspective"],PU=["transform","translate","scale","rotate","perspective","filter"],RU=["paint","layout","strict","content"];function nh(e){const t=rh(),n=cn(e)?dn(e):e;return AU.some(i=>n[i]?n[i]!=="none":!1)||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||PU.some(i=>(n.willChange||"").includes(i))||RU.some(i=>(n.contain||"").includes(i))}function OU(e){let t=cr(e);for(;$n(t)&&!Ii(t);){if(nh(t))return t;if(pu(t))return null;t=cr(t)}return null}function rh(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const NU=new Set(["html","body","#document"]);function Ii(e){return NU.has(Oi(e))}function dn(e){return At(e).getComputedStyle(e)}function fu(e){return cn(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function cr(e){if(Oi(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Rg(e)&&e.host||Pn(e);return Rg(t)?t.host:t}function GE(e){const t=cr(e);return Ii(t)?e.ownerDocument?e.ownerDocument.body:e.body:$n(t)&&ba(t)?t:GE(t)}function Eo(e,t,n){var i;t===void 0&&(t=[]),n===void 0&&(n=!0);const r=GE(e),o=r===((i=e.ownerDocument)==null?void 0:i.body),a=At(r);if(o){const s=sd(a);return t.concat(a,a.visualViewport||[],ba(r)?r:[],s&&n?Eo(s):[])}return t.concat(r,Eo(r,[],n))}function sd(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function KE(e){const t=dn(e);let n=parseFloat(t.width)||0,i=parseFloat(t.height)||0;const r=$n(e),o=r?e.offsetWidth:n,a=r?e.offsetHeight:i,s=Us(n)!==o||Us(i)!==a;return s&&(n=o,i=a),{width:n,height:i,$:s}}function ih(e){return cn(e)?e:e.contextElement}function ii(e){const t=ih(e);if(!$n(t))return kn(1);const n=t.getBoundingClientRect(),{width:i,height:r,$:o}=KE(t);let a=(o?Us(n.width):n.width)/i,s=(o?Us(n.height):n.height)/r;return(!a||!Number.isFinite(a))&&(a=1),(!s||!Number.isFinite(s))&&(s=1),{x:a,y:s}}const jU=kn(0);function YE(e){const t=At(e);return!rh()||!t.visualViewport?jU:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function MU(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==At(e)?!1:t}function Rr(e,t,n,i){t===void 0&&(t=!1),n===void 0&&(n=!1);const r=e.getBoundingClientRect(),o=ih(e);let a=kn(1);t&&(i?cn(i)&&(a=ii(i)):a=ii(e));const s=MU(o,n,i)?YE(o):kn(0);let u=(r.left+s.x)/a.x,l=(r.top+s.y)/a.y,c=r.width/a.x,d=r.height/a.y;if(o){const f=At(o),p=i&&cn(i)?At(i):i;let g=f,m=sd(g);for(;m&&i&&p!==g;){const y=ii(m),v=m.getBoundingClientRect(),_=dn(m),x=v.left+(m.clientLeft+parseFloat(_.paddingLeft))*y.x,b=v.top+(m.clientTop+parseFloat(_.paddingTop))*y.y;u*=y.x,l*=y.y,c*=y.x,d*=y.y,u+=x,l+=b,g=At(m),m=sd(g)}}return Fs({width:c,height:d,x:u,y:l})}function oh(e,t){const n=fu(e).scrollLeft;return t?t.left+n:Rr(Pn(e)).left+n}function XE(e,t,n){n===void 0&&(n=!1);const i=e.getBoundingClientRect(),r=i.left+t.scrollLeft-(n?0:oh(e,i)),o=i.top+t.scrollTop;return{x:r,y:o}}function DU(e){let{elements:t,rect:n,offsetParent:i,strategy:r}=e;const o=r==="fixed",a=Pn(i),s=t?pu(t.floating):!1;if(i===a||s&&o)return n;let u={scrollLeft:0,scrollTop:0},l=kn(1);const c=kn(0),d=$n(i);if((d||!d&&!o)&&((Oi(i)!=="body"||ba(a))&&(u=fu(i)),$n(i))){const p=Rr(i);l=ii(i),c.x=p.x+i.clientLeft,c.y=p.y+i.clientTop}const f=a&&!d&&!o?XE(a,u,!0):kn(0);return{width:n.width*l.x,height:n.height*l.y,x:n.x*l.x-u.scrollLeft*l.x+c.x+f.x,y:n.y*l.y-u.scrollTop*l.y+c.y+f.y}}function zU(e){return Array.from(e.getClientRects())}function UU(e){const t=Pn(e),n=fu(e),i=e.ownerDocument.body,r=Tt(t.scrollWidth,t.clientWidth,i.scrollWidth,i.clientWidth),o=Tt(t.scrollHeight,t.clientHeight,i.scrollHeight,i.clientHeight);let a=-n.scrollLeft+oh(e);const s=-n.scrollTop;return dn(i).direction==="rtl"&&(a+=Tt(t.clientWidth,i.clientWidth)-r),{width:r,height:o,x:a,y:s}}function LU(e,t){const n=At(e),i=Pn(e),r=n.visualViewport;let o=i.clientWidth,a=i.clientHeight,s=0,u=0;if(r){o=r.width,a=r.height;const l=rh();(!l||l&&t==="fixed")&&(s=r.offsetLeft,u=r.offsetTop)}return{width:o,height:a,x:s,y:u}}const FU=new Set(["absolute","fixed"]);function BU(e,t){const n=Rr(e,!0,t==="fixed"),i=n.top+e.clientTop,r=n.left+e.clientLeft,o=$n(e)?ii(e):kn(1),a=e.clientWidth*o.x,s=e.clientHeight*o.y,u=r*o.x,l=i*o.y;return{width:a,height:s,x:u,y:l}}function Og(e,t,n){let i;if(t==="viewport")i=LU(e,n);else if(t==="document")i=UU(Pn(e));else if(cn(t))i=BU(t,n);else{const r=YE(e);i={x:t.x-r.x,y:t.y-r.y,width:t.width,height:t.height}}return Fs(i)}function QE(e,t){const n=cr(e);return n===t||!cn(n)||Ii(n)?!1:dn(n).position==="fixed"||QE(n,t)}function ZU(e,t){const n=t.get(e);if(n)return n;let i=Eo(e,[],!1).filter(s=>cn(s)&&Oi(s)!=="body"),r=null;const o=dn(e).position==="fixed";let a=o?cr(e):e;for(;cn(a)&&!Ii(a);){const s=dn(a),u=nh(a);!u&&s.position==="fixed"&&(r=null),(o?!u&&!r:!u&&s.position==="static"&&!!r&&FU.has(r.position)||ba(a)&&!u&&QE(e,a))?i=i.filter(c=>c!==a):r=s,a=cr(a)}return t.set(e,i),i}function qU(e){let{element:t,boundary:n,rootBoundary:i,strategy:r}=e;const a=[...n==="clippingAncestors"?pu(t)?[]:ZU(t,this._c):[].concat(n),i],s=a[0],u=a.reduce((l,c)=>{const d=Og(t,c,r);return l.top=Tt(d.top,l.top),l.right=ur(d.right,l.right),l.bottom=ur(d.bottom,l.bottom),l.left=Tt(d.left,l.left),l},Og(t,s,r));return{width:u.right-u.left,height:u.bottom-u.top,x:u.left,y:u.top}}function VU(e){const{width:t,height:n}=KE(e);return{width:t,height:n}}function HU(e,t,n){const i=$n(t),r=Pn(t),o=n==="fixed",a=Rr(e,!0,o,t);let s={scrollLeft:0,scrollTop:0};const u=kn(0);function l(){u.x=oh(r)}if(i||!i&&!o)if((Oi(t)!=="body"||ba(r))&&(s=fu(t)),i){const p=Rr(t,!0,o,t);u.x=p.x+t.clientLeft,u.y=p.y+t.clientTop}else r&&l();o&&!i&&r&&l();const c=r&&!i&&!o?XE(r,s):kn(0),d=a.left+s.scrollLeft-u.x-c.x,f=a.top+s.scrollTop-u.y-c.y;return{x:d,y:f,width:a.width,height:a.height}}function Ku(e){return dn(e).position==="static"}function Ng(e,t){if(!$n(e)||dn(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return Pn(e)===n&&(n=n.ownerDocument.body),n}function eT(e,t){const n=At(e);if(pu(e))return n;if(!$n(e)){let r=cr(e);for(;r&&!Ii(r);){if(cn(r)&&!Ku(r))return r;r=cr(r)}return n}let i=Ng(e,t);for(;i&&$U(i)&&Ku(i);)i=Ng(i,t);return i&&Ii(i)&&Ku(i)&&!nh(i)?n:i||OU(e)||n}const JU=async function(e){const t=this.getOffsetParent||eT,n=this.getDimensions,i=await n(e.floating);return{reference:HU(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:i.width,height:i.height}}};function WU(e){return dn(e).direction==="rtl"}const GU={convertOffsetParentRelativeRectToViewportRelativeRect:DU,getDocumentElement:Pn,getClippingRect:qU,getOffsetParent:eT,getElementRects:JU,getClientRects:zU,getDimensions:VU,getScale:ii,isElement:cn,isRTL:WU};function tT(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function KU(e,t){let n=null,i;const r=Pn(e);function o(){var s;clearTimeout(i),(s=n)==null||s.disconnect(),n=null}function a(s,u){s===void 0&&(s=!1),u===void 0&&(u=1),o();const l=e.getBoundingClientRect(),{left:c,top:d,width:f,height:p}=l;if(s||t(),!f||!p)return;const g=qa(d),m=qa(r.clientWidth-(c+f)),y=qa(r.clientHeight-(d+p)),v=qa(c),x={rootMargin:-g+"px "+-m+"px "+-y+"px "+-v+"px",threshold:Tt(0,ur(1,u))||1};let b=!0;function C(E){const $=E[0].intersectionRatio;if($!==u){if(!b)return a();$?a(!1,$):i=setTimeout(()=>{a(!1,1e-7)},1e3)}$===1&&!tT(l,e.getBoundingClientRect())&&a(),b=!1}try{n=new IntersectionObserver(C,{...x,root:r.ownerDocument})}catch{n=new IntersectionObserver(C,x)}n.observe(e)}return a(!0),o}function YU(e,t,n,i){i===void 0&&(i={});const{ancestorScroll:r=!0,ancestorResize:o=!0,elementResize:a=typeof ResizeObserver=="function",layoutShift:s=typeof IntersectionObserver=="function",animationFrame:u=!1}=i,l=ih(e),c=r||o?[...l?Eo(l):[],...Eo(t)]:[];c.forEach(v=>{r&&v.addEventListener("scroll",n,{passive:!0}),o&&v.addEventListener("resize",n)});const d=l&&s?KU(l,n):null;let f=-1,p=null;a&&(p=new ResizeObserver(v=>{let[_]=v;_&&_.target===l&&p&&(p.unobserve(t),cancelAnimationFrame(f),f=requestAnimationFrame(()=>{var x;(x=p)==null||x.observe(t)})),n()}),l&&!u&&p.observe(l),p.observe(t));let g,m=u?Rr(e):null;u&&y();function y(){const v=Rr(e);m&&!tT(m,v)&&n(),m=v,g=requestAnimationFrame(y)}return n(),()=>{var v;c.forEach(_=>{r&&_.removeEventListener("scroll",n),o&&_.removeEventListener("resize",n)}),d?.(),(v=p)==null||v.disconnect(),p=null,u&&cancelAnimationFrame(g)}}const XU=xU,QU=SU,eL=bU,tL=kU,nL=_U,jg=yU,rL=IU,iL=(e,t,n)=>{const i=new Map,r={platform:GU,...n},o={...r.platform,_c:i};return vU(e,t,{...r,platform:o})};var oL=typeof document<"u",aL=function(){},ls=oL?k.useLayoutEffect:aL;function Bs(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,i,r;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(i=n;i--!==0;)if(!Bs(e[i],t[i]))return!1;return!0}if(r=Object.keys(e),n=r.length,n!==Object.keys(t).length)return!1;for(i=n;i--!==0;)if(!{}.hasOwnProperty.call(t,r[i]))return!1;for(i=n;i--!==0;){const o=r[i];if(!(o==="_owner"&&e.$$typeof)&&!Bs(e[o],t[o]))return!1}return!0}return e!==e&&t!==t}function nT(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Mg(e,t){const n=nT(e);return Math.round(t*n)/n}function Yu(e){const t=w.useRef(e);return ls(()=>{t.current=e}),t}function sL(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:i=[],platform:r,elements:{reference:o,floating:a}={},transform:s=!0,whileElementsMounted:u,open:l}=e,[c,d]=w.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[f,p]=w.useState(i);Bs(f,i)||p(i);const[g,m]=w.useState(null),[y,v]=w.useState(null),_=w.useCallback(Q=>{Q!==E.current&&(E.current=Q,m(Q))},[]),x=w.useCallback(Q=>{Q!==$.current&&($.current=Q,v(Q))},[]),b=o||g,C=a||y,E=w.useRef(null),$=w.useRef(null),A=w.useRef(c),j=u!=null,F=Yu(u),z=Yu(r),J=Yu(l),G=w.useCallback(()=>{if(!E.current||!$.current)return;const Q={placement:t,strategy:n,middleware:f};z.current&&(Q.platform=z.current),iL(E.current,$.current,Q).then(me=>{const S={...me,isPositioned:J.current!==!1};D.current&&!Bs(A.current,S)&&(A.current=S,nb.flushSync(()=>{d(S)}))})},[f,t,n,z,J]);ls(()=>{l===!1&&A.current.isPositioned&&(A.current.isPositioned=!1,d(Q=>({...Q,isPositioned:!1})))},[l]);const D=w.useRef(!1);ls(()=>(D.current=!0,()=>{D.current=!1}),[]),ls(()=>{if(b&&(E.current=b),C&&($.current=C),b&&C){if(F.current)return F.current(b,C,G);G()}},[b,C,G,F,j]);const U=w.useMemo(()=>({reference:E,floating:$,setReference:_,setFloating:x}),[_,x]),X=w.useMemo(()=>({reference:b,floating:C}),[b,C]),re=w.useMemo(()=>{const Q={position:n,left:0,top:0};if(!X.floating)return Q;const me=Mg(X.floating,c.x),S=Mg(X.floating,c.y);return s?{...Q,transform:"translate("+me+"px, "+S+"px)",...nT(X.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:me,top:S}},[n,s,X.floating,c.x,c.y]);return w.useMemo(()=>({...c,update:G,refs:U,elements:X,floatingStyles:re}),[c,G,U,X,re])}const lL=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:i,padding:r}=typeof e=="function"?e(n):e;return i&&t(i)?i.current!=null?jg({element:i.current,padding:r}).fn(n):{}:i?jg({element:i,padding:r}).fn(n):{}}}},uL=(e,t)=>({...XU(e),options:[e,t]}),cL=(e,t)=>({...QU(e),options:[e,t]}),dL=(e,t)=>({...rL(e),options:[e,t]}),pL=(e,t)=>({...eL(e),options:[e,t]}),fL=(e,t)=>({...tL(e),options:[e,t]}),hL=(e,t)=>({...nL(e),options:[e,t]}),mL=(e,t)=>({...lL(e),options:[e,t]});var gL="Arrow",rT=w.forwardRef((e,t)=>{const{children:n,width:i=10,height:r=5,...o}=e;return h.jsx(Xe.svg,{...o,ref:t,width:i,height:r,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:h.jsx("polygon",{points:"0,0 30,0 15,10"})})});rT.displayName=gL;var vL=rT;function yL(e){const[t,n]=w.useState(void 0);return Jt(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const i=new ResizeObserver(r=>{if(!Array.isArray(r)||!r.length)return;const o=r[0];let a,s;if("borderBoxSize"in o){const u=o.borderBoxSize,l=Array.isArray(u)?u[0]:u;a=l.inlineSize,s=l.blockSize}else a=e.offsetWidth,s=e.offsetHeight;n({width:a,height:s})});return i.observe(e,{box:"border-box"}),()=>i.unobserve(e)}else n(void 0)},[e]),t}var ah="Popper",[iT,hu]=ya(ah),[bL,oT]=iT(ah),aT=e=>{const{__scopePopper:t,children:n}=e,[i,r]=w.useState(null);return h.jsx(bL,{scope:t,anchor:i,onAnchorChange:r,children:n})};aT.displayName=ah;var sT="PopperAnchor",lT=w.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:i,...r}=e,o=oT(sT,n),a=w.useRef(null),s=Qe(t,a),u=w.useRef(null);return w.useEffect(()=>{const l=u.current;u.current=i?.current||a.current,l!==u.current&&o.onAnchorChange(u.current)}),i?null:h.jsx(Xe.div,{...r,ref:s})});lT.displayName=sT;var sh="PopperContent",[_L,wL]=iT(sh),uT=w.forwardRef((e,t)=>{const{__scopePopper:n,side:i="bottom",sideOffset:r=0,align:o="center",alignOffset:a=0,arrowPadding:s=0,avoidCollisions:u=!0,collisionBoundary:l=[],collisionPadding:c=0,sticky:d="partial",hideWhenDetached:f=!1,updatePositionStrategy:p="optimized",onPlaced:g,...m}=e,y=oT(sh,n),[v,_]=w.useState(null),x=Qe(t,Se=>_(Se)),[b,C]=w.useState(null),E=yL(b),$=E?.width??0,A=E?.height??0,j=i+(o!=="center"?"-"+o:""),F=typeof c=="number"?c:{top:0,right:0,bottom:0,left:0,...c},z=Array.isArray(l)?l:[l],J=z.length>0,G={padding:F,boundary:z.filter(SL),altBoundary:J},{refs:D,floatingStyles:U,placement:X,isPositioned:re,middlewareData:Q}=sL({strategy:"fixed",placement:j,whileElementsMounted:(...Se)=>YU(...Se,{animationFrame:p==="always"}),elements:{reference:y.anchor},middleware:[uL({mainAxis:r+A,alignmentAxis:a}),u&&cL({mainAxis:!0,crossAxis:!1,limiter:d==="partial"?dL():void 0,...G}),u&&pL({...G}),fL({...G,apply:({elements:Se,rects:St,availableWidth:mn,availableHeight:Ut})=>{const{width:rt,height:qr}=St.reference,Ke=Se.floating.style;Ke.setProperty("--radix-popper-available-width",`${mn}px`),Ke.setProperty("--radix-popper-available-height",`${Ut}px`),Ke.setProperty("--radix-popper-anchor-width",`${rt}px`),Ke.setProperty("--radix-popper-anchor-height",`${qr}px`)}}),b&&mL({element:b,padding:s}),IL({arrowWidth:$,arrowHeight:A}),f&&hL({strategy:"referenceHidden",...G})]}),[me,S]=pT(X),Ae=Ot(g);Jt(()=>{re&&Ae?.()},[re,Ae]);const ye=Q.arrow?.x,T=Q.arrow?.y,V=Q.arrow?.centerOffset!==0,[ne,ue]=w.useState();return Jt(()=>{v&&ue(window.getComputedStyle(v).zIndex)},[v]),h.jsx("div",{ref:D.setFloating,"data-radix-popper-content-wrapper":"",style:{...U,transform:re?U.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:ne,"--radix-popper-transform-origin":[Q.transformOrigin?.x,Q.transformOrigin?.y].join(" "),...Q.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:h.jsx(_L,{scope:n,placedSide:me,onArrowChange:C,arrowX:ye,arrowY:T,shouldHideArrow:V,children:h.jsx(Xe.div,{"data-side":me,"data-align":S,...m,ref:x,style:{...m.style,animation:re?void 0:"none"}})})})});uT.displayName=sh;var cT="PopperArrow",xL={top:"bottom",right:"left",bottom:"top",left:"right"},dT=w.forwardRef(function(t,n){const{__scopePopper:i,...r}=t,o=wL(cT,i),a=xL[o.placedSide];return h.jsx("span",{ref:o.onArrowChange,style:{position:"absolute",left:o.arrowX,top:o.arrowY,[a]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[o.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[o.placedSide],visibility:o.shouldHideArrow?"hidden":void 0},children:h.jsx(vL,{...r,ref:n,style:{...r.style,display:"block"}})})});dT.displayName=cT;function SL(e){return e!==null}var IL=e=>({name:"transformOrigin",options:e,fn(t){const{placement:n,rects:i,middlewareData:r}=t,a=r.arrow?.centerOffset!==0,s=a?0:e.arrowWidth,u=a?0:e.arrowHeight,[l,c]=pT(n),d={start:"0%",center:"50%",end:"100%"}[c],f=(r.arrow?.x??0)+s/2,p=(r.arrow?.y??0)+u/2;let g="",m="";return l==="bottom"?(g=a?d:`${f}px`,m=`${-u}px`):l==="top"?(g=a?d:`${f}px`,m=`${i.floating.height+u}px`):l==="right"?(g=`${-u}px`,m=a?d:`${p}px`):l==="left"&&(g=`${i.floating.width+u}px`,m=a?d:`${p}px`),{data:{x:g,y:m}}}});function pT(e){const[t,n="center"]=e.split("-");return[t,n]}var fT=aT,lh=lT,hT=uT,mT=dT,kL="Portal",mu=w.forwardRef((e,t)=>{const{container:n,...i}=e,[r,o]=w.useState(!1);Jt(()=>o(!0),[]);const a=n||r&&globalThis?.document?.body;return a?tb.createPortal(h.jsx(Xe.div,{...i,ref:t}),a):null});mu.displayName=kL;function EL(e,t){return w.useReducer((n,i)=>t[n][i]??n,e)}var Hn=e=>{const{present:t,children:n}=e,i=TL(t),r=typeof n=="function"?n({present:i.isPresent}):w.Children.only(n),o=Qe(i.ref,$L(r));return typeof n=="function"||i.isPresent?w.cloneElement(r,{ref:o}):null};Hn.displayName="Presence";function TL(e){const[t,n]=w.useState(),i=w.useRef(null),r=w.useRef(e),o=w.useRef("none"),a=e?"mounted":"unmounted",[s,u]=EL(a,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return w.useEffect(()=>{const l=Va(i.current);o.current=s==="mounted"?l:"none"},[s]),Jt(()=>{const l=i.current,c=r.current;if(c!==e){const f=o.current,p=Va(l);e?u("MOUNT"):p==="none"||l?.display==="none"?u("UNMOUNT"):u(c&&f!==p?"ANIMATION_OUT":"UNMOUNT"),r.current=e}},[e,u]),Jt(()=>{if(t){let l;const c=t.ownerDocument.defaultView??window,d=p=>{const m=Va(i.current).includes(CSS.escape(p.animationName));if(p.target===t&&m&&(u("ANIMATION_END"),!r.current)){const y=t.style.animationFillMode;t.style.animationFillMode="forwards",l=c.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=y)})}},f=p=>{p.target===t&&(o.current=Va(i.current))};return t.addEventListener("animationstart",f),t.addEventListener("animationcancel",d),t.addEventListener("animationend",d),()=>{c.clearTimeout(l),t.removeEventListener("animationstart",f),t.removeEventListener("animationcancel",d),t.removeEventListener("animationend",d)}}else u("ANIMATION_END")},[t,u]),{isPresent:["mounted","unmountSuspended"].includes(s),ref:w.useCallback(l=>{i.current=l?getComputedStyle(l):null,n(l)},[])}}function Va(e){return e?.animationName||"none"}function $L(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var CL=w[" useInsertionEffect ".trim().toString()]||Jt;function gu({prop:e,defaultProp:t,onChange:n=()=>{},caller:i}){const[r,o,a]=AL({defaultProp:t,onChange:n}),s=e!==void 0,u=s?e:r;{const c=w.useRef(e!==void 0);w.useEffect(()=>{const d=c.current;d!==s&&console.warn(`${i} is changing from ${d?"controlled":"uncontrolled"} to ${s?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),c.current=s},[s,i])}const l=w.useCallback(c=>{if(s){const d=PL(c)?c(e):c;d!==e&&a.current?.(d)}else o(c)},[s,e,o,a]);return[u,l]}function AL({defaultProp:e,onChange:t}){const[n,i]=w.useState(e),r=w.useRef(n),o=w.useRef(t);return CL(()=>{o.current=t},[t]),w.useEffect(()=>{r.current!==n&&(o.current?.(n),r.current=n)},[n,r]),[n,i,o]}function PL(e){return typeof e=="function"}var RL=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},Wr=new WeakMap,Ha=new WeakMap,Ja={},Xu=0,gT=function(e){return e&&(e.host||gT(e.parentNode))},OL=function(e,t){return t.map(function(n){if(e.contains(n))return n;var i=gT(n);return i&&e.contains(i)?i:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},NL=function(e,t,n,i){var r=OL(t,Array.isArray(e)?e:[e]);Ja[n]||(Ja[n]=new WeakMap);var o=Ja[n],a=[],s=new Set,u=new Set(r),l=function(d){!d||s.has(d)||(s.add(d),l(d.parentNode))};r.forEach(l);var c=function(d){!d||u.has(d)||Array.prototype.forEach.call(d.children,function(f){if(s.has(f))c(f);else try{var p=f.getAttribute(i),g=p!==null&&p!=="false",m=(Wr.get(f)||0)+1,y=(o.get(f)||0)+1;Wr.set(f,m),o.set(f,y),a.push(f),m===1&&g&&Ha.set(f,!0),y===1&&f.setAttribute(n,"true"),g||f.setAttribute(i,"true")}catch(v){console.error("aria-hidden: cannot operate on ",f,v)}})};return c(t),s.clear(),Xu++,function(){a.forEach(function(d){var f=Wr.get(d)-1,p=o.get(d)-1;Wr.set(d,f),o.set(d,p),f||(Ha.has(d)||d.removeAttribute(i),Ha.delete(d)),p||d.removeAttribute(n)}),Xu--,Xu||(Wr=new WeakMap,Wr=new WeakMap,Ha=new WeakMap,Ja={})}},vT=function(e,t,n){n===void 0&&(n="data-aria-hidden");var i=Array.from(Array.isArray(e)?e:[e]),r=RL(e);return r?(i.push.apply(i,Array.from(r.querySelectorAll("[aria-live], script"))),NL(i,r,n,"aria-hidden")):function(){return null}},_n=function(){return _n=Object.assign||function(t){for(var n,i=1,r=arguments.length;i<r;i++){n=arguments[i];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(t[o]=n[o])}return t},_n.apply(this,arguments)};function yT(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]]);return n}function jL(e,t,n){if(n||arguments.length===2)for(var i=0,r=t.length,o;i<r;i++)(o||!(i in t))&&(o||(o=Array.prototype.slice.call(t,0,i)),o[i]=t[i]);return e.concat(o||Array.prototype.slice.call(t))}var us="right-scroll-bar-position",cs="width-before-scroll-bar",ML="with-scroll-bars-hidden",DL="--removed-body-scroll-bar-size";function Qu(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function zL(e,t){var n=k.useState(function(){return{value:e,callback:t,facade:{get current(){return n.value},set current(i){var r=n.value;r!==i&&(n.value=i,n.callback(i,r))}}}})[0];return n.callback=t,n.facade}var UL=typeof window<"u"?w.useLayoutEffect:w.useEffect,Dg=new WeakMap;function LL(e,t){var n=zL(null,function(i){return e.forEach(function(r){return Qu(r,i)})});return UL(function(){var i=Dg.get(n);if(i){var r=new Set(i),o=new Set(e),a=n.current;r.forEach(function(s){o.has(s)||Qu(s,null)}),o.forEach(function(s){r.has(s)||Qu(s,a)})}Dg.set(n,e)},[e]),n}function FL(e){return e}function BL(e,t){t===void 0&&(t=FL);var n=[],i=!1,r={read:function(){if(i)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:e},useMedium:function(o){var a=t(o,i);return n.push(a),function(){n=n.filter(function(s){return s!==a})}},assignSyncMedium:function(o){for(i=!0;n.length;){var a=n;n=[],a.forEach(o)}n={push:function(s){return o(s)},filter:function(){return n}}},assignMedium:function(o){i=!0;var a=[];if(n.length){var s=n;n=[],s.forEach(o),a=n}var u=function(){var c=a;a=[],c.forEach(o)},l=function(){return Promise.resolve().then(u)};l(),n={push:function(c){a.push(c),l()},filter:function(c){return a=a.filter(c),n}}}};return r}function ZL(e){e===void 0&&(e={});var t=BL(null);return t.options=_n({async:!0,ssr:!1},e),t}var bT=function(e){var t=e.sideCar,n=yT(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var i=t.read();if(!i)throw new Error("Sidecar medium not found");return w.createElement(i,_n({},n))};bT.isSideCarExport=!0;function qL(e,t){return e.useMedium(t),bT}var _T=ZL(),ec=function(){},vu=w.forwardRef(function(e,t){var n=w.useRef(null),i=w.useState({onScrollCapture:ec,onWheelCapture:ec,onTouchMoveCapture:ec}),r=i[0],o=i[1],a=e.forwardProps,s=e.children,u=e.className,l=e.removeScrollBar,c=e.enabled,d=e.shards,f=e.sideCar,p=e.noRelative,g=e.noIsolation,m=e.inert,y=e.allowPinchZoom,v=e.as,_=v===void 0?"div":v,x=e.gapMode,b=yT(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),C=f,E=LL([n,t]),$=_n(_n({},b),r);return w.createElement(w.Fragment,null,c&&w.createElement(C,{sideCar:_T,removeScrollBar:l,shards:d,noRelative:p,noIsolation:g,inert:m,setCallbacks:o,allowPinchZoom:!!y,lockRef:n,gapMode:x}),a?w.cloneElement(w.Children.only(s),_n(_n({},$),{ref:E})):w.createElement(_,_n({},$,{className:u,ref:E}),s))});vu.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};vu.classNames={fullWidth:cs,zeroRight:us};var VL=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function HL(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=VL();return t&&e.setAttribute("nonce",t),e}function JL(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function WL(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var GL=function(){var e=0,t=null;return{add:function(n){e==0&&(t=HL())&&(JL(t,n),WL(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},KL=function(){var e=GL();return function(t,n){w.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},wT=function(){var e=KL(),t=function(n){var i=n.styles,r=n.dynamic;return e(i,r),null};return t},YL={left:0,top:0,right:0,gap:0},tc=function(e){return parseInt(e||"",10)||0},XL=function(e){var t=window.getComputedStyle(document.body),n=t[e==="padding"?"paddingLeft":"marginLeft"],i=t[e==="padding"?"paddingTop":"marginTop"],r=t[e==="padding"?"paddingRight":"marginRight"];return[tc(n),tc(i),tc(r)]},QL=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return YL;var t=XL(e),n=document.documentElement.clientWidth,i=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,i-n+t[2]-t[0])}},e2=wT(),oi="data-scroll-locked",t2=function(e,t,n,i){var r=e.left,o=e.top,a=e.right,s=e.gap;return n===void 0&&(n="margin"),`
|
|
34
|
-
.`.concat(ML,` {
|
|
35
|
-
overflow: hidden `).concat(i,`;
|
|
36
|
-
padding-right: `).concat(s,"px ").concat(i,`;
|
|
37
|
-
}
|
|
38
|
-
body[`).concat(oi,`] {
|
|
39
|
-
overflow: hidden `).concat(i,`;
|
|
40
|
-
overscroll-behavior: contain;
|
|
41
|
-
`).concat([t&&"position: relative ".concat(i,";"),n==="margin"&&`
|
|
42
|
-
padding-left: `.concat(r,`px;
|
|
43
|
-
padding-top: `).concat(o,`px;
|
|
44
|
-
padding-right: `).concat(a,`px;
|
|
45
|
-
margin-left:0;
|
|
46
|
-
margin-top:0;
|
|
47
|
-
margin-right: `).concat(s,"px ").concat(i,`;
|
|
48
|
-
`),n==="padding"&&"padding-right: ".concat(s,"px ").concat(i,";")].filter(Boolean).join(""),`
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
.`).concat(us,` {
|
|
52
|
-
right: `).concat(s,"px ").concat(i,`;
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
.`).concat(cs,` {
|
|
56
|
-
margin-right: `).concat(s,"px ").concat(i,`;
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
.`).concat(us," .").concat(us,` {
|
|
60
|
-
right: 0 `).concat(i,`;
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
.`).concat(cs," .").concat(cs,` {
|
|
64
|
-
margin-right: 0 `).concat(i,`;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
body[`).concat(oi,`] {
|
|
68
|
-
`).concat(DL,": ").concat(s,`px;
|
|
69
|
-
}
|
|
70
|
-
`)},zg=function(){var e=parseInt(document.body.getAttribute(oi)||"0",10);return isFinite(e)?e:0},n2=function(){w.useEffect(function(){return document.body.setAttribute(oi,(zg()+1).toString()),function(){var e=zg()-1;e<=0?document.body.removeAttribute(oi):document.body.setAttribute(oi,e.toString())}},[])},r2=function(e){var t=e.noRelative,n=e.noImportant,i=e.gapMode,r=i===void 0?"margin":i;n2();var o=w.useMemo(function(){return QL(r)},[r]);return w.createElement(e2,{styles:t2(o,!t,r,n?"":"!important")})},ld=!1;if(typeof window<"u")try{var Wa=Object.defineProperty({},"passive",{get:function(){return ld=!0,!0}});window.addEventListener("test",Wa,Wa),window.removeEventListener("test",Wa,Wa)}catch{ld=!1}var Gr=ld?{passive:!1}:!1,i2=function(e){return e.tagName==="TEXTAREA"},xT=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!i2(e)&&n[t]==="visible")},o2=function(e){return xT(e,"overflowY")},a2=function(e){return xT(e,"overflowX")},Ug=function(e,t){var n=t.ownerDocument,i=t;do{typeof ShadowRoot<"u"&&i instanceof ShadowRoot&&(i=i.host);var r=ST(e,i);if(r){var o=IT(e,i),a=o[1],s=o[2];if(a>s)return!0}i=i.parentNode}while(i&&i!==n.body);return!1},s2=function(e){var t=e.scrollTop,n=e.scrollHeight,i=e.clientHeight;return[t,n,i]},l2=function(e){var t=e.scrollLeft,n=e.scrollWidth,i=e.clientWidth;return[t,n,i]},ST=function(e,t){return e==="v"?o2(t):a2(t)},IT=function(e,t){return e==="v"?s2(t):l2(t)},u2=function(e,t){return e==="h"&&t==="rtl"?-1:1},c2=function(e,t,n,i,r){var o=u2(e,window.getComputedStyle(t).direction),a=o*i,s=n.target,u=t.contains(s),l=!1,c=a>0,d=0,f=0;do{if(!s)break;var p=IT(e,s),g=p[0],m=p[1],y=p[2],v=m-y-o*g;(g||v)&&ST(e,s)&&(d+=v,f+=g);var _=s.parentNode;s=_&&_.nodeType===Node.DOCUMENT_FRAGMENT_NODE?_.host:_}while(!u&&s!==document.body||u&&(t.contains(s)||t===s));return(c&&Math.abs(d)<1||!c&&Math.abs(f)<1)&&(l=!0),l},Ga=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},Lg=function(e){return[e.deltaX,e.deltaY]},Fg=function(e){return e&&"current"in e?e.current:e},d2=function(e,t){return e[0]===t[0]&&e[1]===t[1]},p2=function(e){return`
|
|
71
|
-
.block-interactivity-`.concat(e,` {pointer-events: none;}
|
|
72
|
-
.allow-interactivity-`).concat(e,` {pointer-events: all;}
|
|
73
|
-
`)},f2=0,Kr=[];function h2(e){var t=w.useRef([]),n=w.useRef([0,0]),i=w.useRef(),r=w.useState(f2++)[0],o=w.useState(wT)[0],a=w.useRef(e);w.useEffect(function(){a.current=e},[e]),w.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(r));var m=jL([e.lockRef.current],(e.shards||[]).map(Fg),!0).filter(Boolean);return m.forEach(function(y){return y.classList.add("allow-interactivity-".concat(r))}),function(){document.body.classList.remove("block-interactivity-".concat(r)),m.forEach(function(y){return y.classList.remove("allow-interactivity-".concat(r))})}}},[e.inert,e.lockRef.current,e.shards]);var s=w.useCallback(function(m,y){if("touches"in m&&m.touches.length===2||m.type==="wheel"&&m.ctrlKey)return!a.current.allowPinchZoom;var v=Ga(m),_=n.current,x="deltaX"in m?m.deltaX:_[0]-v[0],b="deltaY"in m?m.deltaY:_[1]-v[1],C,E=m.target,$=Math.abs(x)>Math.abs(b)?"h":"v";if("touches"in m&&$==="h"&&E.type==="range")return!1;var A=Ug($,E);if(!A)return!0;if(A?C=$:(C=$==="v"?"h":"v",A=Ug($,E)),!A)return!1;if(!i.current&&"changedTouches"in m&&(x||b)&&(i.current=C),!C)return!0;var j=i.current||C;return c2(j,y,m,j==="h"?x:b)},[]),u=w.useCallback(function(m){var y=m;if(!(!Kr.length||Kr[Kr.length-1]!==o)){var v="deltaY"in y?Lg(y):Ga(y),_=t.current.filter(function(C){return C.name===y.type&&(C.target===y.target||y.target===C.shadowParent)&&d2(C.delta,v)})[0];if(_&&_.should){y.cancelable&&y.preventDefault();return}if(!_){var x=(a.current.shards||[]).map(Fg).filter(Boolean).filter(function(C){return C.contains(y.target)}),b=x.length>0?s(y,x[0]):!a.current.noIsolation;b&&y.cancelable&&y.preventDefault()}}},[]),l=w.useCallback(function(m,y,v,_){var x={name:m,delta:y,target:v,should:_,shadowParent:m2(v)};t.current.push(x),setTimeout(function(){t.current=t.current.filter(function(b){return b!==x})},1)},[]),c=w.useCallback(function(m){n.current=Ga(m),i.current=void 0},[]),d=w.useCallback(function(m){l(m.type,Lg(m),m.target,s(m,e.lockRef.current))},[]),f=w.useCallback(function(m){l(m.type,Ga(m),m.target,s(m,e.lockRef.current))},[]);w.useEffect(function(){return Kr.push(o),e.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener("wheel",u,Gr),document.addEventListener("touchmove",u,Gr),document.addEventListener("touchstart",c,Gr),function(){Kr=Kr.filter(function(m){return m!==o}),document.removeEventListener("wheel",u,Gr),document.removeEventListener("touchmove",u,Gr),document.removeEventListener("touchstart",c,Gr)}},[]);var p=e.removeScrollBar,g=e.inert;return w.createElement(w.Fragment,null,g?w.createElement(o,{styles:p2(r)}):null,p?w.createElement(r2,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function m2(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const g2=qL(_T,h2);var uh=w.forwardRef(function(e,t){return w.createElement(vu,_n({},e,{ref:t,sideCar:g2}))});uh.classNames=vu.classNames;var yu="Popover",[kT]=ya(yu,[hu]),_a=hu(),[v2,mr]=kT(yu),ET=e=>{const{__scopePopover:t,children:n,open:i,defaultOpen:r,onOpenChange:o,modal:a=!1}=e,s=_a(t),u=w.useRef(null),[l,c]=w.useState(!1),[d,f]=gu({prop:i,defaultProp:r??!1,onChange:o,caller:yu});return h.jsx(fT,{...s,children:h.jsx(v2,{scope:t,contentId:ri(),triggerRef:u,open:d,onOpenChange:f,onOpenToggle:w.useCallback(()=>f(p=>!p),[f]),hasCustomAnchor:l,onCustomAnchorAdd:w.useCallback(()=>c(!0),[]),onCustomAnchorRemove:w.useCallback(()=>c(!1),[]),modal:a,children:n})})};ET.displayName=yu;var TT="PopoverAnchor",y2=w.forwardRef((e,t)=>{const{__scopePopover:n,...i}=e,r=mr(TT,n),o=_a(n),{onCustomAnchorAdd:a,onCustomAnchorRemove:s}=r;return w.useEffect(()=>(a(),()=>s()),[a,s]),h.jsx(lh,{...o,...i,ref:t})});y2.displayName=TT;var $T="PopoverTrigger",CT=w.forwardRef((e,t)=>{const{__scopePopover:n,...i}=e,r=mr($T,n),o=_a(n),a=Qe(t,r.triggerRef),s=h.jsx(Xe.button,{type:"button","aria-haspopup":"dialog","aria-expanded":r.open,"aria-controls":r.contentId,"data-state":NT(r.open),...i,ref:a,onClick:Pe(e.onClick,r.onOpenToggle)});return r.hasCustomAnchor?s:h.jsx(lh,{asChild:!0,...o,children:s})});CT.displayName=$T;var ch="PopoverPortal",[b2,_2]=kT(ch,{forceMount:void 0}),AT=e=>{const{__scopePopover:t,forceMount:n,children:i,container:r}=e,o=mr(ch,t);return h.jsx(b2,{scope:t,forceMount:n,children:h.jsx(Hn,{present:n||o.open,children:h.jsx(mu,{asChild:!0,container:r,children:i})})})};AT.displayName=ch;var ki="PopoverContent",PT=w.forwardRef((e,t)=>{const n=_2(ki,e.__scopePopover),{forceMount:i=n.forceMount,...r}=e,o=mr(ki,e.__scopePopover);return h.jsx(Hn,{present:i||o.open,children:o.modal?h.jsx(x2,{...r,ref:t}):h.jsx(S2,{...r,ref:t})})});PT.displayName=ki;var w2=Yf("PopoverContent.RemoveScroll"),x2=w.forwardRef((e,t)=>{const n=mr(ki,e.__scopePopover),i=w.useRef(null),r=Qe(t,i),o=w.useRef(!1);return w.useEffect(()=>{const a=i.current;if(a)return vT(a)},[]),h.jsx(uh,{as:w2,allowPinchZoom:!0,children:h.jsx(RT,{...e,ref:r,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Pe(e.onCloseAutoFocus,a=>{a.preventDefault(),o.current||n.triggerRef.current?.focus()}),onPointerDownOutside:Pe(e.onPointerDownOutside,a=>{const s=a.detail.originalEvent,u=s.button===0&&s.ctrlKey===!0,l=s.button===2||u;o.current=l},{checkForDefaultPrevented:!1}),onFocusOutside:Pe(e.onFocusOutside,a=>a.preventDefault(),{checkForDefaultPrevented:!1})})})}),S2=w.forwardRef((e,t)=>{const n=mr(ki,e.__scopePopover),i=w.useRef(!1),r=w.useRef(!1);return h.jsx(RT,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{e.onCloseAutoFocus?.(o),o.defaultPrevented||(i.current||n.triggerRef.current?.focus(),o.preventDefault()),i.current=!1,r.current=!1},onInteractOutside:o=>{e.onInteractOutside?.(o),o.defaultPrevented||(i.current=!0,o.detail.originalEvent.type==="pointerdown"&&(r.current=!0));const a=o.target;n.triggerRef.current?.contains(a)&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&r.current&&o.preventDefault()}})}),RT=w.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:i,onOpenAutoFocus:r,onCloseAutoFocus:o,disableOutsidePointerEvents:a,onEscapeKeyDown:s,onPointerDownOutside:u,onFocusOutside:l,onInteractOutside:c,...d}=e,f=mr(ki,n),p=_a(n);return qE(),h.jsx(Xf,{asChild:!0,loop:!0,trapped:i,onMountAutoFocus:r,onUnmountAutoFocus:o,children:h.jsx(cu,{asChild:!0,disableOutsidePointerEvents:a,onInteractOutside:c,onEscapeKeyDown:s,onPointerDownOutside:u,onFocusOutside:l,onDismiss:()=>f.onOpenChange(!1),children:h.jsx(hT,{"data-state":NT(f.open),role:"dialog",id:f.contentId,...p,...d,ref:t,style:{...d.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),OT="PopoverClose",I2=w.forwardRef((e,t)=>{const{__scopePopover:n,...i}=e,r=mr(OT,n);return h.jsx(Xe.button,{type:"button",...i,ref:t,onClick:Pe(e.onClick,()=>r.onOpenChange(!1))})});I2.displayName=OT;var k2="PopoverArrow",E2=w.forwardRef((e,t)=>{const{__scopePopover:n,...i}=e,r=_a(n);return h.jsx(mT,{...r,...i,ref:t})});E2.displayName=k2;function NT(e){return e?"open":"closed"}var T2=ET,$2=CT,C2=AT,A2=PT;const jT=k.forwardRef((e,t)=>h.jsx(et.div,{...e,ref:t}));jT.displayName="AttachmentPrimitive.Root";const MT=()=>{const e=ee(({attachment:t})=>t.name);return h.jsx(h.Fragment,{children:e})};MT.displayName="AttachmentPrimitive.Name";const P2=()=>{const e=_e();return k.useCallback(()=>{e.attachment().remove()},[e])},R2=fn("AttachmentPrimitive.Remove",P2),O2=()=>{const e=_e(),t=ee(({thread:i,message:r})=>!!(r.branchNumber>=r.branchCount||i.isRunning&&!i.capabilities.switchBranchDuringRun)),n=k.useCallback(()=>{e.message().switchToBranch({position:"next"})},[e]);return t?null:n},N2=fn("BranchPickerPrimitive.Next",O2),j2=()=>{const e=_e(),t=ee(({thread:i,message:r})=>!!(r.branchNumber<=1||i.isRunning&&!i.capabilities.switchBranchDuringRun)),n=k.useCallback(()=>{e.message().switchToBranch({position:"previous"})},[e]);return t?null:n},M2=fn("BranchPickerPrimitive.Previous",j2),D2=()=>ee(({message:t})=>t.branchCount),DT=()=>{const e=D2();return h.jsx(h.Fragment,{children:e})};DT.displayName="BranchPickerPrimitive.Count";const z2=()=>ee(({message:t})=>t.branchNumber),zT=()=>{const e=z2();return h.jsx(h.Fragment,{children:e})};zT.displayName="BranchPickerPrimitive.Number";const wa=e=>{const t=k.useRef(void 0);return k.useCallback(i=>{t.current&&t.current(),i&&(t.current=e(i))},[e])},UT=(e,t)=>{const n=k.useCallback(i=>{if(!e)return;const r=e(),o=()=>{const s=t?t(i):i.offsetHeight;r.setHeight(s)},a=new ResizeObserver(o);return a.observe(i),o(),()=>{a.disconnect(),r.unregister()}},[e,t]);return wa(n)},Bg=k.createContext(!1),Zg=(e,t)=>{const n=e.match(/^([\d.]+)(em|px|rem)$/);if(!n)return 0;const i=parseFloat(n[1]),r=n[2];if(r==="px")return i;if(r==="em"){const o=parseFloat(getComputedStyle(t).fontSize)||16;return i*o}if(r==="rem"){const o=parseFloat(getComputedStyle(document.documentElement).fontSize)||16;return i*o}return 0},LT=({children:e,fillClampThreshold:t="10em",fillClampOffset:n="6em"})=>{const i=ee(({message:u})=>u.isLast&&u.index>=2),r=uu({optional:!0}),o=k.useContext(Bg),a=k.useCallback(u=>{if(!r||o)return;const l=()=>{const c=r.getState();if(c.turnAnchor==="top"&&i){const{viewport:d,inset:f,userMessage:p}=c.height,g=Zg(t,u),m=Zg(n,u),y=p<=g?p:m,v=Math.max(0,d-f-y);u.style.minHeight=`${v}px`,u.style.flexShrink="0",u.style.transition="min-height 0s"}else u.style.minHeight="",u.style.flexShrink="",u.style.transition=""};return l(),r.subscribe(l)},[r,i,o,t,n]),s=wa(a);return h.jsx(Bg.Provider,{value:!0,children:h.jsx(Gf,{ref:s,children:e})})};LT.displayName="ThreadPrimitive.ViewportSlack";const U2=()=>{const e=_e(),t=ee(()=>e.message()),n=k.useCallback(i=>{const r=()=>{t.setIsHovering(!0)},o=()=>{t.setIsHovering(!1)};return i.addEventListener("mouseenter",r),i.addEventListener("mouseleave",o),i.matches(":hover")&&queueMicrotask(()=>t.setIsHovering(!0)),()=>{i.removeEventListener("mouseenter",r),i.removeEventListener("mouseleave",o),t.setIsHovering(!1)}},[t]);return wa(n)},L2=()=>{const e=xo(r=>r.turnAnchor),t=xo(r=>r.registerUserMessageHeight),n=ee(({thread:r,message:o})=>e==="top"&&o.role==="user"&&o.index===r.messages.length-2&&r.messages.at(-1)?.role==="assistant"),i=k.useCallback(r=>r.offsetHeight,[]);return UT(n?t:null,i)},dh=k.forwardRef((e,t)=>{const n=U2(),i=L2(),r=Qe(t,n,i);return h.jsx(LT,{children:h.jsx(et.div,{...e,ref:r})})});dh.displayName="MessagePrimitive.Root";const FT=()=>ee(({part:t})=>{if(t.type!=="text"&&t.type!=="reasoning")throw new Error("MessagePartText can only be used inside text or reasoning message parts.");return t}),BT=k.forwardRef(({smooth:e=!0,component:t="span",...n},i)=>{const{text:r,status:o}=OE(FT(),e);return h.jsx(t,{"data-status":o.type,...n,ref:i,children:r})});BT.displayName="MessagePartPrimitive.Text";const F2=()=>ee(({part:t})=>{if(t.type!=="image")throw new Error("MessagePartImage can only be used inside image message parts.");return t}),ZT=k.forwardRef((e,t)=>{const{image:n}=F2();return h.jsx(et.img,{src:n,...e,ref:t})});ZT.displayName="MessagePartPrimitive.Image";const qT=({children:e})=>ee(({part:n})=>n.status.type==="running")?e:null;qT.displayName="MessagePartPrimitive.InProgress";const qg=e=>{let t=-1;return{startGroup:n=>{t===-1&&(t=n)},endGroup:(n,i)=>{t!==-1&&(i.push({type:e,startIndex:t,endIndex:n}),t=-1)},finalize:(n,i)=>{t!==-1&&i.push({type:e,startIndex:t,endIndex:n})}}},B2=e=>{const t=[],n=qg("toolGroup"),i=qg("reasoningGroup");for(let r=0;r<e.length;r++){const o=e[r];o==="tool-call"?(i.endGroup(r-1,t),n.startGroup(r)):o==="reasoning"?(n.endGroup(r-1,t),i.startGroup(r)):(n.endGroup(r-1,t),i.endGroup(r-1,t),t.push({type:"single",index:r}))}return n.finalize(e.length-1,t),i.finalize(e.length-1,t),t},Z2=()=>{const e=ee(eb.useShallow(t=>t.message.parts.map(n=>n.type)));return k.useMemo(()=>e.length===0?[]:B2(e),[e])},q2=({Fallback:e,...t})=>{const n=ee(({tools:i})=>{const r=i.tools[t.toolName]??e;return Array.isArray(r)?r[0]??e:r});return n?h.jsx(n,{...t}):null},jn={Text:()=>h.jsxs("p",{style:{whiteSpace:"pre-line"},children:[h.jsx(BT,{}),h.jsx(qT,{children:h.jsx("span",{style:{fontFamily:"revert"},children:" ●"})})]}),Reasoning:()=>null,Source:()=>null,Image:()=>h.jsx(ZT,{}),File:()=>null,Unstable_Audio:()=>null,ToolGroup:({children:e})=>e,ReasoningGroup:({children:e})=>e},V2=({components:{Text:e=jn.Text,Reasoning:t=jn.Reasoning,Image:n=jn.Image,Source:i=jn.Source,File:r=jn.File,Unstable_Audio:o=jn.Unstable_Audio,tools:a={}}={}})=>{const s=_e(),u=ee(({part:c})=>c),l=u.type;if(l==="tool-call"){const c=s.part().addToolResult,d=s.part().resumeToolCall;if("Override"in a)return h.jsx(a.Override,{...u,addResult:c,resume:d});const f=a.by_name?.[u.toolName]??a.Fallback;return h.jsx(q2,{...u,Fallback:f,addResult:c,resume:d})}if(u.status?.type==="requires-action")throw new Error("Encountered unexpected requires-action status");switch(l){case"text":return h.jsx(e,{...u});case"reasoning":return h.jsx(t,{...u});case"source":return h.jsx(i,{...u});case"image":return h.jsx(n,{...u});case"file":return h.jsx(r,{...u});case"audio":return h.jsx(o,{...u});case"data":return null;default:const c=l;throw new Error(`Unknown message part type: ${c}`)}},ds=k.memo(({index:e,components:t})=>h.jsx(Uz,{index:e,children:h.jsx(V2,{components:t})}),(e,t)=>e.index===t.index&&e.components?.Text===t.components?.Text&&e.components?.Reasoning===t.components?.Reasoning&&e.components?.Source===t.components?.Source&&e.components?.Image===t.components?.Image&&e.components?.File===t.components?.File&&e.components?.Unstable_Audio===t.components?.Unstable_Audio&&e.components?.tools===t.components?.tools&&e.components?.ToolGroup===t.components?.ToolGroup&&e.components?.ReasoningGroup===t.components?.ReasoningGroup);ds.displayName="MessagePrimitive.PartByIndex";const H2=({status:e,component:t})=>h.jsx(Zz,{text:"",isRunning:e.type==="running",children:h.jsx(t,{type:"text",text:"",status:e})}),J2=Object.freeze({type:"complete"}),W2=({components:e})=>{const t=ee(n=>n.message.status??J2);return e?.Empty?h.jsx(e.Empty,{status:t}):h.jsx(H2,{status:t,component:e?.Text??jn.Text})},G2=k.memo(W2,(e,t)=>e.components?.Empty===t.components?.Empty&&e.components?.Text===t.components?.Text),ph=({components:e})=>{const t=ee(({message:r})=>r.parts.length),n=Z2(),i=k.useMemo(()=>t===0?h.jsx(G2,{components:e}):n.map(r=>{if(r.type==="single")return h.jsx(ds,{index:r.index,components:e},r.index);if(r.type==="toolGroup"){const o=e?.ToolGroup??jn.ToolGroup;return h.jsx(o,{startIndex:r.startIndex,endIndex:r.endIndex,children:Array.from({length:r.endIndex-r.startIndex+1},(a,s)=>h.jsx(ds,{index:r.startIndex+s,components:e},s))},`tool-${r.startIndex}`)}else{const o=e?.ReasoningGroup??jn.ReasoningGroup;return h.jsx(o,{startIndex:r.startIndex,endIndex:r.endIndex,children:Array.from({length:r.endIndex-r.startIndex+1},(a,s)=>h.jsx(ds,{index:r.startIndex+s,components:e},s))},`reasoning-${r.startIndex}`)}}),[n,e,t]);return h.jsx(h.Fragment,{children:i})};ph.displayName="MessagePrimitive.Parts";const K2=e=>ee(({message:t})=>{const{role:n,attachments:i,parts:r,branchCount:o,isLast:a,speech:s,isCopied:u,isHovering:l}=t;return!(e.hasBranches===!0&&o<2||e.user&&n!=="user"||e.assistant&&n!=="assistant"||e.system&&n!=="system"||e.lastOrHover===!0&&!l&&!a||e.last!==void 0&&e.last!==a||e.copied===!0&&!u||e.copied===!1&&u||e.speaking===!0&&s==null||e.speaking===!1&&s!=null||e.hasAttachments===!0&&(n!=="user"||!i?.length)||e.hasAttachments===!1&&n==="user"&&i?.length||e.hasContent===!0&&r.length===0||e.hasContent===!1&&r.length>0||e.submittedFeedback!==void 0&&(t.metadata.submittedFeedback?.type??null)!==e.submittedFeedback)}),Zs=({children:e,...t})=>K2(t)?e:null;Zs.displayName="MessagePrimitive.If";const Y2=(e,t)=>{const n=t.type;switch(n){case"image":return e?.Image??e?.Attachment;case"document":return e?.Document??e?.Attachment;case"file":return e?.File??e?.Attachment;default:const i=n;throw new Error(`Unknown attachment type: ${i}`)}},X2=({components:e})=>{const t=ee(({attachment:i})=>i);if(!t)return null;const n=Y2(e,t);return n?h.jsx(n,{}):null},VT=k.memo(({index:e,components:t})=>h.jsx(Lz,{index:e,children:h.jsx(X2,{components:t})}),(e,t)=>e.index===t.index&&e.components?.Image===t.components?.Image&&e.components?.Document===t.components?.Document&&e.components?.File===t.components?.File&&e.components?.Attachment===t.components?.Attachment);VT.displayName="MessagePrimitive.AttachmentByIndex";const HT=({components:e})=>{const t=ee(({message:i})=>i.role!=="user"?0:i.attachments.length);return k.useMemo(()=>Array.from({length:t},(i,r)=>h.jsx(VT,{index:r,components:e},r)),[t,e])};HT.displayName="MessagePrimitive.Attachments";const JT=({children:e})=>ee(({message:n})=>n.status?.type==="incomplete"&&n.status.reason==="error")?e:null;JT.displayName="MessagePrimitive.Error";const WT=k.forwardRef(({hideWhenSingleBranch:e,...t},n)=>h.jsx(Zs,{hasBranches:e?!0:void 0,children:h.jsx(et.div,{...t,ref:n})}));WT.displayName="BranchPickerPrimitive.Root";const GT=()=>{const e=_e(),t=ee(i=>i.thread.isRunning||!i.composer.isEditing||i.composer.isEmpty),n=k.useCallback(()=>{e.composer().send()},[e]);return t?null:n},KT=fn("ComposerPrimitive.Send",GT),fh=k.forwardRef(({onSubmit:e,...t},n)=>{const i=GT(),r=o=>{o.preventDefault(),i&&i()};return h.jsx(et.form,{...t,ref:n,onSubmit:Pe(e,r)})});fh.displayName="ComposerPrimitive.Root";function ud(){return ud=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)({}).hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},ud.apply(null,arguments)}function Q2(e,t){if(e==null)return{};var n={};for(var i in e)if({}.hasOwnProperty.call(e,i)){if(t.indexOf(i)!==-1)continue;n[i]=e[i]}return n}var e6=k.useLayoutEffect,t6=function(t){var n=k.useRef(t);return e6(function(){n.current=t}),n},Vg=function(t,n){if(typeof t=="function"){t(n);return}t.current=n},n6=function(t,n){var i=k.useRef();return k.useCallback(function(r){t.current=r,i.current&&Vg(i.current,null),i.current=n,n&&Vg(n,r)},[n])},Hg={"min-height":"0","max-height":"none",height:"0",visibility:"hidden",overflow:"hidden",position:"absolute","z-index":"-1000",top:"0",right:"0",display:"block"},r6=function(t){Object.keys(Hg).forEach(function(n){t.style.setProperty(n,Hg[n],"important")})},Jg=r6,dt=null,Wg=function(t,n){var i=t.scrollHeight;return n.sizingStyle.boxSizing==="border-box"?i+n.borderSize:i-n.paddingSize};function i6(e,t,n,i){n===void 0&&(n=1),i===void 0&&(i=1/0),dt||(dt=document.createElement("textarea"),dt.setAttribute("tabindex","-1"),dt.setAttribute("aria-hidden","true"),Jg(dt)),dt.parentNode===null&&document.body.appendChild(dt);var r=e.paddingSize,o=e.borderSize,a=e.sizingStyle,s=a.boxSizing;Object.keys(a).forEach(function(f){var p=f;dt.style[p]=a[p]}),Jg(dt),dt.value=t;var u=Wg(dt,e);dt.value=t,u=Wg(dt,e),dt.value="x";var l=dt.scrollHeight-r,c=l*n;s==="border-box"&&(c=c+r+o),u=Math.max(c,u);var d=l*i;return s==="border-box"&&(d=d+r+o),u=Math.min(d,u),[u,l]}var Gg=function(){},o6=function(t,n){return t.reduce(function(i,r){return i[r]=n[r],i},{})},a6=["borderBottomWidth","borderLeftWidth","borderRightWidth","borderTopWidth","boxSizing","fontFamily","fontSize","fontStyle","fontWeight","letterSpacing","lineHeight","paddingBottom","paddingLeft","paddingRight","paddingTop","tabSize","textIndent","textRendering","textTransform","width","wordBreak","wordSpacing","scrollbarGutter"],s6=!!document.documentElement.currentStyle,l6=function(t){var n=window.getComputedStyle(t);if(n===null)return null;var i=o6(a6,n),r=i.boxSizing;if(r==="")return null;s6&&r==="border-box"&&(i.width=parseFloat(i.width)+parseFloat(i.borderRightWidth)+parseFloat(i.borderLeftWidth)+parseFloat(i.paddingRight)+parseFloat(i.paddingLeft)+"px");var o=parseFloat(i.paddingBottom)+parseFloat(i.paddingTop),a=parseFloat(i.borderBottomWidth)+parseFloat(i.borderTopWidth);return{sizingStyle:i,paddingSize:o,borderSize:a}},u6=l6;function hh(e,t,n){var i=t6(n);w.useLayoutEffect(function(){var r=function(a){return i.current(a)};if(e)return e.addEventListener(t,r),function(){return e.removeEventListener(t,r)}},[])}var c6=function(t,n){hh(document.body,"reset",function(i){t.current.form===i.target&&n(i)})},d6=function(t){hh(window,"resize",t)},p6=function(t){hh(document.fonts,"loadingdone",t)},f6=["cacheMeasurements","maxRows","minRows","onChange","onHeightChange"],h6=function(t,n){var i=t.cacheMeasurements,r=t.maxRows,o=t.minRows,a=t.onChange,s=a===void 0?Gg:a,u=t.onHeightChange,l=u===void 0?Gg:u,c=Q2(t,f6),d=c.value!==void 0,f=w.useRef(null),p=n6(f,n),g=w.useRef(0),m=w.useRef(),y=function(){var x=f.current,b=i&&m.current?m.current:u6(x);if(b){m.current=b;var C=i6(b,x.value||x.placeholder||"x",o,r),E=C[0],$=C[1];g.current!==E&&(g.current=E,x.style.setProperty("height",E+"px","important"),l(E,{rowHeight:$}))}},v=function(x){d||y(),s(x)};return w.useLayoutEffect(y),c6(f,function(){if(!d){var _=f.current.value;requestAnimationFrame(function(){var x=f.current;x&&_!==x.value&&y()})}}),d6(y),p6(y),w.createElement("textarea",ud({},c,{onChange:v,ref:p}))},m6=w.forwardRef(h6);const YT=e=>{const t=Ot(e),n=xo(i=>i.onScrollToBottom);k.useEffect(()=>n(t),[n,t])},mh=k.forwardRef(({autoFocus:e=!1,asChild:t,disabled:n,onChange:i,onKeyDown:r,onPaste:o,submitOnEnter:a=!0,cancelOnEscape:s=!0,unstable_focusOnRunStart:u=!0,unstable_focusOnScrollToBottom:l=!0,unstable_focusOnThreadSwitched:c=!0,addAttachmentOnPaste:d=!0,...f},p)=>{const g=_e(),m=ee(({composer:A})=>A.isEditing?A.text:""),y=t?Gf:m6,v=ee(({thread:A})=>A.isDisabled)||n,_=k.useRef(null),x=Qe(p,_);LE(A=>{if(!s||!_.current?.contains(A.target))return;const j=g.composer();j.getState().canCancel&&(j.cancel(),A.preventDefault())});const b=A=>{v||!a||A.nativeEvent.isComposing||A.key==="Enter"&&A.shiftKey===!1&&(g.thread().getState().isRunning||(A.preventDefault(),_.current?.closest("form")?.requestSubmit()))},C=async A=>{if(!d)return;const j=g.thread().getState().capabilities,F=Array.from(A.clipboardData?.files||[]);if(j.attachments&&F.length>0)try{A.preventDefault(),await Promise.all(F.map(z=>g.composer().addAttachment(z)))}catch(z){console.error("Error adding attachment:",z)}},E=e&&!v,$=k.useCallback(()=>{const A=_.current;!A||!E||(A.focus({preventScroll:!0}),A.setSelectionRange(A.value.length,A.value.length))},[E]);return k.useEffect(()=>$(),[$]),YT(()=>{g.composer().getState().type==="thread"&&l&&$()}),k.useEffect(()=>{if(!(g.composer().getState().type!=="thread"||!u))return g.on("thread.run-start",$)},[u,$,g]),k.useEffect(()=>{if(!(g.composer().getState().type!=="thread"||!c))return g.on("thread-list-item.switched-to",$)},[c,$,g]),h.jsx(y,{name:"input",value:m,...f,ref:x,disabled:v,onChange:Pe(i,A=>{g.composer().getState().isEditing&&nd(()=>{g.composer().setText(A.target.value)})}),onKeyDown:Pe(r,b),onPaste:Pe(o,C)})});mh.displayName="ComposerPrimitive.Input";const g6=()=>{const e=_e(),t=ee(({composer:i})=>!i.canCancel),n=k.useCallback(()=>{e.composer().cancel()},[e]);return t?null:n},XT=fn("ComposerPrimitive.Cancel",g6),v6=({multiple:e=!0}={})=>{const t=ee(({composer:r})=>!r.isEditing),n=_e(),i=k.useCallback(()=>{const r=document.createElement("input");r.type="file",r.multiple=e,r.hidden=!0;const o=n.composer().getState().attachmentAccept;o!=="*"&&(r.accept=o),document.body.appendChild(r),r.onchange=a=>{const s=a.target.files;if(s){for(const u of s)n.composer().addAttachment(u);document.body.removeChild(r)}},r.oncancel=()=>{(!r.files||r.files.length===0)&&document.body.removeChild(r)},r.click()},[n,e]);return t?null:i},y6=fn("ComposerPrimitive.AddAttachment",v6,["multiple"]),b6=(e,t)=>{const n=t.type;switch(n){case"image":return e?.Image??e?.Attachment;case"document":return e?.Document??e?.Attachment;case"file":return e?.File??e?.Attachment;default:const i=n;throw new Error(`Unknown attachment type: ${i}`)}},_6=({components:e})=>{const t=ee(({attachment:i})=>i);if(!t)return null;const n=b6(e,t);return n?h.jsx(n,{}):null},QT=k.memo(({index:e,components:t})=>h.jsx(Fz,{index:e,children:h.jsx(_6,{components:t})}),(e,t)=>e.index===t.index&&e.components?.Image===t.components?.Image&&e.components?.Document===t.components?.Document&&e.components?.File===t.components?.File&&e.components?.Attachment===t.components?.Attachment);QT.displayName="ComposerPrimitive.AttachmentByIndex";const e0=({components:e})=>{const t=ee(i=>i.composer.attachments.length);return k.useMemo(()=>Array.from({length:t},(i,r)=>h.jsx(QT,{index:r,components:e},r)),[t,e])};e0.displayName="ComposerPrimitive.Attachments";const t0=k.forwardRef((e,t)=>h.jsx(et.div,{role:"alert",...e,ref:t}));t0.displayName="ErrorPrimitive.Root";const n0=k.forwardRef(({children:e,...t},n)=>{const i=ee(({message:r})=>r.status?.type==="incomplete"&&r.status.reason==="error"?r.status.error:void 0);return i===void 0?null:h.jsx(et.span,{...t,ref:n,children:e??String(i)})});n0.displayName="ErrorPrimitive.Message";const r0=k.forwardRef((e,t)=>h.jsx(et.div,{...e,ref:t}));r0.displayName="ThreadPrimitive.Root";const w6=e=>ee(({thread:t})=>!(e.empty===!0&&!t.isEmpty||e.empty===!1&&t.isEmpty||e.running===!0&&!t.isRunning||e.running===!1&&t.isRunning||e.disabled===!0&&!t.isDisabled||e.disabled===!1&&t.isDisabled)),To=({children:e,...t})=>w6(t)?e:null;To.displayName="ThreadPrimitive.If";const x6=e=>{const t=Ot(e),n=k.useCallback(i=>{const r=new ResizeObserver(()=>{t()}),o=new MutationObserver(()=>{t()});return r.observe(i),o.observe(i,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),()=>{r.disconnect(),o.disconnect()}},[t]);return wa(n)},S6=({autoScroll:e,scrollToBottomOnRunStart:t=!0,scrollToBottomOnInitialize:n=!0,scrollToBottomOnThreadSwitch:i=!0})=>{const r=k.useRef(null),o=uu();e===void 0&&(e=o.getState().turnAnchor!=="top");const a=k.useRef(0),s=k.useRef(null),u=k.useCallback(p=>{const g=r.current;g&&(s.current=p,g.scrollTo({top:g.scrollHeight,behavior:p}))},[]),l=()=>{const p=r.current;if(!p)return;const g=o.getState().isAtBottom,m=Math.abs(p.scrollHeight-p.scrollTop-p.clientHeight)<1||p.scrollHeight<=p.clientHeight;!m&&a.current<p.scrollTop||(m&&(s.current=null),(m||s.current===null)&&m!==g&&Io(o).setState({isAtBottom:m})),a.current=p.scrollTop},c=x6(()=>{const p=s.current;p?u(p):e&&o.getState().isAtBottom&&u("instant"),l()}),d=wa(p=>(p.addEventListener("scroll",l),()=>{p.removeEventListener("scroll",l)}));return YT(({behavior:p})=>{u(p)}),Bu("thread.run-start",()=>{t&&(s.current="auto",requestAnimationFrame(()=>{u("auto")}))}),Bu("thread.initialize",()=>{n&&(s.current="instant",requestAnimationFrame(()=>{u("instant")}))}),Bu("thread-list-item.switched-to",()=>{i&&(s.current="instant",requestAnimationFrame(()=>{u("instant")}))}),Qe(c,d,r)},I6=()=>{const e=xo(n=>n.registerViewport),t=k.useCallback(n=>n.clientHeight,[]);return UT(e,t)},i0=k.forwardRef(({autoScroll:e,scrollToBottomOnRunStart:t,scrollToBottomOnInitialize:n,scrollToBottomOnThreadSwitch:i,children:r,...o},a)=>{const s=S6({autoScroll:e,scrollToBottomOnRunStart:t,scrollToBottomOnInitialize:n,scrollToBottomOnThreadSwitch:i}),u=I6(),l=Qe(a,s,u);return h.jsx(et.div,{...o,ref:l,children:r})});i0.displayName="ThreadPrimitive.ViewportScrollable";const o0=k.forwardRef(({turnAnchor:e,...t},n)=>h.jsx($E,{options:{turnAnchor:e},children:h.jsx(i0,{...t,ref:n})}));o0.displayName="ThreadPrimitive.Viewport";const a0=(e,t)=>e.Message===t.Message&&e.EditComposer===t.EditComposer&&e.UserEditComposer===t.UserEditComposer&&e.AssistantEditComposer===t.AssistantEditComposer&&e.SystemEditComposer===t.SystemEditComposer&&e.UserMessage===t.UserMessage&&e.AssistantMessage===t.AssistantMessage&&e.SystemMessage===t.SystemMessage,k6=()=>null,E6=(e,t,n)=>{switch(t){case"user":return n?e.UserEditComposer??e.EditComposer??e.UserMessage??e.Message:e.UserMessage??e.Message;case"assistant":return n?e.AssistantEditComposer??e.EditComposer??e.AssistantMessage??e.Message:e.AssistantMessage??e.Message;case"system":return n?e.SystemEditComposer??e.EditComposer??e.SystemMessage??e.Message:e.SystemMessage??k6;default:const i=t;throw new Error(`Unknown message role: ${i}`)}},T6=({components:e})=>{const t=ee(({message:r})=>r.role),n=ee(({message:r})=>r.composer.isEditing),i=E6(e,t,n);return h.jsx(i,{})},s0=k.memo(({index:e,components:t})=>h.jsx(zz,{index:e,children:h.jsx(T6,{components:t})}),(e,t)=>e.index===t.index&&a0(e.components,t.components));s0.displayName="ThreadPrimitive.MessageByIndex";const l0=({components:e})=>{const t=ee(({thread:i})=>i.messages.length);return k.useMemo(()=>t===0?null:Array.from({length:t},(i,r)=>h.jsx(s0,{index:r,components:e},r)),[t,e])};l0.displayName="ThreadPrimitive.Messages";const $6=k.memo(l0,(e,t)=>a0(e.components,t.components)),C6=({behavior:e}={})=>{const t=xo(r=>r.isAtBottom),n=uu(),i=k.useCallback(()=>{n.getState().scrollToBottom({behavior:e})},[n,e]);return t?null:i},A6=fn("ThreadPrimitive.ScrollToBottom",C6,["behavior"]),P6=({prompt:e,send:t,clearComposer:n=!0,autoSend:i,method:r})=>{const o=_e(),a=ee(({thread:l})=>l.isDisabled),s=t??i??!1,u=k.useCallback(()=>{const l=o.thread().getState().isRunning;if(s&&!l)o.thread().append(e),n&&o.composer().setText("");else if(n)o.composer().setText(e);else{const c=o.composer().getState().text;o.composer().setText(c.trim()?`${c} ${e}`:e)}},[o,s,n,e]);return a?null:u},R6=fn("ThreadPrimitive.Suggestion",P6,["prompt","send","clearComposer","autoSend","method"]),u0=k.forwardRef(({onClick:e,disabled:t,...n},i)=>{const r=ee(({threads:a})=>a.newThreadId===a.mainThreadId),o=_e();return h.jsx(et.button,{type:"button",...r?{"data-active":"true","aria-current":"true"}:null,...n,ref:i,disabled:t,onClick:Pe(e,()=>{o.threads().switchToNewThread()})})});u0.displayName="ThreadListPrimitive.New";const c0=k.memo(({index:e,archived:t=!1,components:n})=>{const i=n.ThreadListItem;return h.jsx(Mz,{index:e,archived:t,children:h.jsx(i,{})})},(e,t)=>e.index===t.index&&e.archived===t.archived&&e.components.ThreadListItem===t.components.ThreadListItem);c0.displayName="ThreadListPrimitive.ItemByIndex";const d0=({archived:e=!1,components:t})=>{const n=ee(({threads:r})=>e?r.archivedThreadIds.length:r.threadIds.length);return k.useMemo(()=>Array.from({length:n},(r,o)=>h.jsx(c0,{index:o,archived:e,components:t},o)),[n,e,t])};d0.displayName="ThreadListPrimitive.Items";const p0=k.forwardRef((e,t)=>h.jsx(et.div,{...e,ref:t}));p0.displayName="ThreadListPrimitive.Root";const f0=k.forwardRef((e,t)=>{const n=ee(({threads:i,threadListItem:r})=>i.mainThreadId===r.id);return h.jsx(et.div,{...n?{"data-active":"true","aria-current":"true"}:null,...e,ref:t})});f0.displayName="ThreadListItemPrimitive.Root";const O6=()=>{const e=_e();return k.useCallback(()=>{e.threadListItem().switchTo()},[e])},N6=fn("ThreadListItemPrimitive.Trigger",O6),h0=({fallback:e})=>{const t=ee(({threadListItem:n})=>n.title);return h.jsx(h.Fragment,{children:t||e})};h0.displayName="ThreadListItemPrimitive.Title";const j6=(e,t)=>{const n=k.useRef(null),i=k.useRef(null);return k.useEffect(()=>()=>{i.current?.()},[]),k.useCallback(()=>{i.current?.(),(function(){if(n.current||!e.current)return;let d=e.current;for(;d;){const{overflowY:f}=getComputedStyle(d);if(f==="scroll"||f==="auto"){n.current=d;break}d=d.parentElement}})();const o=n.current;if(!o)return;const a=o.scrollTop,s=o.style.scrollbarWidth;o.style.scrollbarWidth="none";const u=()=>o.scrollTop=a;o.addEventListener("scroll",u);const l=setTimeout(()=>{o.removeEventListener("scroll",u),o.style.scrollbarWidth=s,i.current=null},t);i.current=()=>{clearTimeout(l),o.removeEventListener("scroll",u),o.style.scrollbarWidth=s}},[t,e])},M6=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,{...n.description?{description:n.description}:void 0,parameters:n.parameters instanceof ks.ZodType?ks.toJSONSchema(n.parameters):n.parameters}])),D6=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>!t.disabled&&t.type!=="backend"));let qs=null;function z6(e,t){qs={helpers:e,toolsRequiringApproval:new Set(t)}}function U6(){qs=null}const L6=(e,t)=>rz({...e,execute:async(n,i)=>{if(qs?.toolsRequiringApproval.has(t)){const{helpers:r}=qs,o=i.toolCallId??"";if(!r.isToolApproved(t)&&!await r.requestApproval(t,o,n))return{content:[{type:"text",text:`Tool "${t}" execution was denied by the user. Please acknowledge this and continue without using this tool's result.`}],isError:!0}}return e.execute?.(n,i)},toolName:t});function F6(e,t,n){if(!t||t.length===0)return e;const i=new Set(t);return Object.fromEntries(Object.entries(e).map(([r,o])=>{if(!i.has(r))return[r,o];const a=o.execute;return a?[r,{...o,execute:async(s,u)=>{const l=u??{},c=l.toolCallId??"";return n.isToolApproved(r)||await n.requestApproval(r,c,s)?a(s,l):{content:[{type:"text",text:`Tool "${r}" execution was denied by the user. Please acknowledge this and continue without using this tool's result.`}],isError:!0}}}]:[r,o]}))}const B6=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],Z6=R.createLucideIcon("arrow-down",B6);const q6=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],V6=R.createLucideIcon("arrow-up",q6);const H6=[["path",{d:"M12 18V5",key:"adv99a"}],["path",{d:"M15 13a4.17 4.17 0 0 1-3-4 4.17 4.17 0 0 1-3 4",key:"1e3is1"}],["path",{d:"M17.598 6.5A3 3 0 1 0 12 5a3 3 0 1 0-5.598 1.5",key:"1gqd8o"}],["path",{d:"M17.997 5.125a4 4 0 0 1 2.526 5.77",key:"iwvgf7"}],["path",{d:"M18 18a4 4 0 0 0 2-7.464",key:"efp6ie"}],["path",{d:"M19.967 17.483A4 4 0 1 1 12 18a4 4 0 1 1-7.967-.517",key:"1gq6am"}],["path",{d:"M6 18a4 4 0 0 1-2-7.464",key:"k1g0md"}],["path",{d:"M6.003 5.125a4 4 0 0 0-2.526 5.77",key:"q97ue3"}]],J6=R.createLucideIcon("brain",H6);const W6=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],ir=R.createLucideIcon("check",W6);const G6=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Vs=R.createLucideIcon("chevron-down",G6);const K6=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],Y6=R.createLucideIcon("chevron-left",K6);const X6=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],m0=R.createLucideIcon("chevron-right",X6);const Q6=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],gh=R.createLucideIcon("copy",Q6);const eF=[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],tF=R.createLucideIcon("file-text",eF);const nF=[["path",{d:"M12 2v4",key:"3427ic"}],["path",{d:"m16.2 7.8 2.9-2.9",key:"r700ao"}],["path",{d:"M18 12h4",key:"wj9ykh"}],["path",{d:"m16.2 16.2 2.9 2.9",key:"1bxg5t"}],["path",{d:"M12 18v4",key:"jadmvz"}],["path",{d:"m4.9 19.1 2.9-2.9",key:"bwix9q"}],["path",{d:"M2 12h4",key:"j09sii"}],["path",{d:"m4.9 4.9 2.9 2.9",key:"giyufr"}]],Hs=R.createLucideIcon("loader",nF);const rF=[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3",key:"1dcmit"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3",key:"1e4gt3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3",key:"wsl5sc"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3",key:"18trek"}]],iF=R.createLucideIcon("maximize",rF);const oF=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719",key:"1sd12s"}]],aF=R.createLucideIcon("message-circle",oF);const sF=[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3",key:"hohbtr"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3",key:"5jw1f3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3",key:"198tvr"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3",key:"ph8mxp"}]],lF=R.createLucideIcon("minimize",sF);const uF=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}],["path",{d:"m8 9 3 3-3 3",key:"12hl5m"}]],cF=R.createLucideIcon("panel-right-close",uF);const dF=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}],["path",{d:"m10 15-3-3 3-3",key:"1pgupc"}]],pF=R.createLucideIcon("panel-right-open",dF);const fF=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]],hF=R.createLucideIcon("pencil",fF);const mF=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],g0=R.createLucideIcon("plus",mF);const gF=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],vF=R.createLucideIcon("refresh-cw",gF);const yF=[["path",{d:"M14 17H5",key:"gfn3mx"}],["path",{d:"M19 7h-9",key:"6i9tg"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}],["circle",{cx:"7",cy:"7",r:"3",key:"dfmy0x"}]],bF=R.createLucideIcon("settings-2",yF);const _F=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],wF=R.createLucideIcon("square",_F);const xF=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],xa=R.createLucideIcon("x",xF);var Sa=({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:i="-"}={})=>{const r=()=>{const o=n.length,a=new Array(t);for(let s=0;s<t;s++)a[s]=n[Math.random()*o|0];return a.join("")};if(e==null)return r;if(n.includes(i))throw new al({argument:"separator",message:`The separator "${i}" must not be part of the alphabet "${n}".`});return()=>`${e}${i}${r()}`},v0=Sa();function Kg(e=globalThis){var t,n,i;return e.window?"runtime/browser":(t=e.navigator)!=null&&t.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(i=(n=e.process)==null?void 0:n.versions)!=null&&i.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function _r(e){if(e==null)return{};const t={};if(e instanceof Headers)e.forEach((n,i)=>{t[i.toLowerCase()]=n});else{Array.isArray(e)||(e=Object.entries(e));for(const[n,i]of e)i!=null&&(t[n.toLowerCase()]=i)}return t}function Yg(e,...t){const n=new Headers(_r(e)),i=n.get("user-agent")||"";return n.set("user-agent",[i,...t].filter(Boolean).join(" ")),Object.fromEntries(n.entries())}var SF=/"__proto__"\s*:/,IF=/"constructor"\s*:/;function Xg(e){const t=JSON.parse(e);return t===null||typeof t!="object"||SF.test(e)===!1&&IF.test(e)===!1?t:kF(t)}function kF(e){let t=[e];for(;t.length;){const n=t;t=[];for(const i of n){if(Object.prototype.hasOwnProperty.call(i,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(i,"constructor")&&Object.prototype.hasOwnProperty.call(i.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const r in i){const o=i[r];o&&typeof o=="object"&&t.push(o)}}}return e}function EF(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return Xg(e)}try{return Xg(e)}finally{Error.stackTraceLimit=t}}var Js=Symbol.for("vercel.ai.validator");function TF(e){return{[Js]:!0,validate:e}}function $F(e){return typeof e=="object"&&e!==null&&Js in e&&e[Js]===!0&&"validate"in e}function CF(e){let t;return()=>(t==null&&(t=e()),t)}function AF(e){return $F(e)?e:typeof e=="function"?e():PF(e)}function PF(e){return TF(async t=>{const n=await e["~standard"].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new Un({value:t,cause:n.issues})}})}async function Qg({value:e,schema:t}){const n=await vh({value:e,schema:t});if(!n.success)throw Un.wrap({value:e,cause:n.error});return n.value}async function vh({value:e,schema:t}){const n=AF(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};const i=await n.validate(e);return i.success?{success:!0,value:i.value,rawValue:e}:{success:!1,error:Un.wrap({value:e,cause:i.error}),rawValue:e}}catch(i){return{success:!1,error:Un.wrap({value:e,cause:i}),rawValue:e}}}async function Ws({text:e,schema:t}){try{const n=EF(e);return t==null?{success:!0,value:n,rawValue:n}:await vh({value:n,schema:t})}catch(n){return{success:!1,error:di.isInstance(n)?n:new di({text:e,cause:n}),rawValue:void 0}}}function RF({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new uo).pipeThrough(new TransformStream({async transform({data:n},i){n!=="[DONE]"&&i.enqueue(await Ws({text:n,schema:t}))}}))}async function Yr(e){return typeof e=="function"&&(e=e()),Promise.resolve(e)}function ps(e){if(e.type==="object"){e.additionalProperties=!1;const t=e.properties;if(t!=null)for(const n in t)t[n]=ps(t[n])}return e.type==="array"&&e.items!=null&&(Array.isArray(e.items)?e.items=e.items.map(t=>ps(t)):e.items=ps(e.items)),e}var OF=(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("/")},NF=Symbol("Let zodToJsonSchema decide on which parser to use"),ev={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"},jF=e=>typeof e=="string"?{...ev,name:e}:{...ev,...e};function Nt(){return{}}function MF(e,t){var n,i,r;const o={type:"array"};return(n=e.type)!=null&&n._def&&((r=(i=e.type)==null?void 0:i._def)==null?void 0:r.typeName)!==H.ZodAny&&(o.items=Te(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&(o.minItems=e.minLength.value),e.maxLength&&(o.maxItems=e.maxLength.value),e.exactLength&&(o.minItems=e.exactLength.value,o.maxItems=e.exactLength.value),o}function DF(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 zF(){return{type:"boolean"}}function y0(e,t){return Te(e.type._def,t)}var UF=(e,t)=>Te(e.innerType._def,t);function b0(e,t,n){const i=n??t.dateStrategy;if(Array.isArray(i))return{anyOf:i.map((r,o)=>b0(e,t,r))};switch(i){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return LF(e)}}var LF=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 FF(e,t){return{...Te(e.innerType._def,t),default:e.defaultValue()}}function BF(e,t){return t.effectStrategy==="input"?Te(e.schema._def,t):Nt()}function ZF(e){return{type:"string",enum:Array.from(e.values)}}var qF=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function VF(e,t){const n=[Te(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Te(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(r=>!!r),i=[];return n.forEach(r=>{if(qF(r))i.push(...r.allOf);else{let o=r;if("additionalProperties"in r&&r.additionalProperties===!1){const{additionalProperties:a,...s}=r;o=s}i.push(o)}}),i.length?{allOf:i}:void 0}function HF(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 nc=void 0,Xt={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:()=>(nc===void 0&&(nc=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),nc),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 _0(e,t){const n={type:"string"};if(e.checks)for(const i of e.checks)switch(i.kind){case"min":n.minLength=typeof n.minLength=="number"?Math.max(n.minLength,i.value):i.value;break;case"max":n.maxLength=typeof n.maxLength=="number"?Math.min(n.maxLength,i.value):i.value;break;case"email":switch(t.emailStrategy){case"format:email":Qt(n,"email",i.message,t);break;case"format:idn-email":Qt(n,"idn-email",i.message,t);break;case"pattern:zod":pt(n,Xt.email,i.message,t);break}break;case"url":Qt(n,"uri",i.message,t);break;case"uuid":Qt(n,"uuid",i.message,t);break;case"regex":pt(n,i.regex,i.message,t);break;case"cuid":pt(n,Xt.cuid,i.message,t);break;case"cuid2":pt(n,Xt.cuid2,i.message,t);break;case"startsWith":pt(n,RegExp(`^${rc(i.value,t)}`),i.message,t);break;case"endsWith":pt(n,RegExp(`${rc(i.value,t)}$`),i.message,t);break;case"datetime":Qt(n,"date-time",i.message,t);break;case"date":Qt(n,"date",i.message,t);break;case"time":Qt(n,"time",i.message,t);break;case"duration":Qt(n,"duration",i.message,t);break;case"length":n.minLength=typeof n.minLength=="number"?Math.max(n.minLength,i.value):i.value,n.maxLength=typeof n.maxLength=="number"?Math.min(n.maxLength,i.value):i.value;break;case"includes":{pt(n,RegExp(rc(i.value,t)),i.message,t);break}case"ip":{i.version!=="v6"&&Qt(n,"ipv4",i.message,t),i.version!=="v4"&&Qt(n,"ipv6",i.message,t);break}case"base64url":pt(n,Xt.base64url,i.message,t);break;case"jwt":pt(n,Xt.jwt,i.message,t);break;case"cidr":{i.version!=="v6"&&pt(n,Xt.ipv4Cidr,i.message,t),i.version!=="v4"&&pt(n,Xt.ipv6Cidr,i.message,t);break}case"emoji":pt(n,Xt.emoji(),i.message,t);break;case"ulid":{pt(n,Xt.ulid,i.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{Qt(n,"binary",i.message,t);break}case"contentEncoding:base64":{n.contentEncoding="base64";break}case"pattern:zod":{pt(n,Xt.base64,i.message,t);break}}break}case"nanoid":pt(n,Xt.nanoid,i.message,t)}return n}function rc(e,t){return t.patternStrategy==="escape"?WF(e):e}var JF=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function WF(e){let t="";for(let n=0;n<e.length;n++)JF.has(e[n])||(t+="\\"),t+=e[n];return t}function Qt(e,t,n,i){var r;e.format||(r=e.anyOf)!=null&&r.some(o=>o.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format}),delete e.format),e.anyOf.push({format:t,...n&&i.errorMessages&&{errorMessage:{format:n}}})):e.format=t}function pt(e,t,n,i){var r;e.pattern||(r=e.allOf)!=null&&r.some(o=>o.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern}),delete e.pattern),e.allOf.push({pattern:tv(t,i),...n&&i.errorMessages&&{errorMessage:{pattern:n}}})):e.pattern=tv(t,i)}function tv(e,t){var n;if(!t.applyRegexFlags||!e.flags)return e.source;const i={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},r=i.i?e.source.toLowerCase():e.source;let o="",a=!1,s=!1,u=!1;for(let l=0;l<r.length;l++){if(a){o+=r[l],a=!1;continue}if(i.i){if(s){if(r[l].match(/[a-z]/)){u?(o+=r[l],o+=`${r[l-2]}-${r[l]}`.toUpperCase(),u=!1):r[l+1]==="-"&&((n=r[l+2])!=null&&n.match(/[a-z]/))?(o+=r[l],u=!0):o+=`${r[l]}${r[l].toUpperCase()}`;continue}}else if(r[l].match(/[a-z]/)){o+=`[${r[l]}${r[l].toUpperCase()}]`;continue}}if(i.m){if(r[l]==="^"){o+=`(^|(?<=[\r
|
|
74
|
-
]))`;continue}else if(r[l]==="$"){o+=`($|(?=[\r
|
|
75
|
-
]))`;continue}}if(i.s&&r[l]==="."){o+=s?`${r[l]}\r
|
|
76
|
-
`:`[${r[l]}\r
|
|
77
|
-
]`;continue}o+=r[l],r[l]==="\\"?a=!0:s&&r[l]==="]"?s=!1:!s&&r[l]==="["&&(s=!0)}try{new RegExp(o)}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 o}function w0(e,t){var n,i,r,o,a,s;const u={type:"object",additionalProperties:(n=Te(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?n:t.allowedAdditionalProperties};if(((i=e.keyType)==null?void 0:i._def.typeName)===H.ZodString&&((r=e.keyType._def.checks)!=null&&r.length)){const{type:l,...c}=_0(e.keyType._def,t);return{...u,propertyNames:c}}else{if(((o=e.keyType)==null?void 0:o._def.typeName)===H.ZodEnum)return{...u,propertyNames:{enum:e.keyType._def.values}};if(((a=e.keyType)==null?void 0:a._def.typeName)===H.ZodBranded&&e.keyType._def.type._def.typeName===H.ZodString&&((s=e.keyType._def.type._def.checks)!=null&&s.length)){const{type:l,...c}=y0(e.keyType._def,t);return{...u,propertyNames:c}}}return u}function GF(e,t){if(t.mapStrategy==="record")return w0(e,t);const n=Te(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Nt(),i=Te(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Nt();return{type:"array",maxItems:125,items:{type:"array",items:[n,i],minItems:2,maxItems:2}}}function KF(e){const t=e.values,i=Object.keys(e.values).filter(o=>typeof t[t[o]]!="number").map(o=>t[o]),r=Array.from(new Set(i.map(o=>typeof o)));return{type:r.length===1?r[0]==="string"?"string":"number":["string","number"],enum:i}}function YF(){return{not:Nt()}}function XF(){return{type:"null"}}var cd={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function QF(e,t){const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(i=>i._def.typeName in cd&&(!i._def.checks||!i._def.checks.length))){const i=n.reduce((r,o)=>{const a=cd[o._def.typeName];return a&&!r.includes(a)?[...r,a]:r},[]);return{type:i.length>1?i:i[0]}}else if(n.every(i=>i._def.typeName==="ZodLiteral"&&!i.description)){const i=n.reduce((r,o)=>{const a=typeof o._def.value;switch(a){case"string":case"number":case"boolean":return[...r,a];case"bigint":return[...r,"integer"];case"object":if(o._def.value===null)return[...r,"null"];case"symbol":case"undefined":case"function":default:return r}},[]);if(i.length===n.length){const r=i.filter((o,a,s)=>s.indexOf(o)===a);return{type:r.length>1?r:r[0],enum:n.reduce((o,a)=>o.includes(a._def.value)?o:[...o,a._def.value],[])}}}else if(n.every(i=>i._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((i,r)=>[...i,...r._def.values.filter(o=>!i.includes(o))],[])};return eB(e,t)}var eB=(e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((i,r)=>Te(i._def,{...t,currentPath:[...t.currentPath,"anyOf",`${r}`]})).filter(i=>!!i&&(!t.strictUnions||typeof i=="object"&&Object.keys(i).length>0));return n.length?{anyOf:n}:void 0};function tB(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[cd[e.innerType._def.typeName],"null"]};const n=Te(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function nB(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 rB(e,t){const n={type:"object",properties:{}},i=[],r=e.shape();for(const a in r){let s=r[a];if(s===void 0||s._def===void 0)continue;const u=oB(s),l=Te(s._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});l!==void 0&&(n.properties[a]=l,u||i.push(a))}i.length&&(n.required=i);const o=iB(e,t);return o!==void 0&&(n.additionalProperties=o),n}function iB(e,t){if(e.catchall._def.typeName!=="ZodNever")return Te(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 oB(e){try{return e.isOptional()}catch{return!0}}var aB=(e,t)=>{var n;if(t.currentPath.toString()===((n=t.propertyPath)==null?void 0:n.toString()))return Te(e.innerType._def,t);const i=Te(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return i?{anyOf:[{not:Nt()},i]}:Nt()},sB=(e,t)=>{if(t.pipeStrategy==="input")return Te(e.in._def,t);if(t.pipeStrategy==="output")return Te(e.out._def,t);const n=Te(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),i=Te(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,i].filter(r=>r!==void 0)}};function lB(e,t){return Te(e.type._def,t)}function uB(e,t){const i={type:"array",uniqueItems:!0,items:Te(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&(i.minItems=e.minSize.value),e.maxSize&&(i.maxItems=e.maxSize.value),i}function cB(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((n,i)=>Te(n._def,{...t,currentPath:[...t.currentPath,"items",`${i}`]})).reduce((n,i)=>i===void 0?n:[...n,i],[]),additionalItems:Te(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((n,i)=>Te(n._def,{...t,currentPath:[...t.currentPath,"items",`${i}`]})).reduce((n,i)=>i===void 0?n:[...n,i],[])}}function dB(){return{not:Nt()}}function pB(){return Nt()}var fB=(e,t)=>Te(e.innerType._def,t),hB=(e,t,n)=>{switch(t){case H.ZodString:return _0(e,n);case H.ZodNumber:return nB(e);case H.ZodObject:return rB(e,n);case H.ZodBigInt:return DF(e);case H.ZodBoolean:return zF();case H.ZodDate:return b0(e,n);case H.ZodUndefined:return dB();case H.ZodNull:return XF();case H.ZodArray:return MF(e,n);case H.ZodUnion:case H.ZodDiscriminatedUnion:return QF(e,n);case H.ZodIntersection:return VF(e,n);case H.ZodTuple:return cB(e,n);case H.ZodRecord:return w0(e,n);case H.ZodLiteral:return HF(e);case H.ZodEnum:return ZF(e);case H.ZodNativeEnum:return KF(e);case H.ZodNullable:return tB(e,n);case H.ZodOptional:return aB(e,n);case H.ZodMap:return GF(e,n);case H.ZodSet:return uB(e,n);case H.ZodLazy:return()=>e.getter()._def;case H.ZodPromise:return lB(e,n);case H.ZodNaN:case H.ZodNever:return YF();case H.ZodEffects:return BF(e,n);case H.ZodAny:return Nt();case H.ZodUnknown:return pB();case H.ZodDefault:return FF(e,n);case H.ZodBranded:return y0(e,n);case H.ZodReadonly:return fB(e,n);case H.ZodCatch:return UF(e,n);case H.ZodPipeline:return sB(e,n);case H.ZodFunction:case H.ZodVoid:case H.ZodSymbol:return;default:return(i=>{})()}};function Te(e,t,n=!1){var i;const r=t.seen.get(e);if(t.override){const u=(i=t.override)==null?void 0:i.call(t,e,t,r,n);if(u!==NF)return u}if(r&&!n){const u=mB(r,t);if(u!==void 0)return u}const o={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,o);const a=hB(e,e.typeName,t),s=typeof a=="function"?Te(a(),t):a;if(s&&gB(e,t,s),t.postProcess){const u=t.postProcess(s,e,t);return o.jsonSchema=s,u}return o.jsonSchema=s,s}var mB=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:OF(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((n,i)=>t.currentPath[i]===n)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Nt()):t.$refStrategy==="seen"?Nt():void 0}},gB=(e,t,n)=>(e.description&&(n.description=e.description),n),vB=e=>{const t=jF(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(([i,r])=>[r._def,{def:r._def,path:[...t.basePath,t.definitionPath,i],jsonSchema:void 0}]))}},yB=(e,t)=>{var n;const i=vB(t);let r=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((l,[c,d])=>{var f;return{...l,[c]:(f=Te(d._def,{...i,currentPath:[...i.basePath,i.definitionPath,c]},!0))!=null?f:Nt()}},{}):void 0;const o=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,a=(n=Te(e._def,o===void 0?i:{...i,currentPath:[...i.basePath,i.definitionPath,o]},!1))!=null?n:Nt(),s=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;s!==void 0&&(a.title=s);const u=o===void 0?r?{...a,[i.definitionPath]:r}:a:{$ref:[...i.$refStrategy==="relative"?[]:i.basePath,i.definitionPath,o].join("/"),[i.definitionPath]:{...r,[o]:a}};return u.$schema="http://json-schema.org/draft-07/schema#",u},bB=yB;function _B(e,t){var n;const i=(n=void 0)!=null?n:!1;return bu(()=>bB(e,{$refStrategy:i?"root":"none"}),{validate:async r=>{const o=await e.safeParseAsync(r);return o.success?{success:!0,value:o.data}:{success:!1,error:o.error}}})}function wB(e,t){var n;const i=(n=void 0)!=null?n:!1;return bu(()=>ps(Tl(e,{target:"draft-7",io:"input",reused:i?"ref":"inline"})),{validate:async r=>{const o=await $l(e,r);return o.success?{success:!0,value:o.data}:{success:!1,error:o.error}}})}function xB(e){return"_zod"in e}function x0(e,t){return xB(e)?wB(e):_B(e)}var dd=Symbol.for("vercel.ai.schema");function bu(e,{validate:t}={}){return{[dd]:!0,_type:void 0,[Js]:!0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}function SB(e){return typeof e=="object"&&e!==null&&dd in e&&e[dd]===!0&&"jsonSchema"in e&&"validate"in e}function IB(e){return e==null?bu({properties:{},additionalProperties:!1}):SB(e)?e:typeof e=="function"?e():x0(e)}var kB=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},kr="1.9.0",nv=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function EB(e){var t=new Set([e]),n=new Set,i=e.match(nv);if(!i)return function(){return!1};var r={major:+i[1],minor:+i[2],patch:+i[3],prerelease:i[4]};if(r.prerelease!=null)return function(u){return u===e};function o(s){return n.add(s),!1}function a(s){return t.add(s),!0}return function(u){if(t.has(u))return!0;if(n.has(u))return!1;var l=u.match(nv);if(!l)return o(u);var c={major:+l[1],minor:+l[2],patch:+l[3],prerelease:l[4]};return c.prerelease!=null||r.major!==c.major?o(u):r.major===0?r.minor===c.minor&&r.patch<=c.patch?a(u):o(u):r.minor<=c.minor?a(u):o(u)}}var TB=EB(kr),$B=kr.split(".")[0],$o=Symbol.for("opentelemetry.js.api."+$B),Co=kB;function yh(e,t,n,i){var r;i===void 0&&(i=!1);var o=Co[$o]=(r=Co[$o])!==null&&r!==void 0?r:{version:kr};if(!i&&o[e]){var a=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+e);return n.error(a.stack||a.message),!1}if(o.version!==kr){var a=new Error("@opentelemetry/api: Registration of version v"+o.version+" for "+e+" does not match previously registered API v"+kr);return n.error(a.stack||a.message),!1}return o[e]=t,n.debug("@opentelemetry/api: Registered a global for "+e+" v"+kr+"."),!0}function Ao(e){var t,n,i=(t=Co[$o])===null||t===void 0?void 0:t.version;if(!(!i||!TB(i)))return(n=Co[$o])===null||n===void 0?void 0:n[e]}function bh(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+kr+".");var n=Co[$o];n&&delete n[e]}var CB=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var i=n.call(e),r,o=[],a;try{for(;(t===void 0||t-- >0)&&!(r=i.next()).done;)o.push(r.value)}catch(s){a={error:s}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(a)throw a.error}}return o},AB=function(e,t,n){if(n||arguments.length===2)for(var i=0,r=t.length,o;i<r;i++)(o||!(i in t))&&(o||(o=Array.prototype.slice.call(t,0,i)),o[i]=t[i]);return e.concat(o||Array.prototype.slice.call(t))},PB=(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 Li("debug",this._namespace,t)},e.prototype.error=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return Li("error",this._namespace,t)},e.prototype.info=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return Li("info",this._namespace,t)},e.prototype.warn=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return Li("warn",this._namespace,t)},e.prototype.verbose=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return Li("verbose",this._namespace,t)},e})();function Li(e,t,n){var i=Ao("diag");if(i)return n.unshift(t),i[e].apply(i,AB([],CB(n),!1))}var Et;(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"})(Et||(Et={}));function RB(e,t){e<Et.NONE?e=Et.NONE:e>Et.ALL&&(e=Et.ALL),t=t||{};function n(i,r){var o=t[i];return typeof o=="function"&&e>=r?o.bind(t):function(){}}return{error:n("error",Et.ERROR),warn:n("warn",Et.WARN),info:n("info",Et.INFO),debug:n("debug",Et.DEBUG),verbose:n("verbose",Et.VERBOSE)}}var OB=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var i=n.call(e),r,o=[],a;try{for(;(t===void 0||t-- >0)&&!(r=i.next()).done;)o.push(r.value)}catch(s){a={error:s}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(a)throw a.error}}return o},NB=function(e,t,n){if(n||arguments.length===2)for(var i=0,r=t.length,o;i<r;i++)(o||!(i in t))&&(o||(o=Array.prototype.slice.call(t,0,i)),o[i]=t[i]);return e.concat(o||Array.prototype.slice.call(t))},jB="diag",Gs=(function(){function e(){function t(r){return function(){for(var o=[],a=0;a<arguments.length;a++)o[a]=arguments[a];var s=Ao("diag");if(s)return s[r].apply(s,NB([],OB(o),!1))}}var n=this,i=function(r,o){var a,s,u;if(o===void 0&&(o={logLevel:Et.INFO}),r===n){var l=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=l.stack)!==null&&a!==void 0?a:l.message),!1}typeof o=="number"&&(o={logLevel:o});var c=Ao("diag"),d=RB((s=o.logLevel)!==null&&s!==void 0?s:Et.INFO,r);if(c&&!o.suppressOverrideMessage){var f=(u=new Error().stack)!==null&&u!==void 0?u:"<failed to generate stacktrace>";c.warn("Current logger will be overwritten from "+f),d.warn("Current logger will overwrite one already registered from "+f)}return yh("diag",d,n,!0)};n.setLogger=i,n.disable=function(){bh(jB,n)},n.createComponentLogger=function(r){return new PB(r)},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})();function MB(e){return Symbol.for(e)}var DB=(function(){function e(t){var n=this;n._currentContext=t?new Map(t):new Map,n.getValue=function(i){return n._currentContext.get(i)},n.setValue=function(i,r){var o=new e(n._currentContext);return o._currentContext.set(i,r),o},n.deleteValue=function(i){var r=new e(n._currentContext);return r._currentContext.delete(i),r}}return e})(),zB=new DB,UB=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var i=n.call(e),r,o=[],a;try{for(;(t===void 0||t-- >0)&&!(r=i.next()).done;)o.push(r.value)}catch(s){a={error:s}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(a)throw a.error}}return o},LB=function(e,t,n){if(n||arguments.length===2)for(var i=0,r=t.length,o;i<r;i++)(o||!(i in t))&&(o||(o=Array.prototype.slice.call(t,0,i)),o[i]=t[i]);return e.concat(o||Array.prototype.slice.call(t))},FB=(function(){function e(){}return e.prototype.active=function(){return zB},e.prototype.with=function(t,n,i){for(var r=[],o=3;o<arguments.length;o++)r[o-3]=arguments[o];return n.call.apply(n,LB([i],UB(r),!1))},e.prototype.bind=function(t,n){return n},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e})(),BB=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var i=n.call(e),r,o=[],a;try{for(;(t===void 0||t-- >0)&&!(r=i.next()).done;)o.push(r.value)}catch(s){a={error:s}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(a)throw a.error}}return o},ZB=function(e,t,n){if(n||arguments.length===2)for(var i=0,r=t.length,o;i<r;i++)(o||!(i in t))&&(o||(o=Array.prototype.slice.call(t,0,i)),o[i]=t[i]);return e.concat(o||Array.prototype.slice.call(t))},ic="context",qB=new FB,S0=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(t){return yh(ic,t,Gs.instance())},e.prototype.active=function(){return this._getContextManager().active()},e.prototype.with=function(t,n,i){for(var r,o=[],a=3;a<arguments.length;a++)o[a-3]=arguments[a];return(r=this._getContextManager()).with.apply(r,ZB([t,n,i],BB(o),!1))},e.prototype.bind=function(t,n){return this._getContextManager().bind(t,n)},e.prototype._getContextManager=function(){return Ao(ic)||qB},e.prototype.disable=function(){this._getContextManager().disable(),bh(ic,Gs.instance())},e})(),pd;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(pd||(pd={}));var I0="0000000000000000",k0="00000000000000000000000000000000",VB={traceId:k0,spanId:I0,traceFlags:pd.NONE},io=(function(){function e(t){t===void 0&&(t=VB),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})(),_h=MB("OpenTelemetry Context Key SPAN");function wh(e){return e.getValue(_h)||void 0}function HB(){return wh(S0.getInstance().active())}function xh(e,t){return e.setValue(_h,t)}function JB(e){return e.deleteValue(_h)}function WB(e,t){return xh(e,new io(t))}function E0(e){var t;return(t=wh(e))===null||t===void 0?void 0:t.spanContext()}var GB=/^([0-9a-f]{32})$/i,KB=/^[0-9a-f]{16}$/i;function YB(e){return GB.test(e)&&e!==k0}function XB(e){return KB.test(e)&&e!==I0}function T0(e){return YB(e.traceId)&&XB(e.spanId)}function QB(e){return new io(e)}var oc=S0.getInstance(),$0=(function(){function e(){}return e.prototype.startSpan=function(t,n,i){i===void 0&&(i=oc.active());var r=!!n?.root;if(r)return new io;var o=i&&E0(i);return eZ(o)&&T0(o)?new io(o):new io},e.prototype.startActiveSpan=function(t,n,i,r){var o,a,s;if(!(arguments.length<2)){arguments.length===2?s=n:arguments.length===3?(o=n,s=i):(o=n,a=i,s=r);var u=a??oc.active(),l=this.startSpan(t,o,u),c=xh(u,l);return oc.with(c,s,void 0,l)}},e})();function eZ(e){return typeof e=="object"&&typeof e.spanId=="string"&&typeof e.traceId=="string"&&typeof e.traceFlags=="number"}var tZ=new $0,nZ=(function(){function e(t,n,i,r){this._provider=t,this.name=n,this.version=i,this.options=r}return e.prototype.startSpan=function(t,n,i){return this._getTracer().startSpan(t,n,i)},e.prototype.startActiveSpan=function(t,n,i,r){var o=this._getTracer();return Reflect.apply(o.startActiveSpan,o,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):tZ},e})(),rZ=(function(){function e(){}return e.prototype.getTracer=function(t,n,i){return new $0},e})(),iZ=new rZ,rv=(function(){function e(){}return e.prototype.getTracer=function(t,n,i){var r;return(r=this.getDelegateTracer(t,n,i))!==null&&r!==void 0?r:new nZ(this,t,n,i)},e.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:iZ},e.prototype.setDelegate=function(t){this._delegate=t},e.prototype.getDelegateTracer=function(t,n,i){var r;return(r=this._delegate)===null||r===void 0?void 0:r.getTracer(t,n,i)},e})(),Ks;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(Ks||(Ks={}));var ac="trace",oZ=(function(){function e(){this._proxyTracerProvider=new rv,this.wrapSpanContext=QB,this.isSpanContextValid=T0,this.deleteSpan=JB,this.getSpan=wh,this.getActiveSpan=HB,this.getSpanContext=E0,this.setSpan=xh,this.setSpanContext=WB}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(t){var n=yh(ac,this._proxyTracerProvider,Gs.instance());return n&&this._proxyTracerProvider.setDelegate(t),n},e.prototype.getTracerProvider=function(){return Ao(ac)||this._proxyTracerProvider},e.prototype.getTracer=function(t,n){return this.getTracerProvider().getTracer(t,n)},e.prototype.disable=function(){bh(ac,Gs.instance()),this._proxyTracerProvider=new rv},e})(),aZ=oZ.getInstance(),sZ=Object.defineProperty,lZ=(e,t)=>{for(var n in t)sZ(e,n,{get:t[n],enumerable:!0})},C0="AI_NoObjectGeneratedError",A0=`vercel.ai.error.${C0}`,uZ=Symbol.for(A0),P0,iv=class extends ce{constructor({message:t="No object generated.",cause:n,text:i,response:r,usage:o,finishReason:a}){super({name:C0,message:t,cause:n}),this[P0]=!0,this.text=i,this.response=r,this.usage=o,this.finishReason=a}static isInstance(t){return ce.hasMarker(t,A0)}};P0=uZ;var ov="5.0.116",R0=se([I(),En(Uint8Array),En(ArrayBuffer),da(e=>{var t,n;return(n=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?n:!1},{message:"Must be a Buffer"})]),Po=ua(()=>se([oa(),I(),te(),Ce(),Rt(I(),Po),W(Po)])),Ve=Rt(I(),Rt(I(),Po)),O0=O({type:L("text"),text:I(),providerOptions:Ve.optional()}),cZ=O({type:L("image"),image:se([R0,En(URL)]),mediaType:I().optional(),providerOptions:Ve.optional()}),N0=O({type:L("file"),data:se([R0,En(URL)]),filename:I().optional(),mediaType:I(),providerOptions:Ve.optional()}),dZ=O({type:L("reasoning"),text:I(),providerOptions:Ve.optional()}),pZ=O({type:L("tool-call"),toolCallId:I(),toolName:I(),input:Le(),providerOptions:Ve.optional(),providerExecuted:Ce().optional()}),fZ=Kl("type",[O({type:L("text"),value:I()}),O({type:L("json"),value:Po}),O({type:L("error-text"),value:I()}),O({type:L("error-json"),value:Po}),O({type:L("content"),value:W(se([O({type:L("text"),text:I()}),O({type:L("media"),data:I(),mediaType:I()})]))})]),j0=O({type:L("tool-result"),toolCallId:I(),toolName:I(),output:fZ,providerOptions:Ve.optional()}),hZ=O({role:L("system"),content:I(),providerOptions:Ve.optional()}),mZ=O({role:L("user"),content:se([I(),W(se([O0,cZ,N0]))]),providerOptions:Ve.optional()}),gZ=O({role:L("assistant"),content:se([I(),W(se([O0,N0,dZ,pZ,j0]))]),providerOptions:Ve.optional()}),vZ=O({role:L("tool"),content:W(j0),providerOptions:Ve.optional()});se([hZ,mZ,gZ,vZ]);Sa({prefix:"aitxt",size:24});(class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
|
|
78
|
-
|
|
79
|
-
`)},flush(e){e.enqueue(`data: [DONE]
|
|
80
|
-
|
|
81
|
-
`)}})}});var yZ=CF(()=>x0(se([ze({type:L("text-start"),id:I(),providerMetadata:Ve.optional()}),ze({type:L("text-delta"),id:I(),delta:I(),providerMetadata:Ve.optional()}),ze({type:L("text-end"),id:I(),providerMetadata:Ve.optional()}),ze({type:L("error"),errorText:I()}),ze({type:L("tool-input-start"),toolCallId:I(),toolName:I(),providerExecuted:Ce().optional(),dynamic:Ce().optional()}),ze({type:L("tool-input-delta"),toolCallId:I(),inputTextDelta:I()}),ze({type:L("tool-input-available"),toolCallId:I(),toolName:I(),input:Le(),providerExecuted:Ce().optional(),providerMetadata:Ve.optional(),dynamic:Ce().optional()}),ze({type:L("tool-input-error"),toolCallId:I(),toolName:I(),input:Le(),providerExecuted:Ce().optional(),providerMetadata:Ve.optional(),dynamic:Ce().optional(),errorText:I()}),ze({type:L("tool-output-available"),toolCallId:I(),output:Le(),providerExecuted:Ce().optional(),dynamic:Ce().optional(),preliminary:Ce().optional()}),ze({type:L("tool-output-error"),toolCallId:I(),errorText:I(),providerExecuted:Ce().optional(),dynamic:Ce().optional()}),ze({type:L("reasoning-start"),id:I(),providerMetadata:Ve.optional()}),ze({type:L("reasoning-delta"),id:I(),delta:I(),providerMetadata:Ve.optional()}),ze({type:L("reasoning-end"),id:I(),providerMetadata:Ve.optional()}),ze({type:L("source-url"),sourceId:I(),url:I(),title:I().optional(),providerMetadata:Ve.optional()}),ze({type:L("source-document"),sourceId:I(),mediaType:I(),title:I(),filename:I().optional(),providerMetadata:Ve.optional()}),ze({type:L("file"),url:I(),mediaType:I(),providerMetadata:Ve.optional()}),ze({type:da(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:I().optional(),data:Le(),transient:Ce().optional()}),ze({type:L("start-step")}),ze({type:L("finish-step")}),ze({type:L("start"),messageId:I().optional(),messageMetadata:Le().optional()}),ze({type:L("finish"),finishReason:fr(["stop","length","content-filter","tool-calls","error","other","unknown"]).optional(),messageMetadata:Le().optional()}),ze({type:L("abort")}),ze({type:L("message-metadata"),messageMetadata:Le()})])));function bZ(e){return e.type.startsWith("data-")}function M0(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 i in t)if(Object.prototype.hasOwnProperty.call(t,i)){const r=t[i];if(r===void 0)continue;const o=i in e?e[i]:void 0,a=r!==null&&typeof r=="object"&&!Array.isArray(r)&&!(r instanceof Date)&&!(r instanceof RegExp),s=o!=null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp);a&&s?n[i]=M0(o,r):n[i]=r}return n}function _Z(e){const t=["ROOT"];let n=-1,i=null;function r(u,l,c){switch(u){case'"':{n=l,t.pop(),t.push(c),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{n=l,i=l,t.pop(),t.push(c),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(c),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=l,t.pop(),t.push(c),t.push("INSIDE_NUMBER");break}case"{":{n=l,t.pop(),t.push(c),t.push("INSIDE_OBJECT_START");break}case"[":{n=l,t.pop(),t.push(c),t.push("INSIDE_ARRAY_START");break}}}function o(u,l){switch(u){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=l,t.pop();break}}}function a(u,l){switch(u){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=l,t.pop();break}}}for(let u=0;u<e.length;u++){const l=e[u];switch(t[t.length-1]){case"ROOT":r(l,u,"FINISH");break;case"INSIDE_OBJECT_START":{switch(l){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=u,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(l){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(l){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(l){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{r(l,u,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{o(l,u);break}case"INSIDE_STRING":{switch(l){case'"':{t.pop(),n=u;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=u}break}case"INSIDE_ARRAY_START":{switch(l){case"]":{n=u,t.pop();break}default:{n=u,r(l,u,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=u,t.pop();break}default:{n=u;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{r(l,u,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=u;break}case"INSIDE_NUMBER":{switch(l){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=u;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(l,u),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(l,u);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(l,u);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(l,u);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const d=e.substring(i,u+1);!"false".startsWith(d)&&!"true".startsWith(d)&&!"null".startsWith(d)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?o(l,u):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(l,u)):n=u;break}}}let s=e.slice(0,n+1);for(let u=t.length-1;u>=0;u--)switch(t[u]){case"INSIDE_STRING":{s+='"';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":{s+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{s+="]";break}case"INSIDE_LITERAL":{const c=e.substring(i,e.length);"true".startsWith(c)?s+="true".slice(c.length):"false".startsWith(c)?s+="false".slice(c.length):"null".startsWith(c)&&(s+="null".slice(c.length))}}return s}async function D0(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await Ws({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await Ws({text:_Z(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function ai(e){return e.type.startsWith("tool-")}function wZ(e){return e.type==="dynamic-tool"}function av(e){return ai(e)||wZ(e)}function sv(e){return e.type.split("-").slice(1).join("-")}function xZ({lastMessage:e,messageId:t}){return{message:e?.role==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function SZ({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:i,onError:r,onToolCall:o,onData:a}){return e.pipeThrough(new TransformStream({async transform(s,u){await i(async({state:l,write:c})=>{var d,f,p,g;function m(b){const E=l.message.parts.filter(ai).find($=>$.toolCallId===b);if(E==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return E}function y(b){const E=l.message.parts.filter($=>$.type==="dynamic-tool").find($=>$.toolCallId===b);if(E==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return E}function v(b){var C;const E=l.message.parts.find(j=>ai(j)&&j.toolCallId===b.toolCallId),$=b,A=E;E!=null?(E.state=b.state,A.input=$.input,A.output=$.output,A.errorText=$.errorText,A.rawInput=$.rawInput,A.preliminary=$.preliminary,A.providerExecuted=(C=$.providerExecuted)!=null?C:E.providerExecuted,$.providerMetadata!=null&&E.state==="input-available"&&(E.callProviderMetadata=$.providerMetadata)):l.message.parts.push({type:`tool-${b.toolName}`,toolCallId:b.toolCallId,state:b.state,input:$.input,output:$.output,rawInput:$.rawInput,errorText:$.errorText,providerExecuted:$.providerExecuted,preliminary:$.preliminary,...$.providerMetadata!=null?{callProviderMetadata:$.providerMetadata}:{}})}function _(b){var C,E;const $=l.message.parts.find(F=>F.type==="dynamic-tool"&&F.toolCallId===b.toolCallId),A=b,j=$;$!=null?($.state=b.state,j.toolName=b.toolName,j.input=A.input,j.output=A.output,j.errorText=A.errorText,j.rawInput=(C=A.rawInput)!=null?C:j.rawInput,j.preliminary=A.preliminary,j.providerExecuted=(E=A.providerExecuted)!=null?E:$.providerExecuted,A.providerMetadata!=null&&$.state==="input-available"&&($.callProviderMetadata=A.providerMetadata)):l.message.parts.push({type:"dynamic-tool",toolName:b.toolName,toolCallId:b.toolCallId,state:b.state,input:A.input,output:A.output,errorText:A.errorText,preliminary:A.preliminary,providerExecuted:A.providerExecuted,...A.providerMetadata!=null?{callProviderMetadata:A.providerMetadata}:{}})}async function x(b){if(b!=null){const C=l.message.metadata!=null?M0(l.message.metadata,b):b;t!=null&&await Qg({value:C,schema:t}),l.message.metadata=C}}switch(s.type){case"text-start":{const b={type:"text",text:"",providerMetadata:s.providerMetadata,state:"streaming"};l.activeTextParts[s.id]=b,l.message.parts.push(b),c();break}case"text-delta":{const b=l.activeTextParts[s.id];b.text+=s.delta,b.providerMetadata=(d=s.providerMetadata)!=null?d:b.providerMetadata,c();break}case"text-end":{const b=l.activeTextParts[s.id];b.state="done",b.providerMetadata=(f=s.providerMetadata)!=null?f:b.providerMetadata,delete l.activeTextParts[s.id],c();break}case"reasoning-start":{const b={type:"reasoning",text:"",providerMetadata:s.providerMetadata,state:"streaming"};l.activeReasoningParts[s.id]=b,l.message.parts.push(b),c();break}case"reasoning-delta":{const b=l.activeReasoningParts[s.id];b.text+=s.delta,b.providerMetadata=(p=s.providerMetadata)!=null?p:b.providerMetadata,c();break}case"reasoning-end":{const b=l.activeReasoningParts[s.id];b.providerMetadata=(g=s.providerMetadata)!=null?g:b.providerMetadata,b.state="done",delete l.activeReasoningParts[s.id],c();break}case"file":{l.message.parts.push({type:"file",mediaType:s.mediaType,url:s.url}),c();break}case"source-url":{l.message.parts.push({type:"source-url",sourceId:s.sourceId,url:s.url,title:s.title,providerMetadata:s.providerMetadata}),c();break}case"source-document":{l.message.parts.push({type:"source-document",sourceId:s.sourceId,mediaType:s.mediaType,title:s.title,filename:s.filename,providerMetadata:s.providerMetadata}),c();break}case"tool-input-start":{const b=l.message.parts.filter(ai);l.partialToolCalls[s.toolCallId]={text:"",toolName:s.toolName,index:b.length,dynamic:s.dynamic},s.dynamic?_({toolCallId:s.toolCallId,toolName:s.toolName,state:"input-streaming",input:void 0,providerExecuted:s.providerExecuted}):v({toolCallId:s.toolCallId,toolName:s.toolName,state:"input-streaming",input:void 0,providerExecuted:s.providerExecuted}),c();break}case"tool-input-delta":{const b=l.partialToolCalls[s.toolCallId];b.text+=s.inputTextDelta;const{value:C}=await D0(b.text);b.dynamic?_({toolCallId:s.toolCallId,toolName:b.toolName,state:"input-streaming",input:C}):v({toolCallId:s.toolCallId,toolName:b.toolName,state:"input-streaming",input:C}),c();break}case"tool-input-available":{s.dynamic?_({toolCallId:s.toolCallId,toolName:s.toolName,state:"input-available",input:s.input,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata}):v({toolCallId:s.toolCallId,toolName:s.toolName,state:"input-available",input:s.input,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata}),c(),o&&!s.providerExecuted&&await o({toolCall:s});break}case"tool-input-error":{s.dynamic?_({toolCallId:s.toolCallId,toolName:s.toolName,state:"output-error",input:s.input,errorText:s.errorText,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata}):v({toolCallId:s.toolCallId,toolName:s.toolName,state:"output-error",input:void 0,rawInput:s.input,errorText:s.errorText,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata}),c();break}case"tool-output-available":{if(s.dynamic){const b=y(s.toolCallId);_({toolCallId:s.toolCallId,toolName:b.toolName,state:"output-available",input:b.input,output:s.output,preliminary:s.preliminary})}else{const b=m(s.toolCallId);v({toolCallId:s.toolCallId,toolName:sv(b),state:"output-available",input:b.input,output:s.output,providerExecuted:s.providerExecuted,preliminary:s.preliminary})}c();break}case"tool-output-error":{if(s.dynamic){const b=y(s.toolCallId);_({toolCallId:s.toolCallId,toolName:b.toolName,state:"output-error",input:b.input,errorText:s.errorText,providerExecuted:s.providerExecuted})}else{const b=m(s.toolCallId);v({toolCallId:s.toolCallId,toolName:sv(b),state:"output-error",input:b.input,rawInput:b.rawInput,errorText:s.errorText,providerExecuted:s.providerExecuted})}c();break}case"start-step":{l.message.parts.push({type:"step-start"});break}case"finish-step":{l.activeTextParts={},l.activeReasoningParts={};break}case"start":{s.messageId!=null&&(l.message.id=s.messageId),await x(s.messageMetadata),(s.messageId!=null||s.messageMetadata!=null)&&c();break}case"finish":{s.finishReason!=null&&(l.finishReason=s.finishReason),await x(s.messageMetadata),s.messageMetadata!=null&&c();break}case"message-metadata":{await x(s.messageMetadata),s.messageMetadata!=null&&c();break}case"error":{r?.(new Error(s.errorText));break}default:if(bZ(s)){n?.[s.type]!=null&&await Qg({value:s.data,schema:n[s.type]});const b=s;if(b.transient){a?.(b);break}const C=b.id!=null?l.message.parts.find(E=>b.type===E.type&&b.id===E.id):void 0;C!=null?C.data=b.data:l.message.parts.push(b),a?.(b),c()}}u.enqueue(s)})}}))}async function IZ({stream:e,onError:t}){const n=e.getReader();try{for(;;){const{done:i}=await n.read();if(i)break}}catch(i){t?.(i)}finally{n.releaseLock()}}Sa({prefix:"aitxt",size:24});Sa({prefix:"aiobj",size:24});var kZ=class{constructor(){this.queue=[],this.isProcessing=!1}async processQueue(){if(!this.isProcessing){for(this.isProcessing=!0;this.queue.length>0;)await this.queue[0](),this.queue.shift();this.isProcessing=!1}}async run(e){return new Promise((t,n)=>{this.queue.push(async()=>{try{await e(),t()}catch(i){n(i)}}),this.processQueue()})}};Sa({prefix:"aiobj",size:24});var EZ={};lZ(EZ,{object:()=>$Z,text:()=>TZ});var TZ=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),$Z=({schema:e})=>{const t=IB(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const i=await D0(n);switch(i.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:i.value};default:{const r=i.state;throw new Error(`Unsupported parse state: ${r}`)}}},async parseOutput({text:n},i){const r=await Ws({text:n});if(!r.success)throw new iv({message:"No object generated: could not parse the response.",cause:r.error,text:n,response:i.response,usage:i.usage,finishReason:i.finishReason});const o=await vh({value:r.value,schema:t});if(!o.success)throw new iv({message:"No object generated: response did not match schema.",cause:o.error,text:n,response:i.response,usage:i.usage,finishReason:i.finishReason});return o.value}}};async function CZ(e){if(e==null)return[];if(!globalThis.FileList||!(e instanceof globalThis.FileList))throw new Error("FileList is not supported in the current environment");return Promise.all(Array.from(e).map(async t=>{const{name:n,type:i}=t,r=await new Promise((o,a)=>{const s=new FileReader;s.onload=u=>{var l;o((l=u.target)==null?void 0:l.result)},s.onerror=u=>a(u),s.readAsDataURL(t)});return{type:"file",mediaType:i,filename:n,url:r}}))}var AZ=class{constructor({api:e="/api/chat",credentials:t,headers:n,body:i,fetch:r,prepareSendMessagesRequest:o,prepareReconnectToStreamRequest:a}){this.api=e,this.credentials=t,this.headers=n,this.body=i,this.fetch=r,this.prepareSendMessagesRequest=o,this.prepareReconnectToStreamRequest=a}async sendMessages({abortSignal:e,...t}){var n,i,r,o,a;const s=await Yr(this.body),u=await Yr(this.headers),l=await Yr(this.credentials),c={..._r(u),..._r(t.headers)},d=await((n=this.prepareSendMessagesRequest)==null?void 0:n.call(this,{api:this.api,id:t.chatId,messages:t.messages,body:{...s,...t.body},headers:c,credentials:l,requestMetadata:t.metadata,trigger:t.trigger,messageId:t.messageId})),f=(i=d?.api)!=null?i:this.api,p=d?.headers!==void 0?_r(d.headers):c,g=d?.body!==void 0?d.body:{...s,...t.body,id:t.chatId,messages:t.messages,trigger:t.trigger,messageId:t.messageId},m=(r=d?.credentials)!=null?r:l,v=await((o=this.fetch)!=null?o:globalThis.fetch)(f,{method:"POST",headers:Yg({"Content-Type":"application/json",...p},`ai-sdk/${ov}`,Kg()),body:JSON.stringify(g),credentials:m,signal:e});if(!v.ok)throw new Error((a=await v.text())!=null?a:"Failed to fetch the chat response.");if(!v.body)throw new Error("The response body is empty.");return this.processResponseStream(v.body)}async reconnectToStream(e){var t,n,i,r,o;const a=await Yr(this.body),s=await Yr(this.headers),u=await Yr(this.credentials),l={..._r(s),..._r(e.headers)},c=await((t=this.prepareReconnectToStreamRequest)==null?void 0:t.call(this,{api:this.api,id:e.chatId,body:{...a,...e.body},headers:l,credentials:u,requestMetadata:e.metadata})),d=(n=c?.api)!=null?n:`${this.api}/${e.chatId}/stream`,f=c?.headers!==void 0?_r(c.headers):l,p=(i=c?.credentials)!=null?i:u,m=await((r=this.fetch)!=null?r:globalThis.fetch)(d,{method:"GET",headers:Yg(f,`ai-sdk/${ov}`,Kg()),credentials:p});if(m.status===204)return null;if(!m.ok)throw new Error((o=await m.text())!=null?o:"Failed to fetch the chat response.");if(!m.body)throw new Error("The response body is empty.");return this.processResponseStream(m.body)}},z0=class extends AZ{constructor(e={}){super(e)}processResponseStream(e){return RF({stream:e,schema:yZ}).pipeThrough(new TransformStream({async transform(t,n){if(!t.success)throw t.error;n.enqueue(t.value)}}))}},PZ=class{constructor({generateId:e=v0,id:t=e(),transport:n=new z0,messageMetadataSchema:i,dataPartSchemas:r,state:o,onError:a,onToolCall:s,onFinish:u,onData:l,sendAutomaticallyWhen:c}){this.activeResponse=void 0,this.jobExecutor=new kZ,this.sendMessage=async(d,f)=>{var p,g,m,y;if(d==null){await this.makeRequest({trigger:"submit-message",messageId:(p=this.lastMessage)==null?void 0:p.id,...f});return}let v;if("text"in d||"files"in d?v={parts:[...Array.isArray(d.files)?d.files:await CZ(d.files),..."text"in d&&d.text!=null?[{type:"text",text:d.text}]:[]]}:v=d,d.messageId!=null){const _=this.state.messages.findIndex(x=>x.id===d.messageId);if(_===-1)throw new Error(`message with id ${d.messageId} not found`);if(this.state.messages[_].role!=="user")throw new Error(`message with id ${d.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,_+1),this.state.replaceMessage(_,{...v,id:d.messageId,role:(g=v.role)!=null?g:"user",metadata:d.metadata})}else this.state.pushMessage({...v,id:(m=v.id)!=null?m:this.generateId(),role:(y=v.role)!=null?y:"user",metadata:d.metadata});await this.makeRequest({trigger:"submit-message",messageId:d.messageId,...f})},this.regenerate=async({messageId:d,...f}={})=>{const p=d==null?this.state.messages.length-1:this.state.messages.findIndex(g=>g.id===d);if(p===-1)throw new Error(`message ${d} not found`);this.state.messages=this.state.messages.slice(0,this.messages[p].role==="assistant"?p:p+1),await this.makeRequest({trigger:"regenerate-message",messageId:d,...f})},this.resumeStream=async(d={})=>{await this.makeRequest({trigger:"resume-stream",...d})},this.clearError=()=>{this.status==="error"&&(this.state.error=void 0,this.setStatus({status:"ready"}))},this.addToolOutput=async({state:d="output-available",tool:f,toolCallId:p,output:g,errorText:m})=>this.jobExecutor.run(async()=>{var y,v;const _=this.state.messages,x=_[_.length-1];this.state.replaceMessage(_.length-1,{...x,parts:x.parts.map(b=>av(b)&&b.toolCallId===p?{...b,state:d,output:g,errorText:m}:b)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(b=>av(b)&&b.toolCallId===p?{...b,state:d,output:g,errorText:m}:b)),this.status!=="streaming"&&this.status!=="submitted"&&((y=this.sendAutomaticallyWhen)!=null&&y.call(this,{messages:this.state.messages}))&&this.makeRequest({trigger:"submit-message",messageId:(v=this.lastMessage)==null?void 0:v.id})}),this.addToolResult=this.addToolOutput,this.stop=async()=>{var d;this.status!=="streaming"&&this.status!=="submitted"||(d=this.activeResponse)!=null&&d.abortController&&this.activeResponse.abortController.abort()},this.id=t,this.transport=n,this.generateId=e,this.messageMetadataSchema=i,this.dataPartSchemas=r,this.state=o,this.onError=a,this.onToolCall=s,this.onFinish=u,this.onData=l,this.sendAutomaticallyWhen=c}get status(){return this.state.status}setStatus({status:e,error:t}){this.status!==e&&(this.state.status=e,this.state.error=t)}get error(){return this.state.error}get messages(){return this.state.messages}get lastMessage(){return this.state.messages[this.state.messages.length-1]}set messages(e){this.state.messages=e}async makeRequest({trigger:e,metadata:t,headers:n,body:i,messageId:r}){var o,a,s,u;this.setStatus({status:"submitted",error:void 0});const l=this.lastMessage;let c=!1,d=!1,f=!1;try{const p={state:xZ({lastMessage:this.state.snapshot(l),messageId:this.generateId()}),abortController:new AbortController};p.abortController.signal.addEventListener("abort",()=>{c=!0}),this.activeResponse=p;let g;if(e==="resume-stream"){const y=await this.transport.reconnectToStream({chatId:this.id,metadata:t,headers:n,body:i});if(y==null){this.setStatus({status:"ready"});return}g=y}else g=await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:p.abortController.signal,metadata:t,headers:n,body:i,trigger:e,messageId:r});const m=y=>this.jobExecutor.run(()=>y({state:p.state,write:()=>{var v;this.setStatus({status:"streaming"}),p.state.message.id===((v=this.lastMessage)==null?void 0:v.id)?this.state.replaceMessage(this.state.messages.length-1,p.state.message):this.state.pushMessage(p.state.message)}}));await IZ({stream:SZ({stream:g,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:m,onError:y=>{throw y}}),onError:y=>{throw y}}),this.setStatus({status:"ready"})}catch(p){if(c||p.name==="AbortError")return c=!0,this.setStatus({status:"ready"}),null;f=!0,p instanceof TypeError&&(p.message.toLowerCase().includes("fetch")||p.message.toLowerCase().includes("network"))&&(d=!0),this.onError&&p instanceof Error&&this.onError(p),this.setStatus({status:"error",error:p})}finally{try{(a=this.onFinish)==null||a.call(this,{message:this.activeResponse.state.message,messages:this.state.messages,isAbort:c,isDisconnect:d,isError:f,finishReason:(o=this.activeResponse)==null?void 0:o.state.finishReason})}catch(p){console.error(p)}this.activeResponse=void 0}(s=this.sendAutomaticallyWhen)!=null&&s.call(this,{messages:this.state.messages})&&!f&&await this.makeRequest({trigger:"submit-message",messageId:(u=this.lastMessage)==null?void 0:u.id,metadata:t,headers:n,body:i})}};const lv=(e,t)=>{if(t==null)return[];let n=e.findIndex(i=>i.id===t);if(n===-1)throw new Error("useVercelAIThreadState: Message not found. This is likely an internal bug in assistant-ui.");for(;e[n+1]?.role==="assistant";)n++;return e.slice(0,n+1)},uv=e=>{const n=[...e.content.filter(i=>i.type!=="file"),...e.attachments?.flatMap(i=>i.content.map(r=>({...r,filename:i.name})))??[]].map(i=>{switch(i.type){case"text":return{type:"text",text:i.text};case"image":return{type:"file",url:i.image,...i.filename&&{filename:i.filename},mediaType:"image/png"};case"file":return{type:"file",url:i.data,mediaType:i.mimeType,...i.filename&&{filename:i.filename}};default:throw new Error(`Unsupported part type: ${i.type}`)}});return{role:e.role,parts:n}},RZ=e=>new Promise((t,n)=>{const i=new FileReader;i.onload=()=>t(i.result),i.onerror=r=>n(r),i.readAsDataURL(e)}),OZ={accept:"image/*, text/plain, text/html, text/markdown, text/csv, text/xml, text/json, text/css",async add({file:e}){return{id:v0(),type:e.type.startsWith("image/")?"image":"file",name:e.name,file:e,contentType:e.type,content:[],status:{type:"requires-action",reason:"composer-send"}}},async send(e){return{...e,status:{type:"complete"},content:[{type:"file",mimeType:e.contentType,filename:e.name,data:await RZ(e.file)}]}},async remove(){}},cv=e=>Tr(e);function NZ(e){return e.replace(/[}\]"]+$/,"")}const sc=(e,t)=>!e.parts||e.parts.length===0?[]:e.parts.filter(n=>n.type!=="step-start"&&n.type!=="file").map(n=>{const i=n.type;if(i==="text")return{type:"text",text:n.text};if(i==="reasoning")return{type:"reasoning",text:n.text};if(ai(n)){const r=i.replace("tool-",""),o=n.toolCallId;let a={},s,u=!1;n.state==="input-streaming"||n.state==="input-available"?a=n.input||{}:n.state==="output-available"?(a=n.input||{},s=n.output):n.state==="output-error"&&(a=n.input||{},u=!0,s={error:n.errorText});let l=JSON.stringify(a);n.state==="input-streaming"&&(l=NZ(l));const c=t.toolStatuses?.[o];return{type:"tool-call",toolName:r,toolCallId:o,argsText:l,args:a,result:s,isError:u,...c?.type==="interrupt"&&{interrupt:c.payload,status:{type:"requires-action",reason:"interrupt"}}}}if(i==="dynamic-tool"){const r=n.toolName,o=n.toolCallId;let a={},s,u=!1;n.state==="input-streaming"||n.state==="input-available"?a=n.input||{}:n.state==="output-available"?(a=n.input||{},s=n.output):n.state==="output-error"&&(a=n.input||{},u=!0,s={error:n.errorText});const l=t.toolStatuses?.[o];return{type:"tool-call",toolName:r,toolCallId:o,argsText:JSON.stringify(a),args:a,result:s,isError:u,...l?.type==="interrupt"&&{interrupt:l.payload,status:{type:"requires-action",reason:"interrupt"}}}}return i==="source-url"?{type:"source",sourceType:"url",id:n.sourceId,url:n.url,title:n.title||""}:i==="source-document"?(console.warn(`Source document part type ${i} is not yet supported in conversion`),null):i.startsWith("data-")?{type:"data",name:i.substring(5),data:n.data}:(console.warn(`Unsupported message part type: ${i}`),null)}).filter(Boolean),dv=qz((e,t)=>{const n=new Date;switch(e.role){case"user":return{role:"user",id:e.id,createdAt:n,content:sc(e,t),attachments:e.parts?.filter(i=>i.type==="file").map((i,r)=>({id:r.toString(),type:i.mediaType.startsWith("image/")?"image":"file",name:i.filename??"file",content:[i.mediaType.startsWith("image/")?{type:"image",image:i.url,filename:i.filename}:{type:"file",filename:i.filename,data:i.url,mimeType:i.mediaType}],contentType:i.mediaType??"unknown/unknown",status:{type:"complete"}}))};case"system":return{role:"system",id:e.id,createdAt:n,content:sc(e,t)};case"assistant":return{role:"assistant",id:e.id,createdAt:n,content:sc(e,t),metadata:{unstable_annotations:e.annotations,unstable_data:Array.isArray(e.data)?e.data:e.data?[e.data]:void 0,custom:{}}};default:return console.warn(`Unsupported message role: ${e.role}`),[]}}),jZ={format:"ai-sdk/v5",encode({message:{id:e,parts:t,...n}}){return{...n,parts:t.filter(i=>i.type!=="file")}},decode(e){return{parentId:e.parent_id,message:{id:e.id,...e.content}}},getId(e){return e.id}},{MessageRepository:MZ}=NE,DZ=(e,t)=>({headId:t.headId,messages:t.messages.map(n=>{const i=e([n.message])[0];return{...n,message:i}})}),zZ=(e,t,n,i,r)=>{const o=k.useRef(!1),a=_e(),s=k.useCallback(()=>a.threadListItem.source?a.threadListItem():null,[a]),[u,l]=k.useState(!1),c=k.useRef(new Set),d=k.useRef(()=>r);return k.useEffect(()=>{d.current=r}),k.useEffect(()=>{if(!t||o.current)return;const f=async()=>{l(!0);try{const p=await t.withFormat?.(i).load();if(p&&p.messages.length>0){const g=DZ(n,p);e.current.thread.import(g);const m=new MZ;m.import(g);const y=m.getMessages();d.current(y.map(Tr).flat()),c.current=new Set(g.messages.map(v=>v.message.id))}}catch(p){console.error("Failed to load message history:",p)}finally{l(!1)}};if(!o.current){if(o.current=!0,!s()?.getState().remoteId){l(!1);return}f()}},[a,t,i,n,e,s]),k.useEffect(()=>e.current.thread.subscribe(async()=>{const{messages:f,isRunning:p}=e.current.thread.getState();if(!p)for(let g=0;g<f.length;g++){const m=f[g];if(m.status===void 0||m.status.type==="complete"||m.status.type==="incomplete"){if(c.current.has(m.id))continue;c.current.add(m.id);const y=g>0?f[g-1].id:null;await t?.withFormat?.(i).append({parentId:y,message:Tr(m)[0]})}}}),[t,i,e]),u},UZ=(e,{adapters:t,toCreateMessage:n,cancelPendingToolCallsOnSend:i=!0}={})=>{const r=aE(),[o,a]=k.useState({}),s=Object.values(o).some(m=>m?.type==="executing"),u=e.status==="submitted"||e.status==="streaming"||s,l=dv.useThreadMessages({isRunning:u,messages:e.messages,metadata:k.useMemo(()=>({toolStatuses:o,...e.error&&{error:e.error.message}}),[o,e.error])}),[c]=k.useState(()=>({get current(){return g}})),d=lE({state:{messages:l,isRunning:u},getTools:()=>c.current.thread.getModelContext().tools,onResult:m=>{m.type==="add-tool-result"&&e.addToolResult({tool:m.toolName,toolCallId:m.toolCallId,output:m.result})},setToolStatuses:a}),f=zZ(c,t?.history??r?.history,dv.toThreadMessages,jZ,m=>{e.setMessages(m)}),p=async()=>{i&&(await d.abort(),e.setMessages(m=>{const y=m.at(-1);if(y?.role!=="assistant")return m;let v=!1;const _=y.parts?.map(x=>!ai(x)||x.state==="output-available"||x.state==="output-error"?x:(v=!0,{...x,state:"output-error",errorText:"User cancelled tool call by sending a new message."}));return v?[...m.slice(0,-1),{...y,parts:_}]:m}))},g=UD({isRunning:u,messages:l,setMessages:m=>e.setMessages(m.map(cv).filter(Boolean).flat()),onImport:m=>e.setMessages(m.map(cv).filter(Boolean).flat()),onCancel:async()=>{e.stop(),await d.abort()},onNew:async m=>{await p();const y=(n??uv)(m);await e.sendMessage(y,{metadata:m.runConfig})},onEdit:async m=>{const y=lv(e.messages,m.parentId);e.setMessages(y);const v=(n??uv)(m);await e.sendMessage(v,{metadata:m.runConfig})},onReload:async(m,y)=>{const v=lv(e.messages,m);e.setMessages(v),await e.regenerate({metadata:y.runConfig})},onAddToolResult:({toolCallId:m,result:y,isError:v})=>{v?e.addToolOutput({state:"output-error",tool:m,toolCallId:m,errorText:typeof y=="string"?y:JSON.stringify(y)}):e.addToolOutput({state:"output-available",tool:m,toolCallId:m,output:y})},onResumeToolCall:m=>d.resume(m.toolCallId,m.payload),adapters:{attachments:OZ,...r,...t},isLoading:f});return g};var lc,pv;function LZ(){if(pv)return lc;pv=1;function e(t,n){if(typeof t!="function")throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof t}\`.`);let i,r=0;return function(...a){clearTimeout(i);const s=Date.now(),u=s-r,l=n-u;l<=0?(r=s,t.apply(this,a)):i=setTimeout(()=>{r=Date.now(),t.apply(this,a)},l)}}return lc=e,lc}var FZ=LZ();const BZ=ga(FZ);var Ka={exports:{}},uc={};var fv;function ZZ(){if(fv)return uc;fv=1;var e=k;function t(d,f){return d===f&&(d!==0||1/d===1/f)||d!==d&&f!==f}var n=typeof Object.is=="function"?Object.is:t,i=e.useState,r=e.useEffect,o=e.useLayoutEffect,a=e.useDebugValue;function s(d,f){var p=f(),g=i({inst:{value:p,getSnapshot:f}}),m=g[0].inst,y=g[1];return o(function(){m.value=p,m.getSnapshot=f,u(m)&&y({inst:m})},[d,p,f]),r(function(){return u(m)&&y({inst:m}),d(function(){u(m)&&y({inst:m})})},[d]),a(p),p}function u(d){var f=d.getSnapshot;d=d.value;try{var p=f();return!n(d,p)}catch{return!0}}function l(d,f){return f()}var c=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?l:s;return uc.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:c,uc}var cc={};var hv;function qZ(){return hv||(hv=1,process.env.NODE_ENV!=="production"&&(function(){function e(p,g){return p===g&&(p!==0||1/p===1/g)||p!==p&&g!==g}function t(p,g){c||r.startTransition===void 0||(c=!0,console.error("You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release."));var m=g();if(!d){var y=g();o(m,y)||(console.error("The result of getSnapshot should be cached to avoid an infinite loop"),d=!0)}y=a({inst:{value:m,getSnapshot:g}});var v=y[0].inst,_=y[1];return u(function(){v.value=m,v.getSnapshot=g,n(v)&&_({inst:v})},[p,m,g]),s(function(){return n(v)&&_({inst:v}),p(function(){n(v)&&_({inst:v})})},[p]),l(m),m}function n(p){var g=p.getSnapshot;p=p.value;try{var m=g();return!o(p,m)}catch{return!0}}function i(p,g){return g()}typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var r=k,o=typeof Object.is=="function"?Object.is:e,a=r.useState,s=r.useEffect,u=r.useLayoutEffect,l=r.useDebugValue,c=!1,d=!1,f=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?i:t;cc.useSyncExternalStore=r.useSyncExternalStore!==void 0?r.useSyncExternalStore:f,typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())})()),cc}var mv;function VZ(){return mv||(mv=1,process.env.NODE_ENV==="production"?Ka.exports=ZZ():Ka.exports=qZ()),Ka.exports}var HZ=VZ(),U0=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},Ue=(e,t,n)=>(U0(e,t,"read from private field"),n?n.call(e):t.get(e)),vn=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},Qn=(e,t,n,i)=>(U0(e,t,"write to private field"),t.set(e,n),n);function JZ(e,t){return t!=null?BZ(e,t):e}var Bt,fs,hs,Ki,Yi,Xi,ei,fd,hd,WZ=class{constructor(e=[]){vn(this,Bt,void 0),vn(this,fs,"ready"),vn(this,hs,void 0),vn(this,Ki,new Set),vn(this,Yi,new Set),vn(this,Xi,new Set),this.pushMessage=t=>{Qn(this,Bt,Ue(this,Bt).concat(t)),Ue(this,ei).call(this)},this.popMessage=()=>{Qn(this,Bt,Ue(this,Bt).slice(0,-1)),Ue(this,ei).call(this)},this.replaceMessage=(t,n)=>{Qn(this,Bt,[...Ue(this,Bt).slice(0,t),this.snapshot(n),...Ue(this,Bt).slice(t+1)]),Ue(this,ei).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const i=n?JZ(t,n):t;return Ue(this,Ki).add(i),()=>{Ue(this,Ki).delete(i)}},this["~registerStatusCallback"]=t=>(Ue(this,Yi).add(t),()=>{Ue(this,Yi).delete(t)}),this["~registerErrorCallback"]=t=>(Ue(this,Xi).add(t),()=>{Ue(this,Xi).delete(t)}),vn(this,ei,()=>{Ue(this,Ki).forEach(t=>t())}),vn(this,fd,()=>{Ue(this,Yi).forEach(t=>t())}),vn(this,hd,()=>{Ue(this,Xi).forEach(t=>t())}),Qn(this,Bt,e)}get status(){return Ue(this,fs)}set status(e){Qn(this,fs,e),Ue(this,fd).call(this)}get error(){return Ue(this,hs)}set error(e){Qn(this,hs,e),Ue(this,hd).call(this)}get messages(){return Ue(this,Bt)}set messages(e){Qn(this,Bt,[...e]),Ue(this,ei).call(this)}};Bt=new WeakMap;fs=new WeakMap;hs=new WeakMap;Ki=new WeakMap;Yi=new WeakMap;Xi=new WeakMap;ei=new WeakMap;fd=new WeakMap;hd=new WeakMap;var ti,gv=class extends PZ{constructor({messages:t,...n}){const i=new WZ(t);super({...n,state:i}),vn(this,ti,void 0),this["~registerMessagesCallback"]=(r,o)=>Ue(this,ti)["~registerMessagesCallback"](r,o),this["~registerStatusCallback"]=r=>Ue(this,ti)["~registerStatusCallback"](r),this["~registerErrorCallback"]=r=>Ue(this,ti)["~registerErrorCallback"](r),Qn(this,ti,i)}};ti=new WeakMap;function GZ({experimental_throttle:e,resume:t=!1,...n}={}){const i=k.useRef("chat"in n?n.chat:new gv(n));("chat"in n&&n.chat!==i.current||"id"in n&&i.current.id!==n.id)&&(i.current="chat"in n?n.chat:new gv(n));const o=k.useCallback(c=>i.current["~registerMessagesCallback"](c,e),[e,i.current.id]),a=k.useSyncExternalStore(o,()=>i.current.messages,()=>i.current.messages),s=k.useSyncExternalStore(i.current["~registerStatusCallback"],()=>i.current.status,()=>i.current.status),u=k.useSyncExternalStore(i.current["~registerErrorCallback"],()=>i.current.error,()=>i.current.error),l=k.useCallback(c=>{typeof c=="function"&&(c=c(i.current.messages)),i.current.messages=c},[i]);return k.useEffect(()=>{t&&i.current.resumeStream()},[t,i]),{id:i.current.id,messages:a,setMessages:l,sendMessage:i.current.sendMessage,regenerate:i.current.regenerate,clearError:i.current.clearError,stop:i.current.stop,error:u,resumeStream:i.current.resumeStream,status:s,addToolResult:i.current.addToolOutput,addToolOutput:i.current.addToolOutput}}const KZ=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,{...n.description?{description:n.description}:void 0,parameters:n.parameters instanceof ks.ZodType?ks.toJSONSchema(n.parameters):n.parameters}])),YZ=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>!t.disabled&&t.type!=="backend"));class vv extends z0{runtime;constructor(t){super({...t,prepareSendMessagesRequest:async n=>{const i=this.runtime?.thread.getModelContext(),r=(await this.runtime?.threads.mainItem.initialize())?.remoteId??n.id,o={...n,body:{callSettings:i?.callSettings,system:i?.system,tools:KZ(YZ(i?.tools??{})),...n?.body}},a=await t?.prepareSendMessagesRequest?.(o);return{...a,body:a?.body??{...o.body,id:r,messages:n.messages,trigger:n.trigger,messageId:n.messageId,metadata:n.requestMetadata}}}})}setRuntime(t){this.runtime=t}}const XZ=e=>{const t=k.useRef(e);return k.useEffect(()=>{t.current=e}),k.useMemo(()=>new Proxy(t.current,{get(i,r){const o=t.current[r];return typeof o=="function"?o.bind(t.current):o}}),[])},QZ=e=>{const{adapters:t,transport:n,toCreateMessage:i,...r}=e??{},o=XZ(n??new vv),a=ee(({threadListItem:l})=>l.id),s=GZ({...r,id:a,transport:o}),u=UZ(s,{adapters:t,...i&&{toCreateMessage:i}});return o instanceof vv&&o.setRuntime(u),u},L0=({cloud:e,...t}={})=>{const n=a4({cloud:e});return jE({runtimeHook:function(){return QZ(t)},adapter:n,allowNesting:!0})},eq=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,{...n.description?{description:n.description}:void 0,inputSchema:bu(n.parameters)}]));var tq=Object.defineProperty,nq=Object.defineProperties,rq=Object.getOwnPropertyDescriptors,yv=Object.getOwnPropertySymbols,iq=Object.prototype.hasOwnProperty,oq=Object.prototype.propertyIsEnumerable,bv=(e,t,n)=>t in e?tq(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Ee=(e,t)=>{for(var n in t||(t={}))iq.call(t,n)&&bv(e,n,t[n]);if(yv)for(var n of yv(t))oq.call(t,n)&&bv(e,n,t[n]);return e},Ys=(e,t)=>nq(e,rq(t)),F0="vercel.ai.error",aq=Symbol.for(F0),B0,sq=class Z0 extends Error{constructor({name:t,message:n,cause:i}){super(n),this[B0]=!0,this.name=t,this.cause=i}static isInstance(t){return Z0.hasMarker(t,F0)}static hasMarker(t,n){const i=Symbol.for(n);return t!=null&&typeof t=="object"&&i in t&&typeof t[i]=="boolean"&&t[i]===!0}};B0=aq;var Ge=sq,q0="AI_APICallError",V0=`vercel.ai.error.${q0}`,lq=Symbol.for(V0),H0,sn=class extends Ge{constructor({message:e,url:t,requestBodyValues:n,statusCode:i,responseHeaders:r,responseBody:o,cause:a,isRetryable:s=i!=null&&(i===408||i===409||i===429||i>=500),data:u}){super({name:q0,message:e,cause:a}),this[H0]=!0,this.url=t,this.requestBodyValues=n,this.statusCode=i,this.responseHeaders=r,this.responseBody=o,this.isRetryable=s,this.data=u}static isInstance(e){return Ge.hasMarker(e,V0)}};H0=lq;var J0="AI_EmptyResponseBodyError",W0=`vercel.ai.error.${J0}`,uq=Symbol.for(W0),G0,cq=class extends Ge{constructor({message:e="Empty response body"}={}){super({name:J0,message:e}),this[G0]=!0}static isInstance(e){return Ge.hasMarker(e,W0)}};G0=uq;function K0(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var Y0="AI_InvalidArgumentError",X0=`vercel.ai.error.${Y0}`,dq=Symbol.for(X0),Q0,e$=class extends Ge{constructor({message:t,cause:n,argument:i}){super({name:Y0,message:t,cause:n}),this[Q0]=!0,this.argument=i}static isInstance(t){return Ge.hasMarker(t,X0)}};Q0=dq;var t$="AI_InvalidPromptError",n$=`vercel.ai.error.${t$}`,pq=Symbol.for(n$),r$,fq=class extends Ge{constructor({prompt:e,message:t,cause:n}){super({name:t$,message:`Invalid prompt: ${t}`,cause:n}),this[r$]=!0,this.prompt=e}static isInstance(e){return Ge.hasMarker(e,n$)}};r$=pq;var i$="AI_InvalidResponseDataError",o$=`vercel.ai.error.${i$}`,hq=Symbol.for(o$),a$,Fi=class extends Ge{constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:i$,message:t}),this[a$]=!0,this.data=e}static isInstance(e){return Ge.hasMarker(e,o$)}};a$=hq;var s$="AI_JSONParseError",l$=`vercel.ai.error.${s$}`,mq=Symbol.for(l$),u$,Xs=class extends Ge{constructor({text:e,cause:t}){super({name:s$,message:`JSON parsing failed: Text: ${e}.
|
|
82
|
-
Error message: ${K0(t)}`,cause:t}),this[u$]=!0,this.text=e}static isInstance(e){return Ge.hasMarker(e,l$)}};u$=mq;var c$="AI_LoadAPIKeyError",d$=`vercel.ai.error.${c$}`,gq=Symbol.for(d$),p$,Ya=class extends Ge{constructor({message:e}){super({name:c$,message:e}),this[p$]=!0}static isInstance(e){return Ge.hasMarker(e,d$)}};p$=gq;var f$="AI_NoContentGeneratedError",h$=`vercel.ai.error.${f$}`,vq=Symbol.for(h$),m$,g$=class extends Ge{constructor({message:e="No content generated."}={}){super({name:f$,message:e}),this[m$]=!0}static isInstance(e){return Ge.hasMarker(e,h$)}};m$=vq;var v$="AI_TypeValidationError",y$=`vercel.ai.error.${v$}`,yq=Symbol.for(y$),b$,bq=class md extends Ge{constructor({value:t,cause:n}){super({name:v$,message:`Type validation failed: Value: ${JSON.stringify(t)}.
|
|
83
|
-
Error message: ${K0(n)}`,cause:n}),this[b$]=!0,this.value=t}static isInstance(t){return Ge.hasMarker(t,y$)}static wrap({value:t,cause:n}){return md.isInstance(n)&&n.value===t?n:new md({value:t,cause:n})}};b$=yq;var Ro=bq,_$="AI_UnsupportedFunctionalityError",w$=`vercel.ai.error.${_$}`,_q=Symbol.for(w$),x$,er=class extends Ge{constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:_$,message:t}),this[x$]=!0,this.functionality=e}static isInstance(e){return Ge.hasMarker(e,w$)}};x$=_q;var _v=class extends Error{constructor(e,t){super(e),this.name="ParseError",this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function dc(e){}function wq(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=dc,onError:n=dc,onRetry:i=dc,onComment:r}=e;let o="",a=!0,s,u="",l="";function c(m){const y=a?m.replace(/^\xEF\xBB\xBF/,""):m,[v,_]=xq(`${o}${y}`);for(const x of v)d(x);o=_,a=!1}function d(m){if(m===""){p();return}if(m.startsWith(":")){r&&r(m.slice(m.startsWith(": ")?2:1));return}const y=m.indexOf(":");if(y!==-1){const v=m.slice(0,y),_=m[y+1]===" "?2:1,x=m.slice(y+_);f(v,x,m);return}f(m,"",m)}function f(m,y,v){switch(m){case"event":l=y;break;case"data":u=`${u}${y}
|
|
84
|
-
`;break;case"id":s=y.includes("\0")?void 0:y;break;case"retry":/^\d+$/.test(y)?i(parseInt(y,10)):n(new _v(`Invalid \`retry\` value: "${y}"`,{type:"invalid-retry",value:y,line:v}));break;default:n(new _v(`Unknown field "${m.length>20?`${m.slice(0,20)}…`:m}"`,{type:"unknown-field",field:m,value:y,line:v}));break}}function p(){u.length>0&&t({id:s,event:l||void 0,data:u.endsWith(`
|
|
85
|
-
`)?u.slice(0,-1):u}),s=void 0,u="",l=""}function g(m={}){o&&m.consume&&d(o),a=!0,s=void 0,u="",l="",o=""}return{feed:c,reset:g}}function xq(e){const t=[];let n="",i=0;for(;i<e.length;){const r=e.indexOf("\r",i),o=e.indexOf(`
|
|
86
|
-
`,i);let a=-1;if(r!==-1&&o!==-1?a=Math.min(r,o):r!==-1?a=r:o!==-1&&(a=o),a===-1){n=e.slice(i);break}else{const s=e.slice(i,a);t.push(s),i=a+1,e[i-1]==="\r"&&e[i]===`
|
|
87
|
-
`&&i++}}return[t,n]}var Sq=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let i;super({start(r){i=wq({onEvent:o=>{r.enqueue(o)},onError(o){e==="terminate"?r.error(o):typeof e=="function"&&e(o)},onRetry:t,onComment:n})},transform(r){i.feed(r)}})}};new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Oo(...e){return e.reduce((t,n)=>Ee(Ee({},t),n??{}),{})}function _u(e){return Object.fromEntries([...e.headers])}var Iq=({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:i="-"}={})=>{const r=()=>{const o=n.length,a=new Array(t);for(let s=0;s<t;s++)a[s]=n[Math.random()*o|0];return a.join("")};if(e==null)return r;if(n.includes(i))throw new e$({argument:"separator",message:`The separator "${i}" must not be part of the alphabet "${n}".`});return()=>`${e}${i}${r()}`},nn=Iq();function gd(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var kq=["fetch failed","failed to fetch"];function Eq({error:e,url:t,requestBodyValues:n}){if(gd(e))return e;if(e instanceof TypeError&&kq.includes(e.message.toLowerCase())){const i=e.cause;if(i!=null)return new sn({message:`Cannot connect to API: ${i.message}`,cause:i,url:t,requestBodyValues:n,isRetryable:!0})}return e}function Tq(e){return Object.fromEntries(Object.entries(e).filter(([t,n])=>n!=null))}function $q({apiKey:e,environmentVariableName:t,apiKeyParameterName:n="apiKey",description:i}){if(typeof e=="string")return e;if(e!=null)throw new Ya({message:`${i} API key must be a string.`});if(typeof process>"u")throw new Ya({message:`${i} 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 Ya({message:`${i} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new Ya({message:`${i} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}var Cq=/"__proto__"\s*:/,Aq=/"constructor"\s*:/;function Pq(e){const t=JSON.parse(e);return t===null||typeof t!="object"||Cq.test(e)===!1&&Aq.test(e)===!1?t:Rq(t)}function Rq(e){let t=[e];for(;t.length;){const n=t;t=[];for(const i of n){if(Object.prototype.hasOwnProperty.call(i,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(i,"constructor")&&Object.prototype.hasOwnProperty.call(i.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const r in i){const o=i[r];o&&typeof o=="object"&&t.push(o)}}}return e}function Sh(e){const{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return Pq(e)}finally{Error.stackTraceLimit=t}}var vd=Symbol.for("vercel.ai.validator");function Oq(e){return{[vd]:!0,validate:e}}function Nq(e){return typeof e=="object"&&e!==null&&vd in e&&e[vd]===!0&&"validate"in e}function jq(e){return Nq(e)?e:Mq(e)}function Mq(e){return Oq(async t=>{const n=await e["~standard"].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new Ro({value:t,cause:n.issues})}})}async function Dq({value:e,schema:t}){const n=await S$({value:e,schema:t});if(!n.success)throw Ro.wrap({value:e,cause:n.error});return n.value}async function S$({value:e,schema:t}){const n=jq(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};const i=await n.validate(e);return i.success?{success:!0,value:i.value,rawValue:e}:{success:!1,error:Ro.wrap({value:e,cause:i.error}),rawValue:e}}catch(i){return{success:!1,error:Ro.wrap({value:e,cause:i}),rawValue:e}}}async function zq({text:e,schema:t}){try{const n=Sh(e);return t==null?n:Dq({value:n,schema:t})}catch(n){throw Xs.isInstance(n)||Ro.isInstance(n)?n:new Xs({text:e,cause:n})}}async function I$({text:e,schema:t}){try{const n=Sh(e);return t==null?{success:!0,value:n,rawValue:n}:await S$({value:n,schema:t})}catch(n){return{success:!1,error:Xs.isInstance(n)?n:new Xs({text:e,cause:n}),rawValue:void 0}}}function pc(e){try{return Sh(e),!0}catch{return!1}}function Uq({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Sq).pipeThrough(new TransformStream({async transform({data:n},i){n!=="[DONE]"&&i.enqueue(await I$({text:n,schema:t}))}}))}var Lq=()=>globalThis.fetch,No=async({url:e,headers:t,body:n,failedResponseHandler:i,successfulResponseHandler:r,abortSignal:o,fetch:a})=>Fq({url:e,headers:Ee({"Content-Type":"application/json"},t),body:{content:JSON.stringify(n),values:n},failedResponseHandler:i,successfulResponseHandler:r,abortSignal:o,fetch:a}),Fq=async({url:e,headers:t={},body:n,successfulResponseHandler:i,failedResponseHandler:r,abortSignal:o,fetch:a=Lq()})=>{try{const s=await a(e,{method:"POST",headers:Tq(t),body:n.content,signal:o}),u=_u(s);if(!s.ok){let l;try{l=await r({response:s,url:e,requestBodyValues:n.values})}catch(c){throw gd(c)||sn.isInstance(c)?c:new sn({message:"Failed to process error response",cause:c,statusCode:s.status,url:e,responseHeaders:u,requestBodyValues:n.values})}throw l.value}try{return await i({response:s,url:e,requestBodyValues:n.values})}catch(l){throw l instanceof Error&&(gd(l)||sn.isInstance(l))?l:new sn({message:"Failed to process successful response",cause:l,statusCode:s.status,url:e,responseHeaders:u,requestBodyValues:n.values})}}catch(s){throw Eq({error:s,url:e,requestBodyValues:n.values})}},Bq=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:i,url:r,requestBodyValues:o})=>{const a=await i.text(),s=_u(i);if(a.trim()==="")return{responseHeaders:s,value:new sn({message:i.statusText,url:r,requestBodyValues:o,statusCode:i.status,responseHeaders:s,responseBody:a,isRetryable:n?.(i)})};try{const u=await zq({text:a,schema:e});return{responseHeaders:s,value:new sn({message:t(u),url:r,requestBodyValues:o,statusCode:i.status,responseHeaders:s,responseBody:a,data:u,isRetryable:n?.(i,u)})}}catch{return{responseHeaders:s,value:new sn({message:i.statusText,url:r,requestBodyValues:o,statusCode:i.status,responseHeaders:s,responseBody:a,isRetryable:n?.(i)})}}},k$=e=>async({response:t})=>{const n=_u(t);if(t.body==null)throw new cq({});return{responseHeaders:n,value:Uq({stream:t.body,schema:e})}},Ih=e=>async({response:t,url:n,requestBodyValues:i})=>{const r=await t.text(),o=await I$({text:r,schema:e}),a=_u(t);if(!o.success)throw new sn({message:"Invalid JSON response",cause:o.error,statusCode:t.status,responseHeaders:a,responseBody:r,url:n,requestBodyValues:i});return{responseHeaders:a,value:o.value,rawValue:o.rawValue}},{btoa:Zq}=globalThis;function qq(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return Zq(t)}function Vq(e){return e?.replace(/\/$/,"")}function fc(e){return e!=null}var E$=(e=>(e.Unknown="unknown",e.OpenAIResponsesV1="openai-responses-v1",e.XAIResponsesV1="xai-responses-v1",e.AnthropicClaudeV1="anthropic-claude-v1",e.GoogleGeminiV1="google-gemini-v1",e))(E$||{}),kh=O({id:I().nullish(),format:fr(E$).nullish(),index:te().optional()}).loose(),Hq=O({type:L("reasoning.summary"),summary:I()}).extend(kh.shape),Jq=O({type:L("reasoning.encrypted"),data:I()}).extend(kh.shape),Wq=O({type:L("reasoning.text"),text:I().nullish(),signature:I().nullish()}).extend(kh.shape),Eh=se([Hq,Jq,Wq]),ms=se([Eh,Le().transform(()=>null)]),Th=W(ms).transform(e=>e.filter(t=>!!t));se([O({delta:O({reasoning_details:W(ms)})}).transform(e=>e.delta.reasoning_details.filter(fc)),O({message:O({reasoning_details:W(ms)})}).transform(e=>e.message.reasoning_details.filter(fc)),O({text:I(),reasoning_details:W(ms)}).transform(e=>e.reasoning_details.filter(fc))]);var wu=O({error:O({code:se([I(),te()]).nullable().optional().default(null),message:I(),type:I().nullable().optional().default(null),param:Ye().nullable().optional().default(null)}).passthrough()}).passthrough(),jo=Bq({errorSchema:wu,errorToMessage:e=>e.error.message}),T$=O({type:L("file"),file:O({hash:I(),name:I(),content:W(O({type:I(),text:I().optional()}).catchall(Ye())).optional()}).catchall(Ye())}).catchall(Ye()),Gq=O({provider:I(),reasoning_details:W(Eh).optional(),annotations:W(T$).optional(),usage:O({promptTokens:te(),promptTokensDetails:O({cachedTokens:te()}).catchall(Ye()).optional(),completionTokens:te(),completionTokensDetails:O({reasoningTokens:te()}).catchall(Ye()).optional(),totalTokens:te(),cost:te().optional(),costDetails:O({upstreamInferenceCost:te()}).catchall(Ye()).optional()}).catchall(Ye())}).catchall(Ye()),wv=O({openrouter:O({reasoning_details:W(Eh).optional(),annotations:W(T$).optional()}).optional()}).optional();function Qs(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 Kq=["wav","mp3","aiff","aac","ogg","flac","m4a","pcm16","pcm24"];function $h({url:e,protocols:t}){try{const n=new URL(e);return t.has(n.protocol)}catch{return!1}}function yd({part:e,defaultMediaType:t}){var n,i;if(e.data instanceof Uint8Array){const o=qq(e.data);return`data:${(n=e.mediaType)!=null?n:t};base64,${o}`}const r=e.data.toString();return $h({url:r,protocols:new Set(["http:","https:"])})||r.startsWith("data:")?r:`data:${(i=e.mediaType)!=null?i:t};base64,${r}`}function xv(e,t){var n;const i=e.match(/^data:([^;]+)/);return i&&(n=i[1])!=null?n:t}function bd(e){const t=e.match(/^data:[^;]*;base64,(.+)$/);return t?t[1]:e}var Yq={mpeg:"mp3",mp3:"mp3","x-wav":"wav",wave:"wav",wav:"wav",ogg:"ogg",vorbis:"ogg",aac:"aac","x-aac":"aac",m4a:"m4a","x-m4a":"m4a",mp4:"m4a",aiff:"aiff","x-aiff":"aiff",flac:"flac","x-flac":"flac",pcm16:"pcm16",pcm24:"pcm24"};function Xq(e){const t=yd({part:e,defaultMediaType:"audio/mpeg"});if($h({url:t,protocols:new Set(["http:","https:"])}))throw new Error(`Audio files cannot be provided as URLs.
|
|
88
|
-
|
|
89
|
-
OpenRouter requires audio to be base64-encoded. Please:
|
|
90
|
-
1. Download the audio file locally
|
|
91
|
-
2. Read it as a Buffer or Uint8Array
|
|
92
|
-
3. Pass it as the data parameter
|
|
93
|
-
|
|
94
|
-
The AI SDK will automatically handle base64 encoding.
|
|
95
|
-
|
|
96
|
-
Learn more: https://openrouter.ai/docs/features/multimodal/audio`);const n=bd(t),i=e.mediaType||"audio/mpeg",r=i.replace("audio/",""),o=Yq[r];if(o===void 0){const a=Kq.join(", ");throw new Error(`Unsupported audio format: "${i}"
|
|
97
|
-
|
|
98
|
-
OpenRouter supports the following audio formats: ${a}
|
|
99
|
-
|
|
100
|
-
Learn more: https://openrouter.ai/docs/features/multimodal/audio`)}return{data:n,format:o}}function Kn(e){var t,n,i;const r=e?.anthropic,o=e?.openrouter;return(i=(n=(t=o?.cacheControl)!=null?t:o?.cache_control)!=null?n:r?.cacheControl)!=null?i:r?.cache_control}function Qq(e){var t,n,i,r,o,a,s,u,l,c;const d=[];for(const{role:f,content:p,providerOptions:g}of e)switch(f){case"system":{d.push({role:"system",content:p,cache_control:Kn(g)});break}case"user":{if(p.length===1&&((t=p[0])==null?void 0:t.type)==="text"){const v=(n=Kn(g))!=null?n:Kn(p[0].providerOptions),_=v?[{type:"text",text:p[0].text,cache_control:v}]:p[0].text;d.push({role:"user",content:_});break}const m=Kn(g),y=p.map(v=>{var _,x,b,C,E,$,A;const j=(_=Kn(v.providerOptions))!=null?_:m;switch(v.type){case"text":return{type:"text",text:v.text,cache_control:j};case"file":{if((x=v.mediaType)!=null&&x.startsWith("image/"))return{type:"image_url",image_url:{url:yd({part:v,defaultMediaType:"image/jpeg"})},cache_control:j};if((b=v.mediaType)!=null&&b.startsWith("audio/"))return{type:"input_audio",input_audio:Xq(v),cache_control:j};const F=String((A=($=(E=(C=v.providerOptions)==null?void 0:C.openrouter)==null?void 0:E.filename)!=null?$:v.filename)!=null?A:""),z=yd({part:v,defaultMediaType:"application/pdf"});return $h({url:z,protocols:new Set(["http:","https:"])})?{type:"file",file:{filename:F,file_data:z}}:{type:"file",file:{filename:F,file_data:z},cache_control:j}}default:return{type:"text",text:"",cache_control:j}}});d.push({role:"user",content:y});break}case"assistant":{let m="",y="";const v=[],_=[];for(const $ of p)switch($.type){case"text":{m+=$.text;break}case"tool-call":{const A=(i=$.providerOptions)==null?void 0:i.openrouter;A?.reasoning_details&&Array.isArray(A.reasoning_details)&&_.push(...A.reasoning_details),v.push({id:$.toolCallId,type:"function",function:{name:$.toolName,arguments:JSON.stringify($.input)}});break}case"reasoning":{y+=$.text;const A=wv.safeParse($.providerOptions);A.success&&((o=(r=A.data)==null?void 0:r.openrouter)!=null&&o.reasoning_details)&&_.push(...A.data.openrouter.reasoning_details);break}}const x=wv.safeParse(g),b=x.success?(s=(a=x.data)==null?void 0:a.openrouter)==null?void 0:s.reasoning_details:void 0,C=x.success?(l=(u=x.data)==null?void 0:u.openrouter)==null?void 0:l.annotations:void 0,E=b&&Array.isArray(b)&&b.length>0?b:_.length>0?_:void 0;d.push({role:"assistant",content:m,tool_calls:v.length>0?v:void 0,reasoning:y||void 0,reasoning_details:E,annotations:C,cache_control:Kn(g)});break}case"tool":{for(const m of p){const y=eV(m);d.push({role:"tool",tool_call_id:m.toolCallId,content:y,cache_control:(c=Kn(g))!=null?c:Kn(m.providerOptions)})}break}}return d}function eV(e){return e.output.type==="text"?e.output.value:JSON.stringify(e.output.value)}se([L("auto"),L("none"),L("required"),O({type:L("function"),function:O({name:I()})})]);function tV(e){switch(e.type){case"auto":case"none":case"required":return e.type;case"tool":return{type:"function",function:{name:e.toolName}};default:throw new e$({argument:"toolChoice",message:`Invalid tool choice type: ${JSON.stringify(e)}`})}}var nV=O({type:L("image_url"),image_url:O({url:I()}).passthrough()}).passthrough(),rV=se([nV,Le().transform(()=>null)]),$$=W(rV).transform(e=>e.filter(t=>!!t)),C$=O({id:I().optional(),model:I().optional(),provider:I().optional(),usage:O({prompt_tokens:te(),prompt_tokens_details:O({cached_tokens:te()}).passthrough().nullish(),completion_tokens:te(),completion_tokens_details:O({reasoning_tokens:te()}).passthrough().nullish(),total_tokens:te(),cost:te().optional(),cost_details:O({upstream_inference_cost:te().nullish()}).passthrough().nullish()}).passthrough().nullish()}).passthrough(),iV=se([C$.extend({choices:W(O({message:O({role:L("assistant"),content:I().nullable().optional(),reasoning:I().nullable().optional(),reasoning_details:Th.nullish(),images:$$.nullish(),tool_calls:W(O({id:I().optional().nullable(),type:L("function"),function:O({name:I(),arguments:I()}).passthrough()}).passthrough()).optional(),annotations:W(se([O({type:L("url_citation"),url_citation:O({end_index:te(),start_index:te(),title:I(),url:I(),content:I().optional()}).passthrough()}).passthrough(),O({type:L("file_annotation"),file_annotation:O({file_id:I(),quote:I().optional()}).passthrough()}).passthrough(),O({type:L("file"),file:O({hash:I(),name:I(),content:W(O({type:I(),text:I().optional()}).passthrough()).optional()}).passthrough()}).passthrough()])).nullish()}).passthrough(),index:te().nullish(),logprobs:O({content:W(O({token:I(),logprob:te(),top_logprobs:W(O({token:I(),logprob:te()}).passthrough())}).passthrough()).nullable()}).passthrough().nullable().optional(),finish_reason:I().optional().nullable()}).passthrough())}),wu.extend({user_id:I().optional()})]),oV=se([C$.extend({choices:W(O({delta:O({role:fr(["assistant"]).optional(),content:I().nullish(),reasoning:I().nullish().optional(),reasoning_details:Th.nullish(),images:$$.nullish(),tool_calls:W(O({index:te().nullish(),id:I().nullish(),type:L("function").optional(),function:O({name:I().nullish(),arguments:I().nullish()}).passthrough()}).passthrough()).nullish(),annotations:W(se([O({type:L("url_citation"),url_citation:O({end_index:te(),start_index:te(),title:I(),url:I(),content:I().optional()}).passthrough()}).passthrough(),O({type:L("file_annotation"),file_annotation:O({file_id:I(),quote:I().optional()}).passthrough()}).passthrough(),O({type:L("file"),file:O({hash:I(),name:I(),content:W(O({type:I(),text:I().optional()}).passthrough()).optional()}).passthrough()}).passthrough()])).nullish()}).passthrough().nullish(),logprobs:O({content:W(O({token:I(),logprob:te(),top_logprobs:W(O({token:I(),logprob:te()}).passthrough())}).passthrough()).nullable()}).passthrough().nullish(),finish_reason:I().nullable().optional(),index:te().nullish()}).passthrough())}),wu]),aV=class{constructor(e,t,n){this.specificationVersion="v2",this.provider="openrouter",this.defaultObjectGenerationMode="tool",this.supportsImageUrls=!0,this.supportedUrls={"image/*":[/^data:image\/[a-zA-Z]+;base64,/,/^https?:\/\/.+\.(jpg|jpeg|png|gif|webp)$/i],"application/*":[/^data:application\//,/^https?:\/\/.+$/]},this.modelId=e,this.settings=t,this.config=n}getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:i,frequencyPenalty:r,presencePenalty:o,seed:a,stopSequences:s,responseFormat:u,topK:l,tools:c,toolChoice:d}){var f;const p=Ee(Ee({model:this.modelId,models:this.settings.models,logit_bias:this.settings.logitBias,logprobs:this.settings.logprobs===!0||typeof this.settings.logprobs=="number"?!0:void 0,top_logprobs:typeof this.settings.logprobs=="number"?this.settings.logprobs:typeof this.settings.logprobs=="boolean"&&this.settings.logprobs?0:void 0,user:this.settings.user,parallel_tool_calls:this.settings.parallelToolCalls,max_tokens:t,temperature:n,top_p:i,frequency_penalty:r,presence_penalty:o,seed:a,stop:s,response_format:u?.type==="json"?u.schema!=null?{type:"json_schema",json_schema:Ee({schema:u.schema,strict:!0,name:(f=u.name)!=null?f:"response"},u.description&&{description:u.description})}:{type:"json_object"}:void 0,top_k:l,messages:Qq(e),include_reasoning:this.settings.includeReasoning,reasoning:this.settings.reasoning,usage:this.settings.usage,plugins:this.settings.plugins,web_search_options:this.settings.web_search_options,provider:this.settings.provider,debug:this.settings.debug},this.config.extraBody),this.settings.extraBody);if(c&&c.length>0){const g=c.filter(m=>m.type==="function").map(m=>({type:"function",function:{name:m.name,description:m.description,parameters:m.inputSchema}}));return Ys(Ee({},p),{tools:g,tool_choice:d?tV(d):void 0})}return p}async doGenerate(e){var t,n,i,r,o,a,s,u,l,c,d,f,p,g,m,y,v,_,x,b,C,E,$;const j=(e.providerOptions||{}).openrouter||{},F=Ee(Ee({},this.getArgs(e)),j),{value:z,responseHeaders:J}=await No({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Oo(this.config.headers(),e.headers),body:F,failedResponseHandler:jo,successfulResponseHandler:Ih(iV),abortSignal:e.abortSignal,fetch:this.config.fetch});if("error"in z){const V=z.error;throw new sn({message:V.message,url:this.config.url({path:"/chat/completions",modelId:this.modelId}),requestBodyValues:F,statusCode:200,responseHeaders:J,data:V})}const G=z,D=G.choices[0];if(!D)throw new g$({message:"No choice in response"});const U=G.usage?{inputTokens:(t=G.usage.prompt_tokens)!=null?t:0,outputTokens:(n=G.usage.completion_tokens)!=null?n:0,totalTokens:((i=G.usage.prompt_tokens)!=null?i:0)+((r=G.usage.completion_tokens)!=null?r:0),reasoningTokens:(a=(o=G.usage.completion_tokens_details)==null?void 0:o.reasoning_tokens)!=null?a:0,cachedInputTokens:(u=(s=G.usage.prompt_tokens_details)==null?void 0:s.cached_tokens)!=null?u:0}:{inputTokens:0,outputTokens:0,totalTokens:0,reasoningTokens:0,cachedInputTokens:0},X=(l=D.message.reasoning_details)!=null?l:[],re=X.length>0?X.map(V=>{switch(V.type){case"reasoning.text":{if(V.text)return{type:"reasoning",text:V.text,providerMetadata:{openrouter:{reasoning_details:[V]}}};break}case"reasoning.summary":{if(V.summary)return{type:"reasoning",text:V.summary,providerMetadata:{openrouter:{reasoning_details:[V]}}};break}case"reasoning.encrypted":{if(V.data)return{type:"reasoning",text:"[REDACTED]",providerMetadata:{openrouter:{reasoning_details:[V]}}};break}}return null}).filter(V=>V!==null):D.message.reasoning?[{type:"reasoning",text:D.message.reasoning}]:[],Q=[];if(Q.push(...re),D.message.content&&Q.push({type:"text",text:D.message.content}),D.message.tool_calls)for(const V of D.message.tool_calls)Q.push({type:"tool-call",toolCallId:(c=V.id)!=null?c:nn(),toolName:V.function.name,input:V.function.arguments,providerMetadata:{openrouter:{reasoning_details:X}}});if(D.message.images)for(const V of D.message.images)Q.push({type:"file",mediaType:xv(V.image_url.url,"image/jpeg"),data:bd(V.image_url.url)});if(D.message.annotations)for(const V of D.message.annotations)V.type==="url_citation"&&Q.push({type:"source",sourceType:"url",id:V.url_citation.url,url:V.url_citation.url,title:V.url_citation.title,providerMetadata:{openrouter:{content:V.url_citation.content||""}}});const me=(d=D.message.annotations)==null?void 0:d.filter(V=>V.type==="file"),S=D.message.tool_calls&&D.message.tool_calls.length>0,Ae=X.some(V=>V.type==="reasoning.encrypted"&&V.data),T=S&&Ae&&D.finish_reason==="stop"?"tool-calls":Qs(D.finish_reason);return{content:Q,finishReason:T,usage:U,warnings:[],providerMetadata:{openrouter:Gq.parse({provider:(f=G.provider)!=null?f:"",reasoning_details:(p=D.message.reasoning_details)!=null?p:[],annotations:me&&me.length>0?me:void 0,usage:Ee(Ee(Ee({promptTokens:(g=U.inputTokens)!=null?g:0,completionTokens:(m=U.outputTokens)!=null?m:0,totalTokens:(y=U.totalTokens)!=null?y:0,cost:(v=G.usage)==null?void 0:v.cost},((x=(_=G.usage)==null?void 0:_.prompt_tokens_details)==null?void 0:x.cached_tokens)!=null?{promptTokensDetails:{cachedTokens:G.usage.prompt_tokens_details.cached_tokens}}:{}),((C=(b=G.usage)==null?void 0:b.completion_tokens_details)==null?void 0:C.reasoning_tokens)!=null?{completionTokensDetails:{reasoningTokens:G.usage.completion_tokens_details.reasoning_tokens}}:{}),(($=(E=G.usage)==null?void 0:E.cost_details)==null?void 0:$.upstream_inference_cost)!=null?{costDetails:{upstreamInferenceCost:G.usage.cost_details.upstream_inference_cost}}:{})})},request:{body:F},response:{id:G.id,modelId:G.model,headers:J}}}async doStream(e){var t;const i=(e.providerOptions||{}).openrouter||{},r=Ee(Ee({},this.getArgs(e)),i),{value:o,responseHeaders:a}=await No({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Oo(this.config.headers(),e.headers),body:Ys(Ee({},r),{stream:!0,stream_options:this.config.compatibility==="strict"?Ee({include_usage:!0},(t=this.settings.usage)!=null&&t.include?{include_usage:!0}:{}):void 0}),failedResponseHandler:jo,successfulResponseHandler:k$(oV),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=[];let u="other";const l={inputTokens:Number.NaN,outputTokens:Number.NaN,totalTokens:Number.NaN,reasoningTokens:Number.NaN,cachedInputTokens:Number.NaN},c={},d=[],f=[];let p=!1,g=!1,m,y,v,_;return{stream:o.pipeThrough(new TransformStream({transform(x,b){var C,E,$,A,j,F,z,J,G,D,U,X,re,Q,me;if(!x.success){u="error",b.enqueue({type:"error",error:x.error});return}const S=x.value;if("error"in S){u="error",b.enqueue({type:"error",error:S.error});return}if(S.provider&&(_=S.provider),S.id&&(v=S.id,b.enqueue({type:"response-metadata",id:S.id})),S.model&&b.enqueue({type:"response-metadata",modelId:S.model}),S.usage!=null){if(l.inputTokens=S.usage.prompt_tokens,l.outputTokens=S.usage.completion_tokens,l.totalTokens=S.usage.prompt_tokens+S.usage.completion_tokens,c.promptTokens=S.usage.prompt_tokens,S.usage.prompt_tokens_details){const ne=(C=S.usage.prompt_tokens_details.cached_tokens)!=null?C:0;l.cachedInputTokens=ne,c.promptTokensDetails={cachedTokens:ne}}if(c.completionTokens=S.usage.completion_tokens,S.usage.completion_tokens_details){const ne=(E=S.usage.completion_tokens_details.reasoning_tokens)!=null?E:0;l.reasoningTokens=ne,c.completionTokensDetails={reasoningTokens:ne}}c.cost=S.usage.cost,c.totalTokens=S.usage.total_tokens;const V=($=S.usage.cost_details)==null?void 0:$.upstream_inference_cost;V!=null&&(c.costDetails={upstreamInferenceCost:V})}const Ae=S.choices[0];if(Ae?.finish_reason!=null&&(u=Qs(Ae.finish_reason)),Ae?.delta==null)return;const ye=Ae.delta,T=(V,ne)=>{g||(y=v||nn(),b.enqueue({providerMetadata:ne,type:"reasoning-start",id:y}),g=!0),b.enqueue({providerMetadata:ne,type:"reasoning-delta",delta:V,id:y||nn()})};if(ye.reasoning_details&&ye.reasoning_details.length>0){for(const ne of ye.reasoning_details)if(ne.type==="reasoning.text"){const ue=d[d.length-1];ue?.type==="reasoning.text"?(ue.text=(ue.text||"")+(ne.text||""),ue.signature=ue.signature||ne.signature,ue.format=ue.format||ne.format):d.push(Ee({},ne))}else d.push(ne);const V={openrouter:{reasoning_details:ye.reasoning_details}};for(const ne of ye.reasoning_details)switch(ne.type){case"reasoning.text":{ne.text&&T(ne.text,V);break}case"reasoning.encrypted":{ne.data&&T("[REDACTED]",V);break}case"reasoning.summary":{ne.summary&&T(ne.summary,V);break}}}else ye.reasoning&&T(ye.reasoning);if(ye.content&&(g&&!p&&(b.enqueue({type:"reasoning-end",id:y||nn()}),g=!1),p||(m=v||nn(),b.enqueue({type:"text-start",id:m}),p=!0),b.enqueue({type:"text-delta",delta:ye.content,id:m||nn()})),ye.annotations){for(const V of ye.annotations)if(V.type==="url_citation")b.enqueue({type:"source",sourceType:"url",id:V.url_citation.url,url:V.url_citation.url,title:V.url_citation.title,providerMetadata:{openrouter:{content:V.url_citation.content||""}}});else if(V.type==="file"){const ne=V.file;ne&&typeof ne=="object"&&"hash"in ne&&"name"in ne&&f.push(V)}}if(ye.tool_calls!=null)for(const V of ye.tool_calls){const ne=(A=V.index)!=null?A:s.length-1;if(s[ne]==null){if(V.type!=="function")throw new Fi({data:V,message:"Expected 'function' type."});if(V.id==null)throw new Fi({data:V,message:"Expected 'id' to be a string."});if(((j=V.function)==null?void 0:j.name)==null)throw new Fi({data:V,message:"Expected 'function.name' to be a string."});s[ne]={id:V.id,type:"function",function:{name:V.function.name,arguments:(F=V.function.arguments)!=null?F:""},inputStarted:!1,sent:!1};const Se=s[ne];if(Se==null)throw new Fi({data:{index:ne,toolCallsLength:s.length},message:`Tool call at index ${ne} is missing after creation.`});((z=Se.function)==null?void 0:z.name)!=null&&((J=Se.function)==null?void 0:J.arguments)!=null&&pc(Se.function.arguments)&&(Se.inputStarted=!0,b.enqueue({type:"tool-input-start",id:Se.id,toolName:Se.function.name}),b.enqueue({type:"tool-input-delta",id:Se.id,delta:Se.function.arguments}),b.enqueue({type:"tool-input-end",id:Se.id}),b.enqueue({type:"tool-call",toolCallId:Se.id,toolName:Se.function.name,input:Se.function.arguments,providerMetadata:{openrouter:{reasoning_details:d}}}),Se.sent=!0);continue}const ue=s[ne];if(ue==null)throw new Fi({data:{index:ne,toolCallsLength:s.length,toolCallDelta:V},message:`Tool call at index ${ne} is missing during merge.`});ue.inputStarted||(ue.inputStarted=!0,b.enqueue({type:"tool-input-start",id:ue.id,toolName:ue.function.name})),((G=V.function)==null?void 0:G.arguments)!=null&&(ue.function.arguments+=(U=(D=V.function)==null?void 0:D.arguments)!=null?U:""),b.enqueue({type:"tool-input-delta",id:ue.id,delta:(X=V.function.arguments)!=null?X:""}),((re=ue.function)==null?void 0:re.name)!=null&&((Q=ue.function)==null?void 0:Q.arguments)!=null&&pc(ue.function.arguments)&&(b.enqueue({type:"tool-call",toolCallId:(me=ue.id)!=null?me:nn(),toolName:ue.function.name,input:ue.function.arguments,providerMetadata:{openrouter:{reasoning_details:d}}}),ue.sent=!0)}if(ye.images!=null)for(const V of ye.images)b.enqueue({type:"file",mediaType:xv(V.image_url.url,"image/jpeg"),data:bd(V.image_url.url)})},flush(x){var b;const C=s.length>0,E=d.some(A=>A.type==="reasoning.encrypted"&&A.data);if(C&&E&&u==="stop"&&(u="tool-calls"),u==="tool-calls")for(const A of s)A&&!A.sent&&(x.enqueue({type:"tool-call",toolCallId:(b=A.id)!=null?b:nn(),toolName:A.function.name,input:pc(A.function.arguments)?A.function.arguments:"{}",providerMetadata:{openrouter:{reasoning_details:d}}}),A.sent=!0);g&&x.enqueue({type:"reasoning-end",id:y||nn()}),p&&x.enqueue({type:"text-end",id:m||nn()});const $={usage:c};_!==void 0&&($.provider=_),d.length>0&&($.reasoning_details=d),f.length>0&&($.annotations=f),x.enqueue({type:"finish",finishReason:u,usage:l,providerMetadata:{openrouter:$}})}})),warnings:[],request:{body:r},response:{headers:a}}}};function sV({prompt:e,inputFormat:t,user:n="user",assistant:i="assistant"}){if(e.length===1&&e[0]&&e[0].role==="user"&&e[0].content.length===1&&e[0].content[0]&&e[0].content[0].type==="text")return{prompt:e[0].content[0].text};let r="";e[0]&&e[0].role==="system"&&(r+=`${e[0].content}
|
|
101
|
-
|
|
102
|
-
`,e=e.slice(1));for(const{role:o,content:a}of e)switch(o){case"system":throw new fq({message:`Unexpected system message in prompt: ${a}`,prompt:e});case"user":{const s=a.map(u=>{switch(u.type){case"text":return u.text;case"file":throw new er({functionality:"file attachments"});default:return""}}).join("");r+=`${n}:
|
|
103
|
-
${s}
|
|
104
|
-
|
|
105
|
-
`;break}case"assistant":{const s=a.map(u=>{switch(u.type){case"text":return u.text;case"tool-call":throw new er({functionality:"tool-call messages"});case"tool-result":throw new er({functionality:"tool-result messages"});case"reasoning":throw new er({functionality:"reasoning messages"});case"file":throw new er({functionality:"file attachments"});default:return""}}).join("");r+=`${i}:
|
|
106
|
-
${s}
|
|
107
|
-
|
|
108
|
-
`;break}case"tool":throw new er({functionality:"tool messages"})}return r+=`${i}:
|
|
109
|
-
`,{prompt:r}}var Sv=se([O({id:I().optional(),model:I().optional(),choices:W(O({text:I(),reasoning:I().nullish().optional(),reasoning_details:Th.nullish(),finish_reason:I().nullish(),index:te().nullish(),logprobs:O({tokens:W(I()),token_logprobs:W(te()),top_logprobs:W(Rt(I(),te())).nullable()}).passthrough().nullable().optional()}).passthrough()),usage:O({prompt_tokens:te(),prompt_tokens_details:O({cached_tokens:te()}).passthrough().nullish(),completion_tokens:te(),completion_tokens_details:O({reasoning_tokens:te()}).passthrough().nullish(),total_tokens:te(),cost:te().optional(),cost_details:O({upstream_inference_cost:te().nullish()}).passthrough().nullish()}).passthrough().nullish()}).passthrough(),wu]),lV=class{constructor(e,t,n){this.specificationVersion="v2",this.provider="openrouter",this.supportsImageUrls=!0,this.supportedUrls={"image/*":[/^data:image\/[a-zA-Z]+;base64,/,/^https?:\/\/.+\.(jpg|jpeg|png|gif|webp)$/i],"text/*":[/^data:text\//,/^https?:\/\/.+$/],"application/*":[/^data:application\//,/^https?:\/\/.+$/]},this.defaultObjectGenerationMode=void 0,this.modelId=e,this.settings=t,this.config=n}getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:i,frequencyPenalty:r,presencePenalty:o,seed:a,responseFormat:s,topK:u,stopSequences:l,tools:c,toolChoice:d}){const{prompt:f}=sV({prompt:e,inputFormat:"prompt"});if(c?.length)throw new er({functionality:"tools"});if(d)throw new er({functionality:"toolChoice"});return Ee(Ee({model:this.modelId,models:this.settings.models,logit_bias:this.settings.logitBias,logprobs:typeof this.settings.logprobs=="number"?this.settings.logprobs:typeof this.settings.logprobs=="boolean"&&this.settings.logprobs?0:void 0,suffix:this.settings.suffix,user:this.settings.user,max_tokens:t,temperature:n,top_p:i,frequency_penalty:r,presence_penalty:o,seed:a,stop:l,response_format:s,top_k:u,prompt:f,include_reasoning:this.settings.includeReasoning,reasoning:this.settings.reasoning},this.config.extraBody),this.settings.extraBody)}async doGenerate(e){var t,n,i,r,o,a,s,u,l,c,d,f,p,g,m;const v=(e.providerOptions||{}).openrouter||{},_=Ee(Ee({},this.getArgs(e)),v),{value:x,responseHeaders:b}=await No({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Oo(this.config.headers(),e.headers),body:_,failedResponseHandler:jo,successfulResponseHandler:Ih(Sv),abortSignal:e.abortSignal,fetch:this.config.fetch});if("error"in x){const E=x.error;throw new sn({message:E.message,url:this.config.url({path:"/completions",modelId:this.modelId}),requestBodyValues:_,statusCode:200,responseHeaders:b,data:E})}const C=x.choices[0];if(!C)throw new g$({message:"No choice in OpenRouter completion response"});return{content:[{type:"text",text:(t=C.text)!=null?t:""}],finishReason:Qs(C.finish_reason),usage:{inputTokens:(i=(n=x.usage)==null?void 0:n.prompt_tokens)!=null?i:0,outputTokens:(o=(r=x.usage)==null?void 0:r.completion_tokens)!=null?o:0,totalTokens:((s=(a=x.usage)==null?void 0:a.prompt_tokens)!=null?s:0)+((l=(u=x.usage)==null?void 0:u.completion_tokens)!=null?l:0),reasoningTokens:(f=(d=(c=x.usage)==null?void 0:c.completion_tokens_details)==null?void 0:d.reasoning_tokens)!=null?f:0,cachedInputTokens:(m=(g=(p=x.usage)==null?void 0:p.prompt_tokens_details)==null?void 0:g.cached_tokens)!=null?m:0},warnings:[],response:{headers:b}}}async doStream(e){const n=(e.providerOptions||{}).openrouter||{},i=Ee(Ee({},this.getArgs(e)),n),{value:r,responseHeaders:o}=await No({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Oo(this.config.headers(),e.headers),body:Ys(Ee({},i),{stream:!0,stream_options:this.config.compatibility==="strict"?{include_usage:!0}:void 0}),failedResponseHandler:jo,successfulResponseHandler:k$(Sv),abortSignal:e.abortSignal,fetch:this.config.fetch});let a="other";const s={inputTokens:Number.NaN,outputTokens:Number.NaN,totalTokens:Number.NaN,reasoningTokens:Number.NaN,cachedInputTokens:Number.NaN},u={};return{stream:r.pipeThrough(new TransformStream({transform(l,c){var d,f,p;if(!l.success){a="error",c.enqueue({type:"error",error:l.error});return}const g=l.value;if("error"in g){a="error",c.enqueue({type:"error",error:g.error});return}if(g.usage!=null){if(s.inputTokens=g.usage.prompt_tokens,s.outputTokens=g.usage.completion_tokens,s.totalTokens=g.usage.prompt_tokens+g.usage.completion_tokens,u.promptTokens=g.usage.prompt_tokens,g.usage.prompt_tokens_details){const v=(d=g.usage.prompt_tokens_details.cached_tokens)!=null?d:0;s.cachedInputTokens=v,u.promptTokensDetails={cachedTokens:v}}if(u.completionTokens=g.usage.completion_tokens,g.usage.completion_tokens_details){const v=(f=g.usage.completion_tokens_details.reasoning_tokens)!=null?f:0;s.reasoningTokens=v,u.completionTokensDetails={reasoningTokens:v}}u.cost=g.usage.cost,u.totalTokens=g.usage.total_tokens;const y=(p=g.usage.cost_details)==null?void 0:p.upstream_inference_cost;y!=null&&(u.costDetails={upstreamInferenceCost:y})}const m=g.choices[0];m?.finish_reason!=null&&(a=Qs(m.finish_reason)),m?.text!=null&&c.enqueue({type:"text-delta",delta:m.text,id:nn()})},flush(l){l.enqueue({type:"finish",finishReason:a,usage:s,providerMetadata:{openrouter:{usage:u}}})}})),response:{headers:o}}}},uV=O({prompt_tokens:te(),total_tokens:te(),cost:te().optional()}),cV=O({object:L("embedding"),embedding:W(te()),index:te().optional()}),dV=O({id:I().optional(),object:L("list"),data:W(cV),model:I(),usage:uV.optional()}),pV=class{constructor(e,t,n){this.specificationVersion="v2",this.provider="openrouter",this.maxEmbeddingsPerCall=void 0,this.supportsParallelCalls=!0,this.modelId=e,this.settings=t,this.config=n}async doEmbed(e){var t;const{values:n,abortSignal:i,headers:r}=e,o=Ee(Ee({model:this.modelId,input:n,user:this.settings.user,provider:this.settings.provider},this.config.extraBody),this.settings.extraBody),{value:a,responseHeaders:s}=await No({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:Oo(this.config.headers(),r),body:o,failedResponseHandler:jo,successfulResponseHandler:Ih(dV),abortSignal:i,fetch:this.config.fetch});return{embeddings:a.data.map(u=>u.embedding),usage:a.usage?{tokens:a.usage.prompt_tokens}:void 0,providerMetadata:(t=a.usage)!=null&&t.cost?{openrouter:{usage:{cost:a.usage.cost}}}:void 0,response:{headers:s,body:a}}}};function fV(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==null))}function hV(e,...t){const n=fV(e??{}),r=[n["user-agent"]||"",...t].filter(Boolean).join(" ");return Ys(Ee({},n),{"user-agent":r})}var mV="1.5.4";function A$(e={}){var t,n,i;const r=(n=Vq((t=e.baseURL)!=null?t:e.baseUrl))!=null?n:"https://openrouter.ai/api/v1",o=(i=e.compatibility)!=null?i:"compatible",a=()=>hV(Ee(Ee({Authorization:`Bearer ${$q({apiKey:e.apiKey,environmentVariableName:"OPENROUTER_API_KEY",description:"OpenRouter"})}`},e.headers),e.api_keys&&Object.keys(e.api_keys).length>0&&{"X-Provider-API-Keys":JSON.stringify(e.api_keys)}),`ai-sdk/openrouter/${mV}`),s=(f,p={})=>new aV(f,p,{provider:"openrouter.chat",url:({path:g})=>`${r}${g}`,headers:a,compatibility:o,fetch:e.fetch,extraBody:e.extraBody}),u=(f,p={})=>new lV(f,p,{provider:"openrouter.completion",url:({path:g})=>`${r}${g}`,headers:a,compatibility:o,fetch:e.fetch,extraBody:e.extraBody}),l=(f,p={})=>new pV(f,p,{provider:"openrouter.embedding",url:({path:g})=>`${r}${g}`,headers:a,fetch:e.fetch,extraBody:e.extraBody}),c=(f,p)=>{if(new.target)throw new Error("The OpenRouter model function cannot be called with the new keyword.");return f==="openai/gpt-3.5-turbo-instruct"?u(f,p):s(f,p)},d=(f,p)=>c(f,p);return d.languageModel=c,d.chat=s,d.completion=u,d.textEmbeddingModel=l,d.embedding=l,d}A$({compatibility:"strict"});function _d(...e){return e.reduce((t,n)=>({...t,...n??{}}),{})}async function P$(e,t){if(e==null)return Promise.resolve();const n=t?.abortSignal;return new Promise((i,r)=>{if(n?.aborted){r(Iv());return}const o=setTimeout(()=>{a(),i()},e),a=()=>{clearTimeout(o),n?.removeEventListener("abort",s)},s=()=>{a(),r(Iv())};n?.addEventListener("abort",s)})}function Iv(){return new DOMException("Delay was aborted","AbortError")}function Ia(e){return Object.fromEntries([...e.headers])}var ka=({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:i="-"}={})=>{const r=()=>{const o=n.length,a=new Array(t);for(let s=0;s<t;s++)a[s]=n[Math.random()*o|0];return a.join("")};if(e==null)return r;if(n.includes(i))throw new al({argument:"separator",message:`The separator "${i}" must not be part of the alphabet "${n}".`});return()=>`${e}${i}${r()}`},gV=ka();function R$(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}function Or(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var vV=["fetch failed","failed to fetch"];function O$({error:e,url:t,requestBodyValues:n}){if(Or(e))return e;if(e instanceof TypeError&&vV.includes(e.message.toLowerCase())){const i=e.cause;if(i!=null)return new mt({message:`Cannot connect to API: ${i.message}`,cause:i,url:t,requestBodyValues:n,isRetryable:!0})}return e}function Ch(e=globalThis){var t,n,i;return e.window?"runtime/browser":(t=e.navigator)!=null&&t.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(i=(n=e.process)==null?void 0:n.versions)!=null&&i.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function yV(e){if(e==null)return{};const t={};if(e instanceof Headers)e.forEach((n,i)=>{t[i.toLowerCase()]=n});else{Array.isArray(e)||(e=Object.entries(e));for(const[n,i]of e)i!=null&&(t[n.toLowerCase()]=i)}return t}function xu(e,...t){const n=new Headers(yV(e)),i=n.get("user-agent")||"";return n.set("user-agent",[i,...t].filter(Boolean).join(" ")),Object.fromEntries(n.entries())}var N$="3.0.16",bV=()=>globalThis.fetch,kv=async({url:e,headers:t={},successfulResponseHandler:n,failedResponseHandler:i,abortSignal:r,fetch:o=bV()})=>{try{const a=await o(e,{method:"GET",headers:xu(t,`ai-sdk/provider-utils/${N$}`,Ch()),signal:r}),s=Ia(a);if(!a.ok){let u;try{u=await i({response:a,url:e,requestBodyValues:{}})}catch(l){throw Or(l)||mt.isInstance(l)?l:new mt({message:"Failed to process error response",cause:l,statusCode:a.status,url:e,responseHeaders:s,requestBodyValues:{}})}throw u.value}try{return await n({response:a,url:e,requestBodyValues:{}})}catch(u){throw u instanceof Error&&(Or(u)||mt.isInstance(u))?u:new mt({message:"Failed to process successful response",cause:u,statusCode:a.status,url:e,responseHeaders:s,requestBodyValues:{}})}}catch(a){throw O$({error:a,url:e,requestBodyValues:{}})}};function _V({mediaType:e,url:t,supportedUrls:n}){return t=t.toLowerCase(),e=e.toLowerCase(),Object.entries(n).map(([i,r])=>{const o=i.toLowerCase();return o==="*"||o==="*/*"?{mediaTypePrefix:"",regexes:r}:{mediaTypePrefix:o.replace(/\*/,""),regexes:r}}).filter(({mediaTypePrefix:i})=>e.startsWith(i)).flatMap(({regexes:i})=>i).some(i=>i.test(t))}function gs({settingValue:e,environmentVariableName:t}){if(typeof e=="string")return e;if(!(e!=null||typeof process>"u")&&(e=process.env[t],!(e==null||typeof e!="string")))return e}var wV=/"__proto__"\s*:/,xV=/"constructor"\s*:/;function SV(e){const t=JSON.parse(e);return t===null||typeof t!="object"||wV.test(e)===!1&&xV.test(e)===!1?t:IV(t)}function IV(e){let t=[e];for(;t.length;){const n=t;t=[];for(const i of n){if(Object.prototype.hasOwnProperty.call(i,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(i,"constructor")&&Object.prototype.hasOwnProperty.call(i.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const r in i){const o=i[r];o&&typeof o=="object"&&t.push(o)}}}return e}function j$(e){const{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return SV(e)}finally{Error.stackTraceLimit=t}}var el=Symbol.for("vercel.ai.validator");function kV(e){return{[el]:!0,validate:e}}function EV(e){return typeof e=="object"&&e!==null&&el in e&&e[el]===!0&&"validate"in e}function Ni(e){let t;return()=>(t==null&&(t=e()),t)}function TV(e){return EV(e)?e:typeof e=="function"?e():$V(e)}function $V(e){return kV(async t=>{const n=await e["~standard"].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new Un({value:t,cause:n.issues})}})}async function wd({value:e,schema:t}){const n=await dr({value:e,schema:t});if(!n.success)throw Un.wrap({value:e,cause:n.error});return n.value}async function dr({value:e,schema:t}){const n=TV(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};const i=await n.validate(e);return i.success?{success:!0,value:i.value,rawValue:e}:{success:!1,error:Un.wrap({value:e,cause:i.error}),rawValue:e}}catch(i){return{success:!1,error:Un.wrap({value:e,cause:i}),rawValue:e}}}async function CV({text:e,schema:t}){try{const n=j$(e);return t==null?n:wd({value:n,schema:t})}catch(n){throw di.isInstance(n)||Un.isInstance(n)?n:new di({text:e,cause:n})}}async function Nr({text:e,schema:t}){try{const n=j$(e);return t==null?{success:!0,value:n,rawValue:n}:await dr({value:n,schema:t})}catch(n){return{success:!1,error:di.isInstance(n)?n:new di({text:e,cause:n}),rawValue:void 0}}}function AV({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new uo).pipeThrough(new TransformStream({async transform({data:n},i){n!=="[DONE]"&&i.enqueue(await Nr({text:n,schema:t}))}}))}var PV=()=>globalThis.fetch,xd=async({url:e,headers:t,body:n,failedResponseHandler:i,successfulResponseHandler:r,abortSignal:o,fetch:a})=>RV({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:i,successfulResponseHandler:r,abortSignal:o,fetch:a}),RV=async({url:e,headers:t={},body:n,successfulResponseHandler:i,failedResponseHandler:r,abortSignal:o,fetch:a=PV()})=>{try{const s=await a(e,{method:"POST",headers:xu(t,`ai-sdk/provider-utils/${N$}`,Ch()),body:n.content,signal:o}),u=Ia(s);if(!s.ok){let l;try{l=await r({response:s,url:e,requestBodyValues:n.values})}catch(c){throw Or(c)||mt.isInstance(c)?c:new mt({message:"Failed to process error response",cause:c,statusCode:s.status,url:e,responseHeaders:u,requestBodyValues:n.values})}throw l.value}try{return await i({response:s,url:e,requestBodyValues:n.values})}catch(l){throw l instanceof Error&&(Or(l)||mt.isInstance(l))?l:new mt({message:"Failed to process successful response",cause:l,statusCode:s.status,url:e,responseHeaders:u,requestBodyValues:n.values})}}catch(s){throw O$({error:s,url:e,requestBodyValues:n.values})}};async function nr(e){return typeof e=="function"&&(e=e()),Promise.resolve(e)}var Mo=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:i,url:r,requestBodyValues:o})=>{const a=await i.text(),s=Ia(i);if(a.trim()==="")return{responseHeaders:s,value:new mt({message:i.statusText,url:r,requestBodyValues:o,statusCode:i.status,responseHeaders:s,responseBody:a,isRetryable:n?.(i)})};try{const u=await CV({text:a,schema:e});return{responseHeaders:s,value:new mt({message:t(u),url:r,requestBodyValues:o,statusCode:i.status,responseHeaders:s,responseBody:a,data:u,isRetryable:n?.(i,u)})}}catch{return{responseHeaders:s,value:new mt({message:i.statusText,url:r,requestBodyValues:o,statusCode:i.status,responseHeaders:s,responseBody:a,isRetryable:n?.(i)})}}},OV=e=>async({response:t})=>{const n=Ia(t);if(t.body==null)throw new jP({});return{responseHeaders:n,value:AV({stream:t.body,schema:e})}},tl=e=>async({response:t,url:n,requestBodyValues:i})=>{const r=await t.text(),o=await Nr({text:r,schema:e}),a=Ia(t);if(!o.success)throw new mt({message:"Invalid JSON response",cause:o.error,statusCode:t.status,responseHeaders:a,responseBody:r,url:n,requestBodyValues:i});return{responseHeaders:a,value:o.value,rawValue:o.rawValue}},NV=(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("/")},jV=Symbol("Let zodToJsonSchema decide on which parser to use"),Ev={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"},MV=e=>typeof e=="string"?{...Ev,name:e}:{...Ev,...e};function jt(){return{}}function DV(e,t){var n,i,r;const o={type:"array"};return(n=e.type)!=null&&n._def&&((r=(i=e.type)==null?void 0:i._def)==null?void 0:r.typeName)!==H.ZodAny&&(o.items=$e(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&(o.minItems=e.minLength.value),e.maxLength&&(o.maxItems=e.maxLength.value),e.exactLength&&(o.minItems=e.exactLength.value,o.maxItems=e.exactLength.value),o}function zV(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 UV(){return{type:"boolean"}}function M$(e,t){return $e(e.type._def,t)}var LV=(e,t)=>$e(e.innerType._def,t);function D$(e,t,n){const i=n??t.dateStrategy;if(Array.isArray(i))return{anyOf:i.map((r,o)=>D$(e,t,r))};switch(i){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return FV(e)}}var FV=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 BV(e,t){return{...$e(e.innerType._def,t),default:e.defaultValue()}}function ZV(e,t){return t.effectStrategy==="input"?$e(e.schema._def,t):jt()}function qV(e){return{type:"string",enum:Array.from(e.values)}}var VV=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function HV(e,t){const n=[$e(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),$e(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(r=>!!r),i=[];return n.forEach(r=>{if(VV(r))i.push(...r.allOf);else{let o=r;if("additionalProperties"in r&&r.additionalProperties===!1){const{additionalProperties:a,...s}=r;o=s}i.push(o)}}),i.length?{allOf:i}:void 0}function JV(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 hc=void 0,en={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:()=>(hc===void 0&&(hc=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),hc),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 z$(e,t){const n={type:"string"};if(e.checks)for(const i of e.checks)switch(i.kind){case"min":n.minLength=typeof n.minLength=="number"?Math.max(n.minLength,i.value):i.value;break;case"max":n.maxLength=typeof n.maxLength=="number"?Math.min(n.maxLength,i.value):i.value;break;case"email":switch(t.emailStrategy){case"format:email":tn(n,"email",i.message,t);break;case"format:idn-email":tn(n,"idn-email",i.message,t);break;case"pattern:zod":ft(n,en.email,i.message,t);break}break;case"url":tn(n,"uri",i.message,t);break;case"uuid":tn(n,"uuid",i.message,t);break;case"regex":ft(n,i.regex,i.message,t);break;case"cuid":ft(n,en.cuid,i.message,t);break;case"cuid2":ft(n,en.cuid2,i.message,t);break;case"startsWith":ft(n,RegExp(`^${mc(i.value,t)}`),i.message,t);break;case"endsWith":ft(n,RegExp(`${mc(i.value,t)}$`),i.message,t);break;case"datetime":tn(n,"date-time",i.message,t);break;case"date":tn(n,"date",i.message,t);break;case"time":tn(n,"time",i.message,t);break;case"duration":tn(n,"duration",i.message,t);break;case"length":n.minLength=typeof n.minLength=="number"?Math.max(n.minLength,i.value):i.value,n.maxLength=typeof n.maxLength=="number"?Math.min(n.maxLength,i.value):i.value;break;case"includes":{ft(n,RegExp(mc(i.value,t)),i.message,t);break}case"ip":{i.version!=="v6"&&tn(n,"ipv4",i.message,t),i.version!=="v4"&&tn(n,"ipv6",i.message,t);break}case"base64url":ft(n,en.base64url,i.message,t);break;case"jwt":ft(n,en.jwt,i.message,t);break;case"cidr":{i.version!=="v6"&&ft(n,en.ipv4Cidr,i.message,t),i.version!=="v4"&&ft(n,en.ipv6Cidr,i.message,t);break}case"emoji":ft(n,en.emoji(),i.message,t);break;case"ulid":{ft(n,en.ulid,i.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{tn(n,"binary",i.message,t);break}case"contentEncoding:base64":{n.contentEncoding="base64";break}case"pattern:zod":{ft(n,en.base64,i.message,t);break}}break}case"nanoid":ft(n,en.nanoid,i.message,t)}return n}function mc(e,t){return t.patternStrategy==="escape"?GV(e):e}var WV=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function GV(e){let t="";for(let n=0;n<e.length;n++)WV.has(e[n])||(t+="\\"),t+=e[n];return t}function tn(e,t,n,i){var r;e.format||(r=e.anyOf)!=null&&r.some(o=>o.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format}),delete e.format),e.anyOf.push({format:t,...n&&i.errorMessages&&{errorMessage:{format:n}}})):e.format=t}function ft(e,t,n,i){var r;e.pattern||(r=e.allOf)!=null&&r.some(o=>o.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern}),delete e.pattern),e.allOf.push({pattern:Tv(t,i),...n&&i.errorMessages&&{errorMessage:{pattern:n}}})):e.pattern=Tv(t,i)}function Tv(e,t){var n;if(!t.applyRegexFlags||!e.flags)return e.source;const i={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},r=i.i?e.source.toLowerCase():e.source;let o="",a=!1,s=!1,u=!1;for(let l=0;l<r.length;l++){if(a){o+=r[l],a=!1;continue}if(i.i){if(s){if(r[l].match(/[a-z]/)){u?(o+=r[l],o+=`${r[l-2]}-${r[l]}`.toUpperCase(),u=!1):r[l+1]==="-"&&((n=r[l+2])!=null&&n.match(/[a-z]/))?(o+=r[l],u=!0):o+=`${r[l]}${r[l].toUpperCase()}`;continue}}else if(r[l].match(/[a-z]/)){o+=`[${r[l]}${r[l].toUpperCase()}]`;continue}}if(i.m){if(r[l]==="^"){o+=`(^|(?<=[\r
|
|
110
|
-
]))`;continue}else if(r[l]==="$"){o+=`($|(?=[\r
|
|
111
|
-
]))`;continue}}if(i.s&&r[l]==="."){o+=s?`${r[l]}\r
|
|
112
|
-
`:`[${r[l]}\r
|
|
113
|
-
]`;continue}o+=r[l],r[l]==="\\"?a=!0:s&&r[l]==="]"?s=!1:!s&&r[l]==="["&&(s=!0)}try{new RegExp(o)}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 o}function U$(e,t){var n,i,r,o,a,s;const u={type:"object",additionalProperties:(n=$e(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?n:t.allowedAdditionalProperties};if(((i=e.keyType)==null?void 0:i._def.typeName)===H.ZodString&&((r=e.keyType._def.checks)!=null&&r.length)){const{type:l,...c}=z$(e.keyType._def,t);return{...u,propertyNames:c}}else{if(((o=e.keyType)==null?void 0:o._def.typeName)===H.ZodEnum)return{...u,propertyNames:{enum:e.keyType._def.values}};if(((a=e.keyType)==null?void 0:a._def.typeName)===H.ZodBranded&&e.keyType._def.type._def.typeName===H.ZodString&&((s=e.keyType._def.type._def.checks)!=null&&s.length)){const{type:l,...c}=M$(e.keyType._def,t);return{...u,propertyNames:c}}}return u}function KV(e,t){if(t.mapStrategy==="record")return U$(e,t);const n=$e(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||jt(),i=$e(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||jt();return{type:"array",maxItems:125,items:{type:"array",items:[n,i],minItems:2,maxItems:2}}}function YV(e){const t=e.values,i=Object.keys(e.values).filter(o=>typeof t[t[o]]!="number").map(o=>t[o]),r=Array.from(new Set(i.map(o=>typeof o)));return{type:r.length===1?r[0]==="string"?"string":"number":["string","number"],enum:i}}function XV(){return{not:jt()}}function QV(){return{type:"null"}}var Sd={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function e9(e,t){const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(i=>i._def.typeName in Sd&&(!i._def.checks||!i._def.checks.length))){const i=n.reduce((r,o)=>{const a=Sd[o._def.typeName];return a&&!r.includes(a)?[...r,a]:r},[]);return{type:i.length>1?i:i[0]}}else if(n.every(i=>i._def.typeName==="ZodLiteral"&&!i.description)){const i=n.reduce((r,o)=>{const a=typeof o._def.value;switch(a){case"string":case"number":case"boolean":return[...r,a];case"bigint":return[...r,"integer"];case"object":if(o._def.value===null)return[...r,"null"];case"symbol":case"undefined":case"function":default:return r}},[]);if(i.length===n.length){const r=i.filter((o,a,s)=>s.indexOf(o)===a);return{type:r.length>1?r:r[0],enum:n.reduce((o,a)=>o.includes(a._def.value)?o:[...o,a._def.value],[])}}}else if(n.every(i=>i._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((i,r)=>[...i,...r._def.values.filter(o=>!i.includes(o))],[])};return t9(e,t)}var t9=(e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((i,r)=>$e(i._def,{...t,currentPath:[...t.currentPath,"anyOf",`${r}`]})).filter(i=>!!i&&(!t.strictUnions||typeof i=="object"&&Object.keys(i).length>0));return n.length?{anyOf:n}:void 0};function n9(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[Sd[e.innerType._def.typeName],"null"]};const n=$e(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function r9(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 i9(e,t){const n={type:"object",properties:{}},i=[],r=e.shape();for(const a in r){let s=r[a];if(s===void 0||s._def===void 0)continue;const u=a9(s),l=$e(s._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});l!==void 0&&(n.properties[a]=l,u||i.push(a))}i.length&&(n.required=i);const o=o9(e,t);return o!==void 0&&(n.additionalProperties=o),n}function o9(e,t){if(e.catchall._def.typeName!=="ZodNever")return $e(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 a9(e){try{return e.isOptional()}catch{return!0}}var s9=(e,t)=>{var n;if(t.currentPath.toString()===((n=t.propertyPath)==null?void 0:n.toString()))return $e(e.innerType._def,t);const i=$e(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return i?{anyOf:[{not:jt()},i]}:jt()},l9=(e,t)=>{if(t.pipeStrategy==="input")return $e(e.in._def,t);if(t.pipeStrategy==="output")return $e(e.out._def,t);const n=$e(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),i=$e(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,i].filter(r=>r!==void 0)}};function u9(e,t){return $e(e.type._def,t)}function c9(e,t){const i={type:"array",uniqueItems:!0,items:$e(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&(i.minItems=e.minSize.value),e.maxSize&&(i.maxItems=e.maxSize.value),i}function d9(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((n,i)=>$e(n._def,{...t,currentPath:[...t.currentPath,"items",`${i}`]})).reduce((n,i)=>i===void 0?n:[...n,i],[]),additionalItems:$e(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((n,i)=>$e(n._def,{...t,currentPath:[...t.currentPath,"items",`${i}`]})).reduce((n,i)=>i===void 0?n:[...n,i],[])}}function p9(){return{not:jt()}}function f9(){return jt()}var h9=(e,t)=>$e(e.innerType._def,t),m9=(e,t,n)=>{switch(t){case H.ZodString:return z$(e,n);case H.ZodNumber:return r9(e);case H.ZodObject:return i9(e,n);case H.ZodBigInt:return zV(e);case H.ZodBoolean:return UV();case H.ZodDate:return D$(e,n);case H.ZodUndefined:return p9();case H.ZodNull:return QV();case H.ZodArray:return DV(e,n);case H.ZodUnion:case H.ZodDiscriminatedUnion:return e9(e,n);case H.ZodIntersection:return HV(e,n);case H.ZodTuple:return d9(e,n);case H.ZodRecord:return U$(e,n);case H.ZodLiteral:return JV(e);case H.ZodEnum:return qV(e);case H.ZodNativeEnum:return YV(e);case H.ZodNullable:return n9(e,n);case H.ZodOptional:return s9(e,n);case H.ZodMap:return KV(e,n);case H.ZodSet:return c9(e,n);case H.ZodLazy:return()=>e.getter()._def;case H.ZodPromise:return u9(e,n);case H.ZodNaN:case H.ZodNever:return XV();case H.ZodEffects:return ZV(e,n);case H.ZodAny:return jt();case H.ZodUnknown:return f9();case H.ZodDefault:return BV(e,n);case H.ZodBranded:return M$(e,n);case H.ZodReadonly:return h9(e,n);case H.ZodCatch:return LV(e,n);case H.ZodPipeline:return l9(e,n);case H.ZodFunction:case H.ZodVoid:case H.ZodSymbol:return;default:return(i=>{})()}};function $e(e,t,n=!1){var i;const r=t.seen.get(e);if(t.override){const u=(i=t.override)==null?void 0:i.call(t,e,t,r,n);if(u!==jV)return u}if(r&&!n){const u=g9(r,t);if(u!==void 0)return u}const o={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,o);const a=m9(e,e.typeName,t),s=typeof a=="function"?$e(a(),t):a;if(s&&v9(e,t,s),t.postProcess){const u=t.postProcess(s,e,t);return o.jsonSchema=s,u}return o.jsonSchema=s,s}var g9=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:NV(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((n,i)=>t.currentPath[i]===n)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),jt()):t.$refStrategy==="seen"?jt():void 0}},v9=(e,t,n)=>(e.description&&(n.description=e.description),n),y9=e=>{const t=MV(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(([i,r])=>[r._def,{def:r._def,path:[...t.basePath,t.definitionPath,i],jsonSchema:void 0}]))}},b9=(e,t)=>{var n;const i=y9(t);let r=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((l,[c,d])=>{var f;return{...l,[c]:(f=$e(d._def,{...i,currentPath:[...i.basePath,i.definitionPath,c]},!0))!=null?f:jt()}},{}):void 0;const o=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,a=(n=$e(e._def,o===void 0?i:{...i,currentPath:[...i.basePath,i.definitionPath,o]},!1))!=null?n:jt(),s=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;s!==void 0&&(a.title=s);const u=o===void 0?r?{...a,[i.definitionPath]:r}:a:{$ref:[...i.$refStrategy==="relative"?[]:i.basePath,i.definitionPath,o].join("/"),[i.definitionPath]:{...r,[o]:a}};return u.$schema="http://json-schema.org/draft-07/schema#",u},_9=b9;function w9(e,t){var n;const i=(n=void 0)!=null?n:!1;return Ah(()=>_9(e,{$refStrategy:i?"root":"none"}),{validate:async r=>{const o=await e.safeParseAsync(r);return o.success?{success:!0,value:o.data}:{success:!1,error:o.error}}})}function x9(e,t){var n;const i=(n=void 0)!=null?n:!1;return Ah(()=>Tl(e,{target:"draft-7",io:"output",reused:i?"ref":"inline"}),{validate:async r=>{const o=await $l(e,r);return o.success?{success:!0,value:o.data}:{success:!1,error:o.error}}})}function S9(e){return"_zod"in e}function Br(e,t){return S9(e)?x9(e):w9(e)}var Id=Symbol.for("vercel.ai.schema");function Ah(e,{validate:t}={}){return{[Id]:!0,_type:void 0,[el]:!0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}function I9(e){return typeof e=="object"&&e!==null&&Id in e&&e[Id]===!0&&"jsonSchema"in e&&"validate"in e}function Su(e){return e==null?Ah({properties:{},additionalProperties:!1}):I9(e)?e:typeof e=="function"?e():Br(e)}var{btoa:k9,atob:E9}=globalThis;function Ph(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=E9(t);return Uint8Array.from(n,i=>i.codePointAt(0))}function kd(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return k9(t)}function T9(e){return e?.replace(/\/$/,"")}function $9(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*C9({execute:e,input:t,options:n}){const i=e(t,n);if($9(i)){let r;for await(const o of i)r=o,yield{type:"preliminary",output:o};yield{type:"final",output:r}}else yield{type:"final",output:await i}}var gc,$v;function A9(){if($v)return gc;$v=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,i=Object.prototype.hasOwnProperty,r=(c,d)=>{for(var f in d)e(c,f,{get:d[f],enumerable:!0})},o=(c,d,f,p)=>{if(d&&typeof d=="object"||typeof d=="function")for(let g of n(d))!i.call(c,g)&&g!==f&&e(c,g,{get:()=>d[g],enumerable:!(p=t(d,g))||p.enumerable});return c},a=c=>o(e({},"__esModule",{value:!0}),c),s={};r(s,{SYMBOL_FOR_REQ_CONTEXT:()=>u,getContext:()=>l}),gc=a(s);const u=Symbol.for("@vercel/request-context");function l(){return globalThis[u]?.get?.()??{}}return gc}var vc,Cv;function P9(){if(Cv)return vc;Cv=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,i=Object.prototype.hasOwnProperty,r=(d,f)=>{for(var p in f)e(d,p,{get:f[p],enumerable:!0})},o=(d,f,p,g)=>{if(f&&typeof f=="object"||typeof f=="function")for(let m of n(f))!i.call(d,m)&&m!==p&&e(d,m,{get:()=>f[m],enumerable:!(g=t(f,m))||g.enumerable});return d},a=d=>o(e({},"__esModule",{value:!0}),d),s={};r(s,{getContext:()=>u.getContext,getVercelOidcToken:()=>l,getVercelOidcTokenSync:()=>c}),vc=a(s);var u=A9();async function l(){return""}function c(){return""}return vc}var L$=P9(),R9="vercel.ai.gateway.error",yc=Symbol.for(R9),Av,Pv,Mt=class F$ extends(Pv=Error,Av=yc,Pv){constructor({message:t,statusCode:n=500,cause:i}){super(t),this[Av]=!0,this.statusCode=n,this.cause=i}static isInstance(t){return F$.hasMarker(t)}static hasMarker(t){return typeof t=="object"&&t!==null&&yc in t&&t[yc]===!0}},B$="GatewayAuthenticationError",O9=`vercel.ai.gateway.error.${B$}`,Rv=Symbol.for(O9),Ov,Nv,Rh=class Z$ extends(Nv=Mt,Ov=Rv,Nv){constructor({message:t="Authentication failed",statusCode:n=401,cause:i}={}){super({message:t,statusCode:n,cause:i}),this[Ov]=!0,this.name=B$,this.type="authentication_error"}static isInstance(t){return Mt.hasMarker(t)&&Rv in t}static createContextualError({apiKeyProvided:t,oidcTokenProvided:n,message:i="Authentication failed",statusCode:r=401,cause:o}){let a;return t?a=`AI Gateway authentication failed: Invalid API key.
|
|
114
|
-
|
|
115
|
-
Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
|
|
116
|
-
|
|
117
|
-
Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`:n?a=`AI Gateway authentication failed: Invalid OIDC token.
|
|
118
|
-
|
|
119
|
-
Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.
|
|
120
|
-
|
|
121
|
-
Alternatively, use an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys`:a=`AI Gateway authentication failed: No authentication provided.
|
|
122
|
-
|
|
123
|
-
Option 1 - API key:
|
|
124
|
-
Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
|
|
125
|
-
Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
|
|
126
|
-
|
|
127
|
-
Option 2 - OIDC token:
|
|
128
|
-
Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new Z$({message:a,statusCode:r,cause:o})}},q$="GatewayInvalidRequestError",N9=`vercel.ai.gateway.error.${q$}`,jv=Symbol.for(N9),Mv,Dv,j9=class extends(Dv=Mt,Mv=jv,Dv){constructor({message:e="Invalid request",statusCode:t=400,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[Mv]=!0,this.name=q$,this.type="invalid_request_error"}static isInstance(e){return Mt.hasMarker(e)&&jv in e}},V$="GatewayRateLimitError",M9=`vercel.ai.gateway.error.${V$}`,zv=Symbol.for(M9),Uv,Lv,D9=class extends(Lv=Mt,Uv=zv,Lv){constructor({message:e="Rate limit exceeded",statusCode:t=429,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[Uv]=!0,this.name=V$,this.type="rate_limit_exceeded"}static isInstance(e){return Mt.hasMarker(e)&&zv in e}},H$="GatewayModelNotFoundError",z9=`vercel.ai.gateway.error.${H$}`,Fv=Symbol.for(z9),U9=Ni(()=>Br(O({modelId:I()}))),Bv,Zv,J$=class extends(Zv=Mt,Bv=Fv,Zv){constructor({message:e="Model not found",statusCode:t=404,modelId:n,cause:i}={}){super({message:e,statusCode:t,cause:i}),this[Bv]=!0,this.name=H$,this.type="model_not_found",this.modelId=n}static isInstance(e){return Mt.hasMarker(e)&&Fv in e}},W$="GatewayInternalServerError",L9=`vercel.ai.gateway.error.${W$}`,qv=Symbol.for(L9),Vv,Hv,Jv=class extends(Hv=Mt,Vv=qv,Hv){constructor({message:e="Internal server error",statusCode:t=500,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[Vv]=!0,this.name=W$,this.type="internal_server_error"}static isInstance(e){return Mt.hasMarker(e)&&qv in e}},G$="GatewayResponseError",F9=`vercel.ai.gateway.error.${G$}`,Wv=Symbol.for(F9),Gv,Kv,B9=class extends(Kv=Mt,Gv=Wv,Kv){constructor({message:e="Invalid response from Gateway",statusCode:t=502,response:n,validationError:i,cause:r}={}){super({message:e,statusCode:t,cause:r}),this[Gv]=!0,this.name=G$,this.type="response_error",this.response=n,this.validationError=i}static isInstance(e){return Mt.hasMarker(e)&&Wv in e}};async function Yv({response:e,statusCode:t,defaultMessage:n="Gateway request failed",cause:i,authMethod:r}){const o=await dr({value:e,schema:Z9});if(!o.success)return new B9({message:`Invalid error response format: ${n}`,statusCode:t,response:e,validationError:o.error,cause:i});const a=o.value,s=a.error.type,u=a.error.message;switch(s){case"authentication_error":return Rh.createContextualError({apiKeyProvided:r==="api-key",oidcTokenProvided:r==="oidc",statusCode:t,cause:i});case"invalid_request_error":return new j9({message:u,statusCode:t,cause:i});case"rate_limit_exceeded":return new D9({message:u,statusCode:t,cause:i});case"model_not_found":{const l=await dr({value:a.error.param,schema:U9});return new J$({message:u,statusCode:t,modelId:l.success?l.value.modelId:void 0,cause:i})}case"internal_server_error":return new Jv({message:u,statusCode:t,cause:i});default:return new Jv({message:u,statusCode:t,cause:i})}}var Z9=Ni(()=>Br(O({error:O({message:I(),type:I().nullish(),param:Le().nullish(),code:se([I(),te()]).nullish()})})));function jr(e,t){var n;return Mt.isInstance(e)?e:mt.isInstance(e)?Yv({response:q9(e),statusCode:(n=e.statusCode)!=null?n:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):Yv({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}function q9(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 K$="ai-gateway-auth-method";async function Do(e){const t=await dr({value:e[K$],schema:V9});return t.success?t.value:void 0}var V9=Ni(()=>Br(se([L("api-key"),L("oidc")]))),Xv=class{constructor(e){this.config=e}async getAvailableModels(){try{const{value:e}=await kv({url:`${this.config.baseURL}/config`,headers:await nr(this.config.headers()),successfulResponseHandler:tl(H9),failedResponseHandler:Mo({errorSchema:Ye(),errorToMessage:t=>t}),fetch:this.config.fetch});return e}catch(e){throw await jr(e)}}async getCredits(){try{const e=new URL(this.config.baseURL),{value:t}=await kv({url:`${e.origin}/v1/credits`,headers:await nr(this.config.headers()),successfulResponseHandler:tl(J9),failedResponseHandler:Mo({errorSchema:Ye(),errorToMessage:n=>n}),fetch:this.config.fetch});return t}catch(e){throw await jr(e)}}},H9=Ni(()=>Br(O({models:W(O({id:I(),name:I(),description:I().nullish(),pricing:O({input:I(),output:I(),input_cache_read:I().nullish(),input_cache_write:I().nullish()}).transform(({input:e,output:t,input_cache_read:n,input_cache_write:i})=>({input:e,output:t,...n?{cachedInputTokens:n}:{},...i?{cacheCreationInputTokens:i}:{}})).nullish(),specification:O({specificationVersion:L("v2"),provider:I(),modelId:I()}),modelType:fr(["language","embedding","image"]).nullish()}))}))),J9=Ni(()=>Br(O({balance:I(),total_used:I()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),W9=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:i}=e,r=await nr(this.config.headers());try{const{responseHeaders:o,value:a,rawValue:s}=await xd({url:this.getUrl(),headers:_d(r,e.headers,this.getModelConfigHeaders(this.modelId,!1),await nr(this.config.o11yHeaders)),body:t,successfulResponseHandler:tl(Ye()),failedResponseHandler:Mo({errorSchema:Ye(),errorToMessage:u=>u}),...i&&{abortSignal:i},fetch:this.config.fetch});return{...a,request:{body:t},response:{headers:o,body:s},warnings:n}}catch(o){throw await jr(o,await Do(r))}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),{abortSignal:i}=e,r=await nr(this.config.headers());try{const{value:o,responseHeaders:a}=await xd({url:this.getUrl(),headers:_d(r,e.headers,this.getModelConfigHeaders(this.modelId,!0),await nr(this.config.o11yHeaders)),body:t,successfulResponseHandler:OV(Ye()),failedResponseHandler:Mo({errorSchema:Ye(),errorToMessage:s=>s}),...i&&{abortSignal:i},fetch:this.config.fetch});return{stream:o.pipeThrough(new TransformStream({start(s){n.length>0&&s.enqueue({type:"stream-start",warnings:n})},transform(s,u){if(s.success){const l=s.value;if(l.type==="raw"&&!e.includeRawChunks)return;l.type==="response-metadata"&&l.timestamp&&typeof l.timestamp=="string"&&(l.timestamp=new Date(l.timestamp)),u.enqueue(l)}else u.error(s.error)}})),request:{body:t},response:{headers:a}}}catch(o){throw await jr(o,await Do(r))}}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 i=n;if(i.data instanceof Uint8Array){const r=Uint8Array.from(i.data),o=Buffer.from(r).toString("base64");i.data=new URL(`data:${i.mediaType||"application/octet-stream"};base64,${o}`)}}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)}}},G9=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:i}){var r;const o=await nr(this.config.headers());try{const{responseHeaders:a,value:s,rawValue:u}=await xd({url:this.getUrl(),headers:_d(o,t??{},this.getModelConfigHeaders(),await nr(this.config.o11yHeaders)),body:{input:e.length===1?e[0]:e,...i?{providerOptions:i}:{}},successfulResponseHandler:tl(K9),failedResponseHandler:Mo({errorSchema:Ye(),errorToMessage:l=>l}),...n&&{abortSignal:n},fetch:this.config.fetch});return{embeddings:s.embeddings,usage:(r=s.usage)!=null?r:void 0,providerMetadata:s.providerMetadata,response:{headers:a,body:u}}}catch(a){throw await jr(a,await Do(o))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"2","ai-model-id":this.modelId}}},K9=Ni(()=>Br(O({embeddings:W(W(te())),usage:O({tokens:te()}).nullish(),providerMetadata:Rt(I(),Rt(I(),Le())).optional()})));async function Y9(){var e;return(e=L$.getContext().headers)==null?void 0:e["x-vercel-id"]}var X9="2.0.7",Q9="0.0.1";function eH(e={}){var t,n;let i=null,r=null;const o=(t=e.metadataCacheRefreshMillis)!=null?t:1e3*60*5;let a=0;const s=(n=T9(e.baseURL))!=null?n:"https://ai-gateway.vercel.sh/v1/ai",u=async()=>{const g=await nH(e);if(g)return xu({Authorization:`Bearer ${g.token}`,"ai-gateway-protocol-version":Q9,[K$]:g.authMethod,...e.headers},`ai-sdk/gateway/${X9}`);throw Rh.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401})},l=()=>{const g=gs({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),m=gs({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),y=gs({settingValue:void 0,environmentVariableName:"VERCEL_REGION"});return async()=>{const v=await Y9();return{...g&&{"ai-o11y-deployment-id":g},...m&&{"ai-o11y-environment":m},...y&&{"ai-o11y-region":y},...v&&{"ai-o11y-request-id":v}}}},c=g=>new W9(g,{provider:"gateway",baseURL:s,headers:u,fetch:e.fetch,o11yHeaders:l()}),d=async()=>{var g,m,y;const v=(y=(m=(g=e._internal)==null?void 0:g.currentDate)==null?void 0:m.call(g).getTime())!=null?y:Date.now();return(!i||v-a>o)&&(a=v,i=new Xv({baseURL:s,headers:u,fetch:e.fetch}).getAvailableModels().then(_=>(r=_,_)).catch(async _=>{throw await jr(_,await Do(await u()))})),r?Promise.resolve(r):i},f=async()=>new Xv({baseURL:s,headers:u,fetch:e.fetch}).getCredits().catch(async g=>{throw await jr(g,await Do(await u()))}),p=function(g){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return c(g)};return p.getAvailableModels=d,p.getCredits=f,p.imageModel=g=>{throw new LP({modelId:g,modelType:"imageModel"})},p.languageModel=c,p.textEmbeddingModel=g=>new G9(g,{provider:"gateway",baseURL:s,headers:u,fetch:e.fetch,o11yHeaders:l()}),p}var tH=eH();async function nH(e){const t=gs({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});if(t)return{token:t,authMethod:"api-key"};try{return{token:await L$.getVercelOidcToken(),authMethod:"oidc"}}catch{return null}}var rH=Object.defineProperty,iH=(e,t)=>{for(var n in t)rH(e,n,{get:t[n],enumerable:!0})},Y$="AI_NoOutputSpecifiedError",X$=`vercel.ai.error.${Y$}`,oH=Symbol.for(X$),Q$,aH=class extends ce{constructor({message:e="No output specified."}={}){super({name:Y$,message:e}),this[Q$]=!0}static isInstance(e){return ce.hasMarker(e,X$)}};Q$=oH;function sH(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 i=`${t} The tool "${n}" is not supported by this model`;return e.details&&(i+=` - ${e.details}`),i}case"other":return`${t} ${e.message}`;default:return`${t} ${JSON.stringify(e,null,2)}`}}var lH="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",Qv=!1,uH=e=>{if(e.length===0)return;const t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t=="function"){t(e);return}Qv||(Qv=!0,console.info(lH));for(const n of e)console.warn(sH(n))}},eC="AI_InvalidArgumentError",tC=`vercel.ai.error.${eC}`,cH=Symbol.for(tC),nC,yn=class extends ce{constructor({parameter:e,value:t,message:n}){super({name:eC,message:`Invalid argument for parameter ${e}: ${n}`}),this[nC]=!0,this.parameter=e,this.value=t}static isInstance(e){return ce.hasMarker(e,tC)}};nC=cH;var rC="AI_InvalidToolInputError",iC=`vercel.ai.error.${rC}`,dH=Symbol.for(iC),oC,aC=class extends ce{constructor({toolInput:e,toolName:t,cause:n,message:i=`Invalid input for tool ${t}: ${Ti(n)}`}){super({name:rC,message:i,cause:n}),this[oC]=!0,this.toolInput=e,this.toolName=t}static isInstance(e){return ce.hasMarker(e,iC)}};oC=dH;var sC="AI_NoObjectGeneratedError",lC=`vercel.ai.error.${sC}`,pH=Symbol.for(lC),uC,ey=class extends ce{constructor({message:e="No object generated.",cause:t,text:n,response:i,usage:r,finishReason:o}){super({name:sC,message:e,cause:t}),this[uC]=!0,this.text=n,this.response=i,this.usage=r,this.finishReason=o}static isInstance(e){return ce.hasMarker(e,lC)}};uC=pH;var cC="AI_NoOutputGeneratedError",dC=`vercel.ai.error.${cC}`,fH=Symbol.for(dC),pC,hH=class extends ce{constructor({message:e="No output generated.",cause:t}={}){super({name:cC,message:e,cause:t}),this[pC]=!0}static isInstance(e){return ce.hasMarker(e,dC)}};pC=fH;var fC="AI_NoSuchToolError",hC=`vercel.ai.error.${fC}`,mH=Symbol.for(hC),mC,Ed=class extends ce{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:fC,message:n}),this[mC]=!0,this.toolName=e,this.availableTools=t}static isInstance(e){return ce.hasMarker(e,hC)}};mC=mH;var gC="AI_ToolCallRepairError",vC=`vercel.ai.error.${gC}`,gH=Symbol.for(vC),yC,vH=class extends ce{constructor({cause:e,originalError:t,message:n=`Error repairing tool call: ${Ti(e)}`}){super({name:gC,message:n,cause:e}),this[yC]=!0,this.originalError=t}static isInstance(e){return ce.hasMarker(e,vC)}};yC=gH;var yH=class extends ce{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}},bC="AI_InvalidMessageRoleError",_C=`vercel.ai.error.${bC}`,bH=Symbol.for(_C),wC,_H=class extends ce{constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:bC,message:t}),this[wC]=!0,this.role=e}static isInstance(e){return ce.hasMarker(e,_C)}};wC=bH;var xC="AI_MessageConversionError",SC=`vercel.ai.error.${xC}`,wH=Symbol.for(SC),IC,xH=class extends ce{constructor({originalMessage:e,message:t}){super({name:xC,message:t}),this[IC]=!0,this.originalMessage=e}static isInstance(e){return ce.hasMarker(e,SC)}};IC=wH;var kC="AI_DownloadError",EC=`vercel.ai.error.${kC}`,SH=Symbol.for(EC),TC,bc=class extends ce{constructor({url:e,statusCode:t,statusText:n,cause:i,message:r=i==null?`Failed to download ${e}: ${t} ${n}`:`Failed to download ${e}: ${i}`}){super({name:kC,message:r,cause:i}),this[TC]=!0,this.url=e,this.statusCode=t,this.statusText=n}static isInstance(e){return ce.hasMarker(e,EC)}};TC=SH;var $C="AI_RetryError",CC=`vercel.ai.error.${$C}`,IH=Symbol.for(CC),AC,ty=class extends ce{constructor({message:e,reason:t,errors:n}){super({name:$C,message:e}),this[AC]=!0,this.reason=t,this.errors=n,this.lastError=n[n.length-1]}static isInstance(e){return ce.hasMarker(e,CC)}};AC=IH;function PC(e){if(typeof e!="string"){if(e.specificationVersion!=="v2")throw new yH({version:e.specificationVersion,provider:e.provider,modelId:e.modelId});return e}return kH().languageModel(e)}function kH(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:tH}var EH=[{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]}],TH=e=>{const t=typeof e=="string"?Ph(e):e,n=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(n+10)};function $H(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?TH(e):e}function CH({data:e,signatures:t}){const n=$H(e),i=typeof n=="string"?Ph(n.substring(0,Math.min(n.length,24))):n;for(const r of t)if(i.length>=r.bytesPrefix.length&&r.bytesPrefix.every((o,a)=>o===null||i[a]===o))return r.mediaType}var AH="5.0.90",PH=async({url:e})=>{var t;const n=e.toString();try{const i=await fetch(n,{headers:xu({},`ai-sdk/${AH}`,Ch())});if(!i.ok)throw new bc({url:n,statusCode:i.status,statusText:i.statusText});return{data:new Uint8Array(await i.arrayBuffer()),mediaType:(t=i.headers.get("content-type"))!=null?t:void 0}}catch(i){throw bc.isInstance(i)?i:new bc({url:n,cause:i})}},RH=(e=PH)=>t=>Promise.all(t.map(async n=>n.isUrlSupportedByModel?null:e(n)));function OH(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 RC=se([I(),En(Uint8Array),En(ArrayBuffer),da(e=>{var t,n;return(n=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?n:!1},{message:"Must be a Buffer"})]);function OC(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}=OH(e.toString());if(t==null||n==null)throw new ce({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:n,mediaType:t}}return{data:e,mediaType:void 0}}function NH(e){return typeof e=="string"?e:e instanceof ArrayBuffer?kd(new Uint8Array(e)):kd(e)}async function jH({prompt:e,supportedUrls:t,download:n=RH()}){const i=await DH(e.messages,n,t);return[...e.system!=null?[{role:"system",content:e.system}]:[],...e.messages.map(r=>MH({message:r,downloadedAssets:i}))]}function MH({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(i=>zH(i,t)).filter(i=>i.type!=="text"||i.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(i=>i.type!=="text"||i.text!==""||i.providerOptions!=null).map(i=>{const r=i.providerOptions;switch(i.type){case"file":{const{data:o,mediaType:a}=OC(i.data);return{type:"file",data:o,filename:i.filename,mediaType:a??i.mediaType,providerOptions:r}}case"reasoning":return{type:"reasoning",text:i.text,providerOptions:r};case"text":return{type:"text",text:i.text,providerOptions:r};case"tool-call":return{type:"tool-call",toolCallId:i.toolCallId,toolName:i.toolName,input:i.input,providerExecuted:i.providerExecuted,providerOptions:r};case"tool-result":return{type:"tool-result",toolCallId:i.toolCallId,toolName:i.toolName,output:i.output,providerOptions:r}}}),providerOptions:e.providerOptions};case"tool":return{role:"tool",content:e.content.map(i=>({type:"tool-result",toolCallId:i.toolCallId,toolName:i.toolName,output:i.output,providerOptions:i.providerOptions})),providerOptions:e.providerOptions};default:{const i=n;throw new _H({role:i})}}}async function DH(e,t,n){const i=e.filter(o=>o.role==="user").map(o=>o.content).filter(o=>Array.isArray(o)).flat().filter(o=>o.type==="image"||o.type==="file").map(o=>{var a;const s=(a=o.mediaType)!=null?a:o.type==="image"?"image/*":void 0;let u=o.type==="image"?o.image:o.data;if(typeof u=="string")try{u=new URL(u)}catch{}return{mediaType:s,data:u}}).filter(o=>o.data instanceof URL).map(o=>({url:o.data,isUrlSupportedByModel:o.mediaType!=null&&_V({url:o.data.toString(),mediaType:o.mediaType,supportedUrls:n})})),r=await t(i);return Object.fromEntries(r.map((o,a)=>o==null?null:[i[a].url.toString(),{data:o.data,mediaType:o.mediaType}]).filter(o=>o!=null))}function zH(e,t){var n;if(e.type==="text")return{type:"text",text:e.text,providerOptions:e.providerOptions};let i;const r=e.type;switch(r){case"image":i=e.image;break;case"file":i=e.data;break;default:throw new Error(`Unsupported part type: ${r}`)}const{data:o,mediaType:a}=OC(i);let s=a??e.mediaType,u=o;if(u instanceof URL){const l=t[u.toString()];l&&(u=l.data,s??(s=l.mediaType))}switch(r){case"image":return(u instanceof Uint8Array||typeof u=="string")&&(s=(n=CH({data:u,signatures:EH}))!=null?n:s),{type:"file",mediaType:s??"image/*",filename:void 0,data:u,providerOptions:e.providerOptions};case"file":{if(s==null)throw new Error("Media type is missing for file part");return{type:"file",mediaType:s,filename:e.filename,data:u,providerOptions:e.providerOptions}}}}function UH({maxOutputTokens:e,temperature:t,topP:n,topK:i,presencePenalty:r,frequencyPenalty:o,seed:a,stopSequences:s}){if(e!=null){if(!Number.isInteger(e))throw new yn({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new yn({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(t!=null&&typeof t!="number")throw new yn({parameter:"temperature",value:t,message:"temperature must be a number"});if(n!=null&&typeof n!="number")throw new yn({parameter:"topP",value:n,message:"topP must be a number"});if(i!=null&&typeof i!="number")throw new yn({parameter:"topK",value:i,message:"topK must be a number"});if(r!=null&&typeof r!="number")throw new yn({parameter:"presencePenalty",value:r,message:"presencePenalty must be a number"});if(o!=null&&typeof o!="number")throw new yn({parameter:"frequencyPenalty",value:o,message:"frequencyPenalty must be a number"});if(a!=null&&!Number.isInteger(a))throw new yn({parameter:"seed",value:a,message:"seed must be an integer"});return{maxOutputTokens:e,temperature:t,topP:n,topK:i,presencePenalty:r,frequencyPenalty:o,stopSequences:s,seed:a}}function LH(e){return e!=null&&Object.keys(e).length>0}function FH({tools:e,toolChoice:t,activeTools:n}){return LH(e)?{tools:(n!=null?Object.entries(e).filter(([r])=>n.includes(r)):Object.entries(e)).map(([r,o])=>{const a=o.type;switch(a){case void 0:case"dynamic":case"function":return{type:"function",name:r,description:o.description,inputSchema:Su(o.inputSchema).jsonSchema,providerOptions:o.providerOptions};case"provider-defined":return{type:"provider-defined",name:r,id:o.id,args:o.args};default:{const s=a;throw new Error(`Unsupported tool type: ${s}`)}}}),toolChoice:t==null?{type:"auto"}:typeof t=="string"?{type:t}:{type:"tool",toolName:t.toolName}}:{tools:void 0,toolChoice:void 0}}var zo=ua(()=>se([oa(),I(),te(),Ce(),Rt(I(),zo),W(zo)])),Rn=Rt(I(),Rt(I(),zo)),NC=O({type:L("text"),text:I(),providerOptions:Rn.optional()}),BH=O({type:L("image"),image:se([RC,En(URL)]),mediaType:I().optional(),providerOptions:Rn.optional()}),jC=O({type:L("file"),data:se([RC,En(URL)]),filename:I().optional(),mediaType:I(),providerOptions:Rn.optional()}),ZH=O({type:L("reasoning"),text:I(),providerOptions:Rn.optional()}),qH=O({type:L("tool-call"),toolCallId:I(),toolName:I(),input:Le(),providerOptions:Rn.optional(),providerExecuted:Ce().optional()}),VH=Kl("type",[O({type:L("text"),value:I()}),O({type:L("json"),value:zo}),O({type:L("error-text"),value:I()}),O({type:L("error-json"),value:zo}),O({type:L("content"),value:W(se([O({type:L("text"),text:I()}),O({type:L("media"),data:I(),mediaType:I()})]))})]),MC=O({type:L("tool-result"),toolCallId:I(),toolName:I(),output:VH,providerOptions:Rn.optional()}),HH=O({role:L("system"),content:I(),providerOptions:Rn.optional()}),JH=O({role:L("user"),content:se([I(),W(se([NC,BH,jC]))]),providerOptions:Rn.optional()}),WH=O({role:L("assistant"),content:se([I(),W(se([NC,jC,ZH,qH,MC]))]),providerOptions:Rn.optional()}),GH=O({role:L("tool"),content:W(MC),providerOptions:Rn.optional()}),KH=se([HH,JH,WH,GH]);async function YH(e){if(e.prompt==null&&e.messages==null)throw new Hr({prompt:e,message:"prompt or messages must be defined"});if(e.prompt!=null&&e.messages!=null)throw new Hr({prompt:e,message:"prompt and messages cannot be defined at the same time"});if(e.system!=null&&typeof e.system!="string")throw new Hr({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 Hr({prompt:e,message:"prompt or messages must be defined"});if(t.length===0)throw new Hr({prompt:e,message:"messages must not be empty"});const n=await dr({value:t,schema:W(KH)});if(!n.success)throw new Hr({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 XH(e){return Rh.isInstance(e)||J$.isInstance(e)?new ce({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 Td({operationId:e,telemetry:t}){return{"operation.name":`${e}${t?.functionId!=null?` ${t.functionId}`:""}`,"resource.name":t?.functionId,"ai.operationId":e,"ai.telemetry.functionId":t?.functionId}}function QH({model:e,settings:t,telemetry:n,headers:i}){var r;return{"ai.model.provider":e.provider,"ai.model.id":e.modelId,...Object.entries(t).reduce((o,[a,s])=>(o[`ai.settings.${a}`]=s,o),{}),...Object.entries((r=n?.metadata)!=null?r:{}).reduce((o,[a,s])=>(o[`ai.telemetry.metadata.${a}`]=s,o),{}),...Object.entries(i??{}).reduce((o,[a,s])=>(s!==void 0&&(o[`ai.request.headers.${a}`]=s),o),{})}}var e3={startSpan(){return Xa},startActiveSpan(e,t,n,i){if(typeof t=="function")return t(Xa);if(typeof n=="function")return n(Xa);if(typeof i=="function")return i(Xa)}},Xa={spanContext(){return t3},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}},t3={traceId:"",spanId:"",traceFlags:0};function n3({isEnabled:e=!1,tracer:t}={}){return e?t||aZ.getTracer("ai"):e3}function $d({name:e,tracer:t,attributes:n,fn:i,endWhenDone:r=!0}){return t.startActiveSpan(e,{attributes:n},async o=>{try{const a=await i(o);return r&&o.end(),a}catch(a){try{DC(o,a)}finally{o.end()}throw a}})}function DC(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:Ks.ERROR,message:t.message})):e.setStatus({code:Ks.ERROR})}function ni({telemetry:e,attributes:t}){return e?.isEnabled!==!0?{}:Object.entries(t).reduce((n,[i,r])=>{if(r==null)return n;if(typeof r=="object"&&"input"in r&&typeof r.input=="function"){if(e?.recordInputs===!1)return n;const o=r.input();return o==null?n:{...n,[i]:o}}if(typeof r=="object"&&"output"in r&&typeof r.output=="function"){if(e?.recordOutputs===!1)return n;const o=r.output();return o==null?n:{...n,[i]:o}}return{...n,[i]:r}},{})}function r3(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?NH(n.data):n.data}:n)})))}function i3(e,t){return{inputTokens:Bi(e.inputTokens,t.inputTokens),outputTokens:Bi(e.outputTokens,t.outputTokens),totalTokens:Bi(e.totalTokens,t.totalTokens),reasoningTokens:Bi(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:Bi(e.cachedInputTokens,t.cachedInputTokens)}}function Bi(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}function ny(e){return e===void 0?[]:Array.isArray(e)?e:[e]}function o3({error:e,exponentialBackoffDelay:t}){const n=e.responseHeaders;if(!n)return t;let i;const r=n["retry-after-ms"];if(r){const a=parseFloat(r);Number.isNaN(a)||(i=a)}const o=n["retry-after"];if(o&&i===void 0){const a=parseFloat(o);Number.isNaN(a)?i=Date.parse(o)-Date.now():i=a*1e3}return i!=null&&!Number.isNaN(i)&&0<=i&&(i<60*1e3||i<t)?i:t}var a3=({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:n=2,abortSignal:i}={})=>async r=>zC(r,{maxRetries:e,delayInMs:t,backoffFactor:n,abortSignal:i});async function zC(e,{maxRetries:t,delayInMs:n,backoffFactor:i,abortSignal:r},o=[]){try{return await e()}catch(a){if(Or(a)||t===0)throw a;const s=R$(a),u=[...o,a],l=u.length;if(l>t)throw new ty({message:`Failed after ${l} attempts. Last error: ${s}`,reason:"maxRetriesExceeded",errors:u});if(a instanceof Error&&mt.isInstance(a)&&a.isRetryable===!0&&l<=t)return await P$(o3({error:a,exponentialBackoffDelay:n}),{abortSignal:r}),zC(e,{maxRetries:t,delayInMs:i*n,backoffFactor:i,abortSignal:r},u);throw l===1?a:new ty({message:`Failed after ${l} attempts with non-retryable error: '${s}'`,reason:"errorNotRetryable",errors:u})}}function s3({maxRetries:e,abortSignal:t}){if(e!=null){if(!Number.isInteger(e))throw new yn({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});if(e<0)throw new yn({parameter:"maxRetries",value:e,message:"maxRetries must be >= 0"})}const n=e??2;return{maxRetries:n,retry:a3({maxRetries:n,abortSignal:t})}}var l3=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=kd(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=Ph(this.base64Data)),this.uint8ArrayData}},u3=class extends l3{constructor(e){super(e),this.type="file"}};async function c3({toolCall:e,tools:t,repairToolCall:n,system:i,messages:r}){try{if(t==null)throw new Ed({toolName:e.toolName});try{return await ry({toolCall:e,tools:t})}catch(o){if(n==null||!(Ed.isInstance(o)||aC.isInstance(o)))throw o;let a=null;try{a=await n({toolCall:e,tools:t,inputSchema:({toolName:s})=>{const{inputSchema:u}=t[s];return Su(u).jsonSchema},system:i,messages:r,error:o})}catch(s){throw new vH({cause:s,originalError:o})}if(a==null)throw o;return await ry({toolCall:a,tools:t})}}catch(o){const a=await Nr({text:e.input}),s=a.success?a.value:e.input;return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:s,dynamic:!0,invalid:!0,error:o}}}async function ry({toolCall:e,tools:t}){const n=e.toolName,i=t[n];if(i==null)throw new Ed({toolName:e.toolName,availableTools:Object.keys(t)});const r=Su(i.inputSchema),o=e.input.trim()===""?await dr({value:{},schema:r}):await Nr({text:e.input,schema:r});if(o.success===!1)throw new aC({toolName:n,toolInput:e.input,cause:o.error});return i.type==="dynamic"?{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:o.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,dynamic:!0}:{type:"tool-call",toolCallId:e.toolCallId,toolName:n,input:o.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}}var d3=class{constructor({content:e,finishReason:t,usage:n,warnings:i,request:r,response:o,providerMetadata:a}){this.content=e,this.finishReason=t,this.usage=n,this.warnings=i,this.request=r,this.response=o,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 UC(e){return({steps:t})=>t.length===e}async function p3({stopConditions:e,steps:t}){return(await Promise.all(e.map(n=>n({steps:t})))).some(n=>n)}function oo({output:e,tool:t,errorMode:n}){return n==="text"?{type:"error-text",value:Ti(e)}:n==="json"?{type:"error-json",value:iy(e)}:t?.toModelOutput?t.toModelOutput(e):typeof e=="string"?{type:"text",value:e}:{type:"json",value:iy(e)}}function iy(e){return e===void 0?null:e}function oy({content:e,tools:t}){const n=[],i=e.filter(o=>o.type!=="source").filter(o=>(o.type!=="tool-result"||o.providerExecuted)&&(o.type!=="tool-error"||o.providerExecuted)).filter(o=>o.type!=="text"||o.text.length>0).map(o=>{switch(o.type){case"text":return{type:"text",text:o.text,providerOptions:o.providerMetadata};case"reasoning":return{type:"reasoning",text:o.text,providerOptions:o.providerMetadata};case"file":return{type:"file",data:o.file.base64,mediaType:o.file.mediaType,providerOptions:o.providerMetadata};case"tool-call":return{type:"tool-call",toolCallId:o.toolCallId,toolName:o.toolName,input:o.input,providerExecuted:o.providerExecuted,providerOptions:o.providerMetadata};case"tool-result":return{type:"tool-result",toolCallId:o.toolCallId,toolName:o.toolName,output:oo({tool:t?.[o.toolName],output:o.output,errorMode:"none"}),providerExecuted:!0,providerOptions:o.providerMetadata};case"tool-error":return{type:"tool-result",toolCallId:o.toolCallId,toolName:o.toolName,output:oo({tool:t?.[o.toolName],output:o.error,errorMode:"json"}),providerOptions:o.providerMetadata}}});i.length>0&&n.push({role:"assistant",content:i});const r=e.filter(o=>o.type==="tool-result"||o.type==="tool-error").filter(o=>!o.providerExecuted).map(o=>({type:"tool-result",toolCallId:o.toolCallId,toolName:o.toolName,output:oo({tool:t?.[o.toolName],output:o.type==="tool-result"?o.output:o.error,errorMode:o.type==="tool-error"?"text":"none"})}));return r.length>0&&n.push({role:"tool",content:r}),n}ka({prefix:"aitxt",size:24});function Iu(e,t){const n=new Headers(e??{});for(const[i,r]of Object.entries(t))n.has(i)||n.set(i,r);return n}function f3({status:e,statusText:t,headers:n,textStream:i}){return new Response(i.pipeThrough(new TextEncoderStream),{status:e??200,statusText:t,headers:Iu(n,{"content-type":"text/plain; charset=utf-8"})})}function LC({response:e,status:t,statusText:n,headers:i,stream:r}){e.writeHead(t??200,n,i);const o=r.getReader();(async()=>{try{for(;;){const{done:s,value:u}=await o.read();if(s)break;e.write(u)||await new Promise(c=>{e.once("drain",c)})}}catch(s){throw s}finally{e.end()}})()}function h3({response:e,status:t,statusText:n,headers:i,textStream:r}){LC({response:e,status:t,statusText:n,headers:Object.fromEntries(Iu(i,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:r.pipeThrough(new TextEncoderStream)})}var FC=class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
|
|
129
|
-
|
|
130
|
-
`)},flush(e){e.enqueue(`data: [DONE]
|
|
131
|
-
|
|
132
|
-
`)}})}},BC={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function m3({status:e,statusText:t,headers:n,stream:i,consumeSseStream:r}){let o=i.pipeThrough(new FC);if(r){const[a,s]=o.tee();o=a,r({stream:s})}return new Response(o.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:Iu(n,BC)})}function g3({originalMessages:e,responseMessageId:t}){if(e==null)return;const n=e[e.length-1];return n?.role==="assistant"?n.id:typeof t=="function"?t():t}function v3(e){return e.type.startsWith("data-")}function ZC(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 i in t)if(Object.prototype.hasOwnProperty.call(t,i)){const r=t[i];if(r===void 0)continue;const o=i in e?e[i]:void 0,a=r!==null&&typeof r=="object"&&!Array.isArray(r)&&!(r instanceof Date)&&!(r instanceof RegExp),s=o!=null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp);a&&s?n[i]=ZC(o,r):n[i]=r}return n}function y3(e){const t=["ROOT"];let n=-1,i=null;function r(u,l,c){switch(u){case'"':{n=l,t.pop(),t.push(c),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{n=l,i=l,t.pop(),t.push(c),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(c),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=l,t.pop(),t.push(c),t.push("INSIDE_NUMBER");break}case"{":{n=l,t.pop(),t.push(c),t.push("INSIDE_OBJECT_START");break}case"[":{n=l,t.pop(),t.push(c),t.push("INSIDE_ARRAY_START");break}}}function o(u,l){switch(u){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=l,t.pop();break}}}function a(u,l){switch(u){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=l,t.pop();break}}}for(let u=0;u<e.length;u++){const l=e[u];switch(t[t.length-1]){case"ROOT":r(l,u,"FINISH");break;case"INSIDE_OBJECT_START":{switch(l){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=u,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(l){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(l){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(l){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{r(l,u,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{o(l,u);break}case"INSIDE_STRING":{switch(l){case'"':{t.pop(),n=u;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=u}break}case"INSIDE_ARRAY_START":{switch(l){case"]":{n=u,t.pop();break}default:{n=u,r(l,u,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=u,t.pop();break}default:{n=u;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{r(l,u,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=u;break}case"INSIDE_NUMBER":{switch(l){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=u;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(l,u),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(l,u);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(l,u);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(l,u);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const d=e.substring(i,u+1);!"false".startsWith(d)&&!"true".startsWith(d)&&!"null".startsWith(d)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?o(l,u):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(l,u)):n=u;break}}}let s=e.slice(0,n+1);for(let u=t.length-1;u>=0;u--)switch(t[u]){case"INSIDE_STRING":{s+='"';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":{s+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{s+="]";break}case"INSIDE_LITERAL":{const c=e.substring(i,e.length);"true".startsWith(c)?s+="true".slice(c.length):"false".startsWith(c)?s+="false".slice(c.length):"null".startsWith(c)&&(s+="null".slice(c.length))}}return s}async function qC(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await Nr({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await Nr({text:y3(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function _c(e){return e.type.startsWith("data-")}function wc(e){return e.type==="text"}function xc(e){return e.type==="file"}function ay(e){return e.type==="reasoning"}function si(e){return e.type.startsWith("tool-")}function Oh(e){return e.type==="dynamic-tool"}function sy(e){return si(e)||Oh(e)}function nl(e){return e.type.split("-").slice(1).join("-")}function b3(e){return Oh(e)?e.toolName:nl(e)}function _3({lastMessage:e,messageId:t}){return{message:e?.role==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function w3({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:i,onError:r,onToolCall:o,onData:a}){return e.pipeThrough(new TransformStream({async transform(s,u){await i(async({state:l,write:c})=>{var d,f,p,g;function m(b){const E=l.message.parts.filter(si).find($=>$.toolCallId===b);if(E==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return E}function y(b){const E=l.message.parts.filter($=>$.type==="dynamic-tool").find($=>$.toolCallId===b);if(E==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return E}function v(b){var C;const E=l.message.parts.find(j=>si(j)&&j.toolCallId===b.toolCallId),$=b,A=E;E!=null?(E.state=b.state,A.input=$.input,A.output=$.output,A.errorText=$.errorText,A.rawInput=$.rawInput,A.preliminary=$.preliminary,A.providerExecuted=(C=$.providerExecuted)!=null?C:E.providerExecuted,$.providerMetadata!=null&&E.state==="input-available"&&(E.callProviderMetadata=$.providerMetadata)):l.message.parts.push({type:`tool-${b.toolName}`,toolCallId:b.toolCallId,state:b.state,input:$.input,output:$.output,rawInput:$.rawInput,errorText:$.errorText,providerExecuted:$.providerExecuted,preliminary:$.preliminary,...$.providerMetadata!=null?{callProviderMetadata:$.providerMetadata}:{}})}function _(b){var C,E;const $=l.message.parts.find(F=>F.type==="dynamic-tool"&&F.toolCallId===b.toolCallId),A=b,j=$;$!=null?($.state=b.state,j.toolName=b.toolName,j.input=A.input,j.output=A.output,j.errorText=A.errorText,j.rawInput=(C=A.rawInput)!=null?C:j.rawInput,j.preliminary=A.preliminary,j.providerExecuted=(E=A.providerExecuted)!=null?E:$.providerExecuted,A.providerMetadata!=null&&$.state==="input-available"&&($.callProviderMetadata=A.providerMetadata)):l.message.parts.push({type:"dynamic-tool",toolName:b.toolName,toolCallId:b.toolCallId,state:b.state,input:A.input,output:A.output,errorText:A.errorText,preliminary:A.preliminary,providerExecuted:A.providerExecuted,...A.providerMetadata!=null?{callProviderMetadata:A.providerMetadata}:{}})}async function x(b){if(b!=null){const C=l.message.metadata!=null?ZC(l.message.metadata,b):b;t!=null&&await wd({value:C,schema:t}),l.message.metadata=C}}switch(s.type){case"text-start":{const b={type:"text",text:"",providerMetadata:s.providerMetadata,state:"streaming"};l.activeTextParts[s.id]=b,l.message.parts.push(b),c();break}case"text-delta":{const b=l.activeTextParts[s.id];b.text+=s.delta,b.providerMetadata=(d=s.providerMetadata)!=null?d:b.providerMetadata,c();break}case"text-end":{const b=l.activeTextParts[s.id];b.state="done",b.providerMetadata=(f=s.providerMetadata)!=null?f:b.providerMetadata,delete l.activeTextParts[s.id],c();break}case"reasoning-start":{const b={type:"reasoning",text:"",providerMetadata:s.providerMetadata,state:"streaming"};l.activeReasoningParts[s.id]=b,l.message.parts.push(b),c();break}case"reasoning-delta":{const b=l.activeReasoningParts[s.id];b.text+=s.delta,b.providerMetadata=(p=s.providerMetadata)!=null?p:b.providerMetadata,c();break}case"reasoning-end":{const b=l.activeReasoningParts[s.id];b.providerMetadata=(g=s.providerMetadata)!=null?g:b.providerMetadata,b.state="done",delete l.activeReasoningParts[s.id],c();break}case"file":{l.message.parts.push({type:"file",mediaType:s.mediaType,url:s.url}),c();break}case"source-url":{l.message.parts.push({type:"source-url",sourceId:s.sourceId,url:s.url,title:s.title,providerMetadata:s.providerMetadata}),c();break}case"source-document":{l.message.parts.push({type:"source-document",sourceId:s.sourceId,mediaType:s.mediaType,title:s.title,filename:s.filename,providerMetadata:s.providerMetadata}),c();break}case"tool-input-start":{const b=l.message.parts.filter(si);l.partialToolCalls[s.toolCallId]={text:"",toolName:s.toolName,index:b.length,dynamic:s.dynamic},s.dynamic?_({toolCallId:s.toolCallId,toolName:s.toolName,state:"input-streaming",input:void 0,providerExecuted:s.providerExecuted}):v({toolCallId:s.toolCallId,toolName:s.toolName,state:"input-streaming",input:void 0,providerExecuted:s.providerExecuted}),c();break}case"tool-input-delta":{const b=l.partialToolCalls[s.toolCallId];b.text+=s.inputTextDelta;const{value:C}=await qC(b.text);b.dynamic?_({toolCallId:s.toolCallId,toolName:b.toolName,state:"input-streaming",input:C}):v({toolCallId:s.toolCallId,toolName:b.toolName,state:"input-streaming",input:C}),c();break}case"tool-input-available":{s.dynamic?_({toolCallId:s.toolCallId,toolName:s.toolName,state:"input-available",input:s.input,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata}):v({toolCallId:s.toolCallId,toolName:s.toolName,state:"input-available",input:s.input,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata}),c(),o&&!s.providerExecuted&&await o({toolCall:s});break}case"tool-input-error":{s.dynamic?_({toolCallId:s.toolCallId,toolName:s.toolName,state:"output-error",input:s.input,errorText:s.errorText,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata}):v({toolCallId:s.toolCallId,toolName:s.toolName,state:"output-error",input:void 0,rawInput:s.input,errorText:s.errorText,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata}),c();break}case"tool-output-available":{if(s.dynamic){const b=y(s.toolCallId);_({toolCallId:s.toolCallId,toolName:b.toolName,state:"output-available",input:b.input,output:s.output,preliminary:s.preliminary})}else{const b=m(s.toolCallId);v({toolCallId:s.toolCallId,toolName:nl(b),state:"output-available",input:b.input,output:s.output,providerExecuted:s.providerExecuted,preliminary:s.preliminary})}c();break}case"tool-output-error":{if(s.dynamic){const b=y(s.toolCallId);_({toolCallId:s.toolCallId,toolName:b.toolName,state:"output-error",input:b.input,errorText:s.errorText,providerExecuted:s.providerExecuted})}else{const b=m(s.toolCallId);v({toolCallId:s.toolCallId,toolName:nl(b),state:"output-error",input:b.input,rawInput:b.rawInput,errorText:s.errorText,providerExecuted:s.providerExecuted})}c();break}case"start-step":{l.message.parts.push({type:"step-start"});break}case"finish-step":{l.activeTextParts={},l.activeReasoningParts={};break}case"start":{s.messageId!=null&&(l.message.id=s.messageId),await x(s.messageMetadata),(s.messageId!=null||s.messageMetadata!=null)&&c();break}case"finish":{await x(s.messageMetadata),s.messageMetadata!=null&&c();break}case"message-metadata":{await x(s.messageMetadata),s.messageMetadata!=null&&c();break}case"error":{r?.(new Error(s.errorText));break}default:if(v3(s)){n?.[s.type]!=null&&await wd({value:s.data,schema:n[s.type]});const b=s;if(b.transient){a?.(b);break}const C=b.id!=null?l.message.parts.find(E=>b.type===E.type&&b.id===E.id):void 0;C!=null?C.data=b.data:l.message.parts.push(b),a?.(b),c()}}u.enqueue(s)})}}))}function x3({messageId:e,originalMessages:t=[],onFinish:n,onError:i,stream:r}){let o=t?.[t.length-1];o?.role!=="assistant"?o=void 0:e=o.id;let a=!1;const s=r.pipeThrough(new TransformStream({transform(f,p){if(f.type==="start"){const g=f;g.messageId==null&&e!=null&&(g.messageId=e)}f.type==="abort"&&(a=!0),p.enqueue(f)}}));if(n==null)return s;const u=_3({lastMessage:o?structuredClone(o):void 0,messageId:e??""}),l=async f=>{await f({state:u,write:()=>{}})};let c=!1;const d=async()=>{if(c||!n)return;c=!0;const f=u.message.id===o?.id;await n({isAborted:a,isContinuation:f,responseMessage:u.message,messages:[...f?t.slice(0,-1):t,u.message]})};return w3({stream:s,runUpdateMessageJob:l,onError:i}).pipeThrough(new TransformStream({transform(f,p){p.enqueue(f)},async cancel(){await d()},async flush(){await d()}}))}function S3({response:e,status:t,statusText:n,headers:i,stream:r,consumeSseStream:o}){let a=r.pipeThrough(new FC);if(o){const[s,u]=a.tee();a=s,o({stream:u})}LC({response:e,status:t,statusText:n,headers:Object.fromEntries(Iu(i,BC).entries()),stream:a.pipeThrough(new TextEncoderStream)})}function Qa(e){const t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=function(){const n=this.getReader();let i=!1;async function r(o){var a;i=!0;try{o&&await((a=n.cancel)==null?void 0:a.call(n))}finally{try{n.releaseLock()}catch{}}}return{async next(){if(i)return{done:!0,value:void 0};const{done:o,value:a}=await n.read();return o?(await r(!0),{done:!0,value:void 0}):{done:!1,value:a}},async return(){return await r(!0),{done:!0,value:void 0}},async throw(o){throw await r(!0),o}}},t}async function I3({stream:e,onError:t}){const n=e.getReader();try{for(;;){const{done:i}=await n.read();if(i)break}}catch(i){t?.(i)}finally{n.releaseLock()}}function ly(){let e,t;return{promise:new Promise((i,r)=>{e=i,t=r}),resolve:e,reject:t}}function k3(){let e=[],t=null,n=!1,i=ly();const r=()=>{n=!0,i.resolve(),e.forEach(a=>a.cancel()),e=[],t?.close()},o=async()=>{if(n&&e.length===0){t?.close();return}if(e.length===0)return i=ly(),await i.promise,o();try{const{value:a,done:s}=await e[0].read();s?(e.shift(),e.length>0?await o():n&&t?.close()):t?.enqueue(a)}catch(a){t?.error(a),e.shift(),r()}};return{stream:new ReadableStream({start(a){t=a},pull:o,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()),i.resolve()},close:()=>{n=!0,i.resolve(),e.length===0&&t?.close()},terminate:r}}var es=class{constructor(){this.status={type:"pending"},this._resolve=void 0,this._reject=void 0}get promise(){return this._promise?this._promise:(this._promise=new Promise((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 E3(){var e,t;return(t=(e=globalThis?.performance)==null?void 0:e.now())!=null?t:Date.now()}function T3({tools:e,generatorStream:t,tracer:n,telemetry:i,system:r,messages:o,abortSignal:a,repairToolCall:s,experimental_context:u}){let l=null;const c=new ReadableStream({start(v){l=v}}),d=new Set,f=new Map;let p=!1,g;function m(){p&&d.size===0&&(g!=null&&l.enqueue(g),l.close())}const y=new TransformStream({async transform(v,_){const x=v.type;switch(x){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":{_.enqueue(v);break}case"file":{_.enqueue({type:"file",file:new u3({data:v.data,mediaType:v.mediaType})});break}case"finish":{g={type:"finish",finishReason:v.finishReason,usage:v.usage,providerMetadata:v.providerMetadata};break}case"tool-call":{try{const b=await c3({toolCall:v,tools:e,repairToolCall:s,system:r,messages:o});if(_.enqueue(b),b.invalid){l.enqueue({type:"tool-error",toolCallId:b.toolCallId,toolName:b.toolName,input:b.input,error:R$(b.error),dynamic:!0});break}const C=e[b.toolName];if(f.set(b.toolCallId,b.input),C.onInputAvailable!=null&&await C.onInputAvailable({input:b.input,toolCallId:b.toolCallId,messages:o,abortSignal:a,experimental_context:u}),C.execute!=null&&b.providerExecuted!==!0){const E=gV();d.add(E),$d({name:"ai.toolCall",attributes:ni({telemetry:i,attributes:{...Td({operationId:"ai.toolCall",telemetry:i}),"ai.toolCall.name":b.toolName,"ai.toolCall.id":b.toolCallId,"ai.toolCall.args":{output:()=>JSON.stringify(b.input)}}}),tracer:n,fn:async $=>{let A;try{const j=C9({execute:C.execute.bind(C),input:b.input,options:{toolCallId:b.toolCallId,messages:o,abortSignal:a,experimental_context:u}});for await(const F of j)l.enqueue({...b,type:"tool-result",output:F.output,...F.type==="preliminary"&&{preliminary:!0}}),F.type==="final"&&(A=F.output)}catch(j){DC($,j),l.enqueue({...b,type:"tool-error",error:j}),d.delete(E),m();return}d.delete(E),m();try{$.setAttributes(ni({telemetry:i,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(A)}}}))}catch{}}})}}catch(b){l.enqueue({type:"error",error:b})}break}case"tool-result":{const b=v.toolName;v.isError?l.enqueue({type:"tool-error",toolCallId:v.toolCallId,toolName:b,input:f.get(v.toolCallId),providerExecuted:v.providerExecuted,error:v.result}):_.enqueue({type:"tool-result",toolCallId:v.toolCallId,toolName:b,input:f.get(v.toolCallId),output:v.result,providerExecuted:v.providerExecuted});break}default:{const b=x;throw new Error(`Unhandled chunk type: ${b}`)}}},flush(){p=!0,m()}});return new ReadableStream({async start(v){return Promise.all([t.pipeThrough(y).pipeTo(new WritableStream({write(_){v.enqueue(_)},close(){}})),c.pipeTo(new WritableStream({write(_){v.enqueue(_)},close(){v.close()}}))])}})}var $3=ka({prefix:"aitxt",size:24});function C3({model:e,tools:t,toolChoice:n,system:i,prompt:r,messages:o,maxRetries:a,abortSignal:s,headers:u,stopWhen:l=UC(1),experimental_output:c,experimental_telemetry:d,prepareStep:f,providerOptions:p,experimental_activeTools:g,activeTools:m=g,experimental_repairToolCall:y,experimental_transform:v,experimental_download:_,includeRawChunks:x=!1,onChunk:b,onError:C=({error:D})=>{console.error(D)},onFinish:E,onAbort:$,onStepFinish:A,experimental_context:j,_internal:{now:F=E3,generateId:z=$3,currentDate:J=()=>new Date}={},...G}){return new P3({model:PC(e),telemetry:d,headers:u,settings:G,maxRetries:a,abortSignal:s,system:i,prompt:r,messages:o,tools:t,toolChoice:n,transforms:ny(v),activeTools:m,repairToolCall:y,stopConditions:ny(l),output:c,providerOptions:p,prepareStep:f,includeRawChunks:x,onChunk:b,onError:C,onFinish:E,onAbort:$,onStepFinish:A,now:F,currentDate:J,generateId:z,experimental_context:j,download:_})}function A3(e){if(!e)return new TransformStream({transform(a,s){s.enqueue({part:a,partialOutput:void 0})}});let t,n="",i="",r="";function o({controller:a,partialOutput:s=void 0}){a.enqueue({part:{type:"text-delta",id:t,text:i},partialOutput:s}),i=""}return new TransformStream({async transform(a,s){if(a.type==="finish-step"&&i.length>0&&o({controller:s}),a.type!=="text-delta"&&a.type!=="text-start"&&a.type!=="text-end"){s.enqueue({part:a,partialOutput:void 0});return}if(t==null)t=a.id;else if(a.id!==t){s.enqueue({part:a,partialOutput:void 0});return}if(a.type==="text-start"){s.enqueue({part:a,partialOutput:void 0});return}if(a.type==="text-end"){i.length>0&&o({controller:s}),s.enqueue({part:a,partialOutput:void 0});return}n+=a.text,i+=a.text;const u=await e.parsePartial({text:n});if(u!=null){const l=JSON.stringify(u.partial);l!==r&&(o({controller:s,partialOutput:u.partial}),r=l)}}})}var P3=class{constructor({model:e,telemetry:t,headers:n,settings:i,maxRetries:r,abortSignal:o,system:a,prompt:s,messages:u,tools:l,toolChoice:c,transforms:d,activeTools:f,repairToolCall:p,stopConditions:g,output:m,providerOptions:y,prepareStep:v,includeRawChunks:_,now:x,currentDate:b,generateId:C,onChunk:E,onError:$,onFinish:A,onAbort:j,onStepFinish:F,experimental_context:z,download:J}){this._totalUsage=new es,this._finishReason=new es,this._steps=new es,this.output=m,this.includeRawChunks=_,this.tools=l;let G,D=[];const U=[];let X,re,Q={},me=[];const S=[];let Ae,ye={},T={};const V=new TransformStream({async transform(qe,Be){var He,be,It,Jn;Be.enqueue(qe);const{part:Y}=qe;if((Y.type==="text-delta"||Y.type==="reasoning-delta"||Y.type==="source"||Y.type==="tool-call"||Y.type==="tool-result"||Y.type==="tool-input-start"||Y.type==="tool-input-delta"||Y.type==="raw")&&await E?.({chunk:Y}),Y.type==="error"&&await $({error:XH(Y.error)}),Y.type==="text-start"&&(ye[Y.id]={type:"text",text:"",providerMetadata:Y.providerMetadata},D.push(ye[Y.id])),Y.type==="text-delta"){const De=ye[Y.id];if(De==null){Be.enqueue({part:{type:"error",error:`text part ${Y.id} not found`},partialOutput:void 0});return}De.text+=Y.text,De.providerMetadata=(He=Y.providerMetadata)!=null?He:De.providerMetadata}if(Y.type==="text-end"){const De=ye[Y.id];if(De==null){Be.enqueue({part:{type:"error",error:`text part ${Y.id} not found`},partialOutput:void 0});return}De.providerMetadata=(be=Y.providerMetadata)!=null?be:De.providerMetadata,delete ye[Y.id]}if(Y.type==="reasoning-start"&&(T[Y.id]={type:"reasoning",text:"",providerMetadata:Y.providerMetadata},D.push(T[Y.id])),Y.type==="reasoning-delta"){const De=T[Y.id];if(De==null){Be.enqueue({part:{type:"error",error:`reasoning part ${Y.id} not found`},partialOutput:void 0});return}De.text+=Y.text,De.providerMetadata=(It=Y.providerMetadata)!=null?It:De.providerMetadata}if(Y.type==="reasoning-end"){const De=T[Y.id];if(De==null){Be.enqueue({part:{type:"error",error:`reasoning part ${Y.id} not found`},partialOutput:void 0});return}De.providerMetadata=(Jn=Y.providerMetadata)!=null?Jn:De.providerMetadata,delete T[Y.id]}if(Y.type==="file"&&D.push({type:"file",file:Y.file}),Y.type==="source"&&D.push(Y),Y.type==="tool-call"&&D.push(Y),Y.type==="tool-result"&&!Y.preliminary&&D.push(Y),Y.type==="tool-error"&&D.push(Y),Y.type==="start-step"&&(Q=Y.request,me=Y.warnings),Y.type==="finish-step"){const De=oy({content:D,tools:l}),vr=new d3({content:D,finishReason:Y.finishReason,usage:Y.usage,warnings:me,request:Q,response:{...Y.response,messages:[...U,...De]},providerMetadata:Y.providerMetadata});await F?.(vr),uH(me),S.push(vr),D=[],T={},ye={},U.push(...De),G.resolve()}Y.type==="finish"&&(re=Y.totalUsage,X=Y.finishReason)},async flush(qe){try{if(S.length===0){const It=new hH({message:"No output generated. Check the stream for errors."});Ke._finishReason.reject(It),Ke._totalUsage.reject(It),Ke._steps.reject(It);return}const Be=X??"unknown",He=re??{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};Ke._finishReason.resolve(Be),Ke._totalUsage.resolve(He),Ke._steps.resolve(S);const be=S[S.length-1];await A?.({finishReason:Be,totalUsage:He,usage:be.usage,content:be.content,text:be.text,reasoningText:be.reasoningText,reasoning:be.reasoning,files:be.files,sources:be.sources,toolCalls:be.toolCalls,staticToolCalls:be.staticToolCalls,dynamicToolCalls:be.dynamicToolCalls,toolResults:be.toolResults,staticToolResults:be.staticToolResults,dynamicToolResults:be.dynamicToolResults,request:be.request,response:be.response,warnings:be.warnings,providerMetadata:be.providerMetadata,steps:S}),Ae.setAttributes(ni({telemetry:t,attributes:{"ai.response.finishReason":Be,"ai.response.text":{output:()=>be.text},"ai.response.toolCalls":{output:()=>{var It;return(It=be.toolCalls)!=null&&It.length?JSON.stringify(be.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(be.providerMetadata),"ai.usage.inputTokens":He.inputTokens,"ai.usage.outputTokens":He.outputTokens,"ai.usage.totalTokens":He.totalTokens,"ai.usage.reasoningTokens":He.reasoningTokens,"ai.usage.cachedInputTokens":He.cachedInputTokens}}))}catch(Be){qe.error(Be)}finally{Ae.end()}}}),ne=k3();this.addStream=ne.addStream,this.closeStream=ne.close;const ue=ne.stream.getReader();let Se=new ReadableStream({async start(qe){qe.enqueue({type:"start"})},async pull(qe){function Be(){j?.({steps:S}),qe.enqueue({type:"abort"}),qe.close()}try{const{done:He,value:be}=await ue.read();if(He){qe.close();return}if(o?.aborted){Be();return}qe.enqueue(be)}catch(He){Or(He)&&o?.aborted?Be():qe.error(He)}},cancel(qe){return ne.stream.cancel(qe)}});for(const qe of d)Se=Se.pipeThrough(qe({tools:l,stopStream(){ne.terminate()}}));this.baseStream=Se.pipeThrough(A3(m)).pipeThrough(V);const{maxRetries:St,retry:mn}=s3({maxRetries:r,abortSignal:o}),Ut=n3(t),rt=UH(i),qr=QH({model:e,telemetry:t,headers:n,settings:{...rt,maxRetries:St}}),Ke=this;$d({name:"ai.streamText",attributes:ni({telemetry:t,attributes:{...Td({operationId:"ai.streamText",telemetry:t}),...qr,"ai.prompt":{input:()=>JSON.stringify({system:a,prompt:s,messages:u})}}}),tracer:Ut,endWhenDone:!1,fn:async qe=>{Ae=qe;async function Be({currentStep:He,responseMessages:be,usage:It}){var Jn,Y,De,vr,Ca;const Aa=Ke.includeRawChunks;G=new es;const Pa=await YH({system:a,prompt:s,messages:u}),N=[...Pa.messages,...be],Z=await v?.({model:e,steps:S,stepNumber:S.length,messages:N}),ie=PC((Jn=Z?.model)!=null?Jn:e),ge=await jH({prompt:{system:(Y=Z?.system)!=null?Y:Pa.system,messages:(De=Z?.messages)!=null?De:N},supportedUrls:await ie.supportedUrls,download:J}),{toolChoice:we,tools:ut}=FH({tools:l,toolChoice:(vr=Z?.toolChoice)!=null?vr:c,activeTools:(Ca=Z?.activeTools)!=null?Ca:f}),{result:{stream:On,response:Lt,request:Wn},doStreamSpan:Ft,startTimestampMs:it}=await mn(()=>$d({name:"ai.streamText.doStream",attributes:ni({telemetry:t,attributes:{...Td({operationId:"ai.streamText.doStream",telemetry:t}),...qr,"ai.model.provider":ie.provider,"ai.model.id":ie.modelId,"ai.prompt.messages":{input:()=>r3(ge)},"ai.prompt.tools":{input:()=>ut?.map(oe=>JSON.stringify(oe))},"ai.prompt.toolChoice":{input:()=>we!=null?JSON.stringify(we):void 0},"gen_ai.system":ie.provider,"gen_ai.request.model":ie.modelId,"gen_ai.request.frequency_penalty":rt.frequencyPenalty,"gen_ai.request.max_tokens":rt.maxOutputTokens,"gen_ai.request.presence_penalty":rt.presencePenalty,"gen_ai.request.stop_sequences":rt.stopSequences,"gen_ai.request.temperature":rt.temperature,"gen_ai.request.top_k":rt.topK,"gen_ai.request.top_p":rt.topP}}),tracer:Ut,endWhenDone:!1,fn:async oe=>({startTimestampMs:x(),doStreamSpan:oe,result:await ie.doStream({...rt,tools:ut,toolChoice:we,responseFormat:m?.responseFormat,prompt:ge,providerOptions:y,abortSignal:o,headers:n,includeRawChunks:Aa})})})),Gn=T3({tools:l,generatorStream:On,tracer:Ut,telemetry:t,system:a,messages:N,repairToolCall:p,abortSignal:o,experimental_context:z}),Kt=Wn??{},Ra=[],Ru=[];let Ou;const Nu={};let Vr="unknown",Yt={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},ju,fm=!0,gn={id:C(),timestamp:b(),modelId:e.modelId},hm="";Ke.addStream(Gn.pipeThrough(new TransformStream({async transform(oe,tt){var Di,zi,Oa,Nn;if(oe.type==="stream-start"){Ou=oe.warnings;return}if(fm){const ct=x()-it;fm=!1,Ft.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":ct}),Ft.setAttributes({"ai.response.msToFirstChunk":ct}),tt.enqueue({type:"start-step",request:Kt,warnings:Ou??[]})}const mm=oe.type;switch(mm){case"text-start":case"text-end":{tt.enqueue(oe);break}case"text-delta":{oe.delta.length>0&&(tt.enqueue({type:"text-delta",id:oe.id,text:oe.delta,providerMetadata:oe.providerMetadata}),hm+=oe.delta);break}case"reasoning-start":case"reasoning-end":{tt.enqueue(oe);break}case"reasoning-delta":{tt.enqueue({type:"reasoning-delta",id:oe.id,text:oe.delta,providerMetadata:oe.providerMetadata});break}case"tool-call":{tt.enqueue(oe),Ra.push(oe);break}case"tool-result":{tt.enqueue(oe),oe.preliminary||Ru.push(oe);break}case"tool-error":{tt.enqueue(oe),Ru.push(oe);break}case"response-metadata":{gn={id:(Di=oe.id)!=null?Di:gn.id,timestamp:(zi=oe.timestamp)!=null?zi:gn.timestamp,modelId:(Oa=oe.modelId)!=null?Oa:gn.modelId};break}case"finish":{Yt=oe.usage,Vr=oe.finishReason,ju=oe.providerMetadata;const ct=x()-it;Ft.addEvent("ai.stream.finish"),Ft.setAttributes({"ai.response.msToFinish":ct,"ai.response.avgOutputTokensPerSecond":1e3*((Nn=Yt.outputTokens)!=null?Nn:0)/ct});break}case"file":{tt.enqueue(oe);break}case"source":{tt.enqueue(oe);break}case"tool-input-start":{Nu[oe.id]=oe.toolName;const ct=l?.[oe.toolName];ct?.onInputStart!=null&&await ct.onInputStart({toolCallId:oe.id,messages:N,abortSignal:o,experimental_context:z}),tt.enqueue({...oe,dynamic:ct?.type==="dynamic"});break}case"tool-input-end":{delete Nu[oe.id],tt.enqueue(oe);break}case"tool-input-delta":{const ct=Nu[oe.id],Mu=l?.[ct];Mu?.onInputDelta!=null&&await Mu.onInputDelta({inputTextDelta:oe.delta,toolCallId:oe.id,messages:N,abortSignal:o,experimental_context:z}),tt.enqueue(oe);break}case"error":{tt.enqueue(oe),Vr="error";break}case"raw":{Aa&&tt.enqueue(oe);break}default:{const ct=mm;throw new Error(`Unknown chunk type: ${ct}`)}}},async flush(oe){const tt=Ra.length>0?JSON.stringify(Ra):void 0;try{Ft.setAttributes(ni({telemetry:t,attributes:{"ai.response.finishReason":Vr,"ai.response.text":{output:()=>hm},"ai.response.toolCalls":{output:()=>tt},"ai.response.id":gn.id,"ai.response.model":gn.modelId,"ai.response.timestamp":gn.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(ju),"ai.usage.inputTokens":Yt.inputTokens,"ai.usage.outputTokens":Yt.outputTokens,"ai.usage.totalTokens":Yt.totalTokens,"ai.usage.reasoningTokens":Yt.reasoningTokens,"ai.usage.cachedInputTokens":Yt.cachedInputTokens,"gen_ai.response.finish_reasons":[Vr],"gen_ai.response.id":gn.id,"gen_ai.response.model":gn.modelId,"gen_ai.usage.input_tokens":Yt.inputTokens,"gen_ai.usage.output_tokens":Yt.outputTokens}}))}catch{}finally{Ft.end()}oe.enqueue({type:"finish-step",finishReason:Vr,usage:Yt,providerMetadata:ju,response:{...gn,headers:Lt?.headers}});const Di=i3(It,Yt);await G.promise;const zi=Ra.filter(Nn=>Nn.providerExecuted!==!0),Oa=Ru.filter(Nn=>Nn.providerExecuted!==!0);if(zi.length>0&&Oa.length===zi.length&&!await p3({stopConditions:g,steps:S})){be.push(...oy({content:S[S.length-1].content,tools:l}));try{await Be({currentStep:He+1,responseMessages:be,usage:Di})}catch(Nn){oe.enqueue({type:"error",error:Nn}),Ke.closeStream()}}else oe.enqueue({type:"finish",finishReason:Vr,totalUsage:Di}),Ke.closeStream()}})))}await Be({currentStep:0,responseMessages:[],usage:{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0}})}}).catch(qe=>{Ke.addStream(new ReadableStream({start(Be){Be.enqueue({type:"error",error:qe}),Be.close()}})),Ke.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 Qa(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){e.type==="text-delta"&&t.enqueue(e.text)}})))}get fullStream(){return Qa(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){t.enqueue(e)}})))}async consumeStream(e){var t;try{await I3({stream:this.fullStream,onError:e?.onError})}catch(n){(t=e?.onError)==null||t.call(e,n)}}get experimental_partialOutputStream(){if(this.output==null)throw new aH;return Qa(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:e},t){e!=null&&t.enqueue(e)}})))}toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:n,messageMetadata:i,sendReasoning:r=!0,sendSources:o=!1,sendStart:a=!0,sendFinish:s=!0,onError:u=Ti}={}){const l=t!=null?g3({originalMessages:e,responseMessageId:t}):void 0,c={},d=p=>{var g,m;const y=c[p];return((m=(g=this.tools)==null?void 0:g[y])==null?void 0:m.type)==="dynamic"?!0:void 0},f=this.fullStream.pipeThrough(new TransformStream({transform:async(p,g)=>{const m=i?.({part:p}),y=p.type;switch(y){case"text-start":{g.enqueue({type:"text-start",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"text-delta":{g.enqueue({type:"text-delta",id:p.id,delta:p.text,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"text-end":{g.enqueue({type:"text-end",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-start":{g.enqueue({type:"reasoning-start",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-delta":{r&&g.enqueue({type:"reasoning-delta",id:p.id,delta:p.text,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-end":{g.enqueue({type:"reasoning-end",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"file":{g.enqueue({type:"file",mediaType:p.file.mediaType,url:`data:${p.file.mediaType};base64,${p.file.base64}`});break}case"source":{o&&p.sourceType==="url"&&g.enqueue({type:"source-url",sourceId:p.id,url:p.url,title:p.title,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}}),o&&p.sourceType==="document"&&g.enqueue({type:"source-document",sourceId:p.id,mediaType:p.mediaType,title:p.title,filename:p.filename,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"tool-input-start":{c[p.id]=p.toolName;const v=d(p.id);g.enqueue({type:"tool-input-start",toolCallId:p.id,toolName:p.toolName,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...v!=null?{dynamic:v}:{}});break}case"tool-input-delta":{g.enqueue({type:"tool-input-delta",toolCallId:p.id,inputTextDelta:p.delta});break}case"tool-call":{c[p.toolCallId]=p.toolName;const v=d(p.toolCallId);p.invalid?g.enqueue({type:"tool-input-error",toolCallId:p.toolCallId,toolName:p.toolName,input:p.input,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...v!=null?{dynamic:v}:{},errorText:u(p.error)}):g.enqueue({type:"tool-input-available",toolCallId:p.toolCallId,toolName:p.toolName,input:p.input,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...v!=null?{dynamic:v}:{}});break}case"tool-result":{const v=d(p.toolCallId);g.enqueue({type:"tool-output-available",toolCallId:p.toolCallId,output:p.output,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.preliminary!=null?{preliminary:p.preliminary}:{},...v!=null?{dynamic:v}:{}});break}case"tool-error":{const v=d(p.toolCallId);g.enqueue({type:"tool-output-error",toolCallId:p.toolCallId,errorText:u(p.error),...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...v!=null?{dynamic:v}:{}});break}case"error":{g.enqueue({type:"error",errorText:u(p.error)});break}case"start-step":{g.enqueue({type:"start-step"});break}case"finish-step":{g.enqueue({type:"finish-step"});break}case"start":{a&&g.enqueue({type:"start",...m!=null?{messageMetadata:m}:{},...l!=null?{messageId:l}:{}});break}case"finish":{s&&g.enqueue({type:"finish",...m!=null?{messageMetadata:m}:{}});break}case"abort":{g.enqueue(p);break}case"tool-input-end":break;case"raw":break;default:{const v=y;throw new Error(`Unknown chunk type: ${v}`)}}m!=null&&y!=="start"&&y!=="finish"&&g.enqueue({type:"message-metadata",messageMetadata:m})}}));return Qa(x3({stream:f,messageId:l??t?.(),originalMessages:e,onFinish:n,onError:u}))}pipeUIMessageStreamToResponse(e,{originalMessages:t,generateMessageId:n,onFinish:i,messageMetadata:r,sendReasoning:o,sendSources:a,sendFinish:s,sendStart:u,onError:l,...c}={}){S3({response:e,stream:this.toUIMessageStream({originalMessages:t,generateMessageId:n,onFinish:i,messageMetadata:r,sendReasoning:o,sendSources:a,sendFinish:s,sendStart:u,onError:l}),...c})}pipeTextStreamToResponse(e,t){h3({response:e,textStream:this.textStream,...t})}toUIMessageStreamResponse({originalMessages:e,generateMessageId:t,onFinish:n,messageMetadata:i,sendReasoning:r,sendSources:o,sendFinish:a,sendStart:s,onError:u,...l}={}){return m3({stream:this.toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:n,messageMetadata:i,sendReasoning:r,sendSources:o,sendFinish:a,sendStart:s,onError:u}),...l})}toTextStreamResponse(e){return f3({textStream:this.textStream,...e})}};function R3(e,t){const n=[];t?.ignoreIncompleteToolCalls&&(e=e.map(i=>({...i,parts:i.parts.filter(r=>!sy(r)||r.state!=="input-streaming"&&r.state!=="input-available")})));for(const i of e)switch(i.role){case"system":{const r=i.parts.filter(a=>a.type==="text"),o=r.reduce((a,s)=>s.providerMetadata!=null?{...a,...s.providerMetadata}:a,{});n.push({role:"system",content:r.map(a=>a.text).join(""),...Object.keys(o).length>0?{providerOptions:o}:{}});break}case"user":{n.push({role:"user",content:i.parts.map(r=>{var o;if(wc(r))return{type:"text",text:r.text,...r.providerMetadata!=null?{providerOptions:r.providerMetadata}:{}};if(xc(r))return{type:"file",mediaType:r.mediaType,filename:r.filename,data:r.url,...r.providerMetadata!=null?{providerOptions:r.providerMetadata}:{}};if(_c(r))return(o=t?.convertDataPart)==null?void 0:o.call(t,r)}).filter(r=>r!=null)});break}case"assistant":{if(i.parts!=null){let r=function(){var a,s,u;if(o.length===0)return;const l=[];for(const d of o)if(wc(d))l.push({type:"text",text:d.text,...d.providerMetadata!=null?{providerOptions:d.providerMetadata}:{}});else if(xc(d))l.push({type:"file",mediaType:d.mediaType,filename:d.filename,data:d.url});else if(ay(d))l.push({type:"reasoning",text:d.text,providerOptions:d.providerMetadata});else if(Oh(d)){const f=d.toolName;d.state!=="input-streaming"&&l.push({type:"tool-call",toolCallId:d.toolCallId,toolName:f,input:d.input,...d.callProviderMetadata!=null?{providerOptions:d.callProviderMetadata}:{}})}else if(si(d)){const f=nl(d);d.state!=="input-streaming"&&(l.push({type:"tool-call",toolCallId:d.toolCallId,toolName:f,input:d.state==="output-error"?(a=d.input)!=null?a:d.rawInput:d.input,providerExecuted:d.providerExecuted,...d.callProviderMetadata!=null?{providerOptions:d.callProviderMetadata}:{}}),d.providerExecuted===!0&&(d.state==="output-available"||d.state==="output-error")&&l.push({type:"tool-result",toolCallId:d.toolCallId,toolName:f,output:oo({output:d.state==="output-error"?d.errorText:d.output,tool:(s=t?.tools)==null?void 0:s[f],errorMode:d.state==="output-error"?"json":"none"})}))}else if(_c(d)){const f=(u=t?.convertDataPart)==null?void 0:u.call(t,d);f!=null&&l.push(f)}else{const f=d;throw new Error(`Unsupported part: ${f}`)}n.push({role:"assistant",content:l});const c=o.filter(d=>si(d)&&d.providerExecuted!==!0||d.type==="dynamic-tool");c.length>0&&n.push({role:"tool",content:c.map(d=>{var f;switch(d.state){case"output-error":case"output-available":{const p=b3(d);return{type:"tool-result",toolCallId:d.toolCallId,toolName:p,output:oo({output:d.state==="output-error"?d.errorText:d.output,tool:(f=t?.tools)==null?void 0:f[p],errorMode:d.state==="output-error"?"text":"none"})}}default:return null}}).filter(d=>d!=null)}),o=[]},o=[];for(const a of i.parts)wc(a)||ay(a)||xc(a)||sy(a)||_c(a)?o.push(a):a.type==="step-start"&&r();r();break}break}default:{const r=i.role;throw new xH({originalMessage:i,message:`Unsupported role: ${r}`})}}return n}ka({prefix:"aiobj",size:24});ka({prefix:"aiobj",size:24});var O3={};iH(O3,{object:()=>j3,text:()=>N3});var N3=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),j3=({schema:e})=>{const t=Su(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const i=await qC(n);switch(i.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:i.value};default:{const r=i.state;throw new Error(`Unsupported parse state: ${r}`)}}},async parseOutput({text:n},i){const r=await Nr({text:n});if(!r.success)throw new ey({message:"No object generated: could not parse the response.",cause:r.error,text:n,response:i.response,usage:i.usage,finishReason:i.finishReason});const o=await dr({value:r.value,schema:t});if(!o.success)throw new ey({message:"No object generated: response did not match schema.",cause:o.error,text:n,response:i.response,usage:i.usage,finishReason:i.finishReason});return o.value}}},M3={word:/\S+\s+/m,line:/\n+/m};function D3({delayInMs:e=10,chunking:t="word",_internal:{delay:n=P$}={}}={}){let i;if(typeof t=="function")i=r=>{const o=t(r);if(o==null)return null;if(!o.length)throw new Error("Chunking function must return a non-empty string.");if(!r.startsWith(o))throw new Error(`Chunking function must return a match that is a prefix of the buffer. Received: "${o}" expected to start with "${r}"`);return o};else{const r=typeof t=="string"?M3[t]:t;if(r==null)throw new al({argument:"chunking",message:`Chunking must be "word" or "line" or a RegExp. Received: ${t}`});i=o=>{const a=r.exec(o);return a?o.slice(0,a.index)+a?.[0]:null}}return()=>{let r="",o="";return new TransformStream({async transform(a,s){if(a.type!=="text-delta"){r.length>0&&(s.enqueue({type:"text-delta",text:r,id:o}),r=""),s.enqueue(a);return}a.id!==o&&r.length>0&&(s.enqueue({type:"text-delta",text:r,id:o}),r=""),r+=a.text,o=a.id;let u;for(;(u=i(r))!=null;)s.enqueue({type:"text-delta",text:u,id:o}),r=r.slice(u.length),await n(e)}})}}function ts(e){return!!e&&"UNSAFE_apiKey"in e}function z3(e){return e?"sessionFn"in e:!1}const U3=({getSession:e,projectSlug:t,enabled:n})=>{const i=zk(),r=["chatSession",t],o=i.getQueryState(r),a=o?.data!==void 0,s=o?.dataUpdatedAt??0,l=a&&Date.now()-s>1/0,c=!a||l,{data:d}=Lk({queryKey:r,queryFn:()=>e({projectSlug:t}),enabled:n&&c&&e!==null,staleTime:1/0,gcTime:1/0});return d??null};async function L3(e){return(await(await fetch("/chat/session",{method:"POST",headers:{"Gram-Project":e.projectSlug}})).json()).client_token}const F3=({projectSlug:e,auth:t})=>{const n=k.useMemo(()=>ts(t)?null:!ts(t)&&z3(t)?t.sessionFn:L3,[t]),i=U3({enabled:!ts(t),getSession:n,projectSlug:e});return ts(t)?{headers:{"Gram-Project":e,"Gram-Key":t.UNSAFE_apiKey},isLoading:!1}:i?{headers:{"Gram-Project":e,"Gram-Chat-Session":i},isLoading:!1}:{isLoading:!0}};function B3({children:e}){const[t,n]=k.useState(new Map),[i,r]=k.useState(new Set),o=k.useCallback((d,f,p)=>new Promise(g=>{const m={toolCallId:f,toolName:d,args:p,resolve:g};n(y=>{const v=new Map(y);return v.set(f,m),v})}),[]),a=k.useCallback(d=>{r(f=>{const p=new Set(f);return p.add(d),p})},[]),s=k.useCallback(d=>{n(f=>{const p=f.get(d);if(p){p.resolve(!0);const g=new Map(f);return g.delete(d),g}return f})},[]),u=k.useCallback(d=>{n(f=>{const p=f.get(d);if(p){p.resolve(!1);const g=new Map(f);return g.delete(d),g}return f})},[]),l=k.useCallback(d=>i.has(d),[i]),c=k.useCallback(d=>t.get(d),[t]);return h.jsx(R.ToolApprovalContext.Provider,{value:{pendingApprovals:t,approvedTools:i,requestApproval:o,whitelistTool:a,confirmPendingApproval:s,rejectPendingApproval:u,isToolApproved:l,getPendingApproval:c},children:e})}function Z3(e){return e==="user"?"user":e==="assistant"?"assistant":e==="system"?"system":"assistant"}function q3(e){return typeof e=="string"?new Date(e):e}function V3(e){const t=[];return e.content&&t.push({type:"text",text:e.content}),t.length===0&&t.push({type:"text",text:""}),t}function H3(e){const t=[];if(e.content&&t.push({type:"text",text:e.content}),e.toolCalls)try{const n=JSON.parse(e.toolCalls);for(const i of n){const r=i.function?.arguments??i.args??{},o=typeof r=="string"?r:JSON.stringify(r);t.push({type:"tool-call",toolCallId:i.id??i.toolCallId??"",toolName:i.function?.name??i.toolName??"",args:typeof r=="string"?JSON.parse(r):r,argsText:o,result:void 0})}}catch{}return t.length===0&&t.push({type:"text",text:""}),t}function J3(e){const t=Z3(e.role),n=q3(e.createdAt),i={unstable_state:void 0,unstable_annotations:void 0,unstable_data:void 0,steps:void 0,submittedFeedback:void 0,custom:{}};return t==="user"?{id:e.id,role:"user",createdAt:n,content:V3(e),attachments:[],metadata:i}:t==="system"?{id:e.id,role:"system",createdAt:n,content:[{type:"text",text:e.content??""}],metadata:i}:{id:e.id,role:"assistant",createdAt:n,content:H3(e),status:{type:"complete",reason:"stop"},metadata:{unstable_state:null,unstable_annotations:[],unstable_data:[],steps:[],submittedFeedback:void 0,custom:{}}}}function W3(e){if(e.length===0)return{messages:[],headId:null};const t=[];let n=null;for(const i of e){if(i.role==="system")continue;const r=J3(i);t.push({message:r,parentId:n,runConfig:void 0}),n=i.id}return{messages:t,headId:n}}class G3{constructor(t,n,i){this.apiUrl=t,this.headers=n,this.store=i}async load(){const t=this.store.threadListItem().getState().remoteId;if(!t)return{messages:[],headId:null};try{const n=await fetch(`${this.apiUrl}/rpc/chat.load?id=${encodeURIComponent(t)}`,{headers:this.headers});if(!n.ok)return console.error("Failed to load chat:",n.status),{messages:[],headId:null};const i=await n.json();return W3(i.messages)}catch(n){return console.error("Error loading chat:",n),{messages:[],headId:null}}}async append(){}withFormat(t){return{load:async()=>{const n=this.store.threadListItem().getState().remoteId;if(!n)return{messages:[],headId:null};try{const i=await fetch(`${this.apiUrl}/rpc/chat.load?id=${encodeURIComponent(n)}`,{headers:this.headers});if(!i.ok)return console.error("Failed to load chat (withFormat):",i.status),{messages:[],headId:null};const o=(await i.json()).messages.filter(u=>u.role!=="system");if(o.length===0)return{messages:[],headId:null};let a=null;const s=o.map((u,l)=>{const c=u.id||`fallback-${l}-${Date.now()}`,d={parentId:a,message:{id:c,role:u.role,parts:[{type:"text",text:u.content||""}],createdAt:u.createdAt?new Date(u.createdAt):new Date}};return a=c,d});return{headId:a,messages:s}}catch(i){return console.error("Error loading chat (withFormat):",i),{messages:[],headId:null}}},append:async()=>{}}}}function K3(e){const t=_e(),[n]=k.useState(()=>new G3(e.current.apiUrl,e.current.headers,t));return n}function Y3(e){const t=k.useRef(e);k.useEffect(()=>{t.current=e},[e]);const n=k.useCallback(function({children:r}){const o=K3(t),a=k.useMemo(()=>({history:o}),[o]);return h.jsx(Zf,{adapters:a,children:r})},[]);return k.useMemo(()=>({unstable_Provider:n,async list(){try{const i=await fetch(`${t.current.apiUrl}/rpc/chat.list`,{headers:t.current.headers});return i.ok?{threads:(await i.json()).chats.map(o=>({remoteId:o.id,externalId:o.id,status:"regular",title:o.title||"New Chat"}))}:(console.error("Failed to list chats:",i.status),{threads:[]})}catch(i){return console.error("Error listing chats:",i),{threads:[]}}},async initialize(i){return{remoteId:i,externalId:i}},async rename(){},async archive(){},async unarchive(){},async delete(){},async generateTitle(i,r){return new ReadableStream({start(o){o.close()}})},async fetch(i){try{const r=await fetch(`${t.current.apiUrl}/rpc/chat.load?id=${encodeURIComponent(i)}`,{headers:t.current.headers});if(!r.ok)return console.error("Failed to fetch thread:",r.status),{remoteId:i,status:"regular"};const o=await r.json();return{remoteId:o.id,externalId:o.id,status:"regular",title:o.title||"New Chat"}}catch(r){return console.error("Error fetching thread:",r),{remoteId:i,status:"regular"}}}}),[n])}const X3="You are a helpful assistant that can answer questions and help with tasks.";function Q3(e,t){return`
|
|
133
|
-
${X3}
|
|
134
|
-
|
|
135
|
-
User-provided System Prompt:
|
|
136
|
-
${e??"None provided"}
|
|
137
|
-
|
|
138
|
-
Utilities:
|
|
139
|
-
${t.map(n=>`- ${n.language}: ${n.prompt}`).join(`
|
|
140
|
-
`)}`}function e5(e){return e.map(t=>{const n=t.parts;if(!Array.isArray(n))return t;const i=n.map(r=>{const{callProviderMetadata:o,...a}=r;return a});return{...t,parts:i}})}const t5=({children:e,config:t})=>{const n=gM(t),i=F3({auth:t.api,projectSlug:t.projectSlug}),r=Fk(),[o,a]=k.useState(t.model?.defaultModel??jf[0]),[s,u]=k.useState(t.modal?.defaultExpanded??!1),[l,c]=k.useState(t.modal?.defaultOpen),d=t.plugins??R.recommended,f=Q3(t.systemPrompt,d),{data:p}=hM({auth:i,mcp:t.mcp,environment:t.environment??{}}),g=k.useRef({requestApproval:r.requestApproval,isToolApproved:r.isToolApproved,whitelistTool:r.whitelistTool});g.current={requestApproval:r.requestApproval,isToolApproved:r.isToolApproved,whitelistTool:r.whitelistTool};const m=k.useCallback(()=>({requestApproval:(...E)=>g.current.requestApproval(...E),isToolApproved:(...E)=>g.current.isToolApproved(...E),whitelistTool:(...E)=>g.current.whitelistTool(...E)}),[]);k.useEffect(()=>(t.tools?.toolsRequiringApproval?.length&&z6(m(),t.tools.toolsRequiringApproval),()=>{U6()}),[t.tools?.toolsRequiringApproval,m]);const y=k.useRef(null),v=k.useRef(null),_=k.useMemo(()=>({sendMessages:async({messages:E,abortSignal:$})=>{const A=!!t.languageModel;if(i.isLoading)throw new Error("Session is loading");v.current||(v.current=crypto.randomUUID());const j=y.current?.thread.getModelContext(),F=M6(D6(j?.tools??{})),z={...i.headers,"Gram-Chat-ID":v.current},J=A?null:A$({baseURL:n,apiKey:"unused, but must be set",headers:z});t.languageModel&&console.log("Using custom language model",t.languageModel);const G={...p,...eq(F)},D=F6(G,t.tools?.toolsRequiringApproval,m()),U=t.languageModel?t.languageModel:J.chat(o);try{const X=e5(E),re=R3(X);return C3({system:f,model:U,messages:re,tools:D,stopWhen:UC(10),experimental_transform:D3({delayInMs:15}),abortSignal:$,onError:({error:me})=>{console.error("Stream error in onError callback:",me)}}).toUIMessageStream()}catch(X){throw console.error("Error creating stream:",X),X}},reconnectToStream:async()=>{throw new Error("Stream reconnection not supported")}}),[t.languageModel,t.tools?.toolsRequiringApproval,o,f,p,m,n,i.headers,i.isLoading]),x=t.history?.enabled??!1,b=k.useMemo(()=>({config:t,setModel:a,model:o,isExpanded:s,setIsExpanded:u,isOpen:l??!1,setIsOpen:c,plugins:d}),[t,o,s,l,d]),C=t.tools?.frontendTools??{};return x&&!i.isLoading?h.jsx(n5,{transport:_,apiUrl:n,headers:i.headers,contextValue:b,runtimeRef:y,frontendTools:C,children:e}):h.jsx(r5,{transport:_,contextValue:b,runtimeRef:y,frontendTools:C,children:e})},n5=({children:e,transport:t,apiUrl:n,headers:i,contextValue:r,runtimeRef:o,frontendTools:a})=>{const s=Y3({apiUrl:n,headers:i}),u=k.useCallback(()=>L0({transport:t}),[t]),l=jE({adapter:s,runtimeHook:u});k.useEffect(()=>{o.current=l},[l,o]);const c=s.unstable_Provider??(({children:d})=>h.jsx(h.Fragment,{children:d}));return h.jsx(CE,{runtime:l,children:h.jsx(c,{children:h.jsxs(R.ElementsContext.Provider,{value:r,children:[e,h.jsx(rb,{tools:a})]})})})},r5=({children:e,transport:t,contextValue:n,runtimeRef:i,frontendTools:r})=>{const o=L0({transport:t});return k.useEffect(()=>{i.current=o},[o,i]),h.jsx(CE,{runtime:o,children:h.jsxs(R.ElementsContext.Provider,{value:n,children:[e,h.jsx(rb,{tools:r})]})})},i5=new tM,VC=e=>h.jsx(nM,{client:i5,children:h.jsx(B3,{children:h.jsx(t5,{...e})})}),uy=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,cy=R.clsx,HC=(e,t)=>n=>{var i;if(t?.variants==null)return cy(e,n?.class,n?.className);const{variants:r,defaultVariants:o}=t,a=Object.keys(r).map(l=>{const c=n?.[l],d=o?.[l];if(c===null)return null;const f=uy(c)||uy(d);return r[l][f]}),s=n&&Object.entries(n).reduce((l,c)=>{let[d,f]=c;return f===void 0||(l[d]=f),l},{}),u=t==null||(i=t.compoundVariants)===null||i===void 0?void 0:i.reduce((l,c)=>{let{class:d,className:f,...p}=c;return Object.entries(p).every(g=>{let[m,y]=g;return Array.isArray(y)?y.includes({...o,...s}[m]):{...o,...s}[m]===y})?[...l,d,f]:l},[]);return cy(e,a,u,n?.class,n?.className)},o5=HC("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",sm:"h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9","icon-sm":"size-8","icon-lg":"size-10"}},defaultVariants:{variant:"default",size:"default"}}),Pt=w.forwardRef(({className:e,variant:t,size:n,asChild:i=!1,...r},o)=>{const a=i?Gf:"button";return h.jsx(a,{"data-slot":"button",className:R.cn(o5({variant:t,size:n,className:e})),ref:o,...r})});Pt.displayName="Button";const a5=({error:e,onRetry:t})=>h.jsx("div",{className:R.cn("aui-root aui-error-boundary bg-background flex h-full w-full flex-col items-center justify-center p-6"),children:h.jsxs("div",{className:"flex flex-col items-center gap-4 text-center",children:[h.jsx("div",{className:"text-destructive",children:h.jsx(R.CircleAlert,{className:"size-12 stroke-[1.5px]"})}),h.jsxs("div",{className:"flex flex-col gap-2",children:[h.jsx("h3",{className:"text-foreground text-xl font-semibold",children:"Something went wrong"}),h.jsx("p",{className:"text-muted-foreground text-base",children:"An error occurred while loading the chat."}),e&&h.jsx("p",{className:"text-muted-foreground/60 max-w-md truncate text-sm",children:e.message})]}),h.jsx(Pt,{onClick:t,variant:"default",className:"mt-2",children:"Try again"})]})}),s5=({children:e})=>h.jsx(h.Fragment,{children:e});class Nh extends k.Component{constructor(t){super(t),this.handleRetry=()=>{this.setState(n=>({hasError:!1,error:null,resetKey:n.resetKey+1})),this.props.onReset?.()},this.state={hasError:!1,error:null,resetKey:0}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){this.props.onError?.(t,n)}render(){return this.state.hasError?this.props.fallback?this.props.fallback:h.jsx(a5,{error:this.state.error,onRetry:this.handleRetry}):h.jsx(s5,{children:this.props.children},this.state.resetKey)}}var l5=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),u5="VisuallyHidden",JC=w.forwardRef((e,t)=>h.jsx(Xe.span,{...e,ref:t,style:{...l5,...e.style}}));JC.displayName=u5;var c5=JC,[ku]=ya("Tooltip",[hu]),Eu=hu(),WC="TooltipProvider",d5=700,Cd="tooltip.open",[p5,jh]=ku(WC),GC=e=>{const{__scopeTooltip:t,delayDuration:n=d5,skipDelayDuration:i=300,disableHoverableContent:r=!1,children:o}=e,a=w.useRef(!0),s=w.useRef(!1),u=w.useRef(0);return w.useEffect(()=>{const l=u.current;return()=>window.clearTimeout(l)},[]),h.jsx(p5,{scope:t,isOpenDelayedRef:a,delayDuration:n,onOpen:w.useCallback(()=>{window.clearTimeout(u.current),a.current=!1},[]),onClose:w.useCallback(()=>{window.clearTimeout(u.current),u.current=window.setTimeout(()=>a.current=!0,i)},[i]),isPointerInTransitRef:s,onPointerInTransitChange:w.useCallback(l=>{s.current=l},[]),disableHoverableContent:r,children:o})};GC.displayName=WC;var Uo="Tooltip",[f5,Ea]=ku(Uo),KC=e=>{const{__scopeTooltip:t,children:n,open:i,defaultOpen:r,onOpenChange:o,disableHoverableContent:a,delayDuration:s}=e,u=jh(Uo,e.__scopeTooltip),l=Eu(t),[c,d]=w.useState(null),f=ri(),p=w.useRef(0),g=a??u.disableHoverableContent,m=s??u.delayDuration,y=w.useRef(!1),[v,_]=gu({prop:i,defaultProp:r??!1,onChange:$=>{$?(u.onOpen(),document.dispatchEvent(new CustomEvent(Cd))):u.onClose(),o?.($)},caller:Uo}),x=w.useMemo(()=>v?y.current?"delayed-open":"instant-open":"closed",[v]),b=w.useCallback(()=>{window.clearTimeout(p.current),p.current=0,y.current=!1,_(!0)},[_]),C=w.useCallback(()=>{window.clearTimeout(p.current),p.current=0,_(!1)},[_]),E=w.useCallback(()=>{window.clearTimeout(p.current),p.current=window.setTimeout(()=>{y.current=!0,_(!0),p.current=0},m)},[m,_]);return w.useEffect(()=>()=>{p.current&&(window.clearTimeout(p.current),p.current=0)},[]),h.jsx(fT,{...l,children:h.jsx(f5,{scope:t,contentId:f,open:v,stateAttribute:x,trigger:c,onTriggerChange:d,onTriggerEnter:w.useCallback(()=>{u.isOpenDelayedRef.current?E():b()},[u.isOpenDelayedRef,E,b]),onTriggerLeave:w.useCallback(()=>{g?C():(window.clearTimeout(p.current),p.current=0)},[C,g]),onOpen:b,onClose:C,disableHoverableContent:g,children:n})})};KC.displayName=Uo;var Ad="TooltipTrigger",YC=w.forwardRef((e,t)=>{const{__scopeTooltip:n,...i}=e,r=Ea(Ad,n),o=jh(Ad,n),a=Eu(n),s=w.useRef(null),u=Qe(t,s,r.onTriggerChange),l=w.useRef(!1),c=w.useRef(!1),d=w.useCallback(()=>l.current=!1,[]);return w.useEffect(()=>()=>document.removeEventListener("pointerup",d),[d]),h.jsx(lh,{asChild:!0,...a,children:h.jsx(Xe.button,{"aria-describedby":r.open?r.contentId:void 0,"data-state":r.stateAttribute,...i,ref:u,onPointerMove:Pe(e.onPointerMove,f=>{f.pointerType!=="touch"&&!c.current&&!o.isPointerInTransitRef.current&&(r.onTriggerEnter(),c.current=!0)}),onPointerLeave:Pe(e.onPointerLeave,()=>{r.onTriggerLeave(),c.current=!1}),onPointerDown:Pe(e.onPointerDown,()=>{r.open&&r.onClose(),l.current=!0,document.addEventListener("pointerup",d,{once:!0})}),onFocus:Pe(e.onFocus,()=>{l.current||r.onOpen()}),onBlur:Pe(e.onBlur,r.onClose),onClick:Pe(e.onClick,r.onClose)})})});YC.displayName=Ad;var Mh="TooltipPortal",[h5,m5]=ku(Mh,{forceMount:void 0}),XC=e=>{const{__scopeTooltip:t,forceMount:n,children:i,container:r}=e,o=Ea(Mh,t);return h.jsx(h5,{scope:t,forceMount:n,children:h.jsx(Hn,{present:n||o.open,children:h.jsx(mu,{asChild:!0,container:r,children:i})})})};XC.displayName=Mh;var Ei="TooltipContent",QC=w.forwardRef((e,t)=>{const n=m5(Ei,e.__scopeTooltip),{forceMount:i=n.forceMount,side:r="top",...o}=e,a=Ea(Ei,e.__scopeTooltip);return h.jsx(Hn,{present:i||a.open,children:a.disableHoverableContent?h.jsx(eA,{side:r,...o,ref:t}):h.jsx(g5,{side:r,...o,ref:t})})}),g5=w.forwardRef((e,t)=>{const n=Ea(Ei,e.__scopeTooltip),i=jh(Ei,e.__scopeTooltip),r=w.useRef(null),o=Qe(t,r),[a,s]=w.useState(null),{trigger:u,onClose:l}=n,c=r.current,{onPointerInTransitChange:d}=i,f=w.useCallback(()=>{s(null),d(!1)},[d]),p=w.useCallback((g,m)=>{const y=g.currentTarget,v={x:g.clientX,y:g.clientY},_=_5(v,y.getBoundingClientRect()),x=w5(v,_),b=x5(m.getBoundingClientRect()),C=I5([...x,...b]);s(C),d(!0)},[d]);return w.useEffect(()=>()=>f(),[f]),w.useEffect(()=>{if(u&&c){const g=y=>p(y,c),m=y=>p(y,u);return u.addEventListener("pointerleave",g),c.addEventListener("pointerleave",m),()=>{u.removeEventListener("pointerleave",g),c.removeEventListener("pointerleave",m)}}},[u,c,p,f]),w.useEffect(()=>{if(a){const g=m=>{const y=m.target,v={x:m.clientX,y:m.clientY},_=u?.contains(y)||c?.contains(y),x=!S5(v,a);_?f():x&&(f(),l())};return document.addEventListener("pointermove",g),()=>document.removeEventListener("pointermove",g)}},[u,c,a,l,f]),h.jsx(eA,{...e,ref:o})}),[v5,y5]=ku(Uo,{isInside:!1}),b5=z4("TooltipContent"),eA=w.forwardRef((e,t)=>{const{__scopeTooltip:n,children:i,"aria-label":r,onEscapeKeyDown:o,onPointerDownOutside:a,...s}=e,u=Ea(Ei,n),l=Eu(n),{onClose:c}=u;return w.useEffect(()=>(document.addEventListener(Cd,c),()=>document.removeEventListener(Cd,c)),[c]),w.useEffect(()=>{if(u.trigger){const d=f=>{f.target?.contains(u.trigger)&&c()};return window.addEventListener("scroll",d,{capture:!0}),()=>window.removeEventListener("scroll",d,{capture:!0})}},[u.trigger,c]),h.jsx(cu,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:o,onPointerDownOutside:a,onFocusOutside:d=>d.preventDefault(),onDismiss:c,children:h.jsxs(hT,{"data-state":u.stateAttribute,...l,...s,ref:t,style:{...s.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[h.jsx(b5,{children:i}),h.jsx(v5,{scope:n,isInside:!0,children:h.jsx(c5,{id:u.contentId,role:"tooltip",children:r||i})})]})})});QC.displayName=Ei;var tA="TooltipArrow",nA=w.forwardRef((e,t)=>{const{__scopeTooltip:n,...i}=e,r=Eu(n);return y5(tA,n).isInside?null:h.jsx(mT,{...r,...i,ref:t})});nA.displayName=tA;function _5(e,t){const n=Math.abs(t.top-e.y),i=Math.abs(t.bottom-e.y),r=Math.abs(t.right-e.x),o=Math.abs(t.left-e.x);switch(Math.min(n,i,r,o)){case o:return"left";case r:return"right";case n:return"top";case i:return"bottom";default:throw new Error("unreachable")}}function w5(e,t,n=5){const i=[];switch(t){case"top":i.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":i.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":i.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":i.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return i}function x5(e){const{top:t,right:n,bottom:i,left:r}=e;return[{x:r,y:t},{x:n,y:t},{x:n,y:i},{x:r,y:i}]}function S5(e,t){const{x:n,y:i}=e;let r=!1;for(let o=0,a=t.length-1;o<t.length;a=o++){const s=t[o],u=t[a],l=s.x,c=s.y,d=u.x,f=u.y;c>i!=f>i&&n<(d-l)*(i-c)/(f-c)+l&&(r=!r)}return r}function I5(e){const t=e.slice();return t.sort((n,i)=>n.x<i.x?-1:n.x>i.x?1:n.y<i.y?-1:n.y>i.y?1:0),k5(t)}function k5(e){if(e.length<=1)return e.slice();const t=[];for(let i=0;i<e.length;i++){const r=e[i];for(;t.length>=2;){const o=t[t.length-1],a=t[t.length-2];if((o.x-a.x)*(r.y-a.y)>=(o.y-a.y)*(r.x-a.x))t.pop();else break}t.push(r)}t.pop();const n=[];for(let i=e.length-1;i>=0;i--){const r=e[i];for(;n.length>=2;){const o=n[n.length-1],a=n[n.length-2];if((o.x-a.x)*(r.y-a.y)>=(o.y-a.y)*(r.x-a.x))n.pop();else break}n.push(r)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}var E5=GC,T5=KC,$5=YC,C5=XC,A5=QC,P5=nA;function rA({delayDuration:e=0,...t}){return h.jsx(E5,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function Dh({...e}){return h.jsx(rA,{children:h.jsx(T5,{"data-slot":"tooltip",...e})})}function zh({...e}){return h.jsx($5,{"data-slot":"tooltip-trigger",...e})}function Uh({className:e,sideOffset:t=0,children:n,...i}){return h.jsx(C5,{children:h.jsxs(A5,{"data-slot":"tooltip-content",sideOffset:t,className:R.cn("bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-20 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",e),...i,children:[n,h.jsx(P5,{className:"bg-foreground fill-foreground z-20 size-2.5 translate-y-[calc(-50%-2px)] rotate-45 rounded-[2px]"})]})})}var Tu="Dialog",[iA]=ya(Tu),[R5,hn]=iA(Tu),oA=e=>{const{__scopeDialog:t,children:n,open:i,defaultOpen:r,onOpenChange:o,modal:a=!0}=e,s=w.useRef(null),u=w.useRef(null),[l,c]=gu({prop:i,defaultProp:r??!1,onChange:o,caller:Tu});return h.jsx(R5,{scope:t,triggerRef:s,contentRef:u,contentId:ri(),titleId:ri(),descriptionId:ri(),open:l,onOpenChange:c,onOpenToggle:w.useCallback(()=>c(d=>!d),[c]),modal:a,children:n})};oA.displayName=Tu;var aA="DialogTrigger",sA=w.forwardRef((e,t)=>{const{__scopeDialog:n,...i}=e,r=hn(aA,n),o=Qe(t,r.triggerRef);return h.jsx(Xe.button,{type:"button","aria-haspopup":"dialog","aria-expanded":r.open,"aria-controls":r.contentId,"data-state":Bh(r.open),...i,ref:o,onClick:Pe(e.onClick,r.onOpenToggle)})});sA.displayName=aA;var Lh="DialogPortal",[O5,lA]=iA(Lh,{forceMount:void 0}),uA=e=>{const{__scopeDialog:t,forceMount:n,children:i,container:r}=e,o=hn(Lh,t);return h.jsx(O5,{scope:t,forceMount:n,children:w.Children.map(i,a=>h.jsx(Hn,{present:n||o.open,children:h.jsx(mu,{asChild:!0,container:r,children:a})}))})};uA.displayName=Lh;var rl="DialogOverlay",cA=w.forwardRef((e,t)=>{const n=lA(rl,e.__scopeDialog),{forceMount:i=n.forceMount,...r}=e,o=hn(rl,e.__scopeDialog);return o.modal?h.jsx(Hn,{present:i||o.open,children:h.jsx(j5,{...r,ref:t})}):null});cA.displayName=rl;var N5=Yf("DialogOverlay.RemoveScroll"),j5=w.forwardRef((e,t)=>{const{__scopeDialog:n,...i}=e,r=hn(rl,n);return h.jsx(uh,{as:N5,allowPinchZoom:!0,shards:[r.contentRef],children:h.jsx(Xe.div,{"data-state":Bh(r.open),...i,ref:t,style:{pointerEvents:"auto",...i.style}})})}),Mr="DialogContent",dA=w.forwardRef((e,t)=>{const n=lA(Mr,e.__scopeDialog),{forceMount:i=n.forceMount,...r}=e,o=hn(Mr,e.__scopeDialog);return h.jsx(Hn,{present:i||o.open,children:o.modal?h.jsx(M5,{...r,ref:t}):h.jsx(D5,{...r,ref:t})})});dA.displayName=Mr;var M5=w.forwardRef((e,t)=>{const n=hn(Mr,e.__scopeDialog),i=w.useRef(null),r=Qe(t,n.contentRef,i);return w.useEffect(()=>{const o=i.current;if(o)return vT(o)},[]),h.jsx(pA,{...e,ref:r,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Pe(e.onCloseAutoFocus,o=>{o.preventDefault(),n.triggerRef.current?.focus()}),onPointerDownOutside:Pe(e.onPointerDownOutside,o=>{const a=o.detail.originalEvent,s=a.button===0&&a.ctrlKey===!0;(a.button===2||s)&&o.preventDefault()}),onFocusOutside:Pe(e.onFocusOutside,o=>o.preventDefault())})}),D5=w.forwardRef((e,t)=>{const n=hn(Mr,e.__scopeDialog),i=w.useRef(!1),r=w.useRef(!1);return h.jsx(pA,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{e.onCloseAutoFocus?.(o),o.defaultPrevented||(i.current||n.triggerRef.current?.focus(),o.preventDefault()),i.current=!1,r.current=!1},onInteractOutside:o=>{e.onInteractOutside?.(o),o.defaultPrevented||(i.current=!0,o.detail.originalEvent.type==="pointerdown"&&(r.current=!0));const a=o.target;n.triggerRef.current?.contains(a)&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&r.current&&o.preventDefault()}})}),pA=w.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:i,onOpenAutoFocus:r,onCloseAutoFocus:o,...a}=e,s=hn(Mr,n),u=w.useRef(null),l=Qe(t,u);return qE(),h.jsxs(h.Fragment,{children:[h.jsx(Xf,{asChild:!0,loop:!0,trapped:i,onMountAutoFocus:r,onUnmountAutoFocus:o,children:h.jsx(cu,{role:"dialog",id:s.contentId,"aria-describedby":s.descriptionId,"aria-labelledby":s.titleId,"data-state":Bh(s.open),...a,ref:l,onDismiss:()=>s.onOpenChange(!1)})}),h.jsxs(h.Fragment,{children:[h.jsx(U5,{titleId:s.titleId}),h.jsx(F5,{contentRef:u,descriptionId:s.descriptionId})]})]})}),Fh="DialogTitle",fA=w.forwardRef((e,t)=>{const{__scopeDialog:n,...i}=e,r=hn(Fh,n);return h.jsx(Xe.h2,{id:r.titleId,...i,ref:t})});fA.displayName=Fh;var hA="DialogDescription",z5=w.forwardRef((e,t)=>{const{__scopeDialog:n,...i}=e,r=hn(hA,n);return h.jsx(Xe.p,{id:r.descriptionId,...i,ref:t})});z5.displayName=hA;var mA="DialogClose",gA=w.forwardRef((e,t)=>{const{__scopeDialog:n,...i}=e,r=hn(mA,n);return h.jsx(Xe.button,{type:"button",...i,ref:t,onClick:Pe(e.onClick,()=>r.onOpenChange(!1))})});gA.displayName=mA;function Bh(e){return e?"open":"closed"}var vA="DialogTitleWarning",[yY,yA]=j4(vA,{contentName:Mr,titleName:Fh,docsSlug:"dialog"}),U5=({titleId:e})=>{const t=yA(vA),n=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.
|
|
141
|
-
|
|
142
|
-
If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component.
|
|
143
|
-
|
|
144
|
-
For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return w.useEffect(()=>{e&&(document.getElementById(e)||console.error(n))},[n,e]),null},L5="DialogDescriptionWarning",F5=({contentRef:e,descriptionId:t})=>{const i=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${yA(L5).contentName}}.`;return w.useEffect(()=>{const r=e.current?.getAttribute("aria-describedby");t&&r&&(document.getElementById(t)||console.warn(i))},[i,e,t]),null},B5=oA,Z5=sA,q5=uA,V5=cA,H5=dA,J5=fA,W5=gA;function G5({...e}){return h.jsx(B5,{"data-slot":"dialog",...e})}function K5({...e}){return h.jsx(Z5,{"data-slot":"dialog-trigger",...e})}function Y5({...e}){return h.jsx(q5,{"data-slot":"dialog-portal",...e})}function X5({className:e,...t}){return h.jsx(V5,{"data-slot":"dialog-overlay",className:R.cn("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",e),...t})}function Q5({className:e,children:t,showCloseButton:n=!0,...i}){return h.jsxs(Y5,{"data-slot":"dialog-portal",children:[h.jsx(X5,{}),h.jsxs(H5,{"data-slot":"dialog-content",className:R.cn("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",e),...i,children:[t,n&&h.jsxs(W5,{"data-slot":"dialog-close",className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[h.jsx(xa,{}),h.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function eJ({className:e,...t}){return h.jsx(J5,{"data-slot":"dialog-title",className:R.cn("text-lg leading-none font-semibold",e),...t})}function tJ(e,t=[]){let n=[];function i(o,a){const s=w.createContext(a);s.displayName=o+"Context";const u=n.length;n=[...n,a];const l=d=>{const{scope:f,children:p,...g}=d,m=f?.[e]?.[u]||s,y=w.useMemo(()=>g,Object.values(g));return h.jsx(m.Provider,{value:y,children:p})};l.displayName=o+"Provider";function c(d,f){const p=f?.[e]?.[u]||s,g=w.useContext(p);if(g)return g;if(a!==void 0)return a;throw new Error(`\`${d}\` must be used within \`${o}\``)}return[l,c]}const r=()=>{const o=n.map(a=>w.createContext(a));return function(s){const u=s?.[e]||o;return w.useMemo(()=>({[`__scope${e}`]:{...s,[e]:u}}),[s,u])}};return r.scopeName=e,[i,nJ(r,...t)]}function nJ(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const i=e.map(r=>({useScope:r(),scopeName:r.scopeName}));return function(o){const a=i.reduce((s,{useScope:u,scopeName:l})=>{const d=u(o)[`__scope${l}`];return{...s,...d}},{});return w.useMemo(()=>({[`__scope${t.scopeName}`]:a}),[a])}};return n.scopeName=t.scopeName,n}function rJ(){return HZ.useSyncExternalStore(iJ,()=>!0,()=>!1)}function iJ(){return()=>{}}var Zh="Avatar",[oJ]=tJ(Zh),[aJ,bA]=oJ(Zh),_A=w.forwardRef((e,t)=>{const{__scopeAvatar:n,...i}=e,[r,o]=w.useState("idle");return h.jsx(aJ,{scope:n,imageLoadingStatus:r,onImageLoadingStatusChange:o,children:h.jsx(et.span,{...i,ref:t})})});_A.displayName=Zh;var wA="AvatarImage",xA=w.forwardRef((e,t)=>{const{__scopeAvatar:n,src:i,onLoadingStatusChange:r=()=>{},...o}=e,a=bA(wA,n),s=sJ(i,o),u=Ot(l=>{r(l),a.onImageLoadingStatusChange(l)});return Jt(()=>{s!=="idle"&&u(s)},[s,u]),s==="loaded"?h.jsx(et.img,{...o,ref:t,src:i}):null});xA.displayName=wA;var SA="AvatarFallback",IA=w.forwardRef((e,t)=>{const{__scopeAvatar:n,delayMs:i,...r}=e,o=bA(SA,n),[a,s]=w.useState(i===void 0);return w.useEffect(()=>{if(i!==void 0){const u=window.setTimeout(()=>s(!0),i);return()=>window.clearTimeout(u)}},[i]),a&&o.imageLoadingStatus!=="loaded"?h.jsx(et.span,{...r,ref:t}):null});IA.displayName=SA;function dy(e,t){return e?t?(e.src!==t&&(e.src=t),e.complete&&e.naturalWidth>0?"loaded":"loading"):"error":"idle"}function sJ(e,{referrerPolicy:t,crossOrigin:n}){const i=rJ(),r=w.useRef(null),o=i?(r.current||(r.current=new window.Image),r.current):null,[a,s]=w.useState(()=>dy(o,e));return Jt(()=>{s(dy(o,e))},[o,e]),Jt(()=>{const u=d=>()=>{s(d)};if(!o)return;const l=u("loaded"),c=u("error");return o.addEventListener("load",l),o.addEventListener("error",c),t&&(o.referrerPolicy=t),typeof n=="string"&&(o.crossOrigin=n),()=>{o.removeEventListener("load",l),o.removeEventListener("error",c)}},[o,n,t]),a}var lJ=_A,uJ=xA,cJ=IA;function dJ({className:e,...t}){return h.jsx(lJ,{"data-slot":"avatar",className:R.cn("relative flex size-8 shrink-0 overflow-hidden rounded-full",e),...t})}function pJ({className:e,...t}){return h.jsx(uJ,{"data-slot":"avatar-image",className:R.cn("aspect-square size-full",e),...t})}function fJ({className:e,...t}){return h.jsx(cJ,{"data-slot":"avatar-fallback",className:R.cn("bg-muted flex size-full items-center justify-center rounded-full",e),...t})}const Wt=k.forwardRef(({children:e,tooltip:t,side:n="bottom",align:i="center",className:r,...o},a)=>h.jsxs(Dh,{children:[h.jsx(zh,{asChild:!0,children:h.jsxs(Pt,{variant:"ghost",size:"icon",...o,className:R.cn("aui-button-icon size-6 p-1",r),ref:a,children:[h.jsx(I4,{children:e}),h.jsx("span",{className:"aui-sr-only sr-only",children:t})]})}),h.jsx(Uh,{side:n,align:i,children:t})]}));Wt.displayName="TooltipIconButton";const hJ=e=>{const[t,n]=k.useState(void 0);return k.useEffect(()=>{if(!e){n(void 0);return}const i=URL.createObjectURL(e);return n(i),()=>{URL.revokeObjectURL(i)}},[e]),t},kA=()=>{const{file:e,src:t}=ee(eb.useShallow(({attachment:n})=>{if(n.type!=="image")return{};if(n.file)return{file:n.file};const i=n.content?.filter(r=>r.type==="image")[0]?.image;return i?{src:i}:{}}));return hJ(e)??t},mJ=({src:e})=>{const[t,n]=k.useState(!1);return h.jsx("img",{src:e,alt:"Image Preview",className:t?"aui-attachment-preview-image-loaded block h-auto max-h-[80vh] w-auto max-w-full object-contain":"aui-attachment-preview-image-loading hidden",onLoad:()=>n(!0)})},gJ=({children:e})=>{const t=kA();return t?h.jsxs(G5,{children:[h.jsx(K5,{className:"aui-attachment-preview-trigger hover:bg-accent/50 cursor-pointer transition-colors",asChild:!0,children:e}),h.jsxs(Q5,{className:"aui-attachment-preview-dialog-content [&_svg]:text-background [&>button]:bg-foreground/60 [&>button]:hover:[&_svg]:text-destructive p-2 sm:max-w-3xl [&>button]:rounded-full [&>button]:p-1 [&>button]:opacity-100 [&>button]:!ring-0",children:[h.jsx(eJ,{className:"aui-sr-only sr-only",children:"Image Attachment Preview"}),h.jsx("div",{className:"aui-attachment-preview bg-background relative mx-auto flex max-h-[80dvh] w-full items-center justify-center overflow-hidden",children:h.jsx(mJ,{src:t})})]})]}):e},vJ=()=>{const e=ee(({attachment:n})=>n.type==="image"),t=kA();return h.jsxs(dJ,{className:"aui-attachment-tile-avatar h-full w-full rounded-none",children:[h.jsx(pJ,{src:t,alt:"Attachment preview",className:"aui-attachment-tile-image object-cover"}),h.jsx(fJ,{delayMs:e?200:0,children:h.jsx(tF,{className:"aui-attachment-tile-fallback-icon text-muted-foreground size-8"})})]})},EA=()=>{const t=_e().attachment.source==="composer",n=ee(({attachment:r})=>r.type==="image"),i=ee(({attachment:r})=>{const o=r.type;switch(o){case"image":return"Image";case"document":return"Document";case"file":return"File";default:{const a=o;throw new Error(`Unknown attachment type: ${a}`)}}});return h.jsxs(Dh,{children:[h.jsxs(jT,{className:R.cn("aui-attachment-root relative",n&&"aui-attachment-root-composer only:[&>#attachment-tile]:size-24"),children:[h.jsx(gJ,{children:h.jsx(zh,{asChild:!0,children:h.jsx("div",{className:R.cn("aui-attachment-tile bg-muted size-14 cursor-pointer overflow-hidden rounded-[14px] border transition-opacity hover:opacity-75",t&&"aui-attachment-tile-composer border-foreground/20"),role:"button",id:"attachment-tile","aria-label":`${i} attachment`,children:h.jsx(vJ,{})})})}),t&&h.jsx(yJ,{})]}),h.jsx(Uh,{side:"top",children:h.jsx(MT,{})})]})},yJ=()=>h.jsx(R2,{asChild:!0,children:h.jsx(Wt,{tooltip:"Remove file",className:"aui-attachment-tile-remove text-muted-foreground hover:[&_svg]:text-destructive absolute top-1.5 right-1.5 size-3.5 rounded-full bg-white opacity-100 shadow-sm hover:!bg-white [&_svg]:text-black",side:"top",children:h.jsx(xa,{className:"aui-attachment-remove-icon size-3 dark:stroke-[2.5px]"})})}),bJ=()=>h.jsx("div",{className:"aui-user-message-attachments-end col-span-full col-start-1 row-start-1 flex w-full flex-row justify-end gap-2",children:h.jsx(HT,{components:{Attachment:EA}})}),_J=()=>h.jsx("div",{className:"aui-composer-attachments mb-2 flex w-full flex-row items-center gap-2 overflow-x-auto px-1.5 pt-0.5 pb-1 empty:hidden",children:h.jsx(e0,{components:{Attachment:EA}})}),wJ=()=>h.jsx(y6,{asChild:!0,children:h.jsx(Wt,{tooltip:"Add Attachment",side:"top",variant:"ghost",size:"icon",align:"start",className:"aui-composer-add-attachment hover:bg-muted-foreground/15 dark:border-muted-foreground/15 dark:hover:bg-muted-foreground/30 size-[34px] rounded-full p-1 text-xs font-semibold","aria-label":"Add Attachment",children:h.jsx(g0,{className:"aui-attachment-add-icon size-5 stroke-[1.5px]"})})});function xJ(e,t){const n={};return(e[e.length-1]===""?[...e,""]:e).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const SJ=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,IJ=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,kJ={};function py(e,t){return(kJ.jsx?IJ:SJ).test(e)}const EJ=/[ \t\n\f\r]/g;function TJ(e){return typeof e=="object"?e.type==="text"?fy(e.value):!1:fy(e)}function fy(e){return e.replace(EJ,"")===""}class Ta{constructor(t,n,i){this.normal=n,this.property=t,i&&(this.space=i)}}Ta.prototype.normal={};Ta.prototype.property={};Ta.prototype.space=void 0;function TA(e,t){const n={},i={};for(const r of e)Object.assign(n,r.property),Object.assign(i,r.normal);return new Ta(n,i,t)}function Pd(e){return e.toLowerCase()}class xt{constructor(t,n){this.attribute=n,this.property=t}}xt.prototype.attribute="";xt.prototype.booleanish=!1;xt.prototype.boolean=!1;xt.prototype.commaOrSpaceSeparated=!1;xt.prototype.commaSeparated=!1;xt.prototype.defined=!1;xt.prototype.mustUseProperty=!1;xt.prototype.number=!1;xt.prototype.overloadedBoolean=!1;xt.prototype.property="";xt.prototype.spaceSeparated=!1;xt.prototype.space=void 0;let $J=0;const fe=Zr(),We=Zr(),Rd=Zr(),B=Zr(),je=Zr(),li=Zr(),kt=Zr();function Zr(){return 2**++$J}const Od=Object.freeze(Object.defineProperty({__proto__:null,boolean:fe,booleanish:We,commaOrSpaceSeparated:kt,commaSeparated:li,number:B,overloadedBoolean:Rd,spaceSeparated:je},Symbol.toStringTag,{value:"Module"})),Sc=Object.keys(Od);class qh extends xt{constructor(t,n,i,r){let o=-1;if(super(t,n),hy(this,"space",r),typeof i=="number")for(;++o<Sc.length;){const a=Sc[o];hy(this,Sc[o],(i&Od[a])===Od[a])}}}qh.prototype.defined=!0;function hy(e,t,n){n&&(e[t]=n)}function ji(e){const t={},n={};for(const[i,r]of Object.entries(e.properties)){const o=new qh(i,e.transform(e.attributes||{},i),r,e.space);e.mustUseProperty&&e.mustUseProperty.includes(i)&&(o.mustUseProperty=!0),t[i]=o,n[Pd(i)]=i,n[Pd(o.attribute)]=i}return new Ta(t,n,e.space)}const $A=ji({properties:{ariaActiveDescendant:null,ariaAtomic:We,ariaAutoComplete:null,ariaBusy:We,ariaChecked:We,ariaColCount:B,ariaColIndex:B,ariaColSpan:B,ariaControls:je,ariaCurrent:null,ariaDescribedBy:je,ariaDetails:null,ariaDisabled:We,ariaDropEffect:je,ariaErrorMessage:null,ariaExpanded:We,ariaFlowTo:je,ariaGrabbed:We,ariaHasPopup:null,ariaHidden:We,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:je,ariaLevel:B,ariaLive:null,ariaModal:We,ariaMultiLine:We,ariaMultiSelectable:We,ariaOrientation:null,ariaOwns:je,ariaPlaceholder:null,ariaPosInSet:B,ariaPressed:We,ariaReadOnly:We,ariaRelevant:null,ariaRequired:We,ariaRoleDescription:je,ariaRowCount:B,ariaRowIndex:B,ariaRowSpan:B,ariaSelected:We,ariaSetSize:B,ariaSort:null,ariaValueMax:B,ariaValueMin:B,ariaValueNow:B,ariaValueText:null,role:null},transform(e,t){return t==="role"?t:"aria-"+t.slice(4).toLowerCase()}});function CA(e,t){return t in e?e[t]:t}function AA(e,t){return CA(e,t.toLowerCase())}const CJ=ji({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:li,acceptCharset:je,accessKey:je,action:null,allow:null,allowFullScreen:fe,allowPaymentRequest:fe,allowUserMedia:fe,alt:null,as:null,async:fe,autoCapitalize:null,autoComplete:je,autoFocus:fe,autoPlay:fe,blocking:je,capture:null,charSet:null,checked:fe,cite:null,className:je,cols:B,colSpan:null,content:null,contentEditable:We,controls:fe,controlsList:je,coords:B|li,crossOrigin:null,data:null,dateTime:null,decoding:null,default:fe,defer:fe,dir:null,dirName:null,disabled:fe,download:Rd,draggable:We,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:fe,formTarget:null,headers:je,height:B,hidden:Rd,high:B,href:null,hrefLang:null,htmlFor:je,httpEquiv:je,id:null,imageSizes:null,imageSrcSet:null,inert:fe,inputMode:null,integrity:null,is:null,isMap:fe,itemId:null,itemProp:je,itemRef:je,itemScope:fe,itemType:je,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:fe,low:B,manifest:null,max:null,maxLength:B,media:null,method:null,min:null,minLength:B,multiple:fe,muted:fe,name:null,nonce:null,noModule:fe,noValidate:fe,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:fe,optimum:B,pattern:null,ping:je,placeholder:null,playsInline:fe,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:fe,referrerPolicy:null,rel:je,required:fe,reversed:fe,rows:B,rowSpan:B,sandbox:je,scope:null,scoped:fe,seamless:fe,selected:fe,shadowRootClonable:fe,shadowRootDelegatesFocus:fe,shadowRootMode:null,shape:null,size:B,sizes:null,slot:null,span:B,spellCheck:We,src:null,srcDoc:null,srcLang:null,srcSet:null,start:B,step:null,style:null,tabIndex:B,target:null,title:null,translate:null,type:null,typeMustMatch:fe,useMap:null,value:We,width:B,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:je,axis:null,background:null,bgColor:null,border:B,borderColor:null,bottomMargin:B,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:fe,declare:fe,event:null,face:null,frame:null,frameBorder:null,hSpace:B,leftMargin:B,link:null,longDesc:null,lowSrc:null,marginHeight:B,marginWidth:B,noResize:fe,noHref:fe,noShade:fe,noWrap:fe,object:null,profile:null,prompt:null,rev:null,rightMargin:B,rules:null,scheme:null,scrolling:We,standby:null,summary:null,text:null,topMargin:B,valueType:null,version:null,vAlign:null,vLink:null,vSpace:B,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:fe,disableRemotePlayback:fe,prefix:null,property:null,results:B,security:null,unselectable:null},space:"html",transform:AA}),AJ=ji({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:kt,accentHeight:B,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:B,amplitude:B,arabicForm:null,ascent:B,attributeName:null,attributeType:null,azimuth:B,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:B,by:null,calcMode:null,capHeight:B,className:je,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:B,diffuseConstant:B,direction:null,display:null,dur:null,divisor:B,dominantBaseline:null,download:fe,dx:null,dy:null,edgeMode:null,editable:null,elevation:B,enableBackground:null,end:null,event:null,exponent:B,externalResourcesRequired:null,fill:null,fillOpacity:B,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:li,g2:li,glyphName:li,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:B,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:B,horizOriginX:B,horizOriginY:B,id:null,ideographic:B,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:B,k:B,k1:B,k2:B,k3:B,k4:B,kernelMatrix:kt,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:B,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:B,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:B,overlineThickness:B,paintOrder:null,panose1:null,path:null,pathLength:B,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:je,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:B,pointsAtY:B,pointsAtZ:B,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:kt,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:kt,rev:kt,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:kt,requiredFeatures:kt,requiredFonts:kt,requiredFormats:kt,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:B,specularExponent:B,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:B,strikethroughThickness:B,string:null,stroke:null,strokeDashArray:kt,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:B,strokeOpacity:B,strokeWidth:null,style:null,surfaceScale:B,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:kt,tabIndex:B,tableValues:null,target:null,targetX:B,targetY:B,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:kt,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:B,underlineThickness:B,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:B,values:null,vAlphabetic:B,vMathematical:B,vectorEffect:null,vHanging:B,vIdeographic:B,version:null,vertAdvY:B,vertOriginX:B,vertOriginY:B,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:B,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:CA}),PA=ji({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(e,t){return"xlink:"+t.slice(5).toLowerCase()}}),RA=ji({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:AA}),OA=ji({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,t){return"xml:"+t.slice(3).toLowerCase()}}),PJ={classId:"classID",dataType:"datatype",itemId:"itemID",strokeDashArray:"strokeDasharray",strokeDashOffset:"strokeDashoffset",strokeLineCap:"strokeLinecap",strokeLineJoin:"strokeLinejoin",strokeMiterLimit:"strokeMiterlimit",typeOf:"typeof",xLinkActuate:"xlinkActuate",xLinkArcRole:"xlinkArcrole",xLinkHref:"xlinkHref",xLinkRole:"xlinkRole",xLinkShow:"xlinkShow",xLinkTitle:"xlinkTitle",xLinkType:"xlinkType",xmlnsXLink:"xmlnsXlink"},RJ=/[A-Z]/g,my=/-[a-z]/g,OJ=/^data[-\w.:]+$/i;function NJ(e,t){const n=Pd(t);let i=t,r=xt;if(n in e.normal)return e.property[e.normal[n]];if(n.length>4&&n.slice(0,4)==="data"&&OJ.test(t)){if(t.charAt(4)==="-"){const o=t.slice(5).replace(my,MJ);i="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=t.slice(4);if(!my.test(o)){let a=o.replace(RJ,jJ);a.charAt(0)!=="-"&&(a="-"+a),t="data"+a}}r=qh}return new r(i,t)}function jJ(e){return"-"+e.toLowerCase()}function MJ(e){return e.charAt(1).toUpperCase()}const DJ=TA([$A,CJ,PA,RA,OA],"html"),Vh=TA([$A,AJ,PA,RA,OA],"svg");function zJ(e){return e.join(" ").trim()}var Xr={},Ic,gy;function UJ(){if(gy)return Ic;gy=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,n=/^\s*/,i=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,r=/^:\s*/,o=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,a=/^[;\s]*/,s=/^\s+|\s+$/g,u=`
|
|
145
|
-
`,l="/",c="*",d="",f="comment",p="declaration";function g(y,v){if(typeof y!="string")throw new TypeError("First argument must be a string");if(!y)return[];v=v||{};var _=1,x=1;function b(D){var U=D.match(t);U&&(_+=U.length);var X=D.lastIndexOf(u);x=~X?D.length-X:x+D.length}function C(){var D={line:_,column:x};return function(U){return U.position=new E(D),j(),U}}function E(D){this.start=D,this.end={line:_,column:x},this.source=v.source}E.prototype.content=y;function $(D){var U=new Error(v.source+":"+_+":"+x+": "+D);if(U.reason=D,U.filename=v.source,U.line=_,U.column=x,U.source=y,!v.silent)throw U}function A(D){var U=D.exec(y);if(U){var X=U[0];return b(X),y=y.slice(X.length),U}}function j(){A(n)}function F(D){var U;for(D=D||[];U=z();)U!==!1&&D.push(U);return D}function z(){var D=C();if(!(l!=y.charAt(0)||c!=y.charAt(1))){for(var U=2;d!=y.charAt(U)&&(c!=y.charAt(U)||l!=y.charAt(U+1));)++U;if(U+=2,d===y.charAt(U-1))return $("End of comment missing");var X=y.slice(2,U-2);return x+=2,b(X),y=y.slice(U),x+=2,D({type:f,comment:X})}}function J(){var D=C(),U=A(i);if(U){if(z(),!A(r))return $("property missing ':'");var X=A(o),re=D({type:p,property:m(U[0].replace(e,d)),value:X?m(X[0].replace(e,d)):d});return A(a),re}}function G(){var D=[];F(D);for(var U;U=J();)U!==!1&&(D.push(U),F(D));return D}return j(),G()}function m(y){return y?y.replace(s,d):d}return Ic=g,Ic}var vy;function LJ(){if(vy)return Xr;vy=1;var e=Xr&&Xr.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(Xr,"__esModule",{value:!0}),Xr.default=n;const t=e(UJ());function n(i,r){let o=null;if(!i||typeof i!="string")return o;const a=(0,t.default)(i),s=typeof r=="function";return a.forEach(u=>{if(u.type!=="declaration")return;const{property:l,value:c}=u;s?r(l,c,u):c&&(o=o||{},o[l]=c)}),o}return Xr}var Zi={},yy;function FJ(){if(yy)return Zi;yy=1,Object.defineProperty(Zi,"__esModule",{value:!0}),Zi.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,n=/^[^-]+$/,i=/^-(webkit|moz|ms|o|khtml)-/,r=/^-(ms)-/,o=function(l){return!l||n.test(l)||e.test(l)},a=function(l,c){return c.toUpperCase()},s=function(l,c){return"".concat(c,"-")},u=function(l,c){return c===void 0&&(c={}),o(l)?l:(l=l.toLowerCase(),c.reactCompat?l=l.replace(r,s):l=l.replace(i,s),l.replace(t,a))};return Zi.camelCase=u,Zi}var qi,by;function BJ(){if(by)return qi;by=1;var e=qi&&qi.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},t=e(LJ()),n=FJ();function i(r,o){var a={};return!r||typeof r!="string"||(0,t.default)(r,function(s,u){s&&u&&(a[(0,n.camelCase)(s,o)]=u)}),a}return i.default=i,qi=i,qi}var ZJ=BJ();const qJ=ga(ZJ),NA=jA("end"),Hh=jA("start");function jA(e){return t;function t(n){const i=n&&n.position&&n.position[e]||{};if(typeof i.line=="number"&&i.line>0&&typeof i.column=="number"&&i.column>0)return{line:i.line,column:i.column,offset:typeof i.offset=="number"&&i.offset>-1?i.offset:void 0}}}function VJ(e){const t=Hh(e),n=NA(e);if(t&&n)return{start:t,end:n}}function ao(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?_y(e.position):"start"in e||"end"in e?_y(e):"line"in e||"column"in e?Nd(e):""}function Nd(e){return wy(e&&e.line)+":"+wy(e&&e.column)}function _y(e){return Nd(e&&e.start)+"-"+Nd(e&&e.end)}function wy(e){return e&&typeof e=="number"?e:1}class lt extends Error{constructor(t,n,i){super(),typeof n=="string"&&(i=n,n=void 0);let r="",o={},a=!1;if(n&&("line"in n&&"column"in n?o={place:n}:"start"in n&&"end"in n?o={place:n}:"type"in n?o={ancestors:[n],place:n.position}:o={...n}),typeof t=="string"?r=t:!o.cause&&t&&(a=!0,r=t.message,o.cause=t),!o.ruleId&&!o.source&&typeof i=="string"){const u=i.indexOf(":");u===-1?o.ruleId=i:(o.source=i.slice(0,u),o.ruleId=i.slice(u+1))}if(!o.place&&o.ancestors&&o.ancestors){const u=o.ancestors[o.ancestors.length-1];u&&(o.place=u.position)}const s=o.place&&"start"in o.place?o.place.start:o.place;this.ancestors=o.ancestors||void 0,this.cause=o.cause||void 0,this.column=s?s.column:void 0,this.fatal=void 0,this.file="",this.message=r,this.line=s?s.line:void 0,this.name=ao(o.place)||"1:1",this.place=o.place||void 0,this.reason=this.message,this.ruleId=o.ruleId||void 0,this.source=o.source||void 0,this.stack=a&&o.cause&&typeof o.cause.stack=="string"?o.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}lt.prototype.file="";lt.prototype.name="";lt.prototype.reason="";lt.prototype.message="";lt.prototype.stack="";lt.prototype.column=void 0;lt.prototype.line=void 0;lt.prototype.ancestors=void 0;lt.prototype.cause=void 0;lt.prototype.fatal=void 0;lt.prototype.place=void 0;lt.prototype.ruleId=void 0;lt.prototype.source=void 0;const Jh={}.hasOwnProperty,HJ=new Map,JJ=/[A-Z]/g,WJ=new Set(["table","tbody","thead","tfoot","tr"]),GJ=new Set(["td","th"]),MA="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function KJ(e,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const n=t.filePath||void 0;let i;if(t.development){if(typeof t.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");i=iW(n,t.jsxDEV)}else{if(typeof t.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof t.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");i=rW(n,t.jsx,t.jsxs)}const r={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:i,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:n,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space==="svg"?Vh:DJ,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},o=DA(r,e,void 0);return o&&typeof o!="string"?o:r.create(e,r.Fragment,{children:o||void 0},void 0)}function DA(e,t,n){if(t.type==="element")return YJ(e,t,n);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return XJ(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return eW(e,t,n);if(t.type==="mdxjsEsm")return QJ(e,t);if(t.type==="root")return tW(e,t,n);if(t.type==="text")return nW(e,t)}function YJ(e,t,n){const i=e.schema;let r=i;t.tagName.toLowerCase()==="svg"&&i.space==="html"&&(r=Vh,e.schema=r),e.ancestors.push(t);const o=UA(e,t.tagName,!1),a=oW(e,t);let s=Gh(e,t);return WJ.has(t.tagName)&&(s=s.filter(function(u){return typeof u=="string"?!TJ(u):!0})),zA(e,a,o,t),Wh(a,s),e.ancestors.pop(),e.schema=i,e.create(t,o,a,n)}function XJ(e,t){if(t.data&&t.data.estree&&e.evaluater){const i=t.data.estree.body[0];return i.type,e.evaluater.evaluateExpression(i.expression)}Lo(e,t.position)}function QJ(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);Lo(e,t.position)}function eW(e,t,n){const i=e.schema;let r=i;t.name==="svg"&&i.space==="html"&&(r=Vh,e.schema=r),e.ancestors.push(t);const o=t.name===null?e.Fragment:UA(e,t.name,!0),a=aW(e,t),s=Gh(e,t);return zA(e,a,o,t),Wh(a,s),e.ancestors.pop(),e.schema=i,e.create(t,o,a,n)}function tW(e,t,n){const i={};return Wh(i,Gh(e,t)),e.create(t,e.Fragment,i,n)}function nW(e,t){return t.value}function zA(e,t,n,i){typeof n!="string"&&n!==e.Fragment&&e.passNode&&(t.node=i)}function Wh(e,t){if(t.length>0){const n=t.length>1?t:t[0];n&&(e.children=n)}}function rW(e,t,n){return i;function i(r,o,a,s){const l=Array.isArray(a.children)?n:t;return s?l(o,a,s):l(o,a)}}function iW(e,t){return n;function n(i,r,o,a){const s=Array.isArray(o.children),u=Hh(i);return t(r,o,a,s,{columnNumber:u?u.column-1:void 0,fileName:e,lineNumber:u?u.line:void 0},void 0)}}function oW(e,t){const n={};let i,r;for(r in t.properties)if(r!=="children"&&Jh.call(t.properties,r)){const o=sW(e,r,t.properties[r]);if(o){const[a,s]=o;e.tableCellAlignToStyle&&a==="align"&&typeof s=="string"&&GJ.has(t.tagName)?i=s:n[a]=s}}if(i){const o=n.style||(n.style={});o[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=i}return n}function aW(e,t){const n={};for(const i of t.attributes)if(i.type==="mdxJsxExpressionAttribute")if(i.data&&i.data.estree&&e.evaluater){const o=i.data.estree.body[0];o.type;const a=o.expression;a.type;const s=a.properties[0];s.type,Object.assign(n,e.evaluater.evaluateExpression(s.argument))}else Lo(e,t.position);else{const r=i.name;let o;if(i.value&&typeof i.value=="object")if(i.value.data&&i.value.data.estree&&e.evaluater){const s=i.value.data.estree.body[0];s.type,o=e.evaluater.evaluateExpression(s.expression)}else Lo(e,t.position);else o=i.value===null?!0:i.value;n[r]=o}return n}function Gh(e,t){const n=[];let i=-1;const r=e.passKeys?new Map:HJ;for(;++i<t.children.length;){const o=t.children[i];let a;if(e.passKeys){const u=o.type==="element"?o.tagName:o.type==="mdxJsxFlowElement"||o.type==="mdxJsxTextElement"?o.name:void 0;if(u){const l=r.get(u)||0;a=u+"-"+l,r.set(u,l+1)}}const s=DA(e,o,a);s!==void 0&&n.push(s)}return n}function sW(e,t,n){const i=NJ(e.schema,t);if(!(n==null||typeof n=="number"&&Number.isNaN(n))){if(Array.isArray(n)&&(n=i.commaSeparated?xJ(n):zJ(n)),i.property==="style"){let r=typeof n=="object"?n:lW(e,String(n));return e.stylePropertyNameCase==="css"&&(r=uW(r)),["style",r]}return[e.elementAttributeNameCase==="react"&&i.space?PJ[i.property]||i.property:i.attribute,n]}}function lW(e,t){try{return qJ(t,{reactCompat:!0})}catch(n){if(e.ignoreInvalidStyle)return{};const i=n,r=new lt("Cannot parse `style` attribute",{ancestors:e.ancestors,cause:i,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw r.file=e.filePath||void 0,r.url=MA+"#cannot-parse-style-attribute",r}}function UA(e,t,n){let i;if(!n)i={type:"Literal",value:t};else if(t.includes(".")){const r=t.split(".");let o=-1,a;for(;++o<r.length;){const s=py(r[o])?{type:"Identifier",name:r[o]}:{type:"Literal",value:r[o]};a=a?{type:"MemberExpression",object:a,property:s,computed:!!(o&&s.type==="Literal"),optional:!1}:s}i=a}else i=py(t)&&!/^[a-z]/.test(t)?{type:"Identifier",name:t}:{type:"Literal",value:t};if(i.type==="Literal"){const r=i.value;return Jh.call(e.components,r)?e.components[r]:r}if(e.evaluater)return e.evaluater.evaluateExpression(i);Lo(e)}function Lo(e,t){const n=new lt("Cannot handle MDX estrees without `createEvaluater`",{ancestors:e.ancestors,place:t,ruleId:"mdx-estree",source:"hast-util-to-jsx-runtime"});throw n.file=e.filePath||void 0,n.url=MA+"#cannot-handle-mdx-estrees-without-createevaluater",n}function uW(e){const t={};let n;for(n in e)Jh.call(e,n)&&(t[cW(n)]=e[n]);return t}function cW(e){let t=e.replace(JJ,dW);return t.slice(0,3)==="ms-"&&(t="-"+t),t}function dW(e){return"-"+e.toLowerCase()}const kc={action:["form"],cite:["blockquote","del","ins","q"],data:["object"],formAction:["button","input"],href:["a","area","base","link"],icon:["menuitem"],itemId:null,manifest:["html"],ping:["a","area"],poster:["video"],src:["audio","embed","iframe","img","input","script","source","track","video"]},pW={};function fW(e,t){const n=pW,i=typeof n.includeImageAlt=="boolean"?n.includeImageAlt:!0,r=typeof n.includeHtml=="boolean"?n.includeHtml:!0;return LA(e,i,r)}function LA(e,t,n){if(hW(e)){if("value"in e)return e.type==="html"&&!n?"":e.value;if(t&&"alt"in e&&e.alt)return e.alt;if("children"in e)return xy(e.children,t,n)}return Array.isArray(e)?xy(e,t,n):""}function xy(e,t,n){const i=[];let r=-1;for(;++r<e.length;)i[r]=LA(e[r],t,n);return i.join("")}function hW(e){return!!(e&&typeof e=="object")}const Sy=document.createElement("i");function Kh(e){const t="&"+e+";";Sy.innerHTML=t;const n=Sy.textContent;return n.charCodeAt(n.length-1)===59&&e!=="semi"||n===t?!1:n}function Cn(e,t,n,i){const r=e.length;let o=0,a;if(t<0?t=-t>r?0:r+t:t=t>r?r:t,n=n>0?n:0,i.length<1e4)a=Array.from(i),a.unshift(t,n),e.splice(...a);else for(n&&e.splice(t,n);o<i.length;)a=i.slice(o,o+1e4),a.unshift(t,0),e.splice(...a),o+=1e4,t+=1e4}function qt(e,t){return e.length>0?(Cn(e,e.length,0,t),e):t}const Iy={}.hasOwnProperty;function mW(e){const t={};let n=-1;for(;++n<e.length;)gW(t,e[n]);return t}function gW(e,t){let n;for(n in t){const r=(Iy.call(e,n)?e[n]:void 0)||(e[n]={}),o=t[n];let a;if(o)for(a in o){Iy.call(r,a)||(r[a]=[]);const s=o[a];vW(r[a],Array.isArray(s)?s:s?[s]:[])}}}function vW(e,t){let n=-1;const i=[];for(;++n<t.length;)(t[n].add==="after"?e:i).push(t[n]);Cn(e,0,0,i)}function FA(e,t){const n=Number.parseInt(e,t);return n<9||n===11||n>13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||(n&65535)===65535||(n&65535)===65534||n>1114111?"�":String.fromCodePoint(n)}function ui(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const wn=gr(/[A-Za-z]/),$t=gr(/[\dA-Za-z]/),yW=gr(/[#-'*+\--9=?A-Z^-~]/);function jd(e){return e!==null&&(e<32||e===127)}const Md=gr(/\d/),bW=gr(/[\dA-Fa-f]/),_W=gr(/[!-/:-@[-`{-~]/);function le(e){return e!==null&&e<-2}function wt(e){return e!==null&&(e<0||e===32)}function xe(e){return e===-2||e===-1||e===32}const wW=gr(new RegExp("\\p{P}|\\p{S}","u")),xW=gr(/\s/);function gr(e){return t;function t(n){return n!==null&&n>-1&&e.test(String.fromCharCode(n))}}function Mi(e){const t=[];let n=-1,i=0,r=0;for(;++n<e.length;){const o=e.charCodeAt(n);let a="";if(o===37&&$t(e.charCodeAt(n+1))&&$t(e.charCodeAt(n+2)))r=2;else if(o<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(o))||(a=String.fromCharCode(o));else if(o>55295&&o<57344){const s=e.charCodeAt(n+1);o<56320&&s>56319&&s<57344?(a=String.fromCharCode(o,s),r=1):a="�"}else a=String.fromCharCode(o);a&&(t.push(e.slice(i,n),encodeURIComponent(a)),i=n+r+1,a=""),r&&(n+=r,r=0)}return t.join("")+e.slice(i)}function Me(e,t,n,i){const r=i?i-1:Number.POSITIVE_INFINITY;let o=0;return a;function a(u){return xe(u)?(e.enter(n),s(u)):t(u)}function s(u){return xe(u)&&o++<r?(e.consume(u),s):(e.exit(n),t(u))}}const SW={tokenize:IW};function IW(e){const t=e.attempt(this.parser.constructs.contentInitial,i,r);let n;return t;function i(s){if(s===null){e.consume(s);return}return e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),Me(e,t,"linePrefix")}function r(s){return e.enter("paragraph"),o(s)}function o(s){const u=e.enter("chunkText",{contentType:"text",previous:n});return n&&(n.next=u),n=u,a(s)}function a(s){if(s===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(s);return}return le(s)?(e.consume(s),e.exit("chunkText"),o):(e.consume(s),a)}}const kW={tokenize:EW},ky={tokenize:TW};function EW(e){const t=this,n=[];let i=0,r,o,a;return s;function s(x){if(i<n.length){const b=n[i];return t.containerState=b[1],e.attempt(b[0].continuation,u,l)(x)}return l(x)}function u(x){if(i++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,r&&_();const b=t.events.length;let C=b,E;for(;C--;)if(t.events[C][0]==="exit"&&t.events[C][1].type==="chunkFlow"){E=t.events[C][1].end;break}v(i);let $=b;for(;$<t.events.length;)t.events[$][1].end={...E},$++;return Cn(t.events,C+1,0,t.events.slice(b)),t.events.length=$,l(x)}return s(x)}function l(x){if(i===n.length){if(!r)return f(x);if(r.currentConstruct&&r.currentConstruct.concrete)return g(x);t.interrupt=!!(r.currentConstruct&&!r._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(ky,c,d)(x)}function c(x){return r&&_(),v(i),f(x)}function d(x){return t.parser.lazy[t.now().line]=i!==n.length,a=t.now().offset,g(x)}function f(x){return t.containerState={},e.attempt(ky,p,g)(x)}function p(x){return i++,n.push([t.currentConstruct,t.containerState]),f(x)}function g(x){if(x===null){r&&_(),v(0),e.consume(x);return}return r=r||t.parser.flow(t.now()),e.enter("chunkFlow",{_tokenizer:r,contentType:"flow",previous:o}),m(x)}function m(x){if(x===null){y(e.exit("chunkFlow"),!0),v(0),e.consume(x);return}return le(x)?(e.consume(x),y(e.exit("chunkFlow")),i=0,t.interrupt=void 0,s):(e.consume(x),m)}function y(x,b){const C=t.sliceStream(x);if(b&&C.push(null),x.previous=o,o&&(o.next=x),o=x,r.defineSkip(x.start),r.write(C),t.parser.lazy[x.start.line]){let E=r.events.length;for(;E--;)if(r.events[E][1].start.offset<a&&(!r.events[E][1].end||r.events[E][1].end.offset>a))return;const $=t.events.length;let A=$,j,F;for(;A--;)if(t.events[A][0]==="exit"&&t.events[A][1].type==="chunkFlow"){if(j){F=t.events[A][1].end;break}j=!0}for(v(i),E=$;E<t.events.length;)t.events[E][1].end={...F},E++;Cn(t.events,A+1,0,t.events.slice($)),t.events.length=E}}function v(x){let b=n.length;for(;b-- >x;){const C=n[b];t.containerState=C[1],C[0].exit.call(t,e)}n.length=x}function _(){r.write([null]),o=void 0,r=void 0,t.containerState._closeFlow=void 0}}function TW(e,t,n){return Me(e,e.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function Ey(e){if(e===null||wt(e)||xW(e))return 1;if(wW(e))return 2}function Yh(e,t,n){const i=[];let r=-1;for(;++r<e.length;){const o=e[r].resolveAll;o&&!i.includes(o)&&(t=o(t,n),i.push(o))}return t}const Dd={name:"attention",resolveAll:$W,tokenize:CW};function $W(e,t){let n=-1,i,r,o,a,s,u,l,c;for(;++n<e.length;)if(e[n][0]==="enter"&&e[n][1].type==="attentionSequence"&&e[n][1]._close){for(i=n;i--;)if(e[i][0]==="exit"&&e[i][1].type==="attentionSequence"&&e[i][1]._open&&t.sliceSerialize(e[i][1]).charCodeAt(0)===t.sliceSerialize(e[n][1]).charCodeAt(0)){if((e[i][1]._close||e[n][1]._open)&&(e[n][1].end.offset-e[n][1].start.offset)%3&&!((e[i][1].end.offset-e[i][1].start.offset+e[n][1].end.offset-e[n][1].start.offset)%3))continue;u=e[i][1].end.offset-e[i][1].start.offset>1&&e[n][1].end.offset-e[n][1].start.offset>1?2:1;const d={...e[i][1].end},f={...e[n][1].start};Ty(d,-u),Ty(f,u),a={type:u>1?"strongSequence":"emphasisSequence",start:d,end:{...e[i][1].end}},s={type:u>1?"strongSequence":"emphasisSequence",start:{...e[n][1].start},end:f},o={type:u>1?"strongText":"emphasisText",start:{...e[i][1].end},end:{...e[n][1].start}},r={type:u>1?"strong":"emphasis",start:{...a.start},end:{...s.end}},e[i][1].end={...a.start},e[n][1].start={...s.end},l=[],e[i][1].end.offset-e[i][1].start.offset&&(l=qt(l,[["enter",e[i][1],t],["exit",e[i][1],t]])),l=qt(l,[["enter",r,t],["enter",a,t],["exit",a,t],["enter",o,t]]),l=qt(l,Yh(t.parser.constructs.insideSpan.null,e.slice(i+1,n),t)),l=qt(l,[["exit",o,t],["enter",s,t],["exit",s,t],["exit",r,t]]),e[n][1].end.offset-e[n][1].start.offset?(c=2,l=qt(l,[["enter",e[n][1],t],["exit",e[n][1],t]])):c=0,Cn(e,i-1,n-i+3,l),n=i+l.length-c-2;break}}for(n=-1;++n<e.length;)e[n][1].type==="attentionSequence"&&(e[n][1].type="data");return e}function CW(e,t){const n=this.parser.constructs.attentionMarkers.null,i=this.previous,r=Ey(i);let o;return a;function a(u){return o=u,e.enter("attentionSequence"),s(u)}function s(u){if(u===o)return e.consume(u),s;const l=e.exit("attentionSequence"),c=Ey(u),d=!c||c===2&&r||n.includes(u),f=!r||r===2&&c||n.includes(i);return l._open=!!(o===42?d:d&&(r||!f)),l._close=!!(o===42?f:f&&(c||!d)),t(u)}}function Ty(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}const AW={name:"autolink",tokenize:PW};function PW(e,t,n){let i=0;return r;function r(p){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(p),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),o}function o(p){return wn(p)?(e.consume(p),a):p===64?n(p):l(p)}function a(p){return p===43||p===45||p===46||$t(p)?(i=1,s(p)):l(p)}function s(p){return p===58?(e.consume(p),i=0,u):(p===43||p===45||p===46||$t(p))&&i++<32?(e.consume(p),s):(i=0,l(p))}function u(p){return p===62?(e.exit("autolinkProtocol"),e.enter("autolinkMarker"),e.consume(p),e.exit("autolinkMarker"),e.exit("autolink"),t):p===null||p===32||p===60||jd(p)?n(p):(e.consume(p),u)}function l(p){return p===64?(e.consume(p),c):yW(p)?(e.consume(p),l):n(p)}function c(p){return $t(p)?d(p):n(p)}function d(p){return p===46?(e.consume(p),i=0,c):p===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(p),e.exit("autolinkMarker"),e.exit("autolink"),t):f(p)}function f(p){if((p===45||$t(p))&&i++<63){const g=p===45?f:d;return e.consume(p),g}return n(p)}}const $u={partial:!0,tokenize:RW};function RW(e,t,n){return i;function i(o){return xe(o)?Me(e,r,"linePrefix")(o):r(o)}function r(o){return o===null||le(o)?t(o):n(o)}}const BA={continuation:{tokenize:NW},exit:jW,name:"blockQuote",tokenize:OW};function OW(e,t,n){const i=this;return r;function r(a){if(a===62){const s=i.containerState;return s.open||(e.enter("blockQuote",{_container:!0}),s.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(a),e.exit("blockQuoteMarker"),o}return n(a)}function o(a){return xe(a)?(e.enter("blockQuotePrefixWhitespace"),e.consume(a),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),t):(e.exit("blockQuotePrefix"),t(a))}}function NW(e,t,n){const i=this;return r;function r(a){return xe(a)?Me(e,o,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(a):o(a)}function o(a){return e.attempt(BA,t,n)(a)}}function jW(e){e.exit("blockQuote")}const ZA={name:"characterEscape",tokenize:MW};function MW(e,t,n){return i;function i(o){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(o),e.exit("escapeMarker"),r}function r(o){return _W(o)?(e.enter("characterEscapeValue"),e.consume(o),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):n(o)}}const qA={name:"characterReference",tokenize:DW};function DW(e,t,n){const i=this;let r=0,o,a;return s;function s(d){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(d),e.exit("characterReferenceMarker"),u}function u(d){return d===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(d),e.exit("characterReferenceMarkerNumeric"),l):(e.enter("characterReferenceValue"),o=31,a=$t,c(d))}function l(d){return d===88||d===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(d),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),o=6,a=bW,c):(e.enter("characterReferenceValue"),o=7,a=Md,c(d))}function c(d){if(d===59&&r){const f=e.exit("characterReferenceValue");return a===$t&&!Kh(i.sliceSerialize(f))?n(d):(e.enter("characterReferenceMarker"),e.consume(d),e.exit("characterReferenceMarker"),e.exit("characterReference"),t)}return a(d)&&r++<o?(e.consume(d),c):n(d)}}const $y={partial:!0,tokenize:UW},Cy={concrete:!0,name:"codeFenced",tokenize:zW};function zW(e,t,n){const i=this,r={partial:!0,tokenize:C};let o=0,a=0,s;return u;function u(E){return l(E)}function l(E){const $=i.events[i.events.length-1];return o=$&&$[1].type==="linePrefix"?$[2].sliceSerialize($[1],!0).length:0,s=E,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),c(E)}function c(E){return E===s?(a++,e.consume(E),c):a<3?n(E):(e.exit("codeFencedFenceSequence"),xe(E)?Me(e,d,"whitespace")(E):d(E))}function d(E){return E===null||le(E)?(e.exit("codeFencedFence"),i.interrupt?t(E):e.check($y,m,b)(E)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),f(E))}function f(E){return E===null||le(E)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),d(E)):xe(E)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),Me(e,p,"whitespace")(E)):E===96&&E===s?n(E):(e.consume(E),f)}function p(E){return E===null||le(E)?d(E):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),g(E))}function g(E){return E===null||le(E)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),d(E)):E===96&&E===s?n(E):(e.consume(E),g)}function m(E){return e.attempt(r,b,y)(E)}function y(E){return e.enter("lineEnding"),e.consume(E),e.exit("lineEnding"),v}function v(E){return o>0&&xe(E)?Me(e,_,"linePrefix",o+1)(E):_(E)}function _(E){return E===null||le(E)?e.check($y,m,b)(E):(e.enter("codeFlowValue"),x(E))}function x(E){return E===null||le(E)?(e.exit("codeFlowValue"),_(E)):(e.consume(E),x)}function b(E){return e.exit("codeFenced"),t(E)}function C(E,$,A){let j=0;return F;function F(U){return E.enter("lineEnding"),E.consume(U),E.exit("lineEnding"),z}function z(U){return E.enter("codeFencedFence"),xe(U)?Me(E,J,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(U):J(U)}function J(U){return U===s?(E.enter("codeFencedFenceSequence"),G(U)):A(U)}function G(U){return U===s?(j++,E.consume(U),G):j>=a?(E.exit("codeFencedFenceSequence"),xe(U)?Me(E,D,"whitespace")(U):D(U)):A(U)}function D(U){return U===null||le(U)?(E.exit("codeFencedFence"),$(U)):A(U)}}}function UW(e,t,n){const i=this;return r;function r(a){return a===null?n(a):(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),o)}function o(a){return i.parser.lazy[i.now().line]?n(a):t(a)}}const Ec={name:"codeIndented",tokenize:FW},LW={partial:!0,tokenize:BW};function FW(e,t,n){const i=this;return r;function r(l){return e.enter("codeIndented"),Me(e,o,"linePrefix",5)(l)}function o(l){const c=i.events[i.events.length-1];return c&&c[1].type==="linePrefix"&&c[2].sliceSerialize(c[1],!0).length>=4?a(l):n(l)}function a(l){return l===null?u(l):le(l)?e.attempt(LW,a,u)(l):(e.enter("codeFlowValue"),s(l))}function s(l){return l===null||le(l)?(e.exit("codeFlowValue"),a(l)):(e.consume(l),s)}function u(l){return e.exit("codeIndented"),t(l)}}function BW(e,t,n){const i=this;return r;function r(a){return i.parser.lazy[i.now().line]?n(a):le(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),r):Me(e,o,"linePrefix",5)(a)}function o(a){const s=i.events[i.events.length-1];return s&&s[1].type==="linePrefix"&&s[2].sliceSerialize(s[1],!0).length>=4?t(a):le(a)?r(a):n(a)}}const ZW={name:"codeText",previous:VW,resolve:qW,tokenize:HW};function qW(e){let t=e.length-4,n=3,i,r;if((e[n][1].type==="lineEnding"||e[n][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(i=n;++i<t;)if(e[i][1].type==="codeTextData"){e[n][1].type="codeTextPadding",e[t][1].type="codeTextPadding",n+=2,t-=2;break}}for(i=n-1,t++;++i<=t;)r===void 0?i!==t&&e[i][1].type!=="lineEnding"&&(r=i):(i===t||e[i][1].type==="lineEnding")&&(e[r][1].type="codeTextData",i!==r+2&&(e[r][1].end=e[i-1][1].end,e.splice(r+2,i-r-2),t-=i-r-2,i=r+2),r=void 0);return e}function VW(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function HW(e,t,n){let i=0,r,o;return a;function a(d){return e.enter("codeText"),e.enter("codeTextSequence"),s(d)}function s(d){return d===96?(e.consume(d),i++,s):(e.exit("codeTextSequence"),u(d))}function u(d){return d===null?n(d):d===32?(e.enter("space"),e.consume(d),e.exit("space"),u):d===96?(o=e.enter("codeTextSequence"),r=0,c(d)):le(d)?(e.enter("lineEnding"),e.consume(d),e.exit("lineEnding"),u):(e.enter("codeTextData"),l(d))}function l(d){return d===null||d===32||d===96||le(d)?(e.exit("codeTextData"),u(d)):(e.consume(d),l)}function c(d){return d===96?(e.consume(d),r++,c):r===i?(e.exit("codeTextSequence"),e.exit("codeText"),t(d)):(o.type="codeTextData",l(d))}}class JW{constructor(t){this.left=t?[...t]:[],this.right=[]}get(t){if(t<0||t>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return t<this.left.length?this.left[t]:this.right[this.right.length-t+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(t,n){const i=n??Number.POSITIVE_INFINITY;return i<this.left.length?this.left.slice(t,i):t>this.left.length?this.right.slice(this.right.length-i+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-i+this.left.length).reverse())}splice(t,n,i){const r=n||0;this.setCursor(Math.trunc(t));const o=this.right.splice(this.right.length-r,Number.POSITIVE_INFINITY);return i&&Vi(this.left,i),o.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),Vi(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),Vi(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t<this.left.length){const n=this.left.splice(t,Number.POSITIVE_INFINITY);Vi(this.right,n.reverse())}else{const n=this.right.splice(this.left.length+this.right.length-t,Number.POSITIVE_INFINITY);Vi(this.left,n.reverse())}}}function Vi(e,t){let n=0;if(t.length<1e4)e.push(...t);else for(;n<t.length;)e.push(...t.slice(n,n+1e4)),n+=1e4}function VA(e){const t={};let n=-1,i,r,o,a,s,u,l;const c=new JW(e);for(;++n<c.length;){for(;n in t;)n=t[n];if(i=c.get(n),n&&i[1].type==="chunkFlow"&&c.get(n-1)[1].type==="listItemPrefix"&&(u=i[1]._tokenizer.events,o=0,o<u.length&&u[o][1].type==="lineEndingBlank"&&(o+=2),o<u.length&&u[o][1].type==="content"))for(;++o<u.length&&u[o][1].type!=="content";)u[o][1].type==="chunkText"&&(u[o][1]._isInFirstContentOfListItem=!0,o++);if(i[0]==="enter")i[1].contentType&&(Object.assign(t,WW(c,n)),n=t[n],l=!0);else if(i[1]._container){for(o=n,r=void 0;o--;)if(a=c.get(o),a[1].type==="lineEnding"||a[1].type==="lineEndingBlank")a[0]==="enter"&&(r&&(c.get(r)[1].type="lineEndingBlank"),a[1].type="lineEnding",r=o);else if(!(a[1].type==="linePrefix"||a[1].type==="listItemIndent"))break;r&&(i[1].end={...c.get(r)[1].start},s=c.slice(r,n),s.unshift(i),c.splice(r,n-r+1,s))}}return Cn(e,0,Number.POSITIVE_INFINITY,c.slice(0)),!l}function WW(e,t){const n=e.get(t)[1],i=e.get(t)[2];let r=t-1;const o=[];let a=n._tokenizer;a||(a=i.parser[n.contentType](n.start),n._contentTypeTextTrailing&&(a._contentTypeTextTrailing=!0));const s=a.events,u=[],l={};let c,d,f=-1,p=n,g=0,m=0;const y=[m];for(;p;){for(;e.get(++r)[1]!==p;);o.push(r),p._tokenizer||(c=i.sliceStream(p),p.next||c.push(null),d&&a.defineSkip(p.start),p._isInFirstContentOfListItem&&(a._gfmTasklistFirstContentOfListItem=!0),a.write(c),p._isInFirstContentOfListItem&&(a._gfmTasklistFirstContentOfListItem=void 0)),d=p,p=p.next}for(p=n;++f<s.length;)s[f][0]==="exit"&&s[f-1][0]==="enter"&&s[f][1].type===s[f-1][1].type&&s[f][1].start.line!==s[f][1].end.line&&(m=f+1,y.push(m),p._tokenizer=void 0,p.previous=void 0,p=p.next);for(a.events=[],p?(p._tokenizer=void 0,p.previous=void 0):y.pop(),f=y.length;f--;){const v=s.slice(y[f],y[f+1]),_=o.pop();u.push([_,_+v.length-1]),e.splice(_,2,v)}for(u.reverse(),f=-1;++f<u.length;)l[g+u[f][0]]=g+u[f][1],g+=u[f][1]-u[f][0]-1;return l}const GW={resolve:YW,tokenize:XW},KW={partial:!0,tokenize:QW};function YW(e){return VA(e),e}function XW(e,t){let n;return i;function i(s){return e.enter("content"),n=e.enter("chunkContent",{contentType:"content"}),r(s)}function r(s){return s===null?o(s):le(s)?e.check(KW,a,o)(s):(e.consume(s),r)}function o(s){return e.exit("chunkContent"),e.exit("content"),t(s)}function a(s){return e.consume(s),e.exit("chunkContent"),n.next=e.enter("chunkContent",{contentType:"content",previous:n}),n=n.next,r}}function QW(e,t,n){const i=this;return r;function r(a){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),Me(e,o,"linePrefix")}function o(a){if(a===null||le(a))return n(a);const s=i.events[i.events.length-1];return!i.parser.constructs.disable.null.includes("codeIndented")&&s&&s[1].type==="linePrefix"&&s[2].sliceSerialize(s[1],!0).length>=4?t(a):e.interrupt(i.parser.constructs.flow,n,t)(a)}}function HA(e,t,n,i,r,o,a,s,u){const l=u||Number.POSITIVE_INFINITY;let c=0;return d;function d(v){return v===60?(e.enter(i),e.enter(r),e.enter(o),e.consume(v),e.exit(o),f):v===null||v===32||v===41||jd(v)?n(v):(e.enter(i),e.enter(a),e.enter(s),e.enter("chunkString",{contentType:"string"}),m(v))}function f(v){return v===62?(e.enter(o),e.consume(v),e.exit(o),e.exit(r),e.exit(i),t):(e.enter(s),e.enter("chunkString",{contentType:"string"}),p(v))}function p(v){return v===62?(e.exit("chunkString"),e.exit(s),f(v)):v===null||v===60||le(v)?n(v):(e.consume(v),v===92?g:p)}function g(v){return v===60||v===62||v===92?(e.consume(v),p):p(v)}function m(v){return!c&&(v===null||v===41||wt(v))?(e.exit("chunkString"),e.exit(s),e.exit(a),e.exit(i),t(v)):c<l&&v===40?(e.consume(v),c++,m):v===41?(e.consume(v),c--,m):v===null||v===32||v===40||jd(v)?n(v):(e.consume(v),v===92?y:m)}function y(v){return v===40||v===41||v===92?(e.consume(v),m):m(v)}}function JA(e,t,n,i,r,o){const a=this;let s=0,u;return l;function l(p){return e.enter(i),e.enter(r),e.consume(p),e.exit(r),e.enter(o),c}function c(p){return s>999||p===null||p===91||p===93&&!u||p===94&&!s&&"_hiddenFootnoteSupport"in a.parser.constructs?n(p):p===93?(e.exit(o),e.enter(r),e.consume(p),e.exit(r),e.exit(i),t):le(p)?(e.enter("lineEnding"),e.consume(p),e.exit("lineEnding"),c):(e.enter("chunkString",{contentType:"string"}),d(p))}function d(p){return p===null||p===91||p===93||le(p)||s++>999?(e.exit("chunkString"),c(p)):(e.consume(p),u||(u=!xe(p)),p===92?f:d)}function f(p){return p===91||p===92||p===93?(e.consume(p),s++,d):d(p)}}function WA(e,t,n,i,r,o){let a;return s;function s(f){return f===34||f===39||f===40?(e.enter(i),e.enter(r),e.consume(f),e.exit(r),a=f===40?41:f,u):n(f)}function u(f){return f===a?(e.enter(r),e.consume(f),e.exit(r),e.exit(i),t):(e.enter(o),l(f))}function l(f){return f===a?(e.exit(o),u(a)):f===null?n(f):le(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),Me(e,l,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),c(f))}function c(f){return f===a||f===null||le(f)?(e.exit("chunkString"),l(f)):(e.consume(f),f===92?d:c)}function d(f){return f===a||f===92?(e.consume(f),c):c(f)}}function so(e,t){let n;return i;function i(r){return le(r)?(e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),n=!0,i):xe(r)?Me(e,i,n?"linePrefix":"lineSuffix")(r):t(r)}}const eG={name:"definition",tokenize:nG},tG={partial:!0,tokenize:rG};function nG(e,t,n){const i=this;let r;return o;function o(p){return e.enter("definition"),a(p)}function a(p){return JA.call(i,e,s,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function s(p){return r=ui(i.sliceSerialize(i.events[i.events.length-1][1]).slice(1,-1)),p===58?(e.enter("definitionMarker"),e.consume(p),e.exit("definitionMarker"),u):n(p)}function u(p){return wt(p)?so(e,l)(p):l(p)}function l(p){return HA(e,c,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function c(p){return e.attempt(tG,d,d)(p)}function d(p){return xe(p)?Me(e,f,"whitespace")(p):f(p)}function f(p){return p===null||le(p)?(e.exit("definition"),i.parser.defined.push(r),t(p)):n(p)}}function rG(e,t,n){return i;function i(s){return wt(s)?so(e,r)(s):n(s)}function r(s){return WA(e,o,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(s)}function o(s){return xe(s)?Me(e,a,"whitespace")(s):a(s)}function a(s){return s===null||le(s)?t(s):n(s)}}const iG={name:"hardBreakEscape",tokenize:oG};function oG(e,t,n){return i;function i(o){return e.enter("hardBreakEscape"),e.consume(o),r}function r(o){return le(o)?(e.exit("hardBreakEscape"),t(o)):n(o)}}const aG={name:"headingAtx",resolve:sG,tokenize:lG};function sG(e,t){let n=e.length-2,i=3,r,o;return e[i][1].type==="whitespace"&&(i+=2),n-2>i&&e[n][1].type==="whitespace"&&(n-=2),e[n][1].type==="atxHeadingSequence"&&(i===n-1||n-4>i&&e[n-2][1].type==="whitespace")&&(n-=i+1===n?2:4),n>i&&(r={type:"atxHeadingText",start:e[i][1].start,end:e[n][1].end},o={type:"chunkText",start:e[i][1].start,end:e[n][1].end,contentType:"text"},Cn(e,i,n-i+1,[["enter",r,t],["enter",o,t],["exit",o,t],["exit",r,t]])),e}function lG(e,t,n){let i=0;return r;function r(c){return e.enter("atxHeading"),o(c)}function o(c){return e.enter("atxHeadingSequence"),a(c)}function a(c){return c===35&&i++<6?(e.consume(c),a):c===null||wt(c)?(e.exit("atxHeadingSequence"),s(c)):n(c)}function s(c){return c===35?(e.enter("atxHeadingSequence"),u(c)):c===null||le(c)?(e.exit("atxHeading"),t(c)):xe(c)?Me(e,s,"whitespace")(c):(e.enter("atxHeadingText"),l(c))}function u(c){return c===35?(e.consume(c),u):(e.exit("atxHeadingSequence"),s(c))}function l(c){return c===null||c===35||wt(c)?(e.exit("atxHeadingText"),s(c)):(e.consume(c),l)}}const uG=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],Ay=["pre","script","style","textarea"],cG={concrete:!0,name:"htmlFlow",resolveTo:fG,tokenize:hG},dG={partial:!0,tokenize:gG},pG={partial:!0,tokenize:mG};function fG(e){let t=e.length;for(;t--&&!(e[t][0]==="enter"&&e[t][1].type==="htmlFlow"););return t>1&&e[t-2][1].type==="linePrefix"&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function hG(e,t,n){const i=this;let r,o,a,s,u;return l;function l(T){return c(T)}function c(T){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(T),d}function d(T){return T===33?(e.consume(T),f):T===47?(e.consume(T),o=!0,m):T===63?(e.consume(T),r=3,i.interrupt?t:S):wn(T)?(e.consume(T),a=String.fromCharCode(T),y):n(T)}function f(T){return T===45?(e.consume(T),r=2,p):T===91?(e.consume(T),r=5,s=0,g):wn(T)?(e.consume(T),r=4,i.interrupt?t:S):n(T)}function p(T){return T===45?(e.consume(T),i.interrupt?t:S):n(T)}function g(T){const V="CDATA[";return T===V.charCodeAt(s++)?(e.consume(T),s===V.length?i.interrupt?t:J:g):n(T)}function m(T){return wn(T)?(e.consume(T),a=String.fromCharCode(T),y):n(T)}function y(T){if(T===null||T===47||T===62||wt(T)){const V=T===47,ne=a.toLowerCase();return!V&&!o&&Ay.includes(ne)?(r=1,i.interrupt?t(T):J(T)):uG.includes(a.toLowerCase())?(r=6,V?(e.consume(T),v):i.interrupt?t(T):J(T)):(r=7,i.interrupt&&!i.parser.lazy[i.now().line]?n(T):o?_(T):x(T))}return T===45||$t(T)?(e.consume(T),a+=String.fromCharCode(T),y):n(T)}function v(T){return T===62?(e.consume(T),i.interrupt?t:J):n(T)}function _(T){return xe(T)?(e.consume(T),_):F(T)}function x(T){return T===47?(e.consume(T),F):T===58||T===95||wn(T)?(e.consume(T),b):xe(T)?(e.consume(T),x):F(T)}function b(T){return T===45||T===46||T===58||T===95||$t(T)?(e.consume(T),b):C(T)}function C(T){return T===61?(e.consume(T),E):xe(T)?(e.consume(T),C):x(T)}function E(T){return T===null||T===60||T===61||T===62||T===96?n(T):T===34||T===39?(e.consume(T),u=T,$):xe(T)?(e.consume(T),E):A(T)}function $(T){return T===u?(e.consume(T),u=null,j):T===null||le(T)?n(T):(e.consume(T),$)}function A(T){return T===null||T===34||T===39||T===47||T===60||T===61||T===62||T===96||wt(T)?C(T):(e.consume(T),A)}function j(T){return T===47||T===62||xe(T)?x(T):n(T)}function F(T){return T===62?(e.consume(T),z):n(T)}function z(T){return T===null||le(T)?J(T):xe(T)?(e.consume(T),z):n(T)}function J(T){return T===45&&r===2?(e.consume(T),X):T===60&&r===1?(e.consume(T),re):T===62&&r===4?(e.consume(T),Ae):T===63&&r===3?(e.consume(T),S):T===93&&r===5?(e.consume(T),me):le(T)&&(r===6||r===7)?(e.exit("htmlFlowData"),e.check(dG,ye,G)(T)):T===null||le(T)?(e.exit("htmlFlowData"),G(T)):(e.consume(T),J)}function G(T){return e.check(pG,D,ye)(T)}function D(T){return e.enter("lineEnding"),e.consume(T),e.exit("lineEnding"),U}function U(T){return T===null||le(T)?G(T):(e.enter("htmlFlowData"),J(T))}function X(T){return T===45?(e.consume(T),S):J(T)}function re(T){return T===47?(e.consume(T),a="",Q):J(T)}function Q(T){if(T===62){const V=a.toLowerCase();return Ay.includes(V)?(e.consume(T),Ae):J(T)}return wn(T)&&a.length<8?(e.consume(T),a+=String.fromCharCode(T),Q):J(T)}function me(T){return T===93?(e.consume(T),S):J(T)}function S(T){return T===62?(e.consume(T),Ae):T===45&&r===2?(e.consume(T),S):J(T)}function Ae(T){return T===null||le(T)?(e.exit("htmlFlowData"),ye(T)):(e.consume(T),Ae)}function ye(T){return e.exit("htmlFlow"),t(T)}}function mG(e,t,n){const i=this;return r;function r(a){return le(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),o):n(a)}function o(a){return i.parser.lazy[i.now().line]?n(a):t(a)}}function gG(e,t,n){return i;function i(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),e.attempt($u,t,n)}}const vG={name:"htmlText",tokenize:yG};function yG(e,t,n){const i=this;let r,o,a;return s;function s(S){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(S),u}function u(S){return S===33?(e.consume(S),l):S===47?(e.consume(S),C):S===63?(e.consume(S),x):wn(S)?(e.consume(S),A):n(S)}function l(S){return S===45?(e.consume(S),c):S===91?(e.consume(S),o=0,g):wn(S)?(e.consume(S),_):n(S)}function c(S){return S===45?(e.consume(S),p):n(S)}function d(S){return S===null?n(S):S===45?(e.consume(S),f):le(S)?(a=d,re(S)):(e.consume(S),d)}function f(S){return S===45?(e.consume(S),p):d(S)}function p(S){return S===62?X(S):S===45?f(S):d(S)}function g(S){const Ae="CDATA[";return S===Ae.charCodeAt(o++)?(e.consume(S),o===Ae.length?m:g):n(S)}function m(S){return S===null?n(S):S===93?(e.consume(S),y):le(S)?(a=m,re(S)):(e.consume(S),m)}function y(S){return S===93?(e.consume(S),v):m(S)}function v(S){return S===62?X(S):S===93?(e.consume(S),v):m(S)}function _(S){return S===null||S===62?X(S):le(S)?(a=_,re(S)):(e.consume(S),_)}function x(S){return S===null?n(S):S===63?(e.consume(S),b):le(S)?(a=x,re(S)):(e.consume(S),x)}function b(S){return S===62?X(S):x(S)}function C(S){return wn(S)?(e.consume(S),E):n(S)}function E(S){return S===45||$t(S)?(e.consume(S),E):$(S)}function $(S){return le(S)?(a=$,re(S)):xe(S)?(e.consume(S),$):X(S)}function A(S){return S===45||$t(S)?(e.consume(S),A):S===47||S===62||wt(S)?j(S):n(S)}function j(S){return S===47?(e.consume(S),X):S===58||S===95||wn(S)?(e.consume(S),F):le(S)?(a=j,re(S)):xe(S)?(e.consume(S),j):X(S)}function F(S){return S===45||S===46||S===58||S===95||$t(S)?(e.consume(S),F):z(S)}function z(S){return S===61?(e.consume(S),J):le(S)?(a=z,re(S)):xe(S)?(e.consume(S),z):j(S)}function J(S){return S===null||S===60||S===61||S===62||S===96?n(S):S===34||S===39?(e.consume(S),r=S,G):le(S)?(a=J,re(S)):xe(S)?(e.consume(S),J):(e.consume(S),D)}function G(S){return S===r?(e.consume(S),r=void 0,U):S===null?n(S):le(S)?(a=G,re(S)):(e.consume(S),G)}function D(S){return S===null||S===34||S===39||S===60||S===61||S===96?n(S):S===47||S===62||wt(S)?j(S):(e.consume(S),D)}function U(S){return S===47||S===62||wt(S)?j(S):n(S)}function X(S){return S===62?(e.consume(S),e.exit("htmlTextData"),e.exit("htmlText"),t):n(S)}function re(S){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(S),e.exit("lineEnding"),Q}function Q(S){return xe(S)?Me(e,me,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(S):me(S)}function me(S){return e.enter("htmlTextData"),a(S)}}const Xh={name:"labelEnd",resolveAll:xG,resolveTo:SG,tokenize:IG},bG={tokenize:kG},_G={tokenize:EG},wG={tokenize:TG};function xG(e){let t=-1;const n=[];for(;++t<e.length;){const i=e[t][1];if(n.push(e[t]),i.type==="labelImage"||i.type==="labelLink"||i.type==="labelEnd"){const r=i.type==="labelImage"?4:2;i.type="data",t+=r}}return e.length!==n.length&&Cn(e,0,e.length,n),e}function SG(e,t){let n=e.length,i=0,r,o,a,s;for(;n--;)if(r=e[n][1],o){if(r.type==="link"||r.type==="labelLink"&&r._inactive)break;e[n][0]==="enter"&&r.type==="labelLink"&&(r._inactive=!0)}else if(a){if(e[n][0]==="enter"&&(r.type==="labelImage"||r.type==="labelLink")&&!r._balanced&&(o=n,r.type!=="labelLink")){i=2;break}}else r.type==="labelEnd"&&(a=n);const u={type:e[o][1].type==="labelLink"?"link":"image",start:{...e[o][1].start},end:{...e[e.length-1][1].end}},l={type:"label",start:{...e[o][1].start},end:{...e[a][1].end}},c={type:"labelText",start:{...e[o+i+2][1].end},end:{...e[a-2][1].start}};return s=[["enter",u,t],["enter",l,t]],s=qt(s,e.slice(o+1,o+i+3)),s=qt(s,[["enter",c,t]]),s=qt(s,Yh(t.parser.constructs.insideSpan.null,e.slice(o+i+4,a-3),t)),s=qt(s,[["exit",c,t],e[a-2],e[a-1],["exit",l,t]]),s=qt(s,e.slice(a+1)),s=qt(s,[["exit",u,t]]),Cn(e,o,e.length,s),e}function IG(e,t,n){const i=this;let r=i.events.length,o,a;for(;r--;)if((i.events[r][1].type==="labelImage"||i.events[r][1].type==="labelLink")&&!i.events[r][1]._balanced){o=i.events[r][1];break}return s;function s(f){return o?o._inactive?d(f):(a=i.parser.defined.includes(ui(i.sliceSerialize({start:o.end,end:i.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(f),e.exit("labelMarker"),e.exit("labelEnd"),u):n(f)}function u(f){return f===40?e.attempt(bG,c,a?c:d)(f):f===91?e.attempt(_G,c,a?l:d)(f):a?c(f):d(f)}function l(f){return e.attempt(wG,c,d)(f)}function c(f){return t(f)}function d(f){return o._balanced=!0,n(f)}}function kG(e,t,n){return i;function i(d){return e.enter("resource"),e.enter("resourceMarker"),e.consume(d),e.exit("resourceMarker"),r}function r(d){return wt(d)?so(e,o)(d):o(d)}function o(d){return d===41?c(d):HA(e,a,s,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(d)}function a(d){return wt(d)?so(e,u)(d):c(d)}function s(d){return n(d)}function u(d){return d===34||d===39||d===40?WA(e,l,n,"resourceTitle","resourceTitleMarker","resourceTitleString")(d):c(d)}function l(d){return wt(d)?so(e,c)(d):c(d)}function c(d){return d===41?(e.enter("resourceMarker"),e.consume(d),e.exit("resourceMarker"),e.exit("resource"),t):n(d)}}function EG(e,t,n){const i=this;return r;function r(s){return JA.call(i,e,o,a,"reference","referenceMarker","referenceString")(s)}function o(s){return i.parser.defined.includes(ui(i.sliceSerialize(i.events[i.events.length-1][1]).slice(1,-1)))?t(s):n(s)}function a(s){return n(s)}}function TG(e,t,n){return i;function i(o){return e.enter("reference"),e.enter("referenceMarker"),e.consume(o),e.exit("referenceMarker"),r}function r(o){return o===93?(e.enter("referenceMarker"),e.consume(o),e.exit("referenceMarker"),e.exit("reference"),t):n(o)}}const $G={name:"labelStartImage",resolveAll:Xh.resolveAll,tokenize:CG};function CG(e,t,n){const i=this;return r;function r(s){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(s),e.exit("labelImageMarker"),o}function o(s){return s===91?(e.enter("labelMarker"),e.consume(s),e.exit("labelMarker"),e.exit("labelImage"),a):n(s)}function a(s){return s===94&&"_hiddenFootnoteSupport"in i.parser.constructs?n(s):t(s)}}const AG={name:"labelStartLink",resolveAll:Xh.resolveAll,tokenize:PG};function PG(e,t,n){const i=this;return r;function r(a){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(a),e.exit("labelMarker"),e.exit("labelLink"),o}function o(a){return a===94&&"_hiddenFootnoteSupport"in i.parser.constructs?n(a):t(a)}}const Tc={name:"lineEnding",tokenize:RG};function RG(e,t){return n;function n(i){return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),Me(e,t,"linePrefix")}}const vs={name:"thematicBreak",tokenize:OG};function OG(e,t,n){let i=0,r;return o;function o(l){return e.enter("thematicBreak"),a(l)}function a(l){return r=l,s(l)}function s(l){return l===r?(e.enter("thematicBreakSequence"),u(l)):i>=3&&(l===null||le(l))?(e.exit("thematicBreak"),t(l)):n(l)}function u(l){return l===r?(e.consume(l),i++,u):(e.exit("thematicBreakSequence"),xe(l)?Me(e,s,"whitespace")(l):s(l))}}const vt={continuation:{tokenize:DG},exit:UG,name:"list",tokenize:MG},NG={partial:!0,tokenize:LG},jG={partial:!0,tokenize:zG};function MG(e,t,n){const i=this,r=i.events[i.events.length-1];let o=r&&r[1].type==="linePrefix"?r[2].sliceSerialize(r[1],!0).length:0,a=0;return s;function s(p){const g=i.containerState.type||(p===42||p===43||p===45?"listUnordered":"listOrdered");if(g==="listUnordered"?!i.containerState.marker||p===i.containerState.marker:Md(p)){if(i.containerState.type||(i.containerState.type=g,e.enter(g,{_container:!0})),g==="listUnordered")return e.enter("listItemPrefix"),p===42||p===45?e.check(vs,n,l)(p):l(p);if(!i.interrupt||p===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),u(p)}return n(p)}function u(p){return Md(p)&&++a<10?(e.consume(p),u):(!i.interrupt||a<2)&&(i.containerState.marker?p===i.containerState.marker:p===41||p===46)?(e.exit("listItemValue"),l(p)):n(p)}function l(p){return e.enter("listItemMarker"),e.consume(p),e.exit("listItemMarker"),i.containerState.marker=i.containerState.marker||p,e.check($u,i.interrupt?n:c,e.attempt(NG,f,d))}function c(p){return i.containerState.initialBlankLine=!0,o++,f(p)}function d(p){return xe(p)?(e.enter("listItemPrefixWhitespace"),e.consume(p),e.exit("listItemPrefixWhitespace"),f):n(p)}function f(p){return i.containerState.size=o+i.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(p)}}function DG(e,t,n){const i=this;return i.containerState._closeFlow=void 0,e.check($u,r,o);function r(s){return i.containerState.furtherBlankLines=i.containerState.furtherBlankLines||i.containerState.initialBlankLine,Me(e,t,"listItemIndent",i.containerState.size+1)(s)}function o(s){return i.containerState.furtherBlankLines||!xe(s)?(i.containerState.furtherBlankLines=void 0,i.containerState.initialBlankLine=void 0,a(s)):(i.containerState.furtherBlankLines=void 0,i.containerState.initialBlankLine=void 0,e.attempt(jG,t,a)(s))}function a(s){return i.containerState._closeFlow=!0,i.interrupt=void 0,Me(e,e.attempt(vt,t,n),"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(s)}}function zG(e,t,n){const i=this;return Me(e,r,"listItemIndent",i.containerState.size+1);function r(o){const a=i.events[i.events.length-1];return a&&a[1].type==="listItemIndent"&&a[2].sliceSerialize(a[1],!0).length===i.containerState.size?t(o):n(o)}}function UG(e){e.exit(this.containerState.type)}function LG(e,t,n){const i=this;return Me(e,r,"listItemPrefixWhitespace",i.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function r(o){const a=i.events[i.events.length-1];return!xe(o)&&a&&a[1].type==="listItemPrefixWhitespace"?t(o):n(o)}}const Py={name:"setextUnderline",resolveTo:FG,tokenize:BG};function FG(e,t){let n=e.length,i,r,o;for(;n--;)if(e[n][0]==="enter"){if(e[n][1].type==="content"){i=n;break}e[n][1].type==="paragraph"&&(r=n)}else e[n][1].type==="content"&&e.splice(n,1),!o&&e[n][1].type==="definition"&&(o=n);const a={type:"setextHeading",start:{...e[i][1].start},end:{...e[e.length-1][1].end}};return e[r][1].type="setextHeadingText",o?(e.splice(r,0,["enter",a,t]),e.splice(o+1,0,["exit",e[i][1],t]),e[i][1].end={...e[o][1].end}):e[i][1]=a,e.push(["exit",a,t]),e}function BG(e,t,n){const i=this;let r;return o;function o(l){let c=i.events.length,d;for(;c--;)if(i.events[c][1].type!=="lineEnding"&&i.events[c][1].type!=="linePrefix"&&i.events[c][1].type!=="content"){d=i.events[c][1].type==="paragraph";break}return!i.parser.lazy[i.now().line]&&(i.interrupt||d)?(e.enter("setextHeadingLine"),r=l,a(l)):n(l)}function a(l){return e.enter("setextHeadingLineSequence"),s(l)}function s(l){return l===r?(e.consume(l),s):(e.exit("setextHeadingLineSequence"),xe(l)?Me(e,u,"lineSuffix")(l):u(l))}function u(l){return l===null||le(l)?(e.exit("setextHeadingLine"),t(l)):n(l)}}const ZG={tokenize:qG};function qG(e){const t=this,n=e.attempt($u,i,e.attempt(this.parser.constructs.flowInitial,r,Me(e,e.attempt(this.parser.constructs.flow,r,e.attempt(GW,r)),"linePrefix")));return n;function i(o){if(o===null){e.consume(o);return}return e.enter("lineEndingBlank"),e.consume(o),e.exit("lineEndingBlank"),t.currentConstruct=void 0,n}function r(o){if(o===null){e.consume(o);return}return e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),t.currentConstruct=void 0,n}}const VG={resolveAll:KA()},HG=GA("string"),JG=GA("text");function GA(e){return{resolveAll:KA(e==="text"?WG:void 0),tokenize:t};function t(n){const i=this,r=this.parser.constructs[e],o=n.attempt(r,a,s);return a;function a(c){return l(c)?o(c):s(c)}function s(c){if(c===null){n.consume(c);return}return n.enter("data"),n.consume(c),u}function u(c){return l(c)?(n.exit("data"),o(c)):(n.consume(c),u)}function l(c){if(c===null)return!0;const d=r[c];let f=-1;if(d)for(;++f<d.length;){const p=d[f];if(!p.previous||p.previous.call(i,i.previous))return!0}return!1}}}function KA(e){return t;function t(n,i){let r=-1,o;for(;++r<=n.length;)o===void 0?n[r]&&n[r][1].type==="data"&&(o=r,r++):(!n[r]||n[r][1].type!=="data")&&(r!==o+2&&(n[o][1].end=n[r-1][1].end,n.splice(o+2,r-o-2),r=o+2),o=void 0);return e?e(n,i):n}}function WG(e,t){let n=0;for(;++n<=e.length;)if((n===e.length||e[n][1].type==="lineEnding")&&e[n-1][1].type==="data"){const i=e[n-1][1],r=t.sliceStream(i);let o=r.length,a=-1,s=0,u;for(;o--;){const l=r[o];if(typeof l=="string"){for(a=l.length;l.charCodeAt(a-1)===32;)s++,a--;if(a)break;a=-1}else if(l===-2)u=!0,s++;else if(l!==-1){o++;break}}if(t._contentTypeTextTrailing&&n===e.length&&(s=0),s){const l={type:n===e.length||u||s<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:o?a:i.start._bufferIndex+a,_index:i.start._index+o,line:i.end.line,column:i.end.column-s,offset:i.end.offset-s},end:{...i.end}};i.end={...l.start},i.start.offset===i.end.offset?Object.assign(i,l):(e.splice(n,0,["enter",l,t],["exit",l,t]),n+=2)}n++}return e}const GG={42:vt,43:vt,45:vt,48:vt,49:vt,50:vt,51:vt,52:vt,53:vt,54:vt,55:vt,56:vt,57:vt,62:BA},KG={91:eG},YG={[-2]:Ec,[-1]:Ec,32:Ec},XG={35:aG,42:vs,45:[Py,vs],60:cG,61:Py,95:vs,96:Cy,126:Cy},QG={38:qA,92:ZA},e7={[-5]:Tc,[-4]:Tc,[-3]:Tc,33:$G,38:qA,42:Dd,60:[AW,vG],91:AG,92:[iG,ZA],93:Xh,95:Dd,96:ZW},t7={null:[Dd,VG]},n7={null:[42,95]},r7={null:[]},i7=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:n7,contentInitial:KG,disable:r7,document:GG,flow:XG,flowInitial:YG,insideSpan:t7,string:QG,text:e7},Symbol.toStringTag,{value:"Module"}));function o7(e,t,n){let i={_bufferIndex:-1,_index:0,line:n&&n.line||1,column:n&&n.column||1,offset:n&&n.offset||0};const r={},o=[];let a=[],s=[];const u={attempt:$(C),check:$(E),consume:_,enter:x,exit:b,interrupt:$(E,{interrupt:!0})},l={code:null,containerState:{},defineSkip:m,events:[],now:g,parser:e,previous:null,sliceSerialize:f,sliceStream:p,write:d};let c=t.tokenize.call(l,u);return t.resolveAll&&o.push(t),l;function d(z){return a=qt(a,z),y(),a[a.length-1]!==null?[]:(A(t,0),l.events=Yh(o,l.events,l),l.events)}function f(z,J){return s7(p(z),J)}function p(z){return a7(a,z)}function g(){const{_bufferIndex:z,_index:J,line:G,column:D,offset:U}=i;return{_bufferIndex:z,_index:J,line:G,column:D,offset:U}}function m(z){r[z.line]=z.column,F()}function y(){let z;for(;i._index<a.length;){const J=a[i._index];if(typeof J=="string")for(z=i._index,i._bufferIndex<0&&(i._bufferIndex=0);i._index===z&&i._bufferIndex<J.length;)v(J.charCodeAt(i._bufferIndex));else v(J)}}function v(z){c=c(z)}function _(z){le(z)?(i.line++,i.column=1,i.offset+=z===-3?2:1,F()):z!==-1&&(i.column++,i.offset++),i._bufferIndex<0?i._index++:(i._bufferIndex++,i._bufferIndex===a[i._index].length&&(i._bufferIndex=-1,i._index++)),l.previous=z}function x(z,J){const G=J||{};return G.type=z,G.start=g(),l.events.push(["enter",G,l]),s.push(G),G}function b(z){const J=s.pop();return J.end=g(),l.events.push(["exit",J,l]),J}function C(z,J){A(z,J.from)}function E(z,J){J.restore()}function $(z,J){return G;function G(D,U,X){let re,Q,me,S;return Array.isArray(D)?ye(D):"tokenize"in D?ye([D]):Ae(D);function Ae(ue){return Se;function Se(St){const mn=St!==null&&ue[St],Ut=St!==null&&ue.null,rt=[...Array.isArray(mn)?mn:mn?[mn]:[],...Array.isArray(Ut)?Ut:Ut?[Ut]:[]];return ye(rt)(St)}}function ye(ue){return re=ue,Q=0,ue.length===0?X:T(ue[Q])}function T(ue){return Se;function Se(St){return S=j(),me=ue,ue.partial||(l.currentConstruct=ue),ue.name&&l.parser.constructs.disable.null.includes(ue.name)?ne():ue.tokenize.call(J?Object.assign(Object.create(l),J):l,u,V,ne)(St)}}function V(ue){return z(me,S),U}function ne(ue){return S.restore(),++Q<re.length?T(re[Q]):X}}}function A(z,J){z.resolveAll&&!o.includes(z)&&o.push(z),z.resolve&&Cn(l.events,J,l.events.length-J,z.resolve(l.events.slice(J),l)),z.resolveTo&&(l.events=z.resolveTo(l.events,l))}function j(){const z=g(),J=l.previous,G=l.currentConstruct,D=l.events.length,U=Array.from(s);return{from:D,restore:X};function X(){i=z,l.previous=J,l.currentConstruct=G,l.events.length=D,s=U,F()}}function F(){i.line in r&&i.column<2&&(i.column=r[i.line],i.offset+=r[i.line]-1)}}function a7(e,t){const n=t.start._index,i=t.start._bufferIndex,r=t.end._index,o=t.end._bufferIndex;let a;if(n===r)a=[e[n].slice(i,o)];else{if(a=e.slice(n,r),i>-1){const s=a[0];typeof s=="string"?a[0]=s.slice(i):a.shift()}o>0&&a.push(e[r].slice(0,o))}return a}function s7(e,t){let n=-1;const i=[];let r;for(;++n<e.length;){const o=e[n];let a;if(typeof o=="string")a=o;else switch(o){case-5:{a="\r";break}case-4:{a=`
|
|
146
|
-
`;break}case-3:{a=`\r
|
|
147
|
-
`;break}case-2:{a=t?" ":" ";break}case-1:{if(!t&&r)continue;a=" ";break}default:a=String.fromCharCode(o)}r=o===-2,i.push(a)}return i.join("")}function l7(e){const i={constructs:mW([i7,...(e||{}).extensions||[]]),content:r(SW),defined:[],document:r(kW),flow:r(ZG),lazy:{},string:r(HG),text:r(JG)};return i;function r(o){return a;function a(s){return o7(i,o,s)}}}function u7(e){for(;!VA(e););return e}const Ry=/[\0\t\n\r]/g;function c7(){let e=1,t="",n=!0,i;return r;function r(o,a,s){const u=[];let l,c,d,f,p;for(o=t+(typeof o=="string"?o.toString():new TextDecoder(a||void 0).decode(o)),d=0,t="",n&&(o.charCodeAt(0)===65279&&d++,n=void 0);d<o.length;){if(Ry.lastIndex=d,l=Ry.exec(o),f=l&&l.index!==void 0?l.index:o.length,p=o.charCodeAt(f),!l){t=o.slice(d);break}if(p===10&&d===f&&i)u.push(-3),i=void 0;else switch(i&&(u.push(-5),i=void 0),d<f&&(u.push(o.slice(d,f)),e+=f-d),p){case 0:{u.push(65533),e++;break}case 9:{for(c=Math.ceil(e/4)*4,u.push(-2);e++<c;)u.push(-1);break}case 10:{u.push(-4),e=1;break}default:i=!0,e=1}d=f+1}return s&&(i&&u.push(-5),t&&u.push(t),u.push(null)),u}}const d7=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function p7(e){return e.replace(d7,f7)}function f7(e,t,n){if(t)return t;if(n.charCodeAt(0)===35){const r=n.charCodeAt(1),o=r===120||r===88;return FA(n.slice(o?2:1),o?16:10)}return Kh(n)||e}const YA={}.hasOwnProperty;function h7(e,t,n){return typeof t!="string"&&(n=t,t=void 0),m7(n)(u7(l7(n).document().write(c7()(e,t,!0))))}function m7(e){const t={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:o(Jn),autolinkProtocol:j,autolinkEmail:j,atxHeading:o(Be),blockQuote:o(Ut),characterEscape:j,characterReference:j,codeFenced:o(rt),codeFencedFenceInfo:a,codeFencedFenceMeta:a,codeIndented:o(rt,a),codeText:o(qr,a),codeTextData:j,data:j,codeFlowValue:j,definition:o(Ke),definitionDestinationString:a,definitionLabelString:a,definitionTitleString:a,emphasis:o(qe),hardBreakEscape:o(He),hardBreakTrailing:o(He),htmlFlow:o(be,a),htmlFlowData:j,htmlText:o(be,a),htmlTextData:j,image:o(It),label:a,link:o(Jn),listItem:o(De),listItemValue:f,listOrdered:o(Y,d),listUnordered:o(Y),paragraph:o(vr),reference:T,referenceString:a,resourceDestinationString:a,resourceTitleString:a,setextHeading:o(Be),strong:o(Ca),thematicBreak:o(Pa)},exit:{atxHeading:u(),atxHeadingSequence:C,autolink:u(),autolinkEmail:mn,autolinkProtocol:St,blockQuote:u(),characterEscapeValue:F,characterReferenceMarkerHexadecimal:ne,characterReferenceMarkerNumeric:ne,characterReferenceValue:ue,characterReference:Se,codeFenced:u(y),codeFencedFence:m,codeFencedFenceInfo:p,codeFencedFenceMeta:g,codeFlowValue:F,codeIndented:u(v),codeText:u(U),codeTextData:F,data:F,definition:u(),definitionDestinationString:b,definitionLabelString:_,definitionTitleString:x,emphasis:u(),hardBreakEscape:u(J),hardBreakTrailing:u(J),htmlFlow:u(G),htmlFlowData:F,htmlText:u(D),htmlTextData:F,image:u(re),label:me,labelText:Q,lineEnding:z,link:u(X),listItem:u(),listOrdered:u(),listUnordered:u(),paragraph:u(),referenceString:V,resourceDestinationString:S,resourceTitleString:Ae,resource:ye,setextHeading:u(A),setextHeadingLineSequence:$,setextHeadingText:E,strong:u(),thematicBreak:u()}};XA(t,(e||{}).mdastExtensions||[]);const n={};return i;function i(N){let Z={type:"root",children:[]};const ie={stack:[Z],tokenStack:[],config:t,enter:s,exit:l,buffer:a,resume:c,data:n},ge=[];let we=-1;for(;++we<N.length;)if(N[we][1].type==="listOrdered"||N[we][1].type==="listUnordered")if(N[we][0]==="enter")ge.push(we);else{const ut=ge.pop();we=r(N,ut,we)}for(we=-1;++we<N.length;){const ut=t[N[we][0]];YA.call(ut,N[we][1].type)&&ut[N[we][1].type].call(Object.assign({sliceSerialize:N[we][2].sliceSerialize},ie),N[we][1])}if(ie.tokenStack.length>0){const ut=ie.tokenStack[ie.tokenStack.length-1];(ut[1]||Oy).call(ie,void 0,ut[0])}for(Z.position={start:Yn(N.length>0?N[0][1].start:{line:1,column:1,offset:0}),end:Yn(N.length>0?N[N.length-2][1].end:{line:1,column:1,offset:0})},we=-1;++we<t.transforms.length;)Z=t.transforms[we](Z)||Z;return Z}function r(N,Z,ie){let ge=Z-1,we=-1,ut=!1,On,Lt,Wn,Ft;for(;++ge<=ie;){const it=N[ge];switch(it[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{it[0]==="enter"?we++:we--,Ft=void 0;break}case"lineEndingBlank":{it[0]==="enter"&&(On&&!Ft&&!we&&!Wn&&(Wn=ge),Ft=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:Ft=void 0}if(!we&&it[0]==="enter"&&it[1].type==="listItemPrefix"||we===-1&&it[0]==="exit"&&(it[1].type==="listUnordered"||it[1].type==="listOrdered")){if(On){let Gn=ge;for(Lt=void 0;Gn--;){const Kt=N[Gn];if(Kt[1].type==="lineEnding"||Kt[1].type==="lineEndingBlank"){if(Kt[0]==="exit")continue;Lt&&(N[Lt][1].type="lineEndingBlank",ut=!0),Kt[1].type="lineEnding",Lt=Gn}else if(!(Kt[1].type==="linePrefix"||Kt[1].type==="blockQuotePrefix"||Kt[1].type==="blockQuotePrefixWhitespace"||Kt[1].type==="blockQuoteMarker"||Kt[1].type==="listItemIndent"))break}Wn&&(!Lt||Wn<Lt)&&(On._spread=!0),On.end=Object.assign({},Lt?N[Lt][1].start:it[1].end),N.splice(Lt||ge,0,["exit",On,it[2]]),ge++,ie++}if(it[1].type==="listItemPrefix"){const Gn={type:"listItem",_spread:!1,start:Object.assign({},it[1].start),end:void 0};On=Gn,N.splice(ge,0,["enter",Gn,it[2]]),ge++,ie++,Wn=void 0,Ft=!0}}}return N[Z][1]._spread=ut,ie}function o(N,Z){return ie;function ie(ge){s.call(this,N(ge),ge),Z&&Z.call(this,ge)}}function a(){this.stack.push({type:"fragment",children:[]})}function s(N,Z,ie){this.stack[this.stack.length-1].children.push(N),this.stack.push(N),this.tokenStack.push([Z,ie||void 0]),N.position={start:Yn(Z.start),end:void 0}}function u(N){return Z;function Z(ie){N&&N.call(this,ie),l.call(this,ie)}}function l(N,Z){const ie=this.stack.pop(),ge=this.tokenStack.pop();if(ge)ge[0].type!==N.type&&(Z?Z.call(this,N,ge[0]):(ge[1]||Oy).call(this,N,ge[0]));else throw new Error("Cannot close `"+N.type+"` ("+ao({start:N.start,end:N.end})+"): it’s not open");ie.position.end=Yn(N.end)}function c(){return fW(this.stack.pop())}function d(){this.data.expectingFirstListItemValue=!0}function f(N){if(this.data.expectingFirstListItemValue){const Z=this.stack[this.stack.length-2];Z.start=Number.parseInt(this.sliceSerialize(N),10),this.data.expectingFirstListItemValue=void 0}}function p(){const N=this.resume(),Z=this.stack[this.stack.length-1];Z.lang=N}function g(){const N=this.resume(),Z=this.stack[this.stack.length-1];Z.meta=N}function m(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function y(){const N=this.resume(),Z=this.stack[this.stack.length-1];Z.value=N.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function v(){const N=this.resume(),Z=this.stack[this.stack.length-1];Z.value=N.replace(/(\r?\n|\r)$/g,"")}function _(N){const Z=this.resume(),ie=this.stack[this.stack.length-1];ie.label=Z,ie.identifier=ui(this.sliceSerialize(N)).toLowerCase()}function x(){const N=this.resume(),Z=this.stack[this.stack.length-1];Z.title=N}function b(){const N=this.resume(),Z=this.stack[this.stack.length-1];Z.url=N}function C(N){const Z=this.stack[this.stack.length-1];if(!Z.depth){const ie=this.sliceSerialize(N).length;Z.depth=ie}}function E(){this.data.setextHeadingSlurpLineEnding=!0}function $(N){const Z=this.stack[this.stack.length-1];Z.depth=this.sliceSerialize(N).codePointAt(0)===61?1:2}function A(){this.data.setextHeadingSlurpLineEnding=void 0}function j(N){const ie=this.stack[this.stack.length-1].children;let ge=ie[ie.length-1];(!ge||ge.type!=="text")&&(ge=Aa(),ge.position={start:Yn(N.start),end:void 0},ie.push(ge)),this.stack.push(ge)}function F(N){const Z=this.stack.pop();Z.value+=this.sliceSerialize(N),Z.position.end=Yn(N.end)}function z(N){const Z=this.stack[this.stack.length-1];if(this.data.atHardBreak){const ie=Z.children[Z.children.length-1];ie.position.end=Yn(N.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&t.canContainEols.includes(Z.type)&&(j.call(this,N),F.call(this,N))}function J(){this.data.atHardBreak=!0}function G(){const N=this.resume(),Z=this.stack[this.stack.length-1];Z.value=N}function D(){const N=this.resume(),Z=this.stack[this.stack.length-1];Z.value=N}function U(){const N=this.resume(),Z=this.stack[this.stack.length-1];Z.value=N}function X(){const N=this.stack[this.stack.length-1];if(this.data.inReference){const Z=this.data.referenceType||"shortcut";N.type+="Reference",N.referenceType=Z,delete N.url,delete N.title}else delete N.identifier,delete N.label;this.data.referenceType=void 0}function re(){const N=this.stack[this.stack.length-1];if(this.data.inReference){const Z=this.data.referenceType||"shortcut";N.type+="Reference",N.referenceType=Z,delete N.url,delete N.title}else delete N.identifier,delete N.label;this.data.referenceType=void 0}function Q(N){const Z=this.sliceSerialize(N),ie=this.stack[this.stack.length-2];ie.label=p7(Z),ie.identifier=ui(Z).toLowerCase()}function me(){const N=this.stack[this.stack.length-1],Z=this.resume(),ie=this.stack[this.stack.length-1];if(this.data.inReference=!0,ie.type==="link"){const ge=N.children;ie.children=ge}else ie.alt=Z}function S(){const N=this.resume(),Z=this.stack[this.stack.length-1];Z.url=N}function Ae(){const N=this.resume(),Z=this.stack[this.stack.length-1];Z.title=N}function ye(){this.data.inReference=void 0}function T(){this.data.referenceType="collapsed"}function V(N){const Z=this.resume(),ie=this.stack[this.stack.length-1];ie.label=Z,ie.identifier=ui(this.sliceSerialize(N)).toLowerCase(),this.data.referenceType="full"}function ne(N){this.data.characterReferenceType=N.type}function ue(N){const Z=this.sliceSerialize(N),ie=this.data.characterReferenceType;let ge;ie?(ge=FA(Z,ie==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):ge=Kh(Z);const we=this.stack[this.stack.length-1];we.value+=ge}function Se(N){const Z=this.stack.pop();Z.position.end=Yn(N.end)}function St(N){F.call(this,N);const Z=this.stack[this.stack.length-1];Z.url=this.sliceSerialize(N)}function mn(N){F.call(this,N);const Z=this.stack[this.stack.length-1];Z.url="mailto:"+this.sliceSerialize(N)}function Ut(){return{type:"blockquote",children:[]}}function rt(){return{type:"code",lang:null,meta:null,value:""}}function qr(){return{type:"inlineCode",value:""}}function Ke(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function qe(){return{type:"emphasis",children:[]}}function Be(){return{type:"heading",depth:0,children:[]}}function He(){return{type:"break"}}function be(){return{type:"html",value:""}}function It(){return{type:"image",title:null,url:"",alt:null}}function Jn(){return{type:"link",title:null,url:"",children:[]}}function Y(N){return{type:"list",ordered:N.type==="listOrdered",start:null,spread:N._spread,children:[]}}function De(N){return{type:"listItem",spread:N._spread,checked:null,children:[]}}function vr(){return{type:"paragraph",children:[]}}function Ca(){return{type:"strong",children:[]}}function Aa(){return{type:"text",value:""}}function Pa(){return{type:"thematicBreak"}}}function Yn(e){return{line:e.line,column:e.column,offset:e.offset}}function XA(e,t){let n=-1;for(;++n<t.length;){const i=t[n];Array.isArray(i)?XA(e,i):g7(e,i)}}function g7(e,t){let n;for(n in t)if(YA.call(t,n))switch(n){case"canContainEols":{const i=t[n];i&&e[n].push(...i);break}case"transforms":{const i=t[n];i&&e[n].push(...i);break}case"enter":case"exit":{const i=t[n];i&&Object.assign(e[n],i);break}}}function Oy(e,t){throw e?new Error("Cannot close `"+e.type+"` ("+ao({start:e.start,end:e.end})+"): a different token (`"+t.type+"`, "+ao({start:t.start,end:t.end})+") is open"):new Error("Cannot close document, a token (`"+t.type+"`, "+ao({start:t.start,end:t.end})+") is still open")}function v7(e){const t=this;t.parser=n;function n(i){return h7(i,{...t.data("settings"),...e,extensions:t.data("micromarkExtensions")||[],mdastExtensions:t.data("fromMarkdownExtensions")||[]})}}function y7(e,t){const n={type:"element",tagName:"blockquote",properties:{},children:e.wrap(e.all(t),!0)};return e.patch(t,n),e.applyData(t,n)}function b7(e,t){const n={type:"element",tagName:"br",properties:{},children:[]};return e.patch(t,n),[e.applyData(t,n),{type:"text",value:`
|
|
148
|
-
`}]}function _7(e,t){const n=t.value?t.value+`
|
|
149
|
-
`:"",i={},r=t.lang?t.lang.split(/\s+/):[];r.length>0&&(i.className=["language-"+r[0]]);let o={type:"element",tagName:"code",properties:i,children:[{type:"text",value:n}]};return t.meta&&(o.data={meta:t.meta}),e.patch(t,o),o=e.applyData(t,o),o={type:"element",tagName:"pre",properties:{},children:[o]},e.patch(t,o),o}function w7(e,t){const n={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function x7(e,t){const n={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function S7(e,t){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",i=String(t.identifier).toUpperCase(),r=Mi(i.toLowerCase()),o=e.footnoteOrder.indexOf(i);let a,s=e.footnoteCounts.get(i);s===void 0?(s=0,e.footnoteOrder.push(i),a=e.footnoteOrder.length):a=o+1,s+=1,e.footnoteCounts.set(i,s);const u={type:"element",tagName:"a",properties:{href:"#"+n+"fn-"+r,id:n+"fnref-"+r+(s>1?"-"+s:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(a)}]};e.patch(t,u);const l={type:"element",tagName:"sup",properties:{},children:[u]};return e.patch(t,l),e.applyData(t,l)}function I7(e,t){const n={type:"element",tagName:"h"+t.depth,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function k7(e,t){if(e.options.allowDangerousHtml){const n={type:"raw",value:t.value};return e.patch(t,n),e.applyData(t,n)}}function QA(e,t){const n=t.referenceType;let i="]";if(n==="collapsed"?i+="[]":n==="full"&&(i+="["+(t.label||t.identifier)+"]"),t.type==="imageReference")return[{type:"text",value:"!["+t.alt+i}];const r=e.all(t),o=r[0];o&&o.type==="text"?o.value="["+o.value:r.unshift({type:"text",value:"["});const a=r[r.length-1];return a&&a.type==="text"?a.value+=i:r.push({type:"text",value:i}),r}function E7(e,t){const n=String(t.identifier).toUpperCase(),i=e.definitionById.get(n);if(!i)return QA(e,t);const r={src:Mi(i.url||""),alt:t.alt};i.title!==null&&i.title!==void 0&&(r.title=i.title);const o={type:"element",tagName:"img",properties:r,children:[]};return e.patch(t,o),e.applyData(t,o)}function T7(e,t){const n={src:Mi(t.url)};t.alt!==null&&t.alt!==void 0&&(n.alt=t.alt),t.title!==null&&t.title!==void 0&&(n.title=t.title);const i={type:"element",tagName:"img",properties:n,children:[]};return e.patch(t,i),e.applyData(t,i)}function $7(e,t){const n={type:"text",value:t.value.replace(/\r?\n|\r/g," ")};e.patch(t,n);const i={type:"element",tagName:"code",properties:{},children:[n]};return e.patch(t,i),e.applyData(t,i)}function C7(e,t){const n=String(t.identifier).toUpperCase(),i=e.definitionById.get(n);if(!i)return QA(e,t);const r={href:Mi(i.url||"")};i.title!==null&&i.title!==void 0&&(r.title=i.title);const o={type:"element",tagName:"a",properties:r,children:e.all(t)};return e.patch(t,o),e.applyData(t,o)}function A7(e,t){const n={href:Mi(t.url)};t.title!==null&&t.title!==void 0&&(n.title=t.title);const i={type:"element",tagName:"a",properties:n,children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function P7(e,t,n){const i=e.all(t),r=n?R7(n):eP(t),o={},a=[];if(typeof t.checked=="boolean"){const c=i[0];let d;c&&c.type==="element"&&c.tagName==="p"?d=c:(d={type:"element",tagName:"p",properties:{},children:[]},i.unshift(d)),d.children.length>0&&d.children.unshift({type:"text",value:" "}),d.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:t.checked,disabled:!0},children:[]}),o.className=["task-list-item"]}let s=-1;for(;++s<i.length;){const c=i[s];(r||s!==0||c.type!=="element"||c.tagName!=="p")&&a.push({type:"text",value:`
|
|
150
|
-
`}),c.type==="element"&&c.tagName==="p"&&!r?a.push(...c.children):a.push(c)}const u=i[i.length-1];u&&(r||u.type!=="element"||u.tagName!=="p")&&a.push({type:"text",value:`
|
|
151
|
-
`});const l={type:"element",tagName:"li",properties:o,children:a};return e.patch(t,l),e.applyData(t,l)}function R7(e){let t=!1;if(e.type==="list"){t=e.spread||!1;const n=e.children;let i=-1;for(;!t&&++i<n.length;)t=eP(n[i])}return t}function eP(e){const t=e.spread;return t??e.children.length>1}function O7(e,t){const n={},i=e.all(t);let r=-1;for(typeof t.start=="number"&&t.start!==1&&(n.start=t.start);++r<i.length;){const a=i[r];if(a.type==="element"&&a.tagName==="li"&&a.properties&&Array.isArray(a.properties.className)&&a.properties.className.includes("task-list-item")){n.className=["contains-task-list"];break}}const o={type:"element",tagName:t.ordered?"ol":"ul",properties:n,children:e.wrap(i,!0)};return e.patch(t,o),e.applyData(t,o)}function N7(e,t){const n={type:"element",tagName:"p",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function j7(e,t){const n={type:"root",children:e.wrap(e.all(t))};return e.patch(t,n),e.applyData(t,n)}function M7(e,t){const n={type:"element",tagName:"strong",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function D7(e,t){const n=e.all(t),i=n.shift(),r=[];if(i){const a={type:"element",tagName:"thead",properties:{},children:e.wrap([i],!0)};e.patch(t.children[0],a),r.push(a)}if(n.length>0){const a={type:"element",tagName:"tbody",properties:{},children:e.wrap(n,!0)},s=Hh(t.children[1]),u=NA(t.children[t.children.length-1]);s&&u&&(a.position={start:s,end:u}),r.push(a)}const o={type:"element",tagName:"table",properties:{},children:e.wrap(r,!0)};return e.patch(t,o),e.applyData(t,o)}function z7(e,t,n){const i=n?n.children:void 0,o=(i?i.indexOf(t):1)===0?"th":"td",a=n&&n.type==="table"?n.align:void 0,s=a?a.length:t.children.length;let u=-1;const l=[];for(;++u<s;){const d=t.children[u],f={},p=a?a[u]:void 0;p&&(f.align=p);let g={type:"element",tagName:o,properties:f,children:[]};d&&(g.children=e.all(d),e.patch(d,g),g=e.applyData(d,g)),l.push(g)}const c={type:"element",tagName:"tr",properties:{},children:e.wrap(l,!0)};return e.patch(t,c),e.applyData(t,c)}function U7(e,t){const n={type:"element",tagName:"td",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}const Ny=9,jy=32;function L7(e){const t=String(e),n=/\r?\n|\r/g;let i=n.exec(t),r=0;const o=[];for(;i;)o.push(My(t.slice(r,i.index),r>0,!0),i[0]),r=i.index+i[0].length,i=n.exec(t);return o.push(My(t.slice(r),r>0,!1)),o.join("")}function My(e,t,n){let i=0,r=e.length;if(t){let o=e.codePointAt(i);for(;o===Ny||o===jy;)i++,o=e.codePointAt(i)}if(n){let o=e.codePointAt(r-1);for(;o===Ny||o===jy;)r--,o=e.codePointAt(r-1)}return r>i?e.slice(i,r):""}function F7(e,t){const n={type:"text",value:L7(String(t.value))};return e.patch(t,n),e.applyData(t,n)}function B7(e,t){const n={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,n),e.applyData(t,n)}const Z7={blockquote:y7,break:b7,code:_7,delete:w7,emphasis:x7,footnoteReference:S7,heading:I7,html:k7,imageReference:E7,image:T7,inlineCode:$7,linkReference:C7,link:A7,listItem:P7,list:O7,paragraph:N7,root:j7,strong:M7,table:D7,tableCell:U7,tableRow:z7,text:F7,thematicBreak:B7,toml:ns,yaml:ns,definition:ns,footnoteDefinition:ns};function ns(){}const tP=-1,Cu=0,lo=1,il=2,Qh=3,em=4,tm=5,nm=6,nP=7,rP=8,Dy=typeof self=="object"?self:globalThis,q7=(e,t)=>{const n=(r,o)=>(e.set(o,r),r),i=r=>{if(e.has(r))return e.get(r);const[o,a]=t[r];switch(o){case Cu:case tP:return n(a,r);case lo:{const s=n([],r);for(const u of a)s.push(i(u));return s}case il:{const s=n({},r);for(const[u,l]of a)s[i(u)]=i(l);return s}case Qh:return n(new Date(a),r);case em:{const{source:s,flags:u}=a;return n(new RegExp(s,u),r)}case tm:{const s=n(new Map,r);for(const[u,l]of a)s.set(i(u),i(l));return s}case nm:{const s=n(new Set,r);for(const u of a)s.add(i(u));return s}case nP:{const{name:s,message:u}=a;return n(new Dy[s](u),r)}case rP:return n(BigInt(a),r);case"BigInt":return n(Object(BigInt(a)),r);case"ArrayBuffer":return n(new Uint8Array(a).buffer,a);case"DataView":{const{buffer:s}=new Uint8Array(a);return n(new DataView(s),a)}}return n(new Dy[o](a),r)};return i},zy=e=>q7(new Map,e)(0),Qr="",{toString:V7}={},{keys:H7}=Object,Hi=e=>{const t=typeof e;if(t!=="object"||!e)return[Cu,t];const n=V7.call(e).slice(8,-1);switch(n){case"Array":return[lo,Qr];case"Object":return[il,Qr];case"Date":return[Qh,Qr];case"RegExp":return[em,Qr];case"Map":return[tm,Qr];case"Set":return[nm,Qr];case"DataView":return[lo,n]}return n.includes("Array")?[lo,n]:n.includes("Error")?[nP,n]:[il,n]},rs=([e,t])=>e===Cu&&(t==="function"||t==="symbol"),J7=(e,t,n,i)=>{const r=(a,s)=>{const u=i.push(a)-1;return n.set(s,u),u},o=a=>{if(n.has(a))return n.get(a);let[s,u]=Hi(a);switch(s){case Cu:{let c=a;switch(u){case"bigint":s=rP,c=a.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+u);c=null;break;case"undefined":return r([tP],a)}return r([s,c],a)}case lo:{if(u){let f=a;return u==="DataView"?f=new Uint8Array(a.buffer):u==="ArrayBuffer"&&(f=new Uint8Array(a)),r([u,[...f]],a)}const c=[],d=r([s,c],a);for(const f of a)c.push(o(f));return d}case il:{if(u)switch(u){case"BigInt":return r([u,a.toString()],a);case"Boolean":case"Number":case"String":return r([u,a.valueOf()],a)}if(t&&"toJSON"in a)return o(a.toJSON());const c=[],d=r([s,c],a);for(const f of H7(a))(e||!rs(Hi(a[f])))&&c.push([o(f),o(a[f])]);return d}case Qh:return r([s,a.toISOString()],a);case em:{const{source:c,flags:d}=a;return r([s,{source:c,flags:d}],a)}case tm:{const c=[],d=r([s,c],a);for(const[f,p]of a)(e||!(rs(Hi(f))||rs(Hi(p))))&&c.push([o(f),o(p)]);return d}case nm:{const c=[],d=r([s,c],a);for(const f of a)(e||!rs(Hi(f)))&&c.push(o(f));return d}}const{message:l}=a;return r([s,{name:u,message:l}],a)};return o},Uy=(e,{json:t,lossy:n}={})=>{const i=[];return J7(!(t||n),!!t,new Map,i)(e),i},ol=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?zy(Uy(e,t)):structuredClone(e):(e,t)=>zy(Uy(e,t));function W7(e,t){const n=[{type:"text",value:"↩"}];return t>1&&n.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(t)}]}),n}function G7(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function K7(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",n=e.options.footnoteBackContent||W7,i=e.options.footnoteBackLabel||G7,r=e.options.footnoteLabel||"Footnotes",o=e.options.footnoteLabelTagName||"h2",a=e.options.footnoteLabelProperties||{className:["sr-only"]},s=[];let u=-1;for(;++u<e.footnoteOrder.length;){const l=e.footnoteById.get(e.footnoteOrder[u]);if(!l)continue;const c=e.all(l),d=String(l.identifier).toUpperCase(),f=Mi(d.toLowerCase());let p=0;const g=[],m=e.footnoteCounts.get(d);for(;m!==void 0&&++p<=m;){g.length>0&&g.push({type:"text",value:" "});let _=typeof n=="string"?n:n(u,p);typeof _=="string"&&(_={type:"text",value:_}),g.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+f+(p>1?"-"+p:""),dataFootnoteBackref:"",ariaLabel:typeof i=="string"?i:i(u,p),className:["data-footnote-backref"]},children:Array.isArray(_)?_:[_]})}const y=c[c.length-1];if(y&&y.type==="element"&&y.tagName==="p"){const _=y.children[y.children.length-1];_&&_.type==="text"?_.value+=" ":y.children.push({type:"text",value:" "}),y.children.push(...g)}else c.push(...g);const v={type:"element",tagName:"li",properties:{id:t+"fn-"+f},children:e.wrap(c,!0)};e.patch(l,v),s.push(v)}if(s.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...ol(a),id:"footnote-label"},children:[{type:"text",value:r}]},{type:"text",value:`
|
|
152
|
-
`},{type:"element",tagName:"ol",properties:{},children:e.wrap(s,!0)},{type:"text",value:`
|
|
153
|
-
`}]}}const iP=(function(e){if(e==null)return eK;if(typeof e=="function")return Au(e);if(typeof e=="object")return Array.isArray(e)?Y7(e):X7(e);if(typeof e=="string")return Q7(e);throw new Error("Expected function, string, or object as test")});function Y7(e){const t=[];let n=-1;for(;++n<e.length;)t[n]=iP(e[n]);return Au(i);function i(...r){let o=-1;for(;++o<t.length;)if(t[o].apply(this,r))return!0;return!1}}function X7(e){const t=e;return Au(n);function n(i){const r=i;let o;for(o in e)if(r[o]!==t[o])return!1;return!0}}function Q7(e){return Au(t);function t(n){return n&&n.type===e}}function Au(e){return t;function t(n,i,r){return!!(tK(n)&&e.call(this,n,typeof i=="number"?i:void 0,r||void 0))}}function eK(){return!0}function tK(e){return e!==null&&typeof e=="object"&&"type"in e}const oP=[],nK=!0,Ly=!1,rK="skip";function iK(e,t,n,i){let r;typeof t=="function"&&typeof n!="function"?(i=n,n=t):r=t;const o=iP(r),a=i?-1:1;s(e,void 0,[])();function s(u,l,c){const d=u&&typeof u=="object"?u:{};if(typeof d.type=="string"){const p=typeof d.tagName=="string"?d.tagName:typeof d.name=="string"?d.name:void 0;Object.defineProperty(f,"name",{value:"node ("+(u.type+(p?"<"+p+">":""))+")"})}return f;function f(){let p=oP,g,m,y;if((!t||o(u,l,c[c.length-1]||void 0))&&(p=oK(n(u,c)),p[0]===Ly))return p;if("children"in u&&u.children){const v=u;if(v.children&&p[0]!==rK)for(m=(i?v.children.length:-1)+a,y=c.concat(v);m>-1&&m<v.children.length;){const _=v.children[m];if(g=s(_,m,y)(),g[0]===Ly)return g;m=typeof g[1]=="number"?g[1]:m+a}}return p}}}function oK(e){return Array.isArray(e)?e:typeof e=="number"?[nK,e]:e==null?oP:[e]}function aP(e,t,n,i){let r,o,a;typeof t=="function"&&typeof n!="function"?(o=void 0,a=t,r=n):(o=t,a=n,r=i),iK(e,o,s,r);function s(u,l){const c=l[l.length-1],d=c?c.children.indexOf(u):void 0;return a(u,d,c)}}const zd={}.hasOwnProperty,aK={};function sK(e,t){const n=t||aK,i=new Map,r=new Map,o=new Map,a={...Z7,...n.handlers},s={all:l,applyData:uK,definitionById:i,footnoteById:r,footnoteCounts:o,footnoteOrder:[],handlers:a,one:u,options:n,patch:lK,wrap:dK};return aP(e,function(c){if(c.type==="definition"||c.type==="footnoteDefinition"){const d=c.type==="definition"?i:r,f=String(c.identifier).toUpperCase();d.has(f)||d.set(f,c)}}),s;function u(c,d){const f=c.type,p=s.handlers[f];if(zd.call(s.handlers,f)&&p)return p(s,c,d);if(s.options.passThrough&&s.options.passThrough.includes(f)){if("children"in c){const{children:m,...y}=c,v=ol(y);return v.children=s.all(c),v}return ol(c)}return(s.options.unknownHandler||cK)(s,c,d)}function l(c){const d=[];if("children"in c){const f=c.children;let p=-1;for(;++p<f.length;){const g=s.one(f[p],c);if(g){if(p&&f[p-1].type==="break"&&(!Array.isArray(g)&&g.type==="text"&&(g.value=Fy(g.value)),!Array.isArray(g)&&g.type==="element")){const m=g.children[0];m&&m.type==="text"&&(m.value=Fy(m.value))}Array.isArray(g)?d.push(...g):d.push(g)}}}return d}}function lK(e,t){e.position&&(t.position=VJ(e))}function uK(e,t){let n=t;if(e&&e.data){const i=e.data.hName,r=e.data.hChildren,o=e.data.hProperties;if(typeof i=="string")if(n.type==="element")n.tagName=i;else{const a="children"in n?n.children:[n];n={type:"element",tagName:i,properties:{},children:a}}n.type==="element"&&o&&Object.assign(n.properties,ol(o)),"children"in n&&n.children&&r!==null&&r!==void 0&&(n.children=r)}return n}function cK(e,t){const n=t.data||{},i="value"in t&&!(zd.call(n,"hProperties")||zd.call(n,"hChildren"))?{type:"text",value:t.value}:{type:"element",tagName:"div",properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function dK(e,t){const n=[];let i=-1;for(t&&n.push({type:"text",value:`
|
|
154
|
-
`});++i<e.length;)i&&n.push({type:"text",value:`
|
|
155
|
-
`}),n.push(e[i]);return t&&e.length>0&&n.push({type:"text",value:`
|
|
156
|
-
`}),n}function Fy(e){let t=0,n=e.charCodeAt(t);for(;n===9||n===32;)t++,n=e.charCodeAt(t);return e.slice(t)}function By(e,t){const n=sK(e,t),i=n.one(e,void 0),r=K7(n),o=Array.isArray(i)?{type:"root",children:i}:i||{type:"root",children:[]};return r&&o.children.push({type:"text",value:`
|
|
157
|
-
`},r),o}function pK(e,t){return e&&"run"in e?async function(n,i){const r=By(n,{file:i,...t});await e.run(r,i)}:function(n,i){return By(n,{file:i,...e||t})}}function Zy(e){if(e)throw e}var $c,qy;function fK(){if(qy)return $c;qy=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,n=Object.defineProperty,i=Object.getOwnPropertyDescriptor,r=function(l){return typeof Array.isArray=="function"?Array.isArray(l):t.call(l)==="[object Array]"},o=function(l){if(!l||t.call(l)!=="[object Object]")return!1;var c=e.call(l,"constructor"),d=l.constructor&&l.constructor.prototype&&e.call(l.constructor.prototype,"isPrototypeOf");if(l.constructor&&!c&&!d)return!1;var f;for(f in l);return typeof f>"u"||e.call(l,f)},a=function(l,c){n&&c.name==="__proto__"?n(l,c.name,{enumerable:!0,configurable:!0,value:c.newValue,writable:!0}):l[c.name]=c.newValue},s=function(l,c){if(c==="__proto__")if(e.call(l,c)){if(i)return i(l,c).value}else return;return l[c]};return $c=function u(){var l,c,d,f,p,g,m=arguments[0],y=1,v=arguments.length,_=!1;for(typeof m=="boolean"&&(_=m,m=arguments[1]||{},y=2),(m==null||typeof m!="object"&&typeof m!="function")&&(m={});y<v;++y)if(l=arguments[y],l!=null)for(c in l)d=s(m,c),f=s(l,c),m!==f&&(_&&f&&(o(f)||(p=r(f)))?(p?(p=!1,g=d&&r(d)?d:[]):g=d&&o(d)?d:{},a(m,{name:c,newValue:u(_,g,f)})):typeof f<"u"&&a(m,{name:c,newValue:f}));return m},$c}var hK=fK();const Cc=ga(hK);function Ud(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}function mK(){const e=[],t={run:n,use:i};return t;function n(...r){let o=-1;const a=r.pop();if(typeof a!="function")throw new TypeError("Expected function as last argument, not "+a);s(null,...r);function s(u,...l){const c=e[++o];let d=-1;if(u){a(u);return}for(;++d<r.length;)(l[d]===null||l[d]===void 0)&&(l[d]=r[d]);r=l,c?gK(c,s)(...l):a(null,...l)}}function i(r){if(typeof r!="function")throw new TypeError("Expected `middelware` to be a function, not "+r);return e.push(r),t}}function gK(e,t){let n;return i;function i(...a){const s=e.length>a.length;let u;s&&a.push(r);try{u=e.apply(this,a)}catch(l){const c=l;if(s&&n)throw c;return r(c)}s||(u&&u.then&&typeof u.then=="function"?u.then(o,r):u instanceof Error?r(u):o(u))}function r(a,...s){n||(n=!0,t(a,...s))}function o(a){r(null,a)}}const bn={basename:vK,dirname:yK,extname:bK,join:_K,sep:"/"};function vK(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');$a(e);let n=0,i=-1,r=e.length,o;if(t===void 0||t.length===0||t.length>e.length){for(;r--;)if(e.codePointAt(r)===47){if(o){n=r+1;break}}else i<0&&(o=!0,i=r+1);return i<0?"":e.slice(n,i)}if(t===e)return"";let a=-1,s=t.length-1;for(;r--;)if(e.codePointAt(r)===47){if(o){n=r+1;break}}else a<0&&(o=!0,a=r+1),s>-1&&(e.codePointAt(r)===t.codePointAt(s--)?s<0&&(i=r):(s=-1,i=a));return n===i?i=a:i<0&&(i=e.length),e.slice(n,i)}function yK(e){if($a(e),e.length===0)return".";let t=-1,n=e.length,i;for(;--n;)if(e.codePointAt(n)===47){if(i){t=n;break}}else i||(i=!0);return t<0?e.codePointAt(0)===47?"/":".":t===1&&e.codePointAt(0)===47?"//":e.slice(0,t)}function bK(e){$a(e);let t=e.length,n=-1,i=0,r=-1,o=0,a;for(;t--;){const s=e.codePointAt(t);if(s===47){if(a){i=t+1;break}continue}n<0&&(a=!0,n=t+1),s===46?r<0?r=t:o!==1&&(o=1):r>-1&&(o=-1)}return r<0||n<0||o===0||o===1&&r===n-1&&r===i+1?"":e.slice(r,n)}function _K(...e){let t=-1,n;for(;++t<e.length;)$a(e[t]),e[t]&&(n=n===void 0?e[t]:n+"/"+e[t]);return n===void 0?".":wK(n)}function wK(e){$a(e);const t=e.codePointAt(0)===47;let n=xK(e,!t);return n.length===0&&!t&&(n="."),n.length>0&&e.codePointAt(e.length-1)===47&&(n+="/"),t?"/"+n:n}function xK(e,t){let n="",i=0,r=-1,o=0,a=-1,s,u;for(;++a<=e.length;){if(a<e.length)s=e.codePointAt(a);else{if(s===47)break;s=47}if(s===47){if(!(r===a-1||o===1))if(r!==a-1&&o===2){if(n.length<2||i!==2||n.codePointAt(n.length-1)!==46||n.codePointAt(n.length-2)!==46){if(n.length>2){if(u=n.lastIndexOf("/"),u!==n.length-1){u<0?(n="",i=0):(n=n.slice(0,u),i=n.length-1-n.lastIndexOf("/")),r=a,o=0;continue}}else if(n.length>0){n="",i=0,r=a,o=0;continue}}t&&(n=n.length>0?n+"/..":"..",i=2)}else n.length>0?n+="/"+e.slice(r+1,a):n=e.slice(r+1,a),i=a-r-1;r=a,o=0}else s===46&&o>-1?o++:o=-1}return n}function $a(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const SK={cwd:IK};function IK(){return"/"}function Ld(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function kK(e){if(typeof e=="string")e=new URL(e);else if(!Ld(e)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(e.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return EK(e)}function EK(e){if(e.hostname!==""){const i=new TypeError('File URL host must be "localhost" or empty on darwin');throw i.code="ERR_INVALID_FILE_URL_HOST",i}const t=e.pathname;let n=-1;for(;++n<t.length;)if(t.codePointAt(n)===37&&t.codePointAt(n+1)===50){const i=t.codePointAt(n+2);if(i===70||i===102){const r=new TypeError("File URL path must not include encoded / characters");throw r.code="ERR_INVALID_FILE_URL_PATH",r}}return decodeURIComponent(t)}const Ac=["history","path","basename","stem","extname","dirname"];class sP{constructor(t){let n;t?Ld(t)?n={path:t}:typeof t=="string"||TK(t)?n={value:t}:n=t:n={},this.cwd="cwd"in n?"":SK.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let i=-1;for(;++i<Ac.length;){const o=Ac[i];o in n&&n[o]!==void 0&&n[o]!==null&&(this[o]=o==="history"?[...n[o]]:n[o])}let r;for(r in n)Ac.includes(r)||(this[r]=n[r])}get basename(){return typeof this.path=="string"?bn.basename(this.path):void 0}set basename(t){Rc(t,"basename"),Pc(t,"basename"),this.path=bn.join(this.dirname||"",t)}get dirname(){return typeof this.path=="string"?bn.dirname(this.path):void 0}set dirname(t){Vy(this.basename,"dirname"),this.path=bn.join(t||"",this.basename)}get extname(){return typeof this.path=="string"?bn.extname(this.path):void 0}set extname(t){if(Pc(t,"extname"),Vy(this.dirname,"extname"),t){if(t.codePointAt(0)!==46)throw new Error("`extname` must start with `.`");if(t.includes(".",1))throw new Error("`extname` cannot contain multiple dots")}this.path=bn.join(this.dirname,this.stem+(t||""))}get path(){return this.history[this.history.length-1]}set path(t){Ld(t)&&(t=kK(t)),Rc(t,"path"),this.path!==t&&this.history.push(t)}get stem(){return typeof this.path=="string"?bn.basename(this.path,this.extname):void 0}set stem(t){Rc(t,"stem"),Pc(t,"stem"),this.path=bn.join(this.dirname||"",t+(this.extname||""))}fail(t,n,i){const r=this.message(t,n,i);throw r.fatal=!0,r}info(t,n,i){const r=this.message(t,n,i);return r.fatal=void 0,r}message(t,n,i){const r=new lt(t,n,i);return this.path&&(r.name=this.path+":"+r.name,r.file=this.path),r.fatal=!1,this.messages.push(r),r}toString(t){return this.value===void 0?"":typeof this.value=="string"?this.value:new TextDecoder(t||void 0).decode(this.value)}}function Pc(e,t){if(e&&e.includes(bn.sep))throw new Error("`"+t+"` cannot be a path: did not expect `"+bn.sep+"`")}function Rc(e,t){if(!e)throw new Error("`"+t+"` cannot be empty")}function Vy(e,t){if(!e)throw new Error("Setting `"+t+"` requires `path` to be set too")}function TK(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const $K=(function(e){const i=this.constructor.prototype,r=i[e],o=function(){return r.apply(o,arguments)};return Object.setPrototypeOf(o,i),o}),CK={}.hasOwnProperty;class rm extends $K{constructor(){super("copy"),this.Compiler=void 0,this.Parser=void 0,this.attachers=[],this.compiler=void 0,this.freezeIndex=-1,this.frozen=void 0,this.namespace={},this.parser=void 0,this.transformers=mK()}copy(){const t=new rm;let n=-1;for(;++n<this.attachers.length;){const i=this.attachers[n];t.use(...i)}return t.data(Cc(!0,{},this.namespace)),t}data(t,n){return typeof t=="string"?arguments.length===2?(jc("data",this.frozen),this.namespace[t]=n,this):CK.call(this.namespace,t)&&this.namespace[t]||void 0:t?(jc("data",this.frozen),this.namespace=t,this):this.namespace}freeze(){if(this.frozen)return this;const t=this;for(;++this.freezeIndex<this.attachers.length;){const[n,...i]=this.attachers[this.freezeIndex];if(i[0]===!1)continue;i[0]===!0&&(i[0]=void 0);const r=n.call(t,...i);typeof r=="function"&&this.transformers.use(r)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(t){this.freeze();const n=is(t),i=this.parser||this.Parser;return Oc("parse",i),i(String(n),n)}process(t,n){const i=this;return this.freeze(),Oc("process",this.parser||this.Parser),Nc("process",this.compiler||this.Compiler),n?r(void 0,n):new Promise(r);function r(o,a){const s=is(t),u=i.parse(s);i.run(u,s,function(c,d,f){if(c||!d||!f)return l(c);const p=d,g=i.stringify(p,f);RK(g)?f.value=g:f.result=g,l(c,f)});function l(c,d){c||!d?a(c):o?o(d):n(void 0,d)}}}processSync(t){let n=!1,i;return this.freeze(),Oc("processSync",this.parser||this.Parser),Nc("processSync",this.compiler||this.Compiler),this.process(t,r),Jy("processSync","process",n),i;function r(o,a){n=!0,Zy(o),i=a}}run(t,n,i){Hy(t),this.freeze();const r=this.transformers;return!i&&typeof n=="function"&&(i=n,n=void 0),i?o(void 0,i):new Promise(o);function o(a,s){const u=is(n);r.run(t,u,l);function l(c,d,f){const p=d||t;c?s(c):a?a(p):i(void 0,p,f)}}}runSync(t,n){let i=!1,r;return this.run(t,n,o),Jy("runSync","run",i),r;function o(a,s){Zy(a),r=s,i=!0}}stringify(t,n){this.freeze();const i=is(n),r=this.compiler||this.Compiler;return Nc("stringify",r),Hy(t),r(t,i)}use(t,...n){const i=this.attachers,r=this.namespace;if(jc("use",this.frozen),t!=null)if(typeof t=="function")u(t,n);else if(typeof t=="object")Array.isArray(t)?s(t):a(t);else throw new TypeError("Expected usable value, not `"+t+"`");return this;function o(l){if(typeof l=="function")u(l,[]);else if(typeof l=="object")if(Array.isArray(l)){const[c,...d]=l;u(c,d)}else a(l);else throw new TypeError("Expected usable value, not `"+l+"`")}function a(l){if(!("plugins"in l)&&!("settings"in l))throw new Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");s(l.plugins),l.settings&&(r.settings=Cc(!0,r.settings,l.settings))}function s(l){let c=-1;if(l!=null)if(Array.isArray(l))for(;++c<l.length;){const d=l[c];o(d)}else throw new TypeError("Expected a list of plugins, not `"+l+"`")}function u(l,c){let d=-1,f=-1;for(;++d<i.length;)if(i[d][0]===l){f=d;break}if(f===-1)i.push([l,...c]);else if(c.length>0){let[p,...g]=c;const m=i[f][1];Ud(m)&&Ud(p)&&(p=Cc(!0,m,p)),i[f]=[l,p,...g]}}}}const AK=new rm().freeze();function Oc(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Nc(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function jc(e,t){if(t)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function Hy(e){if(!Ud(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Jy(e,t,n){if(!n)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function is(e){return PK(e)?e:new sP(e)}function PK(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function RK(e){return typeof e=="string"||OK(e)}function OK(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const NK="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Wy=[],Gy={allowDangerousHtml:!0},jK=/^(https?|ircs?|mailto|xmpp)$/i,MK=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function DK(e){const t=zK(e),n=UK(e);return LK(t.runSync(t.parse(n),n),e)}function zK(e){const t=e.rehypePlugins||Wy,n=e.remarkPlugins||Wy,i=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...Gy}:Gy;return AK().use(v7).use(n).use(pK,i).use(t)}function UK(e){const t=e.children||"",n=new sP;return typeof t=="string"&&(n.value=t),n}function LK(e,t){const n=t.allowedElements,i=t.allowElement,r=t.components,o=t.disallowedElements,a=t.skipHtml,s=t.unwrapDisallowed,u=t.urlTransform||FK;for(const c of MK)Object.hasOwn(t,c.from)&&(""+c.from+(c.to?"use `"+c.to+"` instead":"remove it")+NK+c.id,void 0);return aP(e,l),KJ(e,{Fragment:h.Fragment,components:r,ignoreInvalidStyle:!0,jsx:h.jsx,jsxs:h.jsxs,passKeys:!0,passNode:!0});function l(c,d,f){if(c.type==="raw"&&f&&typeof d=="number")return a?f.children.splice(d,1):f.children[d]={type:"text",value:c.value},d;if(c.type==="element"){let p;for(p in kc)if(Object.hasOwn(kc,p)&&Object.hasOwn(c.properties,p)){const g=c.properties[p],m=kc[p];(m===null||m.includes(c.tagName))&&(c.properties[p]=u(String(g||""),p,c))}}if(c.type==="element"){let p=n?!n.includes(c.tagName):o?o.includes(c.tagName):!1;if(!p&&i&&typeof d=="number"&&(p=!i(c,d,f)),p&&f&&typeof d=="number")return s&&c.children?f.children.splice(d,1,...c.children):f.children.splice(d,1),d}}}function FK(e){const t=e.indexOf(":"),n=e.indexOf("?"),i=e.indexOf("#"),r=e.indexOf("/");return t===-1||r!==-1&&t>r||n!==-1&&t>n||i!==-1&&t>i||jK.test(e.slice(0,t))?e:""}const BK=(e,t)=>typeof e=="string"?e===t:JSON.stringify(e)===JSON.stringify(t),ZK=(e,t)=>{if(!e||!t)return!1;const n=i=>{const{position:r,data:o,...a}=i||{};return a};return JSON.stringify(n(e.properties))===JSON.stringify(n(t.properties))&&BK(e.children,t.children)},im=(e,t)=>ZK(e.node,t.node),qK=(e={})=>Object.fromEntries(Object.entries(e??{}).map(([t,n])=>{if(!n)return[t,n];const i=n,r=({node:o,...a})=>h.jsx(i,{...a});return[t,k.memo(r,im)]})),om=k.createContext(null),lP=()=>k.useContext(om)!==null,VK=({children:e,...t})=>h.jsx(om.Provider,{value:t,children:e}),HK=k.memo(VK,im),JK=({node:e,...t})=>h.jsx("pre",{...t}),WK=({node:e,...t})=>h.jsx("code",{...t}),am=({node:e,components:{Pre:t,Code:n},code:i})=>h.jsx(t,{children:h.jsx(n,{node:e,children:i})}),GK=()=>null,KK=({node:e,components:{Pre:t,Code:n,SyntaxHighlighter:i,CodeHeader:r},language:o,code:a})=>{const s=k.useMemo(()=>({Pre:t,Code:n}),[t,n]),u=o?i:am;return h.jsxs(h.Fragment,{children:[h.jsx(r,{node:e,language:o,code:a}),h.jsx(u,{node:e,components:s,language:o??"unknown",code:a})]})};var Mc={exports:{}};var Ky;function YK(){return Ky||(Ky=1,(function(e){(function(){var t={}.hasOwnProperty;function n(){for(var o="",a=0;a<arguments.length;a++){var s=arguments[a];s&&(o=r(o,i(s)))}return o}function i(o){if(typeof o=="string"||typeof o=="number")return o;if(typeof o!="object")return"";if(Array.isArray(o))return n.apply(null,o);if(o.toString!==Object.prototype.toString&&!o.toString.toString().includes("[native code]"))return o.toString();var a="";for(var s in o)t.call(o,s)&&o[s]&&(a=r(a,s));return a}function r(o,a){return a?o?o+" "+a:o+a:o}e.exports?(n.default=n,e.exports=n):window.classNames=n})()})(Mc)),Mc.exports}var XK=YK();const uP=ga(XK),Yy=({className:e,...t})=>({className:n,...i})=>({className:uP(e,n),...t,...i}),QK=({node:e,components:{Pre:t,Code:n,SyntaxHighlighter:i,CodeHeader:r},componentsByLanguage:o={},children:a,...s})=>{const u=k.useContext(om),l=Yy(u),c=Ot(y=>h.jsx(t,{...l(y)})),d=Yy(s),f=Ot(y=>h.jsx(n,{...d(y)})),p=/language-(\w+)/.exec(s.className||"")?.[1]??"";if(typeof a!="string")return h.jsx(am,{node:e,components:{Pre:c,Code:f},code:a});const g=o[p]?.SyntaxHighlighter??i,m=o[p]?.CodeHeader??r;return h.jsx(KK,{node:e,components:{Pre:c,Code:f,SyntaxHighlighter:g,CodeHeader:m},language:p||"unknown",code:a})},e8=({node:e,components:t,componentsByLanguage:n,...i})=>lP()?h.jsx(QK,{node:e,components:t,componentsByLanguage:n,...i}):h.jsx(t.Code,{...i}),t8=k.memo(e8,(e,t)=>e.components===t.components&&e.componentsByLanguage===t.componentsByLanguage&&im(e,t)),{useSmooth:n8,useSmoothStatus:r8,withSmoothContextProvider:i8}=NE,o8=({components:e,componentsByLanguage:t,smooth:n=!0,preprocess:i,...r})=>{const o=FT(),a=k.useMemo(()=>i?{...o,text:i(o.text)}:o,[o,i]),{text:s}=n8(a,n),{pre:u=JK,code:l=WK,SyntaxHighlighter:c=am,CodeHeader:d=GK}=e??{},f=k.useMemo(()=>({Pre:u,Code:l,SyntaxHighlighter:c,CodeHeader:d}),[u,l,c,d]),p=Ot(m=>h.jsx(t8,{components:f,componentsByLanguage:t,...m})),g=k.useMemo(()=>{const{pre:m,code:y,SyntaxHighlighter:v,CodeHeader:_,...x}=e??{};return{...x,pre:HK,code:p}},[p,e]);return h.jsx(DK,{components:g,...r,children:s})},cP=k.forwardRef(({className:e,containerProps:t,containerComponent:n="div",...i},r)=>{const o=r8();return h.jsx(n,{"data-status":o.type,...t,className:uP(e,t?.className),ref:r,children:h.jsx(o8,{...i})})});cP.displayName="MarkdownTextPrimitive";const a8=i8(cP);function s8(e){return k.useMemo(()=>e.reduce((t,n)=>(t?.[n.language]&&!n.overrideExisting||(t={...t,[n.language]:{CodeHeader:n.Header??(()=>null),SyntaxHighlighter:n.Component??void 0}}),t),{}),[e])}const l8=()=>{const{plugins:e}=R.useElements(),t=s8(e);return h.jsx(a8,{remarkPlugins:[CP],className:"aui-md",components:d8,componentsByLanguage:t})},dP=k.memo(l8),u8=({language:e,code:t})=>{const i=ee(({message:s})=>s).status?.type==="complete",{isCopied:r,copyToClipboard:o}=c8(),a=()=>{!t||r||o(t)};return i?h.jsxs("div",{className:"aui-code-header-root bg-muted-foreground/15 text-foreground dark:bg-muted-foreground/20 mt-4 flex items-center justify-between gap-4 rounded-t-lg px-4 py-2 text-sm font-semibold",children:[h.jsx("span",{className:"aui-code-header-language lowercase [&>span]:text-xs",children:e}),h.jsxs(Wt,{tooltip:"Copy",onClick:a,children:[!r&&h.jsx(gh,{}),r&&h.jsx(ir,{})]})]}):null},c8=({copiedDuration:e=3e3}={})=>{const[t,n]=k.useState(!1);return{isCopied:t,copyToClipboard:r=>{r&&navigator.clipboard.writeText(r).then(()=>{n(!0),setTimeout(()=>n(!1),e)})}}},d8=qK({h1:({className:e,...t})=>h.jsx("h1",{className:R.cn("aui-md-h1 mb-8 scroll-m-20 text-4xl font-extrabold tracking-tight last:mb-0",e),...t}),h2:({className:e,...t})=>h.jsx("h2",{className:R.cn("aui-md-h2 mt-8 mb-4 scroll-m-20 text-3xl font-semibold tracking-tight first:mt-0 last:mb-0",e),...t}),h3:({className:e,...t})=>h.jsx("h3",{className:R.cn("aui-md-h3 mt-6 mb-4 scroll-m-20 text-2xl font-semibold tracking-tight first:mt-0 last:mb-0",e),...t}),h4:({className:e,...t})=>h.jsx("h4",{className:R.cn("aui-md-h4 mt-6 mb-4 scroll-m-20 text-xl font-semibold tracking-tight first:mt-0 last:mb-0",e),...t}),h5:({className:e,...t})=>h.jsx("h5",{className:R.cn("aui-md-h5 my-4 text-lg font-semibold first:mt-0 last:mb-0",e),...t}),h6:({className:e,...t})=>h.jsx("h6",{className:R.cn("aui-md-h6 my-4 font-semibold first:mt-0 last:mb-0",e),...t}),p:({className:e,...t})=>h.jsx("p",{className:R.cn("aui-md-p mt-5 mb-5 leading-7 first:mt-0 last:mb-0",e),...t}),a:({className:e,...t})=>h.jsx("a",{className:R.cn("aui-md-a text-primary font-medium underline underline-offset-4",e),...t}),blockquote:({className:e,...t})=>h.jsx("blockquote",{className:R.cn("aui-md-blockquote border-l-2 pl-6 italic",e),...t}),ul:({className:e,...t})=>h.jsx("ul",{className:R.cn("aui-md-ul my-5 ml-6 list-disc [&>li]:mt-2",e),...t}),ol:({className:e,...t})=>h.jsx("ol",{className:R.cn("aui-md-ol my-5 ml-6 list-decimal [&>li]:mt-2",e),...t}),hr:({className:e,...t})=>h.jsx("hr",{className:R.cn("aui-md-hr my-5 border-b",e),...t}),table:({className:e,...t})=>h.jsx("table",{className:R.cn("aui-md-table my-5 w-full border-separate border-spacing-0 overflow-y-auto",e),...t}),th:({className:e,...t})=>h.jsx("th",{className:R.cn("aui-md-th bg-muted px-4 py-2 text-left font-bold first:rounded-tl-lg last:rounded-tr-lg [[align=center]]:text-center [[align=right]]:text-right",e),...t}),td:({className:e,...t})=>h.jsx("td",{className:R.cn("aui-md-td border-b border-l px-4 py-2 text-left last:border-r [[align=center]]:text-center [[align=right]]:text-right",e),...t}),tr:({className:e,...t})=>h.jsx("tr",{className:R.cn("aui-md-tr m-0 border-b p-0 first:border-t [&:last-child>td:first-child]:rounded-bl-lg [&:last-child>td:last-child]:rounded-br-lg",e),...t}),sup:({className:e,...t})=>h.jsx("sup",{className:R.cn("aui-md-sup [&>a]:text-xs [&>a]:no-underline",e),...t}),pre:({className:e,...t})=>h.jsx("pre",{className:R.cn("aui-md-pre text-foreground bg-muted overflow-x-auto rounded-t-none! rounded-b-lg border border-t-0 p-4",e),...t}),code:function({className:t,...n}){const i=lP();return h.jsx("code",{className:R.cn(!i&&"aui-md-inline-code bg-muted rounded border font-semibold",t),...n})},CodeHeader:u8});var Pu="Collapsible",[p8]=ya(Pu),[f8,sm]=p8(Pu),pP=w.forwardRef((e,t)=>{const{__scopeCollapsible:n,open:i,defaultOpen:r,disabled:o,onOpenChange:a,...s}=e,[u,l]=gu({prop:i,defaultProp:r??!1,onChange:a,caller:Pu});return h.jsx(f8,{scope:n,disabled:o,contentId:ri(),open:u,onOpenToggle:w.useCallback(()=>l(c=>!c),[l]),children:h.jsx(Xe.div,{"data-state":um(u),"data-disabled":o?"":void 0,...s,ref:t})})});pP.displayName=Pu;var fP="CollapsibleTrigger",hP=w.forwardRef((e,t)=>{const{__scopeCollapsible:n,...i}=e,r=sm(fP,n);return h.jsx(Xe.button,{type:"button","aria-controls":r.contentId,"aria-expanded":r.open||!1,"data-state":um(r.open),"data-disabled":r.disabled?"":void 0,disabled:r.disabled,...i,ref:t,onClick:Pe(e.onClick,r.onOpenToggle)})});hP.displayName=fP;var lm="CollapsibleContent",mP=w.forwardRef((e,t)=>{const{forceMount:n,...i}=e,r=sm(lm,e.__scopeCollapsible);return h.jsx(Hn,{present:n||r.open,children:({present:o})=>h.jsx(h8,{...i,ref:t,present:o})})});mP.displayName=lm;var h8=w.forwardRef((e,t)=>{const{__scopeCollapsible:n,present:i,children:r,...o}=e,a=sm(lm,n),[s,u]=w.useState(i),l=w.useRef(null),c=Qe(t,l),d=w.useRef(0),f=d.current,p=w.useRef(0),g=p.current,m=a.open||s,y=w.useRef(m),v=w.useRef(void 0);return w.useEffect(()=>{const _=requestAnimationFrame(()=>y.current=!1);return()=>cancelAnimationFrame(_)},[]),Jt(()=>{const _=l.current;if(_){v.current=v.current||{transitionDuration:_.style.transitionDuration,animationName:_.style.animationName},_.style.transitionDuration="0s",_.style.animationName="none";const x=_.getBoundingClientRect();d.current=x.height,p.current=x.width,y.current||(_.style.transitionDuration=v.current.transitionDuration,_.style.animationName=v.current.animationName),u(i)}},[a.open,i]),h.jsx(Xe.div,{"data-state":um(a.open),"data-disabled":a.disabled?"":void 0,id:a.contentId,hidden:!m,...o,ref:c,style:{"--radix-collapsible-content-height":f?`${f}px`:void 0,"--radix-collapsible-content-width":g?`${g}px`:void 0,...e.style},children:m&&r})});function um(e){return e?"open":"closed"}var m8=pP;function g8({...e}){return h.jsx(m8,{"data-slot":"collapsible",...e})}function v8({...e}){return h.jsx(hP,{"data-slot":"collapsible-trigger",...e})}function y8({...e}){return h.jsx(mP,{"data-slot":"collapsible-content",...e})}const Xy=200,gP=({className:e,children:t})=>{const n=k.useRef(null),[i,r]=k.useState(!1),o=j6(n,Xy),a=k.useCallback(s=>{s||o(),r(s)},[o]);return h.jsx(g8,{ref:n,open:i,onOpenChange:a,className:R.cn("aui-reasoning-root mb-4 w-full",e),style:{"--animation-duration":`${Xy}ms`},children:t})};gP.displayName="ReasoningRoot";const b8=({className:e})=>h.jsx("div",{className:R.cn("aui-reasoning-fade pointer-events-none absolute inset-x-0 bottom-0 z-10 h-16","bg-[linear-gradient(to_top,var(--color-background),transparent)]","fade-in-0 animate-in","group-data-[state=open]/collapsible-content:animate-out","group-data-[state=open]/collapsible-content:fade-out-0","group-data-[state=open]/collapsible-content:delay-[calc(var(--animation-duration)*0.75)]","group-data-[state=open]/collapsible-content:fill-mode-forwards","duration-(--animation-duration)","group-data-[state=open]/collapsible-content:duration-(--animation-duration)",e)}),_8=({active:e,className:t})=>h.jsxs(v8,{className:R.cn("aui-reasoning-trigger group/trigger text-muted-foreground hover:text-foreground -mb-2 flex max-w-[75%] items-center gap-2 py-2 text-sm transition-colors",t,e&&"shimmer"),children:[h.jsx(J6,{className:"aui-reasoning-trigger-icon size-4 shrink-0"}),h.jsxs("span",{className:"aui-reasoning-trigger-label-wrapper relative inline-block leading-none",children:[h.jsx("span",{children:"Reasoning"}),e?h.jsx("span",{"aria-hidden":!0,className:"aui-reasoning-trigger-shimmer shimmer pointer-events-none absolute inset-0 motion-reduce:animate-none",children:"Reasoning"}):null]}),h.jsx(Vs,{className:R.cn("aui-reasoning-trigger-chevron mt-0.5 size-4 shrink-0","transition-transform duration-(--animation-duration) ease-out","group-data-[state=closed]/trigger:-rotate-90","group-data-[state=open]/trigger:rotate-0")})]}),vP=({className:e,children:t,"aria-busy":n})=>h.jsxs(y8,{className:R.cn("aui-reasoning-content text-muted-foreground relative overflow-hidden text-sm outline-none","group/collapsible-content ease-out","data-[state=closed]:animate-collapsible-up","data-[state=open]:animate-collapsible-down","data-[state=closed]:fill-mode-forwards","data-[state=closed]:pointer-events-none","data-[state=open]:duration-(--animation-duration)","data-[state=closed]:duration-(--animation-duration)",e),"aria-busy":n,children:[t,h.jsx(b8,{})]});vP.displayName="ReasoningContent";const yP=({className:e,children:t})=>h.jsx("div",{className:R.cn("aui-reasoning-text relative z-0 space-y-4 pt-4 pl-6 leading-relaxed","transform-gpu transition-[transform,opacity]","group-data-[state=open]/collapsible-content:animate-in","group-data-[state=closed]/collapsible-content:animate-out","group-data-[state=open]/collapsible-content:fade-in-0","group-data-[state=closed]/collapsible-content:fade-out-0","group-data-[state=open]/collapsible-content:slide-in-from-top-4","group-data-[state=closed]/collapsible-content:slide-out-to-top-4","group-data-[state=open]/collapsible-content:duration-(--animation-duration)","group-data-[state=closed]/collapsible-content:duration-(--animation-duration)","[&_p]:-mb-2",e),children:t});yP.displayName="ReasoningText";const w8=()=>h.jsx(dP,{}),x8=({children:e,startIndex:t,endIndex:n})=>{const i=ee(({message:r})=>{if(r.status?.type!=="running")return!1;const o=r.parts.length-1;return o<0||r.parts[o]?.type!=="reasoning"?!1:o>=t&&o<=n});return h.jsxs(gP,{children:[h.jsx(_8,{active:i}),h.jsx(vP,{"aria-busy":i,children:h.jsx(yP,{children:e})})]})},bP=k.memo(w8);bP.displayName="Reasoning";const _P=k.memo(x8);_P.displayName="ReasoningGroup";function wP({...e}){return h.jsx(T2,{"data-slot":"popover",...e})}function xP({...e}){return h.jsx($2,{"data-slot":"popover-trigger",...e})}function SP({className:e,align:t="center",sideOffset:n=4,...i}){return h.jsx(C2,{children:h.jsx(A2,{"data-slot":"popover-content",align:t,sideOffset:n,className:R.cn("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-20 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",e),...i})})}const S8=HC("flex size-5 items-center justify-center rounded-full",{variants:{status:{pending:"border border-dashed border-muted-foreground/50",running:"text-primary",complete:"text-green-600 dark:text-green-500",error:"text-destructive",approval:"text-amber-500"}},defaultVariants:{status:"pending"}});function I8(e){switch(e){case"text/markdown":return"markdown";case"text/html":return"html";case"text/css":return"css";case"application/json":return"json";case"text/javascript":return"javascript";case"text/typescript":return"typescript";case"text/python":return"python";default:return}}function k8(e,t){if(t==="json")try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}return e}function E8(e){return typeof e=="object"&&e!==null&&"content"in e&&Array.isArray(e.content)}function IP({status:e}){return h.jsxs("div",{className:R.cn(S8({status:e})),children:[e==="pending"&&null,e==="running"&&h.jsx(Hs,{className:"size-4 animate-spin"}),e==="complete"&&h.jsx(ir,{className:"size-4"}),e==="error"&&h.jsx(xa,{className:"size-4"}),e==="approval"&&h.jsx(Hs,{className:"text-muted-foreground size-4 animate-spin"})]})}function T8({content:e}){const[t,n]=k.useState(!1),i=async r=>{r.stopPropagation(),await navigator.clipboard.writeText(e),n(!0),setTimeout(()=>n(!1),2e3)};return h.jsx("button",{onClick:i,className:"text-muted-foreground hover:bg-accent hover:text-foreground rounded p-1 transition-colors","aria-label":"Copy to clipboard",children:t?h.jsx(ir,{className:"size-4"}):h.jsx(gh,{className:"size-4"})})}function kP({text:e,language:t,className:n}){const[i,r]=k.useState(null);return k.useEffect(()=>{t&&AP.codeToHtml(e,{lang:t,theme:"github-dark-default",rootStyle:"background-color: transparent;",transformers:[{pre(o){o.properties.class="w-full py-3 px-4 max-h-[300px] overflow-y-auto whitespace-pre-wrap text-left text-sm"}}]}).then(r)},[e,t]),i?h.jsx("div",{className:R.cn("w-full bg-slate-800/90",n),dangerouslySetInnerHTML:{__html:i}}):h.jsx("pre",{className:R.cn("w-full bg-slate-800/90 px-4 py-3 text-sm whitespace-pre-wrap text-slate-100",n),children:e})}function $8({data:e}){const t=`data:image/png;base64,${e}`;return h.jsx("div",{className:"flex items-center justify-center rounded-lg p-5",style:{backgroundImage:`linear-gradient(45deg, #ccc 25%, transparent 25%),
|
|
158
|
-
linear-gradient(135deg, #ccc 25%, transparent 25%),
|
|
159
|
-
linear-gradient(45deg, transparent 75%, #ccc 75%),
|
|
160
|
-
linear-gradient(135deg, transparent 75%, #ccc 75%)`,backgroundSize:"25px 25px",backgroundPosition:"0 0, 12.5px 0, 12.5px -12.5px, 0px 12.5px"},children:h.jsx("img",{src:t,className:"max-h-[300px] max-w-full object-contain"})})}function C8({content:e}){return h.jsx("div",{className:"w-full",children:e.content.map((t,n)=>{switch(t.type){case"text":{const i=I8(t._meta?.["getgram.ai/mime-type"]??"text/plain"),r=k8(t.text,i);return h.jsx(kP,{text:r,language:i},n)}case"image":return h.jsx($8,{data:t.data},n);default:return h.jsx("pre",{className:"px-4 py-3 text-sm whitespace-pre-wrap",children:JSON.stringify(t,null,2)},n)}})})}function Qy({title:e,content:t,defaultExpanded:n=!1,highlightSyntax:i=!0,language:r="json"}){const[o,a]=k.useState(n),s=E8(t),u=s?JSON.stringify(t,null,2):typeof t=="string"?t:JSON.stringify(t,null,2);return h.jsxs("div",{"data-slot":"tool-ui-section",className:"border-border border-t",children:[h.jsxs("button",{onClick:()=>a(!o),className:"hover:bg-accent/50 flex w-full cursor-pointer items-center justify-between px-4 py-2.5 text-left transition-colors",children:[h.jsx("span",{className:"text-muted-foreground text-sm",children:e}),h.jsxs("div",{className:"flex items-center gap-1",children:[h.jsx(T8,{content:u}),h.jsx(m0,{className:R.cn("text-muted-foreground size-4 transition-transform duration-200",o&&"rotate-90")})]})]}),o&&h.jsx("div",{className:"border-border border-t",children:s?h.jsx(C8,{content:t}):i?h.jsx(kP,{text:u,language:r}):h.jsx("pre",{className:"text-foreground overflow-x-auto px-4 py-3 text-sm whitespace-pre-wrap",children:u})})]})}function A8({name:e,icon:t,provider:n,status:i="complete",request:r,result:o,defaultExpanded:a=!1,className:s,onApproveOnce:u,onApproveForSession:l,onDeny:c}){const d=i==="approval"&&u!==void 0&&c!==void 0,[f,p]=k.useState(a),g=r!==void 0||o!==void 0,[m,y]=k.useState("one-time"),[v,_]=k.useState(!1);k.useEffect(()=>{!d&&f&&!a&&p(!1)},[d]);const x=()=>{m==="for-session"&&l?l():u&&u()};return h.jsxs("div",{"data-slot":"tool-ui",className:R.cn("border-border bg-card overflow-hidden rounded-lg border",s),children:[n&&h.jsxs("div",{"data-slot":"tool-ui-provider",className:R.cn("border-border flex items-center gap-2 border-b px-4 py-2.5"),children:[t?h.jsx("span",{className:"flex size-5 items-center justify-center",children:t}):h.jsx("span",{className:"bg-muted flex size-5 items-center justify-center rounded text-xs font-medium",children:n.charAt(0).toUpperCase()}),h.jsx("span",{className:"text-sm font-medium",children:n})]}),h.jsxs("button",{onClick:()=>g&&p(!f),disabled:!g,className:R.cn("flex w-full items-center gap-2 px-4 py-3 text-left",g&&"hover:bg-accent/50 cursor-pointer transition-colors"),children:[h.jsx(IP,{status:i}),h.jsx("span",{className:R.cn("flex-1 text-sm",!n&&d&&"shimmer"),children:e}),g&&h.jsx(Vs,{className:R.cn("text-muted-foreground size-4 transition-transform duration-200",f&&"rotate-180")})]}),f&&g&&h.jsxs("div",{"data-slot":"tool-ui-content",children:[r!==void 0&&h.jsx(Qy,{title:"Arguments",content:r,highlightSyntax:!0,language:"json"}),o!==void 0&&h.jsx(Qy,{title:"Output",content:o,highlightSyntax:!0,language:"json"})]}),d&&h.jsxs("div",{"data-slot":"tool-ui-approval-actions",className:"border-border flex items-center justify-end gap-2 border-t px-4 py-3",children:[h.jsx("div",{children:h.jsx("span",{className:"text-muted-foreground text-sm",children:"This tool requires approval"})}),h.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[h.jsxs(Pt,{variant:"outline",size:"sm",onClick:c,className:"text-destructive hover:bg-destructive/10",children:[h.jsx(xa,{className:"mr-1 size-3"}),"Deny"]}),h.jsxs("div",{className:"flex items-center",children:[h.jsxs(Pt,{variant:"default",size:"sm",onClick:x,className:"flex cursor-pointer justify-between gap-1 rounded-r-none bg-emerald-600 hover:bg-emerald-700",children:[h.jsx(ir,{className:"mr-1 size-3"}),h.jsx("span",{className:"min-w-[110px]",children:m==="one-time"?"Approve this time":"Approve always"})]}),h.jsxs(wP,{open:v,onOpenChange:_,children:[h.jsx(xP,{asChild:!0,children:h.jsx(Pt,{variant:"default",size:"sm",className:"cursor-pointer rounded-l-none border-l border-emerald-700 bg-emerald-600 px-2 hover:bg-emerald-700",children:h.jsx(Vs,{className:"size-3"})})}),h.jsxs(SP,{align:"end",className:"w-64 p-1",sideOffset:4,children:[h.jsxs("button",{onClick:()=>{y("one-time"),_(!1)},className:"hover:bg-accent relative flex w-full items-start gap-2 rounded-sm px-2 py-2 text-left",children:[h.jsx(ir,{className:R.cn("relative top-1 mt-0.5 size-3 shrink-0",m!=="one-time"&&"invisible")}),h.jsxs("div",{className:"flex flex-col gap-0.5",children:[h.jsx("span",{className:"text-sm",children:"Approve only once"}),h.jsx("span",{className:"text-muted-foreground text-xs",children:"You'll be asked again next time"})]})]}),l&&h.jsxs("button",{onClick:()=>{y("for-session"),_(!1)},className:"hover:bg-accent relative flex w-full items-start gap-2 rounded-sm px-2 py-2 text-left",children:[h.jsx(ir,{className:R.cn("relative top-1 mt-0.5 size-3 shrink-0",m!=="for-session"&&"invisible")}),h.jsxs("div",{className:"flex flex-col gap-0.5",children:[h.jsx("span",{className:"text-sm",children:"Approve always"}),h.jsx("span",{className:"text-muted-foreground text-xs",children:"Trust this tool for the session"})]})]})]})]})]})]})]})]})}function P8({title:e,icon:t,status:n="complete",defaultExpanded:i=!1,children:r,className:o}){const[a,s]=k.useState(i);return h.jsxs("div",{"data-slot":"tool-ui-group",className:R.cn("border-border bg-card overflow-hidden rounded-lg border",o),children:[h.jsxs("button",{onClick:()=>s(!a),className:"hover:bg-accent/50 flex w-full items-center gap-2 px-4 py-3 text-left transition-colors",children:[t||h.jsx(IP,{status:n==="running"?"running":"complete"}),h.jsx("span",{className:R.cn("flex-1 text-sm font-medium",n==="running"&&"shimmer"),children:e}),h.jsx(Vs,{className:R.cn("text-muted-foreground size-4 transition-transform duration-200",a&&"rotate-180")})]}),a&&h.jsx("div",{"data-slot":"tool-ui-group-content",className:"border-border border-t",children:r})]})}const R8=({toolName:e,toolCallId:t,status:n,result:i,args:r})=>{const{pendingApprovals:o,whitelistTool:a,confirmPendingApproval:s,rejectPendingApproval:u}=Fk(),l=o.get(t),d=ee(({message:_})=>_).parts.filter(_=>_.type==="tool-call"),f=d.findIndex(_=>_.toolName===e),p=()=>{s(t)},g=()=>{a(e),s(t)},m=()=>{u(t)},y=()=>l?"approval":n.type==="incomplete"?"error":n.type==="complete"?i&&typeof i=="object"&&"isError"in i&&i.isError?"error":"complete":"running",v=()=>{if(i!==void 0)return typeof i=="object"&&i!==null&&"content"in i&&Array.isArray(i.content)||typeof i=="string",i};return h.jsx("div",{className:R.cn("aui-tool-fallback-root flex w-full flex-col",f!==-1&&f!==d.length-1&&"border-b"),children:h.jsx(A8,{name:e,status:y(),request:r,result:v(),onApproveOnce:l?p:void 0,onApproveForSession:l?g:void 0,onDeny:l?m:void 0,className:"rounded-none border-0"})})},cm=()=>{const{config:e}=R.useElements(),t=e.theme??{};return k.useMemo(()=>{const{colorScheme:n="light"}=t;return{className:n==="dark"||n==="system"&&typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":void 0}},[t])},or=[.23,1,.32,1];function O8(e){return e.replace(/[-_]/g," ").split(/(?=[A-Z])/).join(" ").split(/\s+/).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" ")}const N8=({children:e})=>{const t=ee(({message:s})=>s).parts,n=t.filter(s=>s.type==="tool-call"),i=n.some(s=>s.status?.type==="running"),{config:r}=R.useElements(),o=r.tools?.expandToolGroupsByDefault??!1,a=k.useMemo(()=>{const s=t.filter(u=>u.type==="tool-call");return s.length===0?"No tools called":s.length===1?`Calling ${O8(s[0].toolName)}...`:i?`Calling ${s.length} tools...`:`Executed ${s.length} tools`},[t,i]);return r.tools?.components?.[n[0]?.toolName]?e:n.length===1?h.jsx("div",{className:R.cn("my-4 w-full max-w-xl"),children:h.jsx("div",{className:"border-border bg-card overflow-hidden rounded-lg border",children:e})}):h.jsx("div",{className:"my-4 w-full max-w-xl",children:h.jsx(P8,{title:a,status:i?"running":"complete",defaultExpanded:o,children:e})})},j8=()=>h.jsxs("div",{className:"m-2 rounded-md border border-amber-500 bg-amber-100 px-4 py-3 text-sm text-amber-800 dark:border-amber-600 dark:bg-amber-900/30 dark:text-amber-200",children:[h.jsx("strong",{children:"Warning:"})," You are using an API key directly in the client. Please"," ",h.jsx("a",{href:"https://github.com/speakeasy-api/gram/tree/main/elements#setting-up-your-backend",target:"_blank",rel:"noopener noreferrer",className:"text-amber-700 underline hover:text-amber-800 dark:text-amber-300 dark:hover:text-amber-200",children:"set up a session endpoint"})," ","before deploying to production."]}),dm=({className:e})=>{const t=cm(),n=R.useDensity(),{config:i}=R.useElements(),r=i.components??{},o=i.api&&"UNSAFE_apiKey"in i.api;return h.jsx(zn.LazyMotion,{features:zn.domAnimation,children:h.jsx(zn.MotionConfig,{reducedMotion:"user",children:h.jsx(r0,{className:R.cn("aui-root aui-thread-root bg-background @container flex h-full flex-col",t.className,e),children:h.jsxs(o0,{className:R.cn("aui-thread-viewport relative mx-auto flex w-full flex-1 flex-col overflow-x-auto overflow-y-scroll pb-0!",n("p-lg")),children:[h.jsx(To,{empty:!0,children:r.ThreadWelcome?h.jsx(r.ThreadWelcome,{}):h.jsx(D8,{})}),o&&h.jsx(j8,{}),h.jsx($6,{components:{UserMessage:r.UserMessage??H8,EditComposer:r.EditComposer??W8,AssistantMessage:r.AssistantMessage??Z8}}),h.jsx(To,{empty:!1,children:h.jsx("div",{className:"aui-thread-viewport-spacer min-h-8 grow"})}),h.jsx(U8,{})]})})})})},M8=()=>h.jsx(A6,{asChild:!0,children:h.jsx(Wt,{tooltip:"Scroll to bottom",variant:"outline",className:"aui-thread-scroll-to-bottom dark:bg-background dark:hover:bg-accent absolute -top-12 z-10 self-center rounded-full p-4 disabled:invisible",children:h.jsx(Z6,{})})}),D8=()=>{const{config:e}=R.useElements(),t=R.useDensity(),{title:n,subtitle:i}=e.welcome??{},r=e.variant==="standalone";return h.jsxs("div",{className:R.cn("aui-thread-welcome-root my-auto flex w-full grow flex-col",r?"items-center justify-center":"",t("gap-lg")),children:[h.jsx("div",{className:R.cn("aui-thread-welcome-center flex w-full grow flex-col items-center justify-start"),children:h.jsxs("div",{className:R.cn("aui-thread-welcome-message flex flex-col",r?"items-center text-center":"size-full justify-start",t("gap-sm"),!r&&t("py-md")),children:[h.jsx(Mn.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:10},transition:{duration:.25,ease:or},className:R.cn("aui-thread-welcome-message-motion-1 text-foreground font-semibold",t("text-title")),children:n}),h.jsx(Mn.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:10},transition:{duration:.25,delay:.05,ease:or},className:R.cn("aui-thread-welcome-message-motion-2 text-muted-foreground/65",t("text-subtitle")),children:i})]})}),h.jsx(z8,{})]})},z8=()=>{const{config:e}=R.useElements(),t=R.useRadius(),n=R.useDensity(),i=e.welcome?.suggestions??[],r=e.variant==="standalone";return i.length===0?null:h.jsx("div",{className:R.cn("aui-thread-welcome-suggestions w-full",n("gap-md"),n("py-lg"),r?"flex flex-wrap items-center justify-center":i.length===1?"flex":"grid max-w-fit @md:grid-cols-2"),children:i.map((o,a)=>h.jsx(Mn.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:20},transition:{duration:.25,delay:.03*a,ease:or},className:R.cn("aui-thread-welcome-suggestion-display",!r&&"nth-[n+3]:hidden @md:nth-[n+3]:block"),children:h.jsx(R6,{prompt:o.action,send:!0,asChild:!0,children:h.jsxs(Pt,{variant:"ghost",className:R.cn("aui-thread-welcome-suggestion dark:hover:bg-accent/60 h-auto w-full border text-left whitespace-break-spaces",n("text-base"),r?`flex-row items-center ${n("gap-sm")} ${n("px-md")} ${n("py-sm")} ${t("full")}`:`w-full flex-1 flex-col flex-wrap items-start justify-start ${n("gap-sm")} ${n("px-lg")} ${n("py-md")} ${t("xl")}`),"aria-label":o.action,children:[h.jsx("span",{className:"aui-thread-welcome-suggestion-text-1 text-foreground text-sm font-medium",children:o.title}),h.jsx("span",{className:"aui-thread-welcome-suggestion-text-2 text-muted-foreground text-sm",children:o.label})]})})},`suggested-action-${o.title}-${a}`))})},U8=()=>{const{config:e}=R.useElements(),t=R.useRadius(),n=R.useDensity(),i=e.composer??{placeholder:"Send a message...",attachments:!0},r=e.components??{};return r.Composer?h.jsx(r.Composer,{}):h.jsxs("div",{className:R.cn("aui-composer-wrapper bg-background sticky bottom-0 flex w-full flex-col overflow-visible",n("gap-md"),n("py-md"),t("xl")),children:[h.jsx(M8,{}),h.jsxs(fh,{className:R.cn("aui-composer-root group/input-group border-input bg-background has-[textarea:focus-visible]:border-ring has-[textarea:focus-visible]:ring-ring/5 dark:bg-background relative flex w-full flex-col border px-1 pt-2 shadow-xs transition-[color,box-shadow] outline-none has-[textarea:focus-visible]:ring-1",t("xl")),children:[i.attachments&&h.jsx(_J,{}),h.jsx(mh,{placeholder:i.placeholder,className:R.cn("aui-composer-input placeholder:text-muted-foreground mb-1 max-h-32 w-full resize-none bg-transparent px-3.5 pt-1.5 pb-3 outline-none focus-visible:ring-0",n("h-input"),n("text-base")),rows:1,autoFocus:!0,"aria-label":"Message input"}),h.jsx(F8,{})]})]})},L8=()=>{const{model:e,setModel:t}=R.useElements(),[n,i]=k.useState(!1),[r,o]=k.useState(!1),a=k.useRef(null),s=k.useRef(0),u=k.useRef(!1);k.useEffect(()=>{n&&!u.current&&requestAnimationFrame(()=>{const c=a.current;c&&c.scrollHeight>0&&(c.scrollTop=s.current)}),u.current=n},[n]),k.useEffect(()=>{n&&o(!1)},[n]);const l=c=>{s.current=c.currentTarget.scrollTop};return h.jsx(rA,{children:h.jsxs(Dh,{open:r&&!n,onOpenChange:o,children:[h.jsxs(wP,{open:n,onOpenChange:i,children:[h.jsx(zh,{asChild:!0,children:h.jsx(xP,{asChild:!0,children:h.jsx(Pt,{variant:"ghost",size:"icon","data-state":n?"open":"closed",className:"aui-composer-model-picker data-[state=open]:bg-muted-foreground/15 dark:border-muted-foreground/15 dark:hover:bg-muted-foreground/30 flex w-fit items-center gap-2 rounded-full px-2.5 py-1 text-xs font-semibold","aria-label":"Model Settings",children:h.jsx(bF,{className:"aui-attachment-add-icon size-5 stroke-[1.5px]"})})})}),h.jsx(SP,{side:"top",align:"start",className:"w-min p-0 shadow-none",children:h.jsx("div",{ref:a,className:"max-h-48 overflow-y-auto",onScroll:l,children:jf.map(c=>h.jsxs(Pt,{onClick:()=>{t(c)},variant:"ghost",className:"w-full justify-start gap-2 rounded-none px-2",children:[c===e?h.jsx("div",{children:h.jsx(ir,{className:"size-4 text-emerald-500"})}):h.jsx("div",{className:"size-4",children:" "}),c]},c))})})]}),h.jsx(Uh,{side:"bottom",align:"start",children:"Model Settings"})]})})},F8=()=>{const{config:e}=R.useElements(),t=R.useRadius(),n=e.composer??{attachments:!0};return h.jsxs("div",{className:"aui-composer-action-wrapper relative mx-1 mt-2 mb-2 flex items-center justify-between",children:[h.jsxs("div",{className:"aui-composer-action-wrapper-inner flex items-center",children:[n.attachments?h.jsx(wJ,{}):h.jsx("div",{className:"aui-composer-add-attachment-placeholder"}),e.model?.showModelPicker&&!e.languageModel&&h.jsx(L8,{})]}),h.jsx(To,{running:!1,children:h.jsx(KT,{asChild:!0,children:h.jsx(Wt,{tooltip:"Send message",side:"bottom",type:"submit",variant:"default",size:"icon",className:R.cn("aui-composer-send size-[34px] p-1",t("full")),"aria-label":"Send message",children:h.jsx(V6,{className:"aui-composer-send-icon size-5"})})})}),h.jsx(To,{running:!0,children:h.jsx(XT,{asChild:!0,children:h.jsx(Pt,{type:"button",variant:"default",size:"icon",className:R.cn("aui-composer-cancel border-muted-foreground/60 hover:bg-primary/75 dark:border-muted-foreground/90 size-[34px] border",t("full")),"aria-label":"Stop generating",children:h.jsx(wF,{className:"aui-composer-cancel-icon size-3.5 fill-white dark:fill-black"})})})})]})},B8=()=>h.jsx(JT,{children:h.jsx(t0,{className:"aui-message-error-root border-destructive bg-destructive/10 text-destructive dark:bg-destructive/5 mt-2 rounded-md border p-3 text-sm dark:text-red-200",children:h.jsx(n0,{className:"aui-message-error-message line-clamp-2"})})}),Z8=()=>{const{config:e}=R.useElements(),t=e.tools??{},n=e.components??{};return h.jsx(dh,{asChild:!0,children:h.jsxs("div",{className:"aui-assistant-message-root animate-in fade-in slide-in-from-bottom-1 relative mx-auto w-full py-4 duration-150 ease-out last:mb-24","data-role":"assistant",children:[h.jsxs("div",{className:"aui-assistant-message-content text-foreground mx-2 leading-7 wrap-break-word",children:[h.jsx(ph,{components:{Text:n.Text??dP,Image:n.Image??q8,tools:{by_name:t.components,Fallback:n.ToolFallback??R8},Reasoning:n.Reasoning??bP,ReasoningGroup:n.ReasoningGroup??_P,ToolGroup:n.ToolGroup??N8}}),h.jsx(B8,{})]}),h.jsxs("div",{className:"aui-assistant-message-footer mt-2 ml-2 flex",children:[h.jsx(EP,{}),h.jsx(V8,{})]})]})})},q8=e=>h.jsx("img",{src:e.image}),V8=()=>h.jsxs(Kf,{hideWhenRunning:!0,autohide:"not-last",autohideFloat:"single-branch",className:"aui-assistant-action-bar-root text-muted-foreground data-floating:bg-background col-start-3 row-start-2 -ml-1 flex gap-1 data-floating:absolute data-floating:rounded-md data-floating:border data-floating:p-1 data-floating:shadow-sm",children:[h.jsx(UE,{asChild:!0,children:h.jsxs(Wt,{tooltip:"Copy",children:[h.jsx(Zs,{copied:!0,children:h.jsx(ir,{})}),h.jsx(Zs,{copied:!1,children:h.jsx(gh,{})})]})}),h.jsx(R4,{asChild:!0,children:h.jsx(Wt,{tooltip:"Refresh",children:h.jsx(vF,{})})})]}),H8=()=>{const e=R.useRadius();return h.jsx(dh,{asChild:!0,children:h.jsxs("div",{className:"aui-user-message-root animate-in fade-in slide-in-from-bottom-1 mx-auto grid w-full auto-rows-auto grid-cols-[minmax(72px,1fr)_auto] gap-y-2 px-2 py-4 duration-150 ease-out first:mt-3 last:mb-5 [&:where(>*)]:col-start-2","data-role":"user",children:[h.jsx(bJ,{}),h.jsxs("div",{className:"aui-user-message-content-wrapper relative col-start-2 min-w-0",children:[h.jsx("div",{className:R.cn("aui-user-message-content bg-muted text-foreground px-5 py-2.5 wrap-break-word",e("xl")),children:h.jsx(ph,{})}),h.jsx("div",{className:"aui-user-action-bar-wrapper absolute top-1/2 left-0 -translate-x-full -translate-y-1/2 pr-2",children:h.jsx(J8,{})})]}),h.jsx(EP,{className:"aui-user-branch-picker col-span-full col-start-1 row-start-3 -mr-1 justify-end"})]})})},J8=()=>h.jsx(Kf,{hideWhenRunning:!0,autohide:"not-last",className:"aui-user-action-bar-root flex flex-col items-end",children:h.jsx(N4,{asChild:!0,children:h.jsx(Wt,{tooltip:"Edit",className:"aui-user-action-edit p-4",children:h.jsx(hF,{})})})}),W8=()=>h.jsx("div",{className:"aui-edit-composer-wrapper mx-auto flex w-full flex-col gap-4 px-2 first:mt-4",children:h.jsxs(fh,{className:"aui-edit-composer-root bg-muted ml-auto flex w-full max-w-7/8 flex-col rounded-xl",children:[h.jsx(mh,{className:"aui-edit-composer-input text-foreground flex min-h-[60px] w-full resize-none bg-transparent p-4 outline-none",autoFocus:!0}),h.jsxs("div",{className:"aui-edit-composer-footer mx-3 mb-3 flex items-center justify-center gap-2 self-end",children:[h.jsx(XT,{asChild:!0,children:h.jsx(Pt,{variant:"ghost",size:"sm","aria-label":"Cancel edit",children:"Cancel"})}),h.jsx(KT,{asChild:!0,children:h.jsx(Pt,{size:"sm","aria-label":"Update message",children:"Update"})})]})]})}),EP=({className:e,...t})=>h.jsxs(WT,{hideWhenSingleBranch:!0,className:R.cn("aui-branch-picker-root text-muted-foreground mr-2 -ml-2 inline-flex items-center text-xs",e),...t,children:[h.jsx(M2,{asChild:!0,children:h.jsx(Wt,{tooltip:"Previous",children:h.jsx(Y6,{})})}),h.jsxs("span",{className:"aui-branch-picker-state font-medium",children:[h.jsx(zT,{})," / ",h.jsx(DT,{})]}),h.jsx(N2,{asChild:!0,children:h.jsx(Wt,{tooltip:"Next",children:h.jsx(m0,{})})})]});function G8({className:e,...t}){return h.jsx("div",{"data-slot":"skeleton",className:R.cn("bg-accent animate-pulse rounded-md",e),...t})}const pm=({className:e})=>{const t=R.useDensity();return h.jsxs(p0,{className:R.cn("aui-root aui-thread-list-root bg-background flex flex-col items-stretch",t("gap-sm"),e),children:[h.jsx("div",{className:R.cn("aui-thread-list-new-section border-b pb-2",t("py-sm"),t("px-sm")),children:h.jsx(K8,{})}),h.jsx("div",{className:R.cn("aui-thread-list-items-section flex flex-col gap-1",t("py-xs"),t("px-sm")),children:h.jsx(Y8,{})})]})},K8=()=>{const e=R.useDensity();return h.jsx(u0,{asChild:!0,children:h.jsxs(Pt,{className:R.cn("aui-thread-list-new hover:bg-muted-foreground/10 data-[active=true]:bg-muted-foreground/20! flex w-full cursor-pointer items-center justify-start gap-1 rounded-lg px-2.5 py-2 text-start",e("p-sm"),e("py-xs")),variant:"ghost",children:[h.jsx(g0,{}),"New Thread"]})})},Y8=()=>ee(({threads:t})=>t.isLoading)?h.jsx(X8,{}):h.jsx(d0,{components:{ThreadListItem:Q8}}),X8=()=>h.jsx(h.Fragment,{children:Array.from({length:5},(e,t)=>h.jsx("div",{role:"status","aria-label":"Loading threads","aria-live":"polite",className:"aui-thread-list-skeleton-wrapper flex items-center gap-2 rounded-md px-3 py-2",children:h.jsx(G8,{className:"aui-thread-list-skeleton h-[22px] grow"})},t))}),Q8=()=>{const e=R.useRadius(),t=R.useDensity();return h.jsx(f0,{className:R.cn("aui-thread-list-item group hover:bg-muted focus-visible:bg-muted focus-visible:ring-ring data-[active=true]:bg-muted-foreground/20 flex items-center gap-2 rounded-lg transition-all focus-visible:ring-2 focus-visible:outline-none",e("md")),children:h.jsx(N6,{className:R.cn("aui-thread-list-item-trigger flex grow cursor-pointer items-center text-start",t("px-lg"),t("py-sm")),children:h.jsx(eY,{})})})},eY=()=>h.jsx("span",{className:"aui-thread-list-item-title text-sm",children:h.jsx(h0,{fallback:"New Chat"})}),TP=()=>{const{config:e,isExpanded:t,setIsExpanded:n}=R.useElements(),i=e.modal?.defaultExpanded??!1;return{expandable:e.modal?.expandable??!1,isExpanded:t,setIsExpanded:n,defaultExpanded:i}},tY={layout:{duration:.25,ease:or}},nY=({className:e})=>{const{config:t}=R.useElements(),n=cm(),i=R.useRadius(),r=R.useDensity(),[o,a]=k.useState(t.modal?.defaultOpen??!1),{expandable:s,isExpanded:u,setIsExpanded:l}=TP(),c=t.modal?.title,d=t.modal?.icon,f=t.history?.enabled&&t.history?.showThreadList!==!1,p=t.modal?.position??"bottom-right",g=rY(p),m=k.useMemo(()=>t.modal?.dimensions?.default??{width:"500px",height:"600px",maxHeight:"95vh"},[t.modal?.dimensions?.default]),y=k.useMemo(()=>t.modal?.dimensions?.expanded??{width:"70vw",height:"90vh"},[t.modal?.dimensions?.expanded]),_=ee(({thread:E})=>E).messages.some(E=>E.status?.type==="running"),x=u?y.width:m.width,b=u?y.height:m.height,C=m.maxHeight;return h.jsx(zn.LazyMotion,{features:zn.domMax,children:h.jsx(zn.MotionConfig,{reducedMotion:"user",transition:tY,children:h.jsx("div",{className:R.cn("aui-root aui-modal-anchor fixed z-10",g,n.className,i("lg"),o&&"shadow-xl",e),children:h.jsx(zn.AnimatePresence,{mode:"wait",children:o?h.jsxs(Mn.div,{layout:!0,layoutId:"chat-container",className:R.cn("aui-modal-content bg-popover text-popover-foreground flex flex-col overflow-hidden border [&>.aui-thread-root]:bg-inherit",i("lg")),initial:!1,style:{originX:p.includes("left")?0:1,originY:p.includes("top")?0:1,width:x,height:b,maxHeight:C},children:[h.jsxs(Mn.div,{className:R.cn("aui-modal-header flex shrink-0 items-center justify-between border-b",r("h-header"),r("px-lg")),initial:{opacity:0},animate:{opacity:1},transition:{duration:.2,delay:.1,ease:or},children:[h.jsx("div",{className:R.cn("flex min-w-0 items-center"),children:h.jsxs("span",{className:R.cn("text-md flex items-center gap-2 truncate font-medium",_&&"shimmer"),children:[h.jsx("span",{className:"truncate",children:c}),_&&h.jsx(Hs,{className:"text-muted-foreground size-4.5 animate-spin",strokeWidth:1.25})]})}),h.jsxs("div",{className:"flex flex-row items-center justify-end gap-1",children:[s?h.jsx("button",{type:"button",onClick:()=>l(E=>!E),className:R.cn("text-muted-foreground hover:text-foreground hover:bg-accent flex h-8 cursor-pointer items-center rounded-md px-2 text-xs transition-colors"),"aria-pressed":u,"aria-label":u?"Collapse assistant":"Expand assistant",children:u?h.jsx(lF,{strokeWidth:2,className:"size-3.5 rotate-90"}):h.jsx(iF,{strokeWidth:2,className:"size-3.5 rotate-90"})}):null,h.jsx("button",{onClick:()=>{a(!1),l(!1)},className:"text-muted-foreground hover:text-foreground hover:bg-accent -mr-1 flex size-8 cursor-pointer items-center justify-center rounded-md transition-colors","aria-label":`Close ${c}`,children:h.jsx(xa,{className:"size-4.5"})})]})]}),h.jsxs(Mn.div,{className:"aui-modal-body flex flex-1 overflow-hidden",initial:{opacity:0},animate:{opacity:1},transition:{duration:.2,delay:.05,ease:or},children:[f&&h.jsx("div",{className:"aui-modal-thread-list w-56 shrink-0 overflow-y-auto border-r",children:h.jsx(pm,{})}),h.jsx("div",{className:"aui-modal-thread w-full flex-1 overflow-hidden",children:h.jsx(Nh,{children:h.jsx(dm,{})})})]})]},"chat"):h.jsx(Mn.button,{layout:!0,layoutId:"chat-container",onClick:()=>a(!0),className:R.cn("aui-modal-button bg-primary text-primary-foreground flex size-12 cursor-pointer items-center justify-center border shadow-lg transition-shadow hover:shadow-xl",i("full")),initial:!1,"aria-label":`Open ${c}`,style:{originX:1,originY:1},children:h.jsx(Mn.div,{initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.8},transition:{duration:.2,ease:or},className:"flex size-full items-center justify-center",children:d?d("closed"):h.jsx(aF,{className:"size-6"})})},"button")})})})})};function rY(e){switch(e){case"bottom-left":return"left-4 bottom-4";case"top-right":return"right-4 top-4";case"top-left":return"left-4 top-4";case"bottom-right":return"right-4 bottom-4";default:R.assertNever(e)}}const iY=({className:e})=>{const{config:t}=R.useElements(),n=cm(),i=t.sidecar??{},{title:r,dimensions:o}=i,{isExpanded:a,setIsExpanded:s}=TP(),l=ee(({thread:d})=>d).messages.some(d=>d.status?.type==="running"),c=t.history?.enabled&&t.history?.showThreadList!==!1;return h.jsx(zn.LazyMotion,{features:zn.domMax,children:h.jsxs(Mn.div,{initial:{width:o?.default?.width??"400px",height:o?.default?.height??"100vh"},animate:{width:a?o?.expanded?.width??"800px":o?.default?.width??"400px",height:a?o?.expanded?.height??"100%":o?.default?.height??"100vh"},transition:{duration:.3,ease:or},className:R.cn("aui-root aui-sidecar bg-popover text-popover-foreground fixed top-0 right-0 border-l",n.className,e),children:[h.jsxs("div",{className:"aui-sidecar-header flex h-14 items-center justify-between border-b px-4",children:[h.jsxs("span",{className:R.cn("text-md flex items-center gap-2 font-medium",l&&"shimmer"),children:[r,l&&h.jsx(Hs,{className:"text-muted-foreground size-4.5 animate-spin",strokeWidth:1.25})]}),h.jsx("div",{className:"aui-sidecar-header-actions flex items-center gap-1",children:h.jsx(Wt,{tooltip:a?"Collapse":"Pop out",variant:"ghost",className:"aui-sidecar-popout size-8",onClick:()=>s(d=>!d),children:a?h.jsx(cF,{className:"size-4.5"}):h.jsx(pF,{className:"size-4.5"})})})]}),h.jsxs("div",{className:"aui-sidecar-body flex h-[calc(100%-3.5rem)] overflow-hidden",children:[c&&h.jsx("div",{className:"aui-sidecar-thread-list w-56 shrink-0 overflow-y-auto border-r",children:h.jsx(pm,{})}),h.jsx("div",{className:"aui-sidecar-content flex-1 overflow-hidden",children:h.jsx(Nh,{children:h.jsx(dm,{})})})]})]})})},oY=({className:e})=>{const{config:t}=R.useElements();switch(t.variant){case"standalone":return h.jsx(Nh,{children:h.jsx(dm,{})});case"sidecar":return h.jsx(iY,{});default:return h.jsx(nY,{className:e})}};exports.useElements=R.useElements;exports.useGramElements=R.useElements;exports.Chat=oY;exports.ChatHistory=pm;exports.ElementsProvider=VC;exports.GramElementsProvider=VC;exports.MODELS=jf;exports.defineFrontendTool=L6;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./index-BVvrv2G3.cjs"),r=require("./index-D8g4LkEy.cjs");exports.Chat=e.Chat;exports.ChatHistory=e.ThreadList;exports.ElementsProvider=e.ElementsProvider;exports.GramElementsProvider=e.ElementsProvider;exports.MODELS=e.MODELS;exports.defineFrontendTool=e.defineFrontendTool;exports.trackError=e.trackError;exports.useElements=r.useElements;exports.useGramElements=r.useElements;
|
|
161
2
|
//# sourceMappingURL=elements.cjs.map
|