@applica-software-guru/persona-sdk 0.0.1-preview1 → 0.0.1-preview2

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.
@@ -1,27 +1,19 @@
1
- "use strict";var Mr=Object.defineProperty;var Pr=(t,e,s)=>e in t?Mr(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var h=(t,e,s)=>Pr(t,typeof e!="symbol"?e+"":e,s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const T=require("react");function Nr(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var As={exports:{}},De={},_s;function jr(){if(_s)return De;_s=1;/**
1
+ "use strict";var xs=Object.defineProperty;var Ts=(t,e,s)=>e in t?xs(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var h=(t,e,s)=>Ts(t,typeof e!="symbol"?e+"":e,s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const S=require("react");function ks(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Yt={exports:{}},ke={},Nt;function Es(){if(Nt)return ke;Nt=1;/**
2
2
  * @license React
3
3
  * react-jsx-runtime.development.js
4
4
  *
5
- * Copyright (c) Facebook, Inc. and its affiliates.
5
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
6
6
  *
7
7
  * This source code is licensed under the MIT license found in the
8
8
  * LICENSE file in the root directory of this source tree.
9
- */return function(){var t=T,e=Symbol.for("react.element"),s=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),n=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),o=Symbol.for("react.provider"),c=Symbol.for("react.context"),d=Symbol.for("react.forward_ref"),u=Symbol.for("react.suspense"),l=Symbol.for("react.suspense_list"),g=Symbol.for("react.memo"),I=Symbol.for("react.lazy"),N=Symbol.for("react.offscreen"),fe=Symbol.iterator,ee="@@iterator";function Pe(a){if(a===null||typeof a!="object")return null;var f=fe&&a[fe]||a[ee];return typeof f=="function"?f:null}var Y=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function D(a){{for(var f=arguments.length,b=new Array(f>1?f-1:0),w=1;w<f;w++)b[w-1]=arguments[w];kt("error",a,b)}}function kt(a,f,b){{var w=Y.ReactDebugCurrentFrame,A=w.getStackAddendum();A!==""&&(f+="%s",b=b.concat([A]));var O=b.map(function(C){return String(C)});O.unshift("Warning: "+f),Function.prototype.apply.call(console[a],console,O)}}var P=!1,J=!1,te=!1,Ne=!1,V=!1,pe;pe=Symbol.for("react.module.reference");function nt(a){return!!(typeof a=="string"||typeof a=="function"||a===r||a===i||V||a===n||a===u||a===l||Ne||a===N||P||J||te||typeof a=="object"&&a!==null&&(a.$$typeof===I||a.$$typeof===g||a.$$typeof===o||a.$$typeof===c||a.$$typeof===d||a.$$typeof===pe||a.getModuleId!==void 0))}function it(a,f,b){var w=a.displayName;if(w)return w;var A=f.displayName||f.name||"";return A!==""?b+"("+A+")":b}function Jt(a){return a.displayName||"Context"}function ce(a){if(a==null)return null;if(typeof a.tag=="number"&&D("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof a=="function")return a.displayName||a.name||null;if(typeof a=="string")return a;switch(a){case r:return"Fragment";case s:return"Portal";case i:return"Profiler";case n:return"StrictMode";case u:return"Suspense";case l:return"SuspenseList"}if(typeof a=="object")switch(a.$$typeof){case c:var f=a;return Jt(f)+".Consumer";case o:var b=a;return Jt(b._context)+".Provider";case d:return it(a,a.render,"ForwardRef");case g:var w=a.displayName||null;return w!==null?w:ce(a.type)||"Memo";case I:{var A=a,O=A._payload,C=A._init;try{return ce(C(O))}catch{return null}}}return null}var ge=Object.assign,je=0,qt,Kt,Ht,Gt,Xt,Qt,es;function ts(){}ts.__reactDisabledLog=!0;function ir(){{if(je===0){qt=console.log,Kt=console.info,Ht=console.warn,Gt=console.error,Xt=console.group,Qt=console.groupCollapsed,es=console.groupEnd;var a={configurable:!0,enumerable:!0,value:ts,writable:!0};Object.defineProperties(console,{info:a,log:a,warn:a,error:a,group:a,groupCollapsed:a,groupEnd:a})}je++}}function ar(){{if(je--,je===0){var a={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:ge({},a,{value:qt}),info:ge({},a,{value:Kt}),warn:ge({},a,{value:Ht}),error:ge({},a,{value:Gt}),group:ge({},a,{value:Xt}),groupCollapsed:ge({},a,{value:Qt}),groupEnd:ge({},a,{value:es})})}je<0&&D("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var Ct=Y.ReactCurrentDispatcher,Rt;function at(a,f,b){{if(Rt===void 0)try{throw Error()}catch(A){var w=A.stack.trim().match(/\n( *(at )?)/);Rt=w&&w[1]||""}return`
10
- `+Rt+a}}var It=!1,ot;{var or=typeof WeakMap=="function"?WeakMap:Map;ot=new or}function ss(a,f){if(!a||It)return"";{var b=ot.get(a);if(b!==void 0)return b}var w;It=!0;var A=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var O;O=Ct.current,Ct.current=null,ir();try{if(f){var C=function(){throw Error()};if(Object.defineProperty(C.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(C,[])}catch(F){w=F}Reflect.construct(a,[],C)}else{try{C.call()}catch(F){w=F}a.call(C.prototype)}}else{try{throw Error()}catch(F){w=F}a()}}catch(F){if(F&&w&&typeof F.stack=="string"){for(var k=F.stack.split(`
11
- `),$=w.stack.split(`
12
- `),j=k.length-1,B=$.length-1;j>=1&&B>=0&&k[j]!==$[B];)B--;for(;j>=1&&B>=0;j--,B--)if(k[j]!==$[B]){if(j!==1||B!==1)do if(j--,B--,B<0||k[j]!==$[B]){var W=`
13
- `+k[j].replace(" at new "," at ");return a.displayName&&W.includes("<anonymous>")&&(W=W.replace("<anonymous>",a.displayName)),typeof a=="function"&&ot.set(a,W),W}while(j>=1&&B>=0);break}}}finally{It=!1,Ct.current=O,ar(),Error.prepareStackTrace=A}var xe=a?a.displayName||a.name:"",me=xe?at(xe):"";return typeof a=="function"&&ot.set(a,me),me}function cr(a,f,b){return ss(a,!1)}function ur(a){var f=a.prototype;return!!(f&&f.isReactComponent)}function ct(a,f,b){if(a==null)return"";if(typeof a=="function")return ss(a,ur(a));if(typeof a=="string")return at(a);switch(a){case u:return at("Suspense");case l:return at("SuspenseList")}if(typeof a=="object")switch(a.$$typeof){case d:return cr(a.render);case g:return ct(a.type,f,b);case I:{var w=a,A=w._payload,O=w._init;try{return ct(O(A),f,b)}catch{}}}return""}var Be=Object.prototype.hasOwnProperty,rs={},ns=Y.ReactDebugCurrentFrame;function ut(a){if(a){var f=a._owner,b=ct(a.type,a._source,f?f.type:null);ns.setExtraStackFrame(b)}else ns.setExtraStackFrame(null)}function dr(a,f,b,w,A){{var O=Function.call.bind(Be);for(var C in a)if(O(a,C)){var k=void 0;try{if(typeof a[C]!="function"){var $=Error((w||"React class")+": "+b+" type `"+C+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof a[C]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw $.name="Invariant Violation",$}k=a[C](f,C,w,b,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(j){k=j}k&&!(k instanceof Error)&&(ut(A),D("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",w||"React class",b,C,typeof k),ut(null)),k instanceof Error&&!(k.message in rs)&&(rs[k.message]=!0,ut(A),D("Failed %s type: %s",b,k.message),ut(null))}}}var lr=Array.isArray;function At(a){return lr(a)}function hr(a){{var f=typeof Symbol=="function"&&Symbol.toStringTag,b=f&&a[Symbol.toStringTag]||a.constructor.name||"Object";return b}}function fr(a){try{return is(a),!1}catch{return!0}}function is(a){return""+a}function as(a){if(fr(a))return D("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",hr(a)),is(a)}var os=Y.ReactCurrentOwner,pr={key:!0,ref:!0,__self:!0,__source:!0},cs,us;function gr(a){if(Be.call(a,"ref")){var f=Object.getOwnPropertyDescriptor(a,"ref").get;if(f&&f.isReactWarning)return!1}return a.ref!==void 0}function mr(a){if(Be.call(a,"key")){var f=Object.getOwnPropertyDescriptor(a,"key").get;if(f&&f.isReactWarning)return!1}return a.key!==void 0}function _r(a,f){typeof a.ref=="string"&&os.current}function br(a,f){{var b=function(){cs||(cs=!0,D("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",f))};b.isReactWarning=!0,Object.defineProperty(a,"key",{get:b,configurable:!0})}}function vr(a,f){{var b=function(){us||(us=!0,D("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",f))};b.isReactWarning=!0,Object.defineProperty(a,"ref",{get:b,configurable:!0})}}var yr=function(a,f,b,w,A,O,C){var k={$$typeof:e,type:a,key:f,ref:b,props:C,_owner:O};return k._store={},Object.defineProperty(k._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(k,"_self",{configurable:!1,enumerable:!1,writable:!1,value:w}),Object.defineProperty(k,"_source",{configurable:!1,enumerable:!1,writable:!1,value:A}),Object.freeze&&(Object.freeze(k.props),Object.freeze(k)),k};function Sr(a,f,b,w,A){{var O,C={},k=null,$=null;b!==void 0&&(as(b),k=""+b),mr(f)&&(as(f.key),k=""+f.key),gr(f)&&($=f.ref,_r(f,A));for(O in f)Be.call(f,O)&&!pr.hasOwnProperty(O)&&(C[O]=f[O]);if(a&&a.defaultProps){var j=a.defaultProps;for(O in j)C[O]===void 0&&(C[O]=j[O])}if(k||$){var B=typeof a=="function"?a.displayName||a.name||"Unknown":a;k&&br(C,B),$&&vr(C,B)}return yr(a,k,$,A,w,os.current,C)}}var Ot=Y.ReactCurrentOwner,ds=Y.ReactDebugCurrentFrame;function we(a){if(a){var f=a._owner,b=ct(a.type,a._source,f?f.type:null);ds.setExtraStackFrame(b)}else ds.setExtraStackFrame(null)}var Mt;Mt=!1;function Pt(a){return typeof a=="object"&&a!==null&&a.$$typeof===e}function ls(){{if(Ot.current){var a=ce(Ot.current.type);if(a)return`
14
-
15
- Check the render method of \``+a+"`."}return""}}function wr(a){return""}var hs={};function xr(a){{var f=ls();if(!f){var b=typeof a=="string"?a:a.displayName||a.name;b&&(f=`
16
-
17
- Check the top-level render call using <`+b+">.")}return f}}function fs(a,f){{if(!a._store||a._store.validated||a.key!=null)return;a._store.validated=!0;var b=xr(f);if(hs[b])return;hs[b]=!0;var w="";a&&a._owner&&a._owner!==Ot.current&&(w=" It was passed a child from "+ce(a._owner.type)+"."),we(a),D('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',b,w),we(null)}}function ps(a,f){{if(typeof a!="object")return;if(At(a))for(var b=0;b<a.length;b++){var w=a[b];Pt(w)&&fs(w,f)}else if(Pt(a))a._store&&(a._store.validated=!0);else if(a){var A=Pe(a);if(typeof A=="function"&&A!==a.entries)for(var O=A.call(a),C;!(C=O.next()).done;)Pt(C.value)&&fs(C.value,f)}}}function Tr(a){{var f=a.type;if(f==null||typeof f=="string")return;var b;if(typeof f=="function")b=f.propTypes;else if(typeof f=="object"&&(f.$$typeof===d||f.$$typeof===g))b=f.propTypes;else return;if(b){var w=ce(f);dr(b,a.props,"prop",w,a)}else if(f.PropTypes!==void 0&&!Mt){Mt=!0;var A=ce(f);D("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",A||"Unknown")}typeof f.getDefaultProps=="function"&&!f.getDefaultProps.isReactClassApproved&&D("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function Er(a){{for(var f=Object.keys(a.props),b=0;b<f.length;b++){var w=f[b];if(w!=="children"&&w!=="key"){we(a),D("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",w),we(null);break}}a.ref!==null&&(we(a),D("Invalid attribute `ref` supplied to `React.Fragment`."),we(null))}}var gs={};function ms(a,f,b,w,A,O){{var C=nt(a);if(!C){var k="";(a===void 0||typeof a=="object"&&a!==null&&Object.keys(a).length===0)&&(k+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var $=wr();$?k+=$:k+=ls();var j;a===null?j="null":At(a)?j="array":a!==void 0&&a.$$typeof===e?(j="<"+(ce(a.type)||"Unknown")+" />",k=" Did you accidentally export a JSX literal instead of a component?"):j=typeof a,D("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",j,k)}var B=Sr(a,f,b,A,O);if(B==null)return B;if(C){var W=f.children;if(W!==void 0)if(w)if(At(W)){for(var xe=0;xe<W.length;xe++)ps(W[xe],a);Object.freeze&&Object.freeze(W)}else D("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else ps(W,a)}if(Be.call(f,"key")){var me=ce(a),F=Object.keys(f).filter(function(Or){return Or!=="key"}),Nt=F.length>0?"{key: someKey, "+F.join(": ..., ")+": ...}":"{key: someKey}";if(!gs[me+Nt]){var Ar=F.length>0?"{"+F.join(": ..., ")+": ...}":"{}";D(`A props object containing a "key" prop is being spread into JSX:
9
+ */return function(){function t(f){if(f==null)return null;if(typeof f=="function")return f.$$typeof===Ye?null:f.displayName||f.name||null;if(typeof f=="string")return f;switch(f){case D:return"Fragment";case ue:return"Profiler";case xe:return"StrictMode";case Z:return"Suspense";case W:return"SuspenseList";case he:return"Activity"}if(typeof f=="object")switch(typeof f.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),f.$$typeof){case de:return"Portal";case ut:return(f.displayName||"Context")+".Provider";case dt:return(f._context.displayName||"Context")+".Consumer";case R:var x=f.render;return f=f.displayName,f||(f=x.displayName||x.name||"",f=f!==""?"ForwardRef("+f+")":"ForwardRef"),f;case Te:return x=f.displayName||null,x!==null?x:t(f.type)||"Memo";case P:x=f._payload,f=f._init;try{return t(f(x))}catch{}}return null}function e(f){return""+f}function s(f){try{e(f);var x=!1}catch{x=!0}if(x){x=console;var E=x.error,A=typeof Symbol=="function"&&Symbol.toStringTag&&f[Symbol.toStringTag]||f.constructor.name||"Object";return E.call(x,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",A),e(f)}}function r(f){if(f===D)return"<>";if(typeof f=="object"&&f!==null&&f.$$typeof===P)return"<...>";try{var x=t(f);return x?"<"+x+">":"<...>"}catch{return"<...>"}}function n(){var f=le.A;return f===null?null:f.getOwner()}function i(){return Error("react-stack-top-frame")}function a(f){if(Ct.call(f,"key")){var x=Object.getOwnPropertyDescriptor(f,"key").get;if(x&&x.isReactWarning)return!1}return f.key!==void 0}function o(f,x){function E(){It||(It=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",x))}E.isReactWarning=!0,Object.defineProperty(f,"key",{get:E,configurable:!0})}function d(){var f=t(this.type);return Rt[f]||(Rt[f]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),f=this.props.ref,f!==void 0?f:null}function c(f,x,E,A,Q,Y,lt,ft){return E=Y.ref,f={$$typeof:I,type:f,key:x,props:Y,_owner:Q},(E!==void 0?E:null)!==null?Object.defineProperty(f,"ref",{enumerable:!1,get:d}):Object.defineProperty(f,"ref",{enumerable:!1,value:null}),f._store={},Object.defineProperty(f._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(f,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(f,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:lt}),Object.defineProperty(f,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:ft}),Object.freeze&&(Object.freeze(f.props),Object.freeze(f)),f}function u(f,x,E,A,Q,Y,lt,ft){var O=x.children;if(O!==void 0)if(A)if(Ss(O)){for(A=0;A<O.length;A++)g(O[A]);Object.freeze&&Object.freeze(O)}else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else g(O);if(Ct.call(x,"key")){O=t(f);var fe=Object.keys(x).filter(function(ws){return ws!=="key"});A=0<fe.length?"{key: someKey, "+fe.join(": ..., ")+": ...}":"{key: someKey}",Mt[O+A]||(fe=0<fe.length?"{"+fe.join(": ..., ")+": ...}":"{}",console.error(`A props object containing a "key" prop is being spread into JSX:
18
10
  let props = %s;
19
11
  <%s {...props} />
20
12
  React keys must be passed directly to JSX without using spread:
21
13
  let props = %s;
22
- <%s key={someKey} {...props} />`,Nt,me,Ar,me),gs[me+Nt]=!0}}return a===r?Er(B):Tr(B),B}}function kr(a,f,b){return ms(a,f,b,!0)}function Cr(a,f,b){return ms(a,f,b,!1)}var Rr=Cr,Ir=kr;De.Fragment=r,De.jsx=Rr,De.jsxs=Ir}(),De}As.exports=jr();var H=As.exports,R;(function(t){t.assertEqual=n=>n;function e(n){}t.assertIs=e;function s(n){throw new Error}t.assertNever=s,t.arrayToEnum=n=>{const i={};for(const o of n)i[o]=o;return i},t.getValidEnumValues=n=>{const i=t.objectKeys(n).filter(c=>typeof n[n[c]]!="number"),o={};for(const c of i)o[c]=n[c];return t.objectValues(o)},t.objectValues=n=>t.objectKeys(n).map(function(i){return n[i]}),t.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{const i=[];for(const o in n)Object.prototype.hasOwnProperty.call(n,o)&&i.push(o);return i},t.find=(n,i)=>{for(const o of n)if(i(o))return o},t.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&isFinite(n)&&Math.floor(n)===n;function r(n,i=" | "){return n.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}t.joinValues=r,t.jsonStringifyReplacer=(n,i)=>typeof i=="bigint"?i.toString():i})(R||(R={}));var Bt;(function(t){t.mergeShapes=(e,s)=>({...e,...s})})(Bt||(Bt={}));const _=R.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ae=t=>{switch(typeof t){case"undefined":return _.undefined;case"string":return _.string;case"number":return isNaN(t)?_.nan:_.number;case"boolean":return _.boolean;case"function":return _.function;case"bigint":return _.bigint;case"symbol":return _.symbol;case"object":return Array.isArray(t)?_.array:t===null?_.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?_.promise:typeof Map<"u"&&t instanceof Map?_.map:typeof Set<"u"&&t instanceof Set?_.set:typeof Date<"u"&&t instanceof Date?_.date:_.object;default:return _.unknown}},p=R.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"]),Br=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");class z extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const s=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,s):this.__proto__=s,this.name="ZodError",this.issues=e}format(e){const s=e||function(i){return i.message},r={_errors:[]},n=i=>{for(const o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(n);else if(o.code==="invalid_return_type")n(o.returnTypeError);else if(o.code==="invalid_arguments")n(o.argumentsError);else if(o.path.length===0)r._errors.push(s(o));else{let c=r,d=0;for(;d<o.path.length;){const u=o.path[d];d===o.path.length-1?(c[u]=c[u]||{_errors:[]},c[u]._errors.push(s(o))):c[u]=c[u]||{_errors:[]},c=c[u],d++}}};return n(this),r}static assert(e){if(!(e instanceof z))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,R.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=s=>s.message){const s={},r=[];for(const n of this.issues)n.path.length>0?(s[n.path[0]]=s[n.path[0]]||[],s[n.path[0]].push(e(n))):r.push(e(n));return{formErrors:r,fieldErrors:s}}get formErrors(){return this.flatten()}}z.create=t=>new z(t);const Re=(t,e)=>{let s;switch(t.code){case p.invalid_type:t.received===_.undefined?s="Required":s=`Expected ${t.expected}, received ${t.received}`;break;case p.invalid_literal:s=`Invalid literal value, expected ${JSON.stringify(t.expected,R.jsonStringifyReplacer)}`;break;case p.unrecognized_keys:s=`Unrecognized key(s) in object: ${R.joinValues(t.keys,", ")}`;break;case p.invalid_union:s="Invalid input";break;case p.invalid_union_discriminator:s=`Invalid discriminator value. Expected ${R.joinValues(t.options)}`;break;case p.invalid_enum_value:s=`Invalid enum value. Expected ${R.joinValues(t.options)}, received '${t.received}'`;break;case p.invalid_arguments:s="Invalid function arguments";break;case p.invalid_return_type:s="Invalid function return type";break;case p.invalid_date:s="Invalid date";break;case p.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(s=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(s=`${s} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?s=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?s=`Invalid input: must end with "${t.validation.endsWith}"`:R.assertNever(t.validation):t.validation!=="regex"?s=`Invalid ${t.validation}`:s="Invalid";break;case p.too_small:t.type==="array"?s=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?s=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?s=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?s=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:s="Invalid input";break;case p.too_big:t.type==="array"?s=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?s=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?s=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?s=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?s=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:s="Invalid input";break;case p.custom:s="Invalid input";break;case p.invalid_intersection_types:s="Intersection results could not be merged";break;case p.not_multiple_of:s=`Number must be a multiple of ${t.multipleOf}`;break;case p.not_finite:s="Number must be finite";break;default:s=e.defaultError,R.assertNever(t)}return{message:s}};let Os=Re;function Dr(t){Os=t}function pt(){return Os}const gt=t=>{const{data:e,path:s,errorMaps:r,issueData:n}=t,i=[...s,...n.path||[]],o={...n,path:i};if(n.message!==void 0)return{...n,path:i,message:n.message};let c="";const d=r.filter(u=>!!u).slice().reverse();for(const u of d)c=u(o,{data:e,defaultError:c}).message;return{...n,path:i,message:c}},Zr=[];function m(t,e){const s=pt(),r=gt({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,s,s===Re?void 0:Re].filter(n=>!!n)});t.common.issues.push(r)}class Z{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,s){const r=[];for(const n of s){if(n.status==="aborted")return S;n.status==="dirty"&&e.dirty(),r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,s){const r=[];for(const n of s){const i=await n.key,o=await n.value;r.push({key:i,value:o})}return Z.mergeObjectSync(e,r)}static mergeObjectSync(e,s){const r={};for(const n of s){const{key:i,value:o}=n;if(i.status==="aborted"||o.status==="aborted")return S;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||n.alwaysSet)&&(r[i.value]=o.value)}return{status:e.value,value:r}}}const S=Object.freeze({status:"aborted"}),Ee=t=>({status:"dirty",value:t}),L=t=>({status:"valid",value:t}),Dt=t=>t.status==="aborted",Zt=t=>t.status==="dirty",ve=t=>t.status==="valid",Le=t=>typeof Promise<"u"&&t instanceof Promise;function mt(t,e,s,r){if(typeof e=="function"?t!==e||!0:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e.get(t)}function Ms(t,e,s,r,n){if(typeof e=="function"?t!==e||!0:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,s),s}var v;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(v||(v={}));var Ze,$e;class re{constructor(e,s,r,n){this._cachedPath=[],this.parent=e,this.data=s,this._path=r,this._key=n}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const bs=(t,e)=>{if(ve(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const s=new z(t.common.issues);return this._error=s,this._error}}};function x(t){if(!t)return{};const{errorMap:e,invalid_type_error:s,required_error:r,description:n}=t;if(e&&(s||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(o,c)=>{var d,u;const{message:l}=t;return o.code==="invalid_enum_value"?{message:l??c.defaultError}:typeof c.data>"u"?{message:(d=l??r)!==null&&d!==void 0?d:c.defaultError}:o.code!=="invalid_type"?{message:c.defaultError}:{message:(u=l??s)!==null&&u!==void 0?u:c.defaultError}},description:n}}class E{get description(){return this._def.description}_getType(e){return ae(e.data)}_getOrReturnCtx(e,s){return s||{common:e.parent.common,data:e.data,parsedType:ae(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Z,ctx:{common:e.parent.common,data:e.data,parsedType:ae(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const s=this._parse(e);if(Le(s))throw new Error("Synchronous parse encountered promise.");return s}_parseAsync(e){const s=this._parse(e);return Promise.resolve(s)}parse(e,s){const r=this.safeParse(e,s);if(r.success)return r.data;throw r.error}safeParse(e,s){var r;const n={common:{issues:[],async:(r=s==null?void 0:s.async)!==null&&r!==void 0?r:!1,contextualErrorMap:s==null?void 0:s.errorMap},path:(s==null?void 0:s.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ae(e)},i=this._parseSync({data:e,path:n.path,parent:n});return bs(n,i)}"~validate"(e){var s,r;const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ae(e)};if(!this["~standard"].async)try{const i=this._parseSync({data:e,path:[],parent:n});return ve(i)?{value:i.value}:{issues:n.common.issues}}catch(i){!((r=(s=i==null?void 0:i.message)===null||s===void 0?void 0:s.toLowerCase())===null||r===void 0)&&r.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(i=>ve(i)?{value:i.value}:{issues:n.common.issues})}async parseAsync(e,s){const r=await this.safeParseAsync(e,s);if(r.success)return r.data;throw r.error}async safeParseAsync(e,s){const r={common:{issues:[],contextualErrorMap:s==null?void 0:s.errorMap,async:!0},path:(s==null?void 0:s.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ae(e)},n=this._parse({data:e,path:r.path,parent:r}),i=await(Le(n)?n:Promise.resolve(n));return bs(r,i)}refine(e,s){const r=n=>typeof s=="string"||typeof s>"u"?{message:s}:typeof s=="function"?s(n):s;return this._refinement((n,i)=>{const o=e(n),c=()=>i.addIssue({code:p.custom,...r(n)});return typeof Promise<"u"&&o instanceof Promise?o.then(d=>d?!0:(c(),!1)):o?!0:(c(),!1)})}refinement(e,s){return this._refinement((r,n)=>e(r)?!0:(n.addIssue(typeof s=="function"?s(r,n):s),!1))}_refinement(e){return new X({schema:this,typeName:y.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:s=>this["~validate"](s)}}optional(){return se.create(this,this._def)}nullable(){return he.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return G.create(this)}promise(){return Ae.create(this,this._def)}or(e){return ze.create([this,e],this._def)}and(e){return We.create(this,e,this._def)}transform(e){return new X({...x(this._def),schema:this,typeName:y.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const s=typeof e=="function"?e:()=>e;return new He({...x(this._def),innerType:this,defaultValue:s,typeName:y.ZodDefault})}brand(){return new Ut({typeName:y.ZodBranded,type:this,...x(this._def)})}catch(e){const s=typeof e=="function"?e:()=>e;return new Ge({...x(this._def),innerType:this,catchValue:s,typeName:y.ZodCatch})}describe(e){const s=this.constructor;return new s({...this._def,description:e})}pipe(e){return st.create(this,e)}readonly(){return Xe.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const $r=/^c[^\s-]{8,}$/i,Lr=/^[0-9a-z]+$/,Fr=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Vr=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Ur=/^[a-z0-9_-]{21}$/i,zr=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Wr=/^[-+]?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)?)??$/,Yr=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Jr="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let jt;const qr=/^(?:(?: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])$/,Kr=/^(?:(?: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])$/,Hr=/^(([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]))$/,Gr=/^(([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])$/,Xr=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Qr=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ps="((\\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])))",en=new RegExp(`^${Ps}$`);function Ns(t){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`),e}function tn(t){return new RegExp(`^${Ns(t)}$`)}function js(t){let e=`${Ps}T${Ns(t)}`;const s=[];return s.push(t.local?"Z?":"Z"),t.offset&&s.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${s.join("|")})`,new RegExp(`^${e}$`)}function sn(t,e){return!!((e==="v4"||!e)&&qr.test(t)||(e==="v6"||!e)&&Hr.test(t))}function rn(t,e){if(!zr.test(t))return!1;try{const[s]=t.split("."),r=s.replace(/-/g,"+").replace(/_/g,"/").padEnd(s.length+(4-s.length%4)%4,"="),n=JSON.parse(atob(r));return!(typeof n!="object"||n===null||!n.typ||!n.alg||e&&n.alg!==e)}catch{return!1}}function nn(t,e){return!!((e==="v4"||!e)&&Kr.test(t)||(e==="v6"||!e)&&Gr.test(t))}class q extends E{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==_.string){const i=this._getOrReturnCtx(e);return m(i,{code:p.invalid_type,expected:_.string,received:i.parsedType}),S}const r=new Z;let n;for(const i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(n=this._getOrReturnCtx(e,n),m(n,{code:p.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(n=this._getOrReturnCtx(e,n),m(n,{code:p.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const o=e.data.length>i.value,c=e.data.length<i.value;(o||c)&&(n=this._getOrReturnCtx(e,n),o?m(n,{code:p.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):c&&m(n,{code:p.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")Yr.test(e.data)||(n=this._getOrReturnCtx(e,n),m(n,{validation:"email",code:p.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")jt||(jt=new RegExp(Jr,"u")),jt.test(e.data)||(n=this._getOrReturnCtx(e,n),m(n,{validation:"emoji",code:p.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")Vr.test(e.data)||(n=this._getOrReturnCtx(e,n),m(n,{validation:"uuid",code:p.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")Ur.test(e.data)||(n=this._getOrReturnCtx(e,n),m(n,{validation:"nanoid",code:p.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")$r.test(e.data)||(n=this._getOrReturnCtx(e,n),m(n,{validation:"cuid",code:p.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")Lr.test(e.data)||(n=this._getOrReturnCtx(e,n),m(n,{validation:"cuid2",code:p.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")Fr.test(e.data)||(n=this._getOrReturnCtx(e,n),m(n,{validation:"ulid",code:p.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),m(n,{validation:"url",code:p.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),m(n,{validation:"regex",code:p.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(n=this._getOrReturnCtx(e,n),m(n,{code:p.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(n=this._getOrReturnCtx(e,n),m(n,{code:p.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(n=this._getOrReturnCtx(e,n),m(n,{code:p.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?js(i).test(e.data)||(n=this._getOrReturnCtx(e,n),m(n,{code:p.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?en.test(e.data)||(n=this._getOrReturnCtx(e,n),m(n,{code:p.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?tn(i).test(e.data)||(n=this._getOrReturnCtx(e,n),m(n,{code:p.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?Wr.test(e.data)||(n=this._getOrReturnCtx(e,n),m(n,{validation:"duration",code:p.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?sn(e.data,i.version)||(n=this._getOrReturnCtx(e,n),m(n,{validation:"ip",code:p.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?rn(e.data,i.alg)||(n=this._getOrReturnCtx(e,n),m(n,{validation:"jwt",code:p.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?nn(e.data,i.version)||(n=this._getOrReturnCtx(e,n),m(n,{validation:"cidr",code:p.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?Xr.test(e.data)||(n=this._getOrReturnCtx(e,n),m(n,{validation:"base64",code:p.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?Qr.test(e.data)||(n=this._getOrReturnCtx(e,n),m(n,{validation:"base64url",code:p.invalid_string,message:i.message}),r.dirty()):R.assertNever(i);return{status:r.value,value:e.data}}_regex(e,s,r){return this.refinement(n=>e.test(n),{validation:s,code:p.invalid_string,...v.errToObj(r)})}_addCheck(e){return new q({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...v.errToObj(e)})}url(e){return this._addCheck({kind:"url",...v.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...v.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...v.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...v.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...v.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...v.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...v.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...v.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...v.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...v.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...v.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...v.errToObj(e)})}datetime(e){var s,r;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(s=e==null?void 0:e.offset)!==null&&s!==void 0?s:!1,local:(r=e==null?void 0:e.local)!==null&&r!==void 0?r:!1,...v.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...v.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...v.errToObj(e)})}regex(e,s){return this._addCheck({kind:"regex",regex:e,...v.errToObj(s)})}includes(e,s){return this._addCheck({kind:"includes",value:e,position:s==null?void 0:s.position,...v.errToObj(s==null?void 0:s.message)})}startsWith(e,s){return this._addCheck({kind:"startsWith",value:e,...v.errToObj(s)})}endsWith(e,s){return this._addCheck({kind:"endsWith",value:e,...v.errToObj(s)})}min(e,s){return this._addCheck({kind:"min",value:e,...v.errToObj(s)})}max(e,s){return this._addCheck({kind:"max",value:e,...v.errToObj(s)})}length(e,s){return this._addCheck({kind:"length",value:e,...v.errToObj(s)})}nonempty(e){return this.min(1,v.errToObj(e))}trim(){return new q({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new q({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new q({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const s of this._def.checks)s.kind==="min"&&(e===null||s.value>e)&&(e=s.value);return e}get maxLength(){let e=null;for(const s of this._def.checks)s.kind==="max"&&(e===null||s.value<e)&&(e=s.value);return e}}q.create=t=>{var e;return new q({checks:[],typeName:y.ZodString,coerce:(e=t==null?void 0:t.coerce)!==null&&e!==void 0?e:!1,...x(t)})};function an(t,e){const s=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,n=s>r?s:r,i=parseInt(t.toFixed(n).replace(".","")),o=parseInt(e.toFixed(n).replace(".",""));return i%o/Math.pow(10,n)}class ue extends E{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==_.number){const i=this._getOrReturnCtx(e);return m(i,{code:p.invalid_type,expected:_.number,received:i.parsedType}),S}let r;const n=new Z;for(const i of this._def.checks)i.kind==="int"?R.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),m(r,{code:p.invalid_type,expected:"integer",received:"float",message:i.message}),n.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),m(r,{code:p.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),m(r,{code:p.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty()):i.kind==="multipleOf"?an(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),m(r,{code:p.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),m(r,{code:p.not_finite,message:i.message}),n.dirty()):R.assertNever(i);return{status:n.value,value:e.data}}gte(e,s){return this.setLimit("min",e,!0,v.toString(s))}gt(e,s){return this.setLimit("min",e,!1,v.toString(s))}lte(e,s){return this.setLimit("max",e,!0,v.toString(s))}lt(e,s){return this.setLimit("max",e,!1,v.toString(s))}setLimit(e,s,r,n){return new ue({...this._def,checks:[...this._def.checks,{kind:e,value:s,inclusive:r,message:v.toString(n)}]})}_addCheck(e){return new ue({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:v.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:v.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:v.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:v.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:v.toString(e)})}multipleOf(e,s){return this._addCheck({kind:"multipleOf",value:e,message:v.toString(s)})}finite(e){return this._addCheck({kind:"finite",message:v.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:v.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:v.toString(e)})}get minValue(){let e=null;for(const s of this._def.checks)s.kind==="min"&&(e===null||s.value>e)&&(e=s.value);return e}get maxValue(){let e=null;for(const s of this._def.checks)s.kind==="max"&&(e===null||s.value<e)&&(e=s.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&R.isInteger(e.value))}get isFinite(){let e=null,s=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(s===null||r.value>s)&&(s=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(s)&&Number.isFinite(e)}}ue.create=t=>new ue({checks:[],typeName:y.ZodNumber,coerce:(t==null?void 0:t.coerce)||!1,...x(t)});class de extends E{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==_.bigint)return this._getInvalidInput(e);let r;const n=new Z;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),m(r,{code:p.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),n.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),m(r,{code:p.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),n.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),m(r,{code:p.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):R.assertNever(i);return{status:n.value,value:e.data}}_getInvalidInput(e){const s=this._getOrReturnCtx(e);return m(s,{code:p.invalid_type,expected:_.bigint,received:s.parsedType}),S}gte(e,s){return this.setLimit("min",e,!0,v.toString(s))}gt(e,s){return this.setLimit("min",e,!1,v.toString(s))}lte(e,s){return this.setLimit("max",e,!0,v.toString(s))}lt(e,s){return this.setLimit("max",e,!1,v.toString(s))}setLimit(e,s,r,n){return new de({...this._def,checks:[...this._def.checks,{kind:e,value:s,inclusive:r,message:v.toString(n)}]})}_addCheck(e){return new de({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:v.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:v.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:v.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:v.toString(e)})}multipleOf(e,s){return this._addCheck({kind:"multipleOf",value:e,message:v.toString(s)})}get minValue(){let e=null;for(const s of this._def.checks)s.kind==="min"&&(e===null||s.value>e)&&(e=s.value);return e}get maxValue(){let e=null;for(const s of this._def.checks)s.kind==="max"&&(e===null||s.value<e)&&(e=s.value);return e}}de.create=t=>{var e;return new de({checks:[],typeName:y.ZodBigInt,coerce:(e=t==null?void 0:t.coerce)!==null&&e!==void 0?e:!1,...x(t)})};class Fe extends E{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==_.boolean){const r=this._getOrReturnCtx(e);return m(r,{code:p.invalid_type,expected:_.boolean,received:r.parsedType}),S}return L(e.data)}}Fe.create=t=>new Fe({typeName:y.ZodBoolean,coerce:(t==null?void 0:t.coerce)||!1,...x(t)});class ye extends E{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==_.date){const i=this._getOrReturnCtx(e);return m(i,{code:p.invalid_type,expected:_.date,received:i.parsedType}),S}if(isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return m(i,{code:p.invalid_date}),S}const r=new Z;let n;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(n=this._getOrReturnCtx(e,n),m(n,{code:p.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(n=this._getOrReturnCtx(e,n),m(n,{code:p.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):R.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ye({...this._def,checks:[...this._def.checks,e]})}min(e,s){return this._addCheck({kind:"min",value:e.getTime(),message:v.toString(s)})}max(e,s){return this._addCheck({kind:"max",value:e.getTime(),message:v.toString(s)})}get minDate(){let e=null;for(const s of this._def.checks)s.kind==="min"&&(e===null||s.value>e)&&(e=s.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const s of this._def.checks)s.kind==="max"&&(e===null||s.value<e)&&(e=s.value);return e!=null?new Date(e):null}}ye.create=t=>new ye({checks:[],coerce:(t==null?void 0:t.coerce)||!1,typeName:y.ZodDate,...x(t)});class _t extends E{_parse(e){if(this._getType(e)!==_.symbol){const r=this._getOrReturnCtx(e);return m(r,{code:p.invalid_type,expected:_.symbol,received:r.parsedType}),S}return L(e.data)}}_t.create=t=>new _t({typeName:y.ZodSymbol,...x(t)});class Ve extends E{_parse(e){if(this._getType(e)!==_.undefined){const r=this._getOrReturnCtx(e);return m(r,{code:p.invalid_type,expected:_.undefined,received:r.parsedType}),S}return L(e.data)}}Ve.create=t=>new Ve({typeName:y.ZodUndefined,...x(t)});class Ue extends E{_parse(e){if(this._getType(e)!==_.null){const r=this._getOrReturnCtx(e);return m(r,{code:p.invalid_type,expected:_.null,received:r.parsedType}),S}return L(e.data)}}Ue.create=t=>new Ue({typeName:y.ZodNull,...x(t)});class Ie extends E{constructor(){super(...arguments),this._any=!0}_parse(e){return L(e.data)}}Ie.create=t=>new Ie({typeName:y.ZodAny,...x(t)});class be extends E{constructor(){super(...arguments),this._unknown=!0}_parse(e){return L(e.data)}}be.create=t=>new be({typeName:y.ZodUnknown,...x(t)});class oe extends E{_parse(e){const s=this._getOrReturnCtx(e);return m(s,{code:p.invalid_type,expected:_.never,received:s.parsedType}),S}}oe.create=t=>new oe({typeName:y.ZodNever,...x(t)});class bt extends E{_parse(e){if(this._getType(e)!==_.undefined){const r=this._getOrReturnCtx(e);return m(r,{code:p.invalid_type,expected:_.void,received:r.parsedType}),S}return L(e.data)}}bt.create=t=>new bt({typeName:y.ZodVoid,...x(t)});class G extends E{_parse(e){const{ctx:s,status:r}=this._processInputParams(e),n=this._def;if(s.parsedType!==_.array)return m(s,{code:p.invalid_type,expected:_.array,received:s.parsedType}),S;if(n.exactLength!==null){const o=s.data.length>n.exactLength.value,c=s.data.length<n.exactLength.value;(o||c)&&(m(s,{code:o?p.too_big:p.too_small,minimum:c?n.exactLength.value:void 0,maximum:o?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),r.dirty())}if(n.minLength!==null&&s.data.length<n.minLength.value&&(m(s,{code:p.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),r.dirty()),n.maxLength!==null&&s.data.length>n.maxLength.value&&(m(s,{code:p.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),r.dirty()),s.common.async)return Promise.all([...s.data].map((o,c)=>n.type._parseAsync(new re(s,o,s.path,c)))).then(o=>Z.mergeArray(r,o));const i=[...s.data].map((o,c)=>n.type._parseSync(new re(s,o,s.path,c)));return Z.mergeArray(r,i)}get element(){return this._def.type}min(e,s){return new G({...this._def,minLength:{value:e,message:v.toString(s)}})}max(e,s){return new G({...this._def,maxLength:{value:e,message:v.toString(s)}})}length(e,s){return new G({...this._def,exactLength:{value:e,message:v.toString(s)}})}nonempty(e){return this.min(1,e)}}G.create=(t,e)=>new G({type:t,minLength:null,maxLength:null,exactLength:null,typeName:y.ZodArray,...x(e)});function Te(t){if(t instanceof M){const e={};for(const s in t.shape){const r=t.shape[s];e[s]=se.create(Te(r))}return new M({...t._def,shape:()=>e})}else return t instanceof G?new G({...t._def,type:Te(t.element)}):t instanceof se?se.create(Te(t.unwrap())):t instanceof he?he.create(Te(t.unwrap())):t instanceof ne?ne.create(t.items.map(e=>Te(e))):t}class M extends E{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),s=R.objectKeys(e);return this._cached={shape:e,keys:s}}_parse(e){if(this._getType(e)!==_.object){const u=this._getOrReturnCtx(e);return m(u,{code:p.invalid_type,expected:_.object,received:u.parsedType}),S}const{status:r,ctx:n}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),c=[];if(!(this._def.catchall instanceof oe&&this._def.unknownKeys==="strip"))for(const u in n.data)o.includes(u)||c.push(u);const d=[];for(const u of o){const l=i[u],g=n.data[u];d.push({key:{status:"valid",value:u},value:l._parse(new re(n,g,n.path,u)),alwaysSet:u in n.data})}if(this._def.catchall instanceof oe){const u=this._def.unknownKeys;if(u==="passthrough")for(const l of c)d.push({key:{status:"valid",value:l},value:{status:"valid",value:n.data[l]}});else if(u==="strict")c.length>0&&(m(n,{code:p.unrecognized_keys,keys:c}),r.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const l of c){const g=n.data[l];d.push({key:{status:"valid",value:l},value:u._parse(new re(n,g,n.path,l)),alwaysSet:l in n.data})}}return n.common.async?Promise.resolve().then(async()=>{const u=[];for(const l of d){const g=await l.key,I=await l.value;u.push({key:g,value:I,alwaysSet:l.alwaysSet})}return u}).then(u=>Z.mergeObjectSync(r,u)):Z.mergeObjectSync(r,d)}get shape(){return this._def.shape()}strict(e){return v.errToObj,new M({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(s,r)=>{var n,i,o,c;const d=(o=(i=(n=this._def).errorMap)===null||i===void 0?void 0:i.call(n,s,r).message)!==null&&o!==void 0?o:r.defaultError;return s.code==="unrecognized_keys"?{message:(c=v.errToObj(e).message)!==null&&c!==void 0?c:d}:{message:d}}}:{}})}strip(){return new M({...this._def,unknownKeys:"strip"})}passthrough(){return new M({...this._def,unknownKeys:"passthrough"})}extend(e){return new M({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new M({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:y.ZodObject})}setKey(e,s){return this.augment({[e]:s})}catchall(e){return new M({...this._def,catchall:e})}pick(e){const s={};return R.objectKeys(e).forEach(r=>{e[r]&&this.shape[r]&&(s[r]=this.shape[r])}),new M({...this._def,shape:()=>s})}omit(e){const s={};return R.objectKeys(this.shape).forEach(r=>{e[r]||(s[r]=this.shape[r])}),new M({...this._def,shape:()=>s})}deepPartial(){return Te(this)}partial(e){const s={};return R.objectKeys(this.shape).forEach(r=>{const n=this.shape[r];e&&!e[r]?s[r]=n:s[r]=n.optional()}),new M({...this._def,shape:()=>s})}required(e){const s={};return R.objectKeys(this.shape).forEach(r=>{if(e&&!e[r])s[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof se;)i=i._def.innerType;s[r]=i}}),new M({...this._def,shape:()=>s})}keyof(){return Bs(R.objectKeys(this.shape))}}M.create=(t,e)=>new M({shape:()=>t,unknownKeys:"strip",catchall:oe.create(),typeName:y.ZodObject,...x(e)});M.strictCreate=(t,e)=>new M({shape:()=>t,unknownKeys:"strict",catchall:oe.create(),typeName:y.ZodObject,...x(e)});M.lazycreate=(t,e)=>new M({shape:t,unknownKeys:"strip",catchall:oe.create(),typeName:y.ZodObject,...x(e)});class ze extends E{_parse(e){const{ctx:s}=this._processInputParams(e),r=this._def.options;function n(i){for(const c of i)if(c.result.status==="valid")return c.result;for(const c of i)if(c.result.status==="dirty")return s.common.issues.push(...c.ctx.common.issues),c.result;const o=i.map(c=>new z(c.ctx.common.issues));return m(s,{code:p.invalid_union,unionErrors:o}),S}if(s.common.async)return Promise.all(r.map(async i=>{const o={...s,common:{...s.common,issues:[]},parent:null};return{result:await i._parseAsync({data:s.data,path:s.path,parent:o}),ctx:o}})).then(n);{let i;const o=[];for(const d of r){const u={...s,common:{...s.common,issues:[]},parent:null},l=d._parseSync({data:s.data,path:s.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!i&&(i={result:l,ctx:u}),u.common.issues.length&&o.push(u.common.issues)}if(i)return s.common.issues.push(...i.ctx.common.issues),i.result;const c=o.map(d=>new z(d));return m(s,{code:p.invalid_union,unionErrors:c}),S}}get options(){return this._def.options}}ze.create=(t,e)=>new ze({options:t,typeName:y.ZodUnion,...x(e)});const ie=t=>t instanceof Je?ie(t.schema):t instanceof X?ie(t.innerType()):t instanceof qe?[t.value]:t instanceof le?t.options:t instanceof Ke?R.objectValues(t.enum):t instanceof He?ie(t._def.innerType):t instanceof Ve?[void 0]:t instanceof Ue?[null]:t instanceof se?[void 0,...ie(t.unwrap())]:t instanceof he?[null,...ie(t.unwrap())]:t instanceof Ut||t instanceof Xe?ie(t.unwrap()):t instanceof Ge?ie(t._def.innerType):[];class wt extends E{_parse(e){const{ctx:s}=this._processInputParams(e);if(s.parsedType!==_.object)return m(s,{code:p.invalid_type,expected:_.object,received:s.parsedType}),S;const r=this.discriminator,n=s.data[r],i=this.optionsMap.get(n);return i?s.common.async?i._parseAsync({data:s.data,path:s.path,parent:s}):i._parseSync({data:s.data,path:s.path,parent:s}):(m(s,{code:p.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),S)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,s,r){const n=new Map;for(const i of s){const o=ie(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const c of o){if(n.has(c))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(c)}`);n.set(c,i)}}return new wt({typeName:y.ZodDiscriminatedUnion,discriminator:e,options:s,optionsMap:n,...x(r)})}}function $t(t,e){const s=ae(t),r=ae(e);if(t===e)return{valid:!0,data:t};if(s===_.object&&r===_.object){const n=R.objectKeys(e),i=R.objectKeys(t).filter(c=>n.indexOf(c)!==-1),o={...t,...e};for(const c of i){const d=$t(t[c],e[c]);if(!d.valid)return{valid:!1};o[c]=d.data}return{valid:!0,data:o}}else if(s===_.array&&r===_.array){if(t.length!==e.length)return{valid:!1};const n=[];for(let i=0;i<t.length;i++){const o=t[i],c=e[i],d=$t(o,c);if(!d.valid)return{valid:!1};n.push(d.data)}return{valid:!0,data:n}}else return s===_.date&&r===_.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class We extends E{_parse(e){const{status:s,ctx:r}=this._processInputParams(e),n=(i,o)=>{if(Dt(i)||Dt(o))return S;const c=$t(i.value,o.value);return c.valid?((Zt(i)||Zt(o))&&s.dirty(),{status:s.value,value:c.data}):(m(r,{code:p.invalid_intersection_types}),S)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,o])=>n(i,o)):n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}We.create=(t,e,s)=>new We({left:t,right:e,typeName:y.ZodIntersection,...x(s)});class ne extends E{_parse(e){const{status:s,ctx:r}=this._processInputParams(e);if(r.parsedType!==_.array)return m(r,{code:p.invalid_type,expected:_.array,received:r.parsedType}),S;if(r.data.length<this._def.items.length)return m(r,{code:p.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),S;!this._def.rest&&r.data.length>this._def.items.length&&(m(r,{code:p.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),s.dirty());const i=[...r.data].map((o,c)=>{const d=this._def.items[c]||this._def.rest;return d?d._parse(new re(r,o,r.path,c)):null}).filter(o=>!!o);return r.common.async?Promise.all(i).then(o=>Z.mergeArray(s,o)):Z.mergeArray(s,i)}get items(){return this._def.items}rest(e){return new ne({...this._def,rest:e})}}ne.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ne({items:t,typeName:y.ZodTuple,rest:null,...x(e)})};class Ye extends E{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:s,ctx:r}=this._processInputParams(e);if(r.parsedType!==_.object)return m(r,{code:p.invalid_type,expected:_.object,received:r.parsedType}),S;const n=[],i=this._def.keyType,o=this._def.valueType;for(const c in r.data)n.push({key:i._parse(new re(r,c,r.path,c)),value:o._parse(new re(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?Z.mergeObjectAsync(s,n):Z.mergeObjectSync(s,n)}get element(){return this._def.valueType}static create(e,s,r){return s instanceof E?new Ye({keyType:e,valueType:s,typeName:y.ZodRecord,...x(r)}):new Ye({keyType:q.create(),valueType:e,typeName:y.ZodRecord,...x(s)})}}class vt extends E{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:s,ctx:r}=this._processInputParams(e);if(r.parsedType!==_.map)return m(r,{code:p.invalid_type,expected:_.map,received:r.parsedType}),S;const n=this._def.keyType,i=this._def.valueType,o=[...r.data.entries()].map(([c,d],u)=>({key:n._parse(new re(r,c,r.path,[u,"key"])),value:i._parse(new re(r,d,r.path,[u,"value"]))}));if(r.common.async){const c=new Map;return Promise.resolve().then(async()=>{for(const d of o){const u=await d.key,l=await d.value;if(u.status==="aborted"||l.status==="aborted")return S;(u.status==="dirty"||l.status==="dirty")&&s.dirty(),c.set(u.value,l.value)}return{status:s.value,value:c}})}else{const c=new Map;for(const d of o){const u=d.key,l=d.value;if(u.status==="aborted"||l.status==="aborted")return S;(u.status==="dirty"||l.status==="dirty")&&s.dirty(),c.set(u.value,l.value)}return{status:s.value,value:c}}}}vt.create=(t,e,s)=>new vt({valueType:e,keyType:t,typeName:y.ZodMap,...x(s)});class Se extends E{_parse(e){const{status:s,ctx:r}=this._processInputParams(e);if(r.parsedType!==_.set)return m(r,{code:p.invalid_type,expected:_.set,received:r.parsedType}),S;const n=this._def;n.minSize!==null&&r.data.size<n.minSize.value&&(m(r,{code:p.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),s.dirty()),n.maxSize!==null&&r.data.size>n.maxSize.value&&(m(r,{code:p.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),s.dirty());const i=this._def.valueType;function o(d){const u=new Set;for(const l of d){if(l.status==="aborted")return S;l.status==="dirty"&&s.dirty(),u.add(l.value)}return{status:s.value,value:u}}const c=[...r.data.values()].map((d,u)=>i._parse(new re(r,d,r.path,u)));return r.common.async?Promise.all(c).then(d=>o(d)):o(c)}min(e,s){return new Se({...this._def,minSize:{value:e,message:v.toString(s)}})}max(e,s){return new Se({...this._def,maxSize:{value:e,message:v.toString(s)}})}size(e,s){return this.min(e,s).max(e,s)}nonempty(e){return this.min(1,e)}}Se.create=(t,e)=>new Se({valueType:t,minSize:null,maxSize:null,typeName:y.ZodSet,...x(e)});class Ce extends E{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:s}=this._processInputParams(e);if(s.parsedType!==_.function)return m(s,{code:p.invalid_type,expected:_.function,received:s.parsedType}),S;function r(c,d){return gt({data:c,path:s.path,errorMaps:[s.common.contextualErrorMap,s.schemaErrorMap,pt(),Re].filter(u=>!!u),issueData:{code:p.invalid_arguments,argumentsError:d}})}function n(c,d){return gt({data:c,path:s.path,errorMaps:[s.common.contextualErrorMap,s.schemaErrorMap,pt(),Re].filter(u=>!!u),issueData:{code:p.invalid_return_type,returnTypeError:d}})}const i={errorMap:s.common.contextualErrorMap},o=s.data;if(this._def.returns instanceof Ae){const c=this;return L(async function(...d){const u=new z([]),l=await c._def.args.parseAsync(d,i).catch(N=>{throw u.addIssue(r(d,N)),u}),g=await Reflect.apply(o,this,l);return await c._def.returns._def.type.parseAsync(g,i).catch(N=>{throw u.addIssue(n(g,N)),u})})}else{const c=this;return L(function(...d){const u=c._def.args.safeParse(d,i);if(!u.success)throw new z([r(d,u.error)]);const l=Reflect.apply(o,this,u.data),g=c._def.returns.safeParse(l,i);if(!g.success)throw new z([n(l,g.error)]);return g.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new Ce({...this._def,args:ne.create(e).rest(be.create())})}returns(e){return new Ce({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,s,r){return new Ce({args:e||ne.create([]).rest(be.create()),returns:s||be.create(),typeName:y.ZodFunction,...x(r)})}}class Je extends E{get schema(){return this._def.getter()}_parse(e){const{ctx:s}=this._processInputParams(e);return this._def.getter()._parse({data:s.data,path:s.path,parent:s})}}Je.create=(t,e)=>new Je({getter:t,typeName:y.ZodLazy,...x(e)});class qe extends E{_parse(e){if(e.data!==this._def.value){const s=this._getOrReturnCtx(e);return m(s,{received:s.data,code:p.invalid_literal,expected:this._def.value}),S}return{status:"valid",value:e.data}}get value(){return this._def.value}}qe.create=(t,e)=>new qe({value:t,typeName:y.ZodLiteral,...x(e)});function Bs(t,e){return new le({values:t,typeName:y.ZodEnum,...x(e)})}class le extends E{constructor(){super(...arguments),Ze.set(this,void 0)}_parse(e){if(typeof e.data!="string"){const s=this._getOrReturnCtx(e),r=this._def.values;return m(s,{expected:R.joinValues(r),received:s.parsedType,code:p.invalid_type}),S}if(mt(this,Ze)||Ms(this,Ze,new Set(this._def.values)),!mt(this,Ze).has(e.data)){const s=this._getOrReturnCtx(e),r=this._def.values;return m(s,{received:s.data,code:p.invalid_enum_value,options:r}),S}return L(e.data)}get options(){return this._def.values}get enum(){const e={};for(const s of this._def.values)e[s]=s;return e}get Values(){const e={};for(const s of this._def.values)e[s]=s;return e}get Enum(){const e={};for(const s of this._def.values)e[s]=s;return e}extract(e,s=this._def){return le.create(e,{...this._def,...s})}exclude(e,s=this._def){return le.create(this.options.filter(r=>!e.includes(r)),{...this._def,...s})}}Ze=new WeakMap;le.create=Bs;class Ke extends E{constructor(){super(...arguments),$e.set(this,void 0)}_parse(e){const s=R.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==_.string&&r.parsedType!==_.number){const n=R.objectValues(s);return m(r,{expected:R.joinValues(n),received:r.parsedType,code:p.invalid_type}),S}if(mt(this,$e)||Ms(this,$e,new Set(R.getValidEnumValues(this._def.values))),!mt(this,$e).has(e.data)){const n=R.objectValues(s);return m(r,{received:r.data,code:p.invalid_enum_value,options:n}),S}return L(e.data)}get enum(){return this._def.values}}$e=new WeakMap;Ke.create=(t,e)=>new Ke({values:t,typeName:y.ZodNativeEnum,...x(e)});class Ae extends E{unwrap(){return this._def.type}_parse(e){const{ctx:s}=this._processInputParams(e);if(s.parsedType!==_.promise&&s.common.async===!1)return m(s,{code:p.invalid_type,expected:_.promise,received:s.parsedType}),S;const r=s.parsedType===_.promise?s.data:Promise.resolve(s.data);return L(r.then(n=>this._def.type.parseAsync(n,{path:s.path,errorMap:s.common.contextualErrorMap})))}}Ae.create=(t,e)=>new Ae({type:t,typeName:y.ZodPromise,...x(e)});class X extends E{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===y.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:s,ctx:r}=this._processInputParams(e),n=this._def.effect||null,i={addIssue:o=>{m(r,o),o.fatal?s.abort():s.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),n.type==="preprocess"){const o=n.transform(r.data,i);if(r.common.async)return Promise.resolve(o).then(async c=>{if(s.value==="aborted")return S;const d=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return d.status==="aborted"?S:d.status==="dirty"||s.value==="dirty"?Ee(d.value):d});{if(s.value==="aborted")return S;const c=this._def.schema._parseSync({data:o,path:r.path,parent:r});return c.status==="aborted"?S:c.status==="dirty"||s.value==="dirty"?Ee(c.value):c}}if(n.type==="refinement"){const o=c=>{const d=n.refinement(c,i);if(r.common.async)return Promise.resolve(d);if(d instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c};if(r.common.async===!1){const c=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return c.status==="aborted"?S:(c.status==="dirty"&&s.dirty(),o(c.value),{status:s.value,value:c.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(c=>c.status==="aborted"?S:(c.status==="dirty"&&s.dirty(),o(c.value).then(()=>({status:s.value,value:c.value}))))}if(n.type==="transform")if(r.common.async===!1){const o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!ve(o))return o;const c=n.transform(o.value,i);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:s.value,value:c}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>ve(o)?Promise.resolve(n.transform(o.value,i)).then(c=>({status:s.value,value:c})):o);R.assertNever(n)}}X.create=(t,e,s)=>new X({schema:t,typeName:y.ZodEffects,effect:e,...x(s)});X.createWithPreprocess=(t,e,s)=>new X({schema:e,effect:{type:"preprocess",transform:t},typeName:y.ZodEffects,...x(s)});class se extends E{_parse(e){return this._getType(e)===_.undefined?L(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}se.create=(t,e)=>new se({innerType:t,typeName:y.ZodOptional,...x(e)});class he extends E{_parse(e){return this._getType(e)===_.null?L(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}he.create=(t,e)=>new he({innerType:t,typeName:y.ZodNullable,...x(e)});class He extends E{_parse(e){const{ctx:s}=this._processInputParams(e);let r=s.data;return s.parsedType===_.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:s.path,parent:s})}removeDefault(){return this._def.innerType}}He.create=(t,e)=>new He({innerType:t,typeName:y.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...x(e)});class Ge extends E{_parse(e){const{ctx:s}=this._processInputParams(e),r={...s,common:{...s.common,issues:[]}},n=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Le(n)?n.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new z(r.common.issues)},input:r.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new z(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Ge.create=(t,e)=>new Ge({innerType:t,typeName:y.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...x(e)});class yt extends E{_parse(e){if(this._getType(e)!==_.nan){const r=this._getOrReturnCtx(e);return m(r,{code:p.invalid_type,expected:_.nan,received:r.parsedType}),S}return{status:"valid",value:e.data}}}yt.create=t=>new yt({typeName:y.ZodNaN,...x(t)});const on=Symbol("zod_brand");class Ut extends E{_parse(e){const{ctx:s}=this._processInputParams(e),r=s.data;return this._def.type._parse({data:r,path:s.path,parent:s})}unwrap(){return this._def.type}}class st extends E{_parse(e){const{status:s,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?S:i.status==="dirty"?(s.dirty(),Ee(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const n=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return n.status==="aborted"?S:n.status==="dirty"?(s.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:r.path,parent:r})}}static create(e,s){return new st({in:e,out:s,typeName:y.ZodPipeline})}}class Xe extends E{_parse(e){const s=this._def.innerType._parse(e),r=n=>(ve(n)&&(n.value=Object.freeze(n.value)),n);return Le(s)?s.then(n=>r(n)):r(s)}unwrap(){return this._def.innerType}}Xe.create=(t,e)=>new Xe({innerType:t,typeName:y.ZodReadonly,...x(e)});function vs(t,e){const s=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof s=="string"?{message:s}:s}function Ds(t,e={},s){return t?Ie.create().superRefine((r,n)=>{var i,o;const c=t(r);if(c instanceof Promise)return c.then(d=>{var u,l;if(!d){const g=vs(e,r),I=(l=(u=g.fatal)!==null&&u!==void 0?u:s)!==null&&l!==void 0?l:!0;n.addIssue({code:"custom",...g,fatal:I})}});if(!c){const d=vs(e,r),u=(o=(i=d.fatal)!==null&&i!==void 0?i:s)!==null&&o!==void 0?o:!0;n.addIssue({code:"custom",...d,fatal:u})}}):Ie.create()}const cn={object:M.lazycreate};var y;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(y||(y={}));const un=(t,e={message:`Input not instance of ${t.name}`})=>Ds(s=>s instanceof t,e),Zs=q.create,$s=ue.create,dn=yt.create,ln=de.create,Ls=Fe.create,hn=ye.create,fn=_t.create,pn=Ve.create,gn=Ue.create,mn=Ie.create,_n=be.create,bn=oe.create,vn=bt.create,yn=G.create,Sn=M.create,wn=M.strictCreate,xn=ze.create,Tn=wt.create,En=We.create,kn=ne.create,Cn=Ye.create,Rn=vt.create,In=Se.create,An=Ce.create,On=Je.create,Mn=qe.create,Pn=le.create,Nn=Ke.create,jn=Ae.create,ys=X.create,Bn=se.create,Dn=he.create,Zn=X.createWithPreprocess,$n=st.create,Ln=()=>Zs().optional(),Fn=()=>$s().optional(),Vn=()=>Ls().optional(),Un={string:t=>q.create({...t,coerce:!0}),number:t=>ue.create({...t,coerce:!0}),boolean:t=>Fe.create({...t,coerce:!0}),bigint:t=>de.create({...t,coerce:!0}),date:t=>ye.create({...t,coerce:!0})},zn=S;var U=Object.freeze({__proto__:null,defaultErrorMap:Re,setErrorMap:Dr,getErrorMap:pt,makeIssue:gt,EMPTY_PATH:Zr,addIssueToContext:m,ParseStatus:Z,INVALID:S,DIRTY:Ee,OK:L,isAborted:Dt,isDirty:Zt,isValid:ve,isAsync:Le,get util(){return R},get objectUtil(){return Bt},ZodParsedType:_,getParsedType:ae,ZodType:E,datetimeRegex:js,ZodString:q,ZodNumber:ue,ZodBigInt:de,ZodBoolean:Fe,ZodDate:ye,ZodSymbol:_t,ZodUndefined:Ve,ZodNull:Ue,ZodAny:Ie,ZodUnknown:be,ZodNever:oe,ZodVoid:bt,ZodArray:G,ZodObject:M,ZodUnion:ze,ZodDiscriminatedUnion:wt,ZodIntersection:We,ZodTuple:ne,ZodRecord:Ye,ZodMap:vt,ZodSet:Se,ZodFunction:Ce,ZodLazy:Je,ZodLiteral:qe,ZodEnum:le,ZodNativeEnum:Ke,ZodPromise:Ae,ZodEffects:X,ZodTransformer:X,ZodOptional:se,ZodNullable:he,ZodDefault:He,ZodCatch:Ge,ZodNaN:yt,BRAND:on,ZodBranded:Ut,ZodPipeline:st,ZodReadonly:Xe,custom:Ds,Schema:E,ZodSchema:E,late:cn,get ZodFirstPartyTypeKind(){return y},coerce:Un,any:mn,array:yn,bigint:ln,boolean:Ls,date:hn,discriminatedUnion:Tn,effect:ys,enum:Pn,function:An,instanceof:un,intersection:En,lazy:On,literal:Mn,map:Rn,nan:dn,nativeEnum:Nn,never:bn,null:gn,nullable:Dn,number:$s,object:Sn,oboolean:Vn,onumber:Fn,optional:Bn,ostring:Ln,pipeline:$n,preprocess:Zn,promise:jn,record:Cn,set:In,strictObject:wn,string:Zs,symbol:fn,transformer:ys,tuple:kn,undefined:pn,union:xn,unknown:_n,void:vn,NEVER:zn,ZodIssueCode:p,quotelessJson:Br,ZodError:z});U.object({maxTokens:U.number().int().positive().optional(),temperature:U.number().optional(),topP:U.number().optional(),presencePenalty:U.number().optional(),frequencyPenalty:U.number().optional(),seed:U.number().int().optional(),headers:U.record(U.string().optional()).optional()});U.object({apiKey:U.string().optional(),baseUrl:U.string().optional(),modelName:U.string().optional()});var Wn=t=>Array.from(t).map(s=>s.getModelContext()).sort((s,r)=>(r.priority??0)-(s.priority??0)).reduce((s,r)=>{var n;if(r.system&&(s.system?s.system+=`
14
+ <%s key={someKey} {...props} />`,A,O,fe,O),Mt[O+A]=!0)}if(O=null,E!==void 0&&(s(E),O=""+E),a(x)&&(s(x.key),O=""+x.key),"key"in x){E={};for(var pt in x)pt!=="key"&&(E[pt]=x[pt])}else E=x;return O&&o(E,typeof f=="function"?f.displayName||f.name||"Unknown":f),c(f,O,Y,Q,n(),E,lt,ft)}function g(f){typeof f=="object"&&f!==null&&f.$$typeof===I&&f._store&&(f._store.validated=1)}var k=S,I=Symbol.for("react.transitional.element"),de=Symbol.for("react.portal"),D=Symbol.for("react.fragment"),xe=Symbol.for("react.strict_mode"),ue=Symbol.for("react.profiler"),dt=Symbol.for("react.consumer"),ut=Symbol.for("react.context"),R=Symbol.for("react.forward_ref"),Z=Symbol.for("react.suspense"),W=Symbol.for("react.suspense_list"),Te=Symbol.for("react.memo"),P=Symbol.for("react.lazy"),he=Symbol.for("react.activity"),Ye=Symbol.for("react.client.reference"),le=k.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,Ct=Object.prototype.hasOwnProperty,Ss=Array.isArray,ht=console.createTask?console.createTask:function(){return null};k={"react-stack-bottom-frame":function(f){return f()}};var It,Rt={},At=k["react-stack-bottom-frame"].bind(k,i)(),Ot=ht(r(i)),Mt={};ke.Fragment=D,ke.jsx=function(f,x,E,A,Q){var Y=1e4>le.recentlyCreatedOwnerStacks++;return u(f,x,E,!1,A,Q,Y?Error("react-stack-top-frame"):At,Y?ht(r(f)):Ot)},ke.jsxs=function(f,x,E,A,Q){var Y=1e4>le.recentlyCreatedOwnerStacks++;return u(f,x,E,!0,A,Q,Y?Error("react-stack-top-frame"):At,Y?ht(r(f)):Ot)}}(),ke}Yt.exports=Es();var F=Yt.exports,T;(function(t){t.assertEqual=n=>n;function e(n){}t.assertIs=e;function s(n){throw new Error}t.assertNever=s,t.arrayToEnum=n=>{const i={};for(const a of n)i[a]=a;return i},t.getValidEnumValues=n=>{const i=t.objectKeys(n).filter(o=>typeof n[n[o]]!="number"),a={};for(const o of i)a[o]=n[o];return t.objectValues(a)},t.objectValues=n=>t.objectKeys(n).map(function(i){return n[i]}),t.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{const i=[];for(const a in n)Object.prototype.hasOwnProperty.call(n,a)&&i.push(a);return i},t.find=(n,i)=>{for(const a of n)if(i(a))return a},t.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&isFinite(n)&&Math.floor(n)===n;function r(n,i=" | "){return n.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}t.joinValues=r,t.jsonStringifyReplacer=(n,i)=>typeof i=="bigint"?i.toString():i})(T||(T={}));var mt;(function(t){t.mergeShapes=(e,s)=>({...e,...s})})(mt||(mt={}));const m=T.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),G=t=>{switch(typeof t){case"undefined":return m.undefined;case"string":return m.string;case"number":return isNaN(t)?m.nan:m.number;case"boolean":return m.boolean;case"function":return m.function;case"bigint":return m.bigint;case"symbol":return m.symbol;case"object":return Array.isArray(t)?m.array:t===null?m.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?m.promise:typeof Map<"u"&&t instanceof Map?m.map:typeof Set<"u"&&t instanceof Set?m.set:typeof Date<"u"&&t instanceof Date?m.date:m.object;default:return m.unknown}},l=T.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"]),Cs=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");class B extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const s=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,s):this.__proto__=s,this.name="ZodError",this.issues=e}format(e){const s=e||function(i){return i.message},r={_errors:[]},n=i=>{for(const a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(n);else if(a.code==="invalid_return_type")n(a.returnTypeError);else if(a.code==="invalid_arguments")n(a.argumentsError);else if(a.path.length===0)r._errors.push(s(a));else{let o=r,d=0;for(;d<a.path.length;){const c=a.path[d];d===a.path.length-1?(o[c]=o[c]||{_errors:[]},o[c]._errors.push(s(a))):o[c]=o[c]||{_errors:[]},o=o[c],d++}}};return n(this),r}static assert(e){if(!(e instanceof B))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,T.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=s=>s.message){const s={},r=[];for(const n of this.issues)n.path.length>0?(s[n.path[0]]=s[n.path[0]]||[],s[n.path[0]].push(e(n))):r.push(e(n));return{formErrors:r,fieldErrors:s}}get formErrors(){return this.flatten()}}B.create=t=>new B(t);const be=(t,e)=>{let s;switch(t.code){case l.invalid_type:t.received===m.undefined?s="Required":s=`Expected ${t.expected}, received ${t.received}`;break;case l.invalid_literal:s=`Invalid literal value, expected ${JSON.stringify(t.expected,T.jsonStringifyReplacer)}`;break;case l.unrecognized_keys:s=`Unrecognized key(s) in object: ${T.joinValues(t.keys,", ")}`;break;case l.invalid_union:s="Invalid input";break;case l.invalid_union_discriminator:s=`Invalid discriminator value. Expected ${T.joinValues(t.options)}`;break;case l.invalid_enum_value:s=`Invalid enum value. Expected ${T.joinValues(t.options)}, received '${t.received}'`;break;case l.invalid_arguments:s="Invalid function arguments";break;case l.invalid_return_type:s="Invalid function return type";break;case l.invalid_date:s="Invalid date";break;case l.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(s=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(s=`${s} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?s=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?s=`Invalid input: must end with "${t.validation.endsWith}"`:T.assertNever(t.validation):t.validation!=="regex"?s=`Invalid ${t.validation}`:s="Invalid";break;case l.too_small:t.type==="array"?s=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?s=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?s=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?s=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:s="Invalid input";break;case l.too_big:t.type==="array"?s=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?s=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?s=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?s=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?s=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:s="Invalid input";break;case l.custom:s="Invalid input";break;case l.invalid_intersection_types:s="Intersection results could not be merged";break;case l.not_multiple_of:s=`Number must be a multiple of ${t.multipleOf}`;break;case l.not_finite:s="Number must be finite";break;default:s=e.defaultError,T.assertNever(t)}return{message:s}};let Jt=be;function Is(t){Jt=t}function Ge(){return Jt}const Xe=t=>{const{data:e,path:s,errorMaps:r,issueData:n}=t,i=[...s,...n.path||[]],a={...n,path:i};if(n.message!==void 0)return{...n,path:i,message:n.message};let o="";const d=r.filter(c=>!!c).slice().reverse();for(const c of d)o=c(a,{data:e,defaultError:o}).message;return{...n,path:i,message:o}},Rs=[];function p(t,e){const s=Ge(),r=Xe({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,s,s===be?void 0:be].filter(n=>!!n)});t.common.issues.push(r)}class M{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,s){const r=[];for(const n of s){if(n.status==="aborted")return y;n.status==="dirty"&&e.dirty(),r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,s){const r=[];for(const n of s){const i=await n.key,a=await n.value;r.push({key:i,value:a})}return M.mergeObjectSync(e,r)}static mergeObjectSync(e,s){const r={};for(const n of s){const{key:i,value:a}=n;if(i.status==="aborted"||a.status==="aborted")return y;i.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof a.value<"u"||n.alwaysSet)&&(r[i.value]=a.value)}return{status:e.value,value:r}}}const y=Object.freeze({status:"aborted"}),ge=t=>({status:"dirty",value:t}),N=t=>({status:"valid",value:t}),_t=t=>t.status==="aborted",bt=t=>t.status==="dirty",ae=t=>t.status==="valid",Ie=t=>typeof Promise<"u"&&t instanceof Promise;function Qe(t,e,s,r){if(typeof e=="function"?t!==e||!0:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e.get(t)}function qt(t,e,s,r,n){if(typeof e=="function"?t!==e||!0:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,s),s}var _;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(_||(_={}));var Ee,Ce;class q{constructor(e,s,r,n){this._cachedPath=[],this.parent=e,this.data=s,this._path=r,this._key=n}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Pt=(t,e)=>{if(ae(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const s=new B(t.common.issues);return this._error=s,this._error}}};function v(t){if(!t)return{};const{errorMap:e,invalid_type_error:s,required_error:r,description:n}=t;if(e&&(s||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(a,o)=>{var d,c;const{message:u}=t;return a.code==="invalid_enum_value"?{message:u??o.defaultError}:typeof o.data>"u"?{message:(d=u??r)!==null&&d!==void 0?d:o.defaultError}:a.code!=="invalid_type"?{message:o.defaultError}:{message:(c=u??s)!==null&&c!==void 0?c:o.defaultError}},description:n}}class w{get description(){return this._def.description}_getType(e){return G(e.data)}_getOrReturnCtx(e,s){return s||{common:e.parent.common,data:e.data,parsedType:G(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new M,ctx:{common:e.parent.common,data:e.data,parsedType:G(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const s=this._parse(e);if(Ie(s))throw new Error("Synchronous parse encountered promise.");return s}_parseAsync(e){const s=this._parse(e);return Promise.resolve(s)}parse(e,s){const r=this.safeParse(e,s);if(r.success)return r.data;throw r.error}safeParse(e,s){var r;const n={common:{issues:[],async:(r=s==null?void 0:s.async)!==null&&r!==void 0?r:!1,contextualErrorMap:s==null?void 0:s.errorMap},path:(s==null?void 0:s.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:G(e)},i=this._parseSync({data:e,path:n.path,parent:n});return Pt(n,i)}"~validate"(e){var s,r;const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:G(e)};if(!this["~standard"].async)try{const i=this._parseSync({data:e,path:[],parent:n});return ae(i)?{value:i.value}:{issues:n.common.issues}}catch(i){!((r=(s=i==null?void 0:i.message)===null||s===void 0?void 0:s.toLowerCase())===null||r===void 0)&&r.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(i=>ae(i)?{value:i.value}:{issues:n.common.issues})}async parseAsync(e,s){const r=await this.safeParseAsync(e,s);if(r.success)return r.data;throw r.error}async safeParseAsync(e,s){const r={common:{issues:[],contextualErrorMap:s==null?void 0:s.errorMap,async:!0},path:(s==null?void 0:s.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:G(e)},n=this._parse({data:e,path:r.path,parent:r}),i=await(Ie(n)?n:Promise.resolve(n));return Pt(r,i)}refine(e,s){const r=n=>typeof s=="string"||typeof s>"u"?{message:s}:typeof s=="function"?s(n):s;return this._refinement((n,i)=>{const a=e(n),o=()=>i.addIssue({code:l.custom,...r(n)});return typeof Promise<"u"&&a instanceof Promise?a.then(d=>d?!0:(o(),!1)):a?!0:(o(),!1)})}refinement(e,s){return this._refinement((r,n)=>e(r)?!0:(n.addIssue(typeof s=="function"?s(r,n):s),!1))}_refinement(e){return new U({schema:this,typeName:b.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:s=>this["~validate"](s)}}optional(){return J.create(this,this._def)}nullable(){return re.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return z.create(this)}promise(){return ve.create(this,this._def)}or(e){return Me.create([this,e],this._def)}and(e){return Ne.create(this,e,this._def)}transform(e){return new U({...v(this._def),schema:this,typeName:b.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const s=typeof e=="function"?e:()=>e;return new Ze({...v(this._def),innerType:this,defaultValue:s,typeName:b.ZodDefault})}brand(){return new xt({typeName:b.ZodBranded,type:this,...v(this._def)})}catch(e){const s=typeof e=="function"?e:()=>e;return new Le({...v(this._def),innerType:this,catchValue:s,typeName:b.ZodCatch})}describe(e){const s=this.constructor;return new s({...this._def,description:e})}pipe(e){return Ve.create(this,e)}readonly(){return $e.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const As=/^c[^\s-]{8,}$/i,Os=/^[0-9a-z]+$/,Ms=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ns=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Ps=/^[a-z0-9_-]{21}$/i,js=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Bs=/^[-+]?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)?)??$/,Ds=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Zs="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let gt;const Ls=/^(?:(?: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])$/,$s=/^(?:(?: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])$/,Fs=/^(([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]))$/,zs=/^(([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])$/,Us=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Vs=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ht="((\\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])))",Ws=new RegExp(`^${Ht}$`);function Kt(t){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`),e}function Ys(t){return new RegExp(`^${Kt(t)}$`)}function Gt(t){let e=`${Ht}T${Kt(t)}`;const s=[];return s.push(t.local?"Z?":"Z"),t.offset&&s.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${s.join("|")})`,new RegExp(`^${e}$`)}function Js(t,e){return!!((e==="v4"||!e)&&Ls.test(t)||(e==="v6"||!e)&&Fs.test(t))}function qs(t,e){if(!js.test(t))return!1;try{const[s]=t.split("."),r=s.replace(/-/g,"+").replace(/_/g,"/").padEnd(s.length+(4-s.length%4)%4,"="),n=JSON.parse(atob(r));return!(typeof n!="object"||n===null||!n.typ||!n.alg||e&&n.alg!==e)}catch{return!1}}function Hs(t,e){return!!((e==="v4"||!e)&&$s.test(t)||(e==="v6"||!e)&&zs.test(t))}class L extends w{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==m.string){const i=this._getOrReturnCtx(e);return p(i,{code:l.invalid_type,expected:m.string,received:i.parsedType}),y}const r=new M;let n;for(const i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(n=this._getOrReturnCtx(e,n),p(n,{code:l.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(n=this._getOrReturnCtx(e,n),p(n,{code:l.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const a=e.data.length>i.value,o=e.data.length<i.value;(a||o)&&(n=this._getOrReturnCtx(e,n),a?p(n,{code:l.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):o&&p(n,{code:l.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")Ds.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"email",code:l.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")gt||(gt=new RegExp(Zs,"u")),gt.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"emoji",code:l.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")Ns.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"uuid",code:l.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")Ps.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"nanoid",code:l.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")As.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"cuid",code:l.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")Os.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"cuid2",code:l.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")Ms.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"ulid",code:l.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),p(n,{validation:"url",code:l.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"regex",code:l.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(n=this._getOrReturnCtx(e,n),p(n,{code:l.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(n=this._getOrReturnCtx(e,n),p(n,{code:l.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(n=this._getOrReturnCtx(e,n),p(n,{code:l.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?Gt(i).test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:l.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?Ws.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:l.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?Ys(i).test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:l.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?Bs.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"duration",code:l.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?Js(e.data,i.version)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"ip",code:l.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?qs(e.data,i.alg)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"jwt",code:l.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?Hs(e.data,i.version)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"cidr",code:l.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?Us.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"base64",code:l.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?Vs.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"base64url",code:l.invalid_string,message:i.message}),r.dirty()):T.assertNever(i);return{status:r.value,value:e.data}}_regex(e,s,r){return this.refinement(n=>e.test(n),{validation:s,code:l.invalid_string,..._.errToObj(r)})}_addCheck(e){return new L({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",..._.errToObj(e)})}url(e){return this._addCheck({kind:"url",..._.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",..._.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",..._.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",..._.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",..._.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",..._.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",..._.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",..._.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",..._.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",..._.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",..._.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",..._.errToObj(e)})}datetime(e){var s,r;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(s=e==null?void 0:e.offset)!==null&&s!==void 0?s:!1,local:(r=e==null?void 0:e.local)!==null&&r!==void 0?r:!1,..._.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,..._.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",..._.errToObj(e)})}regex(e,s){return this._addCheck({kind:"regex",regex:e,..._.errToObj(s)})}includes(e,s){return this._addCheck({kind:"includes",value:e,position:s==null?void 0:s.position,..._.errToObj(s==null?void 0:s.message)})}startsWith(e,s){return this._addCheck({kind:"startsWith",value:e,..._.errToObj(s)})}endsWith(e,s){return this._addCheck({kind:"endsWith",value:e,..._.errToObj(s)})}min(e,s){return this._addCheck({kind:"min",value:e,..._.errToObj(s)})}max(e,s){return this._addCheck({kind:"max",value:e,..._.errToObj(s)})}length(e,s){return this._addCheck({kind:"length",value:e,..._.errToObj(s)})}nonempty(e){return this.min(1,_.errToObj(e))}trim(){return new L({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new L({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new L({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const s of this._def.checks)s.kind==="min"&&(e===null||s.value>e)&&(e=s.value);return e}get maxLength(){let e=null;for(const s of this._def.checks)s.kind==="max"&&(e===null||s.value<e)&&(e=s.value);return e}}L.create=t=>{var e;return new L({checks:[],typeName:b.ZodString,coerce:(e=t==null?void 0:t.coerce)!==null&&e!==void 0?e:!1,...v(t)})};function Ks(t,e){const s=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,n=s>r?s:r,i=parseInt(t.toFixed(n).replace(".","")),a=parseInt(e.toFixed(n).replace(".",""));return i%a/Math.pow(10,n)}class ee extends w{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==m.number){const i=this._getOrReturnCtx(e);return p(i,{code:l.invalid_type,expected:m.number,received:i.parsedType}),y}let r;const n=new M;for(const i of this._def.checks)i.kind==="int"?T.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),p(r,{code:l.invalid_type,expected:"integer",received:"float",message:i.message}),n.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),p(r,{code:l.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),p(r,{code:l.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty()):i.kind==="multipleOf"?Ks(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),p(r,{code:l.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),p(r,{code:l.not_finite,message:i.message}),n.dirty()):T.assertNever(i);return{status:n.value,value:e.data}}gte(e,s){return this.setLimit("min",e,!0,_.toString(s))}gt(e,s){return this.setLimit("min",e,!1,_.toString(s))}lte(e,s){return this.setLimit("max",e,!0,_.toString(s))}lt(e,s){return this.setLimit("max",e,!1,_.toString(s))}setLimit(e,s,r,n){return new ee({...this._def,checks:[...this._def.checks,{kind:e,value:s,inclusive:r,message:_.toString(n)}]})}_addCheck(e){return new ee({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:_.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:_.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:_.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:_.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:_.toString(e)})}multipleOf(e,s){return this._addCheck({kind:"multipleOf",value:e,message:_.toString(s)})}finite(e){return this._addCheck({kind:"finite",message:_.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:_.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:_.toString(e)})}get minValue(){let e=null;for(const s of this._def.checks)s.kind==="min"&&(e===null||s.value>e)&&(e=s.value);return e}get maxValue(){let e=null;for(const s of this._def.checks)s.kind==="max"&&(e===null||s.value<e)&&(e=s.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&T.isInteger(e.value))}get isFinite(){let e=null,s=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(s===null||r.value>s)&&(s=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(s)&&Number.isFinite(e)}}ee.create=t=>new ee({checks:[],typeName:b.ZodNumber,coerce:(t==null?void 0:t.coerce)||!1,...v(t)});class te extends w{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==m.bigint)return this._getInvalidInput(e);let r;const n=new M;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),p(r,{code:l.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),n.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),p(r,{code:l.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),n.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),p(r,{code:l.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):T.assertNever(i);return{status:n.value,value:e.data}}_getInvalidInput(e){const s=this._getOrReturnCtx(e);return p(s,{code:l.invalid_type,expected:m.bigint,received:s.parsedType}),y}gte(e,s){return this.setLimit("min",e,!0,_.toString(s))}gt(e,s){return this.setLimit("min",e,!1,_.toString(s))}lte(e,s){return this.setLimit("max",e,!0,_.toString(s))}lt(e,s){return this.setLimit("max",e,!1,_.toString(s))}setLimit(e,s,r,n){return new te({...this._def,checks:[...this._def.checks,{kind:e,value:s,inclusive:r,message:_.toString(n)}]})}_addCheck(e){return new te({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:_.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:_.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:_.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:_.toString(e)})}multipleOf(e,s){return this._addCheck({kind:"multipleOf",value:e,message:_.toString(s)})}get minValue(){let e=null;for(const s of this._def.checks)s.kind==="min"&&(e===null||s.value>e)&&(e=s.value);return e}get maxValue(){let e=null;for(const s of this._def.checks)s.kind==="max"&&(e===null||s.value<e)&&(e=s.value);return e}}te.create=t=>{var e;return new te({checks:[],typeName:b.ZodBigInt,coerce:(e=t==null?void 0:t.coerce)!==null&&e!==void 0?e:!1,...v(t)})};class Re extends w{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==m.boolean){const r=this._getOrReturnCtx(e);return p(r,{code:l.invalid_type,expected:m.boolean,received:r.parsedType}),y}return N(e.data)}}Re.create=t=>new Re({typeName:b.ZodBoolean,coerce:(t==null?void 0:t.coerce)||!1,...v(t)});class oe extends w{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==m.date){const i=this._getOrReturnCtx(e);return p(i,{code:l.invalid_type,expected:m.date,received:i.parsedType}),y}if(isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return p(i,{code:l.invalid_date}),y}const r=new M;let n;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(n=this._getOrReturnCtx(e,n),p(n,{code:l.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(n=this._getOrReturnCtx(e,n),p(n,{code:l.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):T.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new oe({...this._def,checks:[...this._def.checks,e]})}min(e,s){return this._addCheck({kind:"min",value:e.getTime(),message:_.toString(s)})}max(e,s){return this._addCheck({kind:"max",value:e.getTime(),message:_.toString(s)})}get minDate(){let e=null;for(const s of this._def.checks)s.kind==="min"&&(e===null||s.value>e)&&(e=s.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const s of this._def.checks)s.kind==="max"&&(e===null||s.value<e)&&(e=s.value);return e!=null?new Date(e):null}}oe.create=t=>new oe({checks:[],coerce:(t==null?void 0:t.coerce)||!1,typeName:b.ZodDate,...v(t)});class et extends w{_parse(e){if(this._getType(e)!==m.symbol){const r=this._getOrReturnCtx(e);return p(r,{code:l.invalid_type,expected:m.symbol,received:r.parsedType}),y}return N(e.data)}}et.create=t=>new et({typeName:b.ZodSymbol,...v(t)});class Ae extends w{_parse(e){if(this._getType(e)!==m.undefined){const r=this._getOrReturnCtx(e);return p(r,{code:l.invalid_type,expected:m.undefined,received:r.parsedType}),y}return N(e.data)}}Ae.create=t=>new Ae({typeName:b.ZodUndefined,...v(t)});class Oe extends w{_parse(e){if(this._getType(e)!==m.null){const r=this._getOrReturnCtx(e);return p(r,{code:l.invalid_type,expected:m.null,received:r.parsedType}),y}return N(e.data)}}Oe.create=t=>new Oe({typeName:b.ZodNull,...v(t)});class ye extends w{constructor(){super(...arguments),this._any=!0}_parse(e){return N(e.data)}}ye.create=t=>new ye({typeName:b.ZodAny,...v(t)});class ie extends w{constructor(){super(...arguments),this._unknown=!0}_parse(e){return N(e.data)}}ie.create=t=>new ie({typeName:b.ZodUnknown,...v(t)});class X extends w{_parse(e){const s=this._getOrReturnCtx(e);return p(s,{code:l.invalid_type,expected:m.never,received:s.parsedType}),y}}X.create=t=>new X({typeName:b.ZodNever,...v(t)});class tt extends w{_parse(e){if(this._getType(e)!==m.undefined){const r=this._getOrReturnCtx(e);return p(r,{code:l.invalid_type,expected:m.void,received:r.parsedType}),y}return N(e.data)}}tt.create=t=>new tt({typeName:b.ZodVoid,...v(t)});class z extends w{_parse(e){const{ctx:s,status:r}=this._processInputParams(e),n=this._def;if(s.parsedType!==m.array)return p(s,{code:l.invalid_type,expected:m.array,received:s.parsedType}),y;if(n.exactLength!==null){const a=s.data.length>n.exactLength.value,o=s.data.length<n.exactLength.value;(a||o)&&(p(s,{code:a?l.too_big:l.too_small,minimum:o?n.exactLength.value:void 0,maximum:a?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),r.dirty())}if(n.minLength!==null&&s.data.length<n.minLength.value&&(p(s,{code:l.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),r.dirty()),n.maxLength!==null&&s.data.length>n.maxLength.value&&(p(s,{code:l.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),r.dirty()),s.common.async)return Promise.all([...s.data].map((a,o)=>n.type._parseAsync(new q(s,a,s.path,o)))).then(a=>M.mergeArray(r,a));const i=[...s.data].map((a,o)=>n.type._parseSync(new q(s,a,s.path,o)));return M.mergeArray(r,i)}get element(){return this._def.type}min(e,s){return new z({...this._def,minLength:{value:e,message:_.toString(s)}})}max(e,s){return new z({...this._def,maxLength:{value:e,message:_.toString(s)}})}length(e,s){return new z({...this._def,exactLength:{value:e,message:_.toString(s)}})}nonempty(e){return this.min(1,e)}}z.create=(t,e)=>new z({type:t,minLength:null,maxLength:null,exactLength:null,typeName:b.ZodArray,...v(e)});function pe(t){if(t instanceof C){const e={};for(const s in t.shape){const r=t.shape[s];e[s]=J.create(pe(r))}return new C({...t._def,shape:()=>e})}else return t instanceof z?new z({...t._def,type:pe(t.element)}):t instanceof J?J.create(pe(t.unwrap())):t instanceof re?re.create(pe(t.unwrap())):t instanceof H?H.create(t.items.map(e=>pe(e))):t}class C extends w{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),s=T.objectKeys(e);return this._cached={shape:e,keys:s}}_parse(e){if(this._getType(e)!==m.object){const c=this._getOrReturnCtx(e);return p(c,{code:l.invalid_type,expected:m.object,received:c.parsedType}),y}const{status:r,ctx:n}=this._processInputParams(e),{shape:i,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof X&&this._def.unknownKeys==="strip"))for(const c in n.data)a.includes(c)||o.push(c);const d=[];for(const c of a){const u=i[c],g=n.data[c];d.push({key:{status:"valid",value:c},value:u._parse(new q(n,g,n.path,c)),alwaysSet:c in n.data})}if(this._def.catchall instanceof X){const c=this._def.unknownKeys;if(c==="passthrough")for(const u of o)d.push({key:{status:"valid",value:u},value:{status:"valid",value:n.data[u]}});else if(c==="strict")o.length>0&&(p(n,{code:l.unrecognized_keys,keys:o}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const u of o){const g=n.data[u];d.push({key:{status:"valid",value:u},value:c._parse(new q(n,g,n.path,u)),alwaysSet:u in n.data})}}return n.common.async?Promise.resolve().then(async()=>{const c=[];for(const u of d){const g=await u.key,k=await u.value;c.push({key:g,value:k,alwaysSet:u.alwaysSet})}return c}).then(c=>M.mergeObjectSync(r,c)):M.mergeObjectSync(r,d)}get shape(){return this._def.shape()}strict(e){return _.errToObj,new C({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(s,r)=>{var n,i,a,o;const d=(a=(i=(n=this._def).errorMap)===null||i===void 0?void 0:i.call(n,s,r).message)!==null&&a!==void 0?a:r.defaultError;return s.code==="unrecognized_keys"?{message:(o=_.errToObj(e).message)!==null&&o!==void 0?o:d}:{message:d}}}:{}})}strip(){return new C({...this._def,unknownKeys:"strip"})}passthrough(){return new C({...this._def,unknownKeys:"passthrough"})}extend(e){return new C({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new C({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:b.ZodObject})}setKey(e,s){return this.augment({[e]:s})}catchall(e){return new C({...this._def,catchall:e})}pick(e){const s={};return T.objectKeys(e).forEach(r=>{e[r]&&this.shape[r]&&(s[r]=this.shape[r])}),new C({...this._def,shape:()=>s})}omit(e){const s={};return T.objectKeys(this.shape).forEach(r=>{e[r]||(s[r]=this.shape[r])}),new C({...this._def,shape:()=>s})}deepPartial(){return pe(this)}partial(e){const s={};return T.objectKeys(this.shape).forEach(r=>{const n=this.shape[r];e&&!e[r]?s[r]=n:s[r]=n.optional()}),new C({...this._def,shape:()=>s})}required(e){const s={};return T.objectKeys(this.shape).forEach(r=>{if(e&&!e[r])s[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof J;)i=i._def.innerType;s[r]=i}}),new C({...this._def,shape:()=>s})}keyof(){return Xt(T.objectKeys(this.shape))}}C.create=(t,e)=>new C({shape:()=>t,unknownKeys:"strip",catchall:X.create(),typeName:b.ZodObject,...v(e)});C.strictCreate=(t,e)=>new C({shape:()=>t,unknownKeys:"strict",catchall:X.create(),typeName:b.ZodObject,...v(e)});C.lazycreate=(t,e)=>new C({shape:t,unknownKeys:"strip",catchall:X.create(),typeName:b.ZodObject,...v(e)});class Me extends w{_parse(e){const{ctx:s}=this._processInputParams(e),r=this._def.options;function n(i){for(const o of i)if(o.result.status==="valid")return o.result;for(const o of i)if(o.result.status==="dirty")return s.common.issues.push(...o.ctx.common.issues),o.result;const a=i.map(o=>new B(o.ctx.common.issues));return p(s,{code:l.invalid_union,unionErrors:a}),y}if(s.common.async)return Promise.all(r.map(async i=>{const a={...s,common:{...s.common,issues:[]},parent:null};return{result:await i._parseAsync({data:s.data,path:s.path,parent:a}),ctx:a}})).then(n);{let i;const a=[];for(const d of r){const c={...s,common:{...s.common,issues:[]},parent:null},u=d._parseSync({data:s.data,path:s.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!i&&(i={result:u,ctx:c}),c.common.issues.length&&a.push(c.common.issues)}if(i)return s.common.issues.push(...i.ctx.common.issues),i.result;const o=a.map(d=>new B(d));return p(s,{code:l.invalid_union,unionErrors:o}),y}}get options(){return this._def.options}}Me.create=(t,e)=>new Me({options:t,typeName:b.ZodUnion,...v(e)});const K=t=>t instanceof je?K(t.schema):t instanceof U?K(t.innerType()):t instanceof Be?[t.value]:t instanceof se?t.options:t instanceof De?T.objectValues(t.enum):t instanceof Ze?K(t._def.innerType):t instanceof Ae?[void 0]:t instanceof Oe?[null]:t instanceof J?[void 0,...K(t.unwrap())]:t instanceof re?[null,...K(t.unwrap())]:t instanceof xt||t instanceof $e?K(t.unwrap()):t instanceof Le?K(t._def.innerType):[];class it extends w{_parse(e){const{ctx:s}=this._processInputParams(e);if(s.parsedType!==m.object)return p(s,{code:l.invalid_type,expected:m.object,received:s.parsedType}),y;const r=this.discriminator,n=s.data[r],i=this.optionsMap.get(n);return i?s.common.async?i._parseAsync({data:s.data,path:s.path,parent:s}):i._parseSync({data:s.data,path:s.path,parent:s}):(p(s,{code:l.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),y)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,s,r){const n=new Map;for(const i of s){const a=K(i.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const o of a){if(n.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);n.set(o,i)}}return new it({typeName:b.ZodDiscriminatedUnion,discriminator:e,options:s,optionsMap:n,...v(r)})}}function yt(t,e){const s=G(t),r=G(e);if(t===e)return{valid:!0,data:t};if(s===m.object&&r===m.object){const n=T.objectKeys(e),i=T.objectKeys(t).filter(o=>n.indexOf(o)!==-1),a={...t,...e};for(const o of i){const d=yt(t[o],e[o]);if(!d.valid)return{valid:!1};a[o]=d.data}return{valid:!0,data:a}}else if(s===m.array&&r===m.array){if(t.length!==e.length)return{valid:!1};const n=[];for(let i=0;i<t.length;i++){const a=t[i],o=e[i],d=yt(a,o);if(!d.valid)return{valid:!1};n.push(d.data)}return{valid:!0,data:n}}else return s===m.date&&r===m.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class Ne extends w{_parse(e){const{status:s,ctx:r}=this._processInputParams(e),n=(i,a)=>{if(_t(i)||_t(a))return y;const o=yt(i.value,a.value);return o.valid?((bt(i)||bt(a))&&s.dirty(),{status:s.value,value:o.data}):(p(r,{code:l.invalid_intersection_types}),y)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,a])=>n(i,a)):n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}Ne.create=(t,e,s)=>new Ne({left:t,right:e,typeName:b.ZodIntersection,...v(s)});class H extends w{_parse(e){const{status:s,ctx:r}=this._processInputParams(e);if(r.parsedType!==m.array)return p(r,{code:l.invalid_type,expected:m.array,received:r.parsedType}),y;if(r.data.length<this._def.items.length)return p(r,{code:l.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),y;!this._def.rest&&r.data.length>this._def.items.length&&(p(r,{code:l.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),s.dirty());const i=[...r.data].map((a,o)=>{const d=this._def.items[o]||this._def.rest;return d?d._parse(new q(r,a,r.path,o)):null}).filter(a=>!!a);return r.common.async?Promise.all(i).then(a=>M.mergeArray(s,a)):M.mergeArray(s,i)}get items(){return this._def.items}rest(e){return new H({...this._def,rest:e})}}H.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new H({items:t,typeName:b.ZodTuple,rest:null,...v(e)})};class Pe extends w{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:s,ctx:r}=this._processInputParams(e);if(r.parsedType!==m.object)return p(r,{code:l.invalid_type,expected:m.object,received:r.parsedType}),y;const n=[],i=this._def.keyType,a=this._def.valueType;for(const o in r.data)n.push({key:i._parse(new q(r,o,r.path,o)),value:a._parse(new q(r,r.data[o],r.path,o)),alwaysSet:o in r.data});return r.common.async?M.mergeObjectAsync(s,n):M.mergeObjectSync(s,n)}get element(){return this._def.valueType}static create(e,s,r){return s instanceof w?new Pe({keyType:e,valueType:s,typeName:b.ZodRecord,...v(r)}):new Pe({keyType:L.create(),valueType:e,typeName:b.ZodRecord,...v(s)})}}class st extends w{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:s,ctx:r}=this._processInputParams(e);if(r.parsedType!==m.map)return p(r,{code:l.invalid_type,expected:m.map,received:r.parsedType}),y;const n=this._def.keyType,i=this._def.valueType,a=[...r.data.entries()].map(([o,d],c)=>({key:n._parse(new q(r,o,r.path,[c,"key"])),value:i._parse(new q(r,d,r.path,[c,"value"]))}));if(r.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const d of a){const c=await d.key,u=await d.value;if(c.status==="aborted"||u.status==="aborted")return y;(c.status==="dirty"||u.status==="dirty")&&s.dirty(),o.set(c.value,u.value)}return{status:s.value,value:o}})}else{const o=new Map;for(const d of a){const c=d.key,u=d.value;if(c.status==="aborted"||u.status==="aborted")return y;(c.status==="dirty"||u.status==="dirty")&&s.dirty(),o.set(c.value,u.value)}return{status:s.value,value:o}}}}st.create=(t,e,s)=>new st({valueType:e,keyType:t,typeName:b.ZodMap,...v(s)});class ce extends w{_parse(e){const{status:s,ctx:r}=this._processInputParams(e);if(r.parsedType!==m.set)return p(r,{code:l.invalid_type,expected:m.set,received:r.parsedType}),y;const n=this._def;n.minSize!==null&&r.data.size<n.minSize.value&&(p(r,{code:l.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),s.dirty()),n.maxSize!==null&&r.data.size>n.maxSize.value&&(p(r,{code:l.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),s.dirty());const i=this._def.valueType;function a(d){const c=new Set;for(const u of d){if(u.status==="aborted")return y;u.status==="dirty"&&s.dirty(),c.add(u.value)}return{status:s.value,value:c}}const o=[...r.data.values()].map((d,c)=>i._parse(new q(r,d,r.path,c)));return r.common.async?Promise.all(o).then(d=>a(d)):a(o)}min(e,s){return new ce({...this._def,minSize:{value:e,message:_.toString(s)}})}max(e,s){return new ce({...this._def,maxSize:{value:e,message:_.toString(s)}})}size(e,s){return this.min(e,s).max(e,s)}nonempty(e){return this.min(1,e)}}ce.create=(t,e)=>new ce({valueType:t,minSize:null,maxSize:null,typeName:b.ZodSet,...v(e)});class _e extends w{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:s}=this._processInputParams(e);if(s.parsedType!==m.function)return p(s,{code:l.invalid_type,expected:m.function,received:s.parsedType}),y;function r(o,d){return Xe({data:o,path:s.path,errorMaps:[s.common.contextualErrorMap,s.schemaErrorMap,Ge(),be].filter(c=>!!c),issueData:{code:l.invalid_arguments,argumentsError:d}})}function n(o,d){return Xe({data:o,path:s.path,errorMaps:[s.common.contextualErrorMap,s.schemaErrorMap,Ge(),be].filter(c=>!!c),issueData:{code:l.invalid_return_type,returnTypeError:d}})}const i={errorMap:s.common.contextualErrorMap},a=s.data;if(this._def.returns instanceof ve){const o=this;return N(async function(...d){const c=new B([]),u=await o._def.args.parseAsync(d,i).catch(I=>{throw c.addIssue(r(d,I)),c}),g=await Reflect.apply(a,this,u);return await o._def.returns._def.type.parseAsync(g,i).catch(I=>{throw c.addIssue(n(g,I)),c})})}else{const o=this;return N(function(...d){const c=o._def.args.safeParse(d,i);if(!c.success)throw new B([r(d,c.error)]);const u=Reflect.apply(a,this,c.data),g=o._def.returns.safeParse(u,i);if(!g.success)throw new B([n(u,g.error)]);return g.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new _e({...this._def,args:H.create(e).rest(ie.create())})}returns(e){return new _e({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,s,r){return new _e({args:e||H.create([]).rest(ie.create()),returns:s||ie.create(),typeName:b.ZodFunction,...v(r)})}}class je extends w{get schema(){return this._def.getter()}_parse(e){const{ctx:s}=this._processInputParams(e);return this._def.getter()._parse({data:s.data,path:s.path,parent:s})}}je.create=(t,e)=>new je({getter:t,typeName:b.ZodLazy,...v(e)});class Be extends w{_parse(e){if(e.data!==this._def.value){const s=this._getOrReturnCtx(e);return p(s,{received:s.data,code:l.invalid_literal,expected:this._def.value}),y}return{status:"valid",value:e.data}}get value(){return this._def.value}}Be.create=(t,e)=>new Be({value:t,typeName:b.ZodLiteral,...v(e)});function Xt(t,e){return new se({values:t,typeName:b.ZodEnum,...v(e)})}class se extends w{constructor(){super(...arguments),Ee.set(this,void 0)}_parse(e){if(typeof e.data!="string"){const s=this._getOrReturnCtx(e),r=this._def.values;return p(s,{expected:T.joinValues(r),received:s.parsedType,code:l.invalid_type}),y}if(Qe(this,Ee)||qt(this,Ee,new Set(this._def.values)),!Qe(this,Ee).has(e.data)){const s=this._getOrReturnCtx(e),r=this._def.values;return p(s,{received:s.data,code:l.invalid_enum_value,options:r}),y}return N(e.data)}get options(){return this._def.values}get enum(){const e={};for(const s of this._def.values)e[s]=s;return e}get Values(){const e={};for(const s of this._def.values)e[s]=s;return e}get Enum(){const e={};for(const s of this._def.values)e[s]=s;return e}extract(e,s=this._def){return se.create(e,{...this._def,...s})}exclude(e,s=this._def){return se.create(this.options.filter(r=>!e.includes(r)),{...this._def,...s})}}Ee=new WeakMap;se.create=Xt;class De extends w{constructor(){super(...arguments),Ce.set(this,void 0)}_parse(e){const s=T.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==m.string&&r.parsedType!==m.number){const n=T.objectValues(s);return p(r,{expected:T.joinValues(n),received:r.parsedType,code:l.invalid_type}),y}if(Qe(this,Ce)||qt(this,Ce,new Set(T.getValidEnumValues(this._def.values))),!Qe(this,Ce).has(e.data)){const n=T.objectValues(s);return p(r,{received:r.data,code:l.invalid_enum_value,options:n}),y}return N(e.data)}get enum(){return this._def.values}}Ce=new WeakMap;De.create=(t,e)=>new De({values:t,typeName:b.ZodNativeEnum,...v(e)});class ve extends w{unwrap(){return this._def.type}_parse(e){const{ctx:s}=this._processInputParams(e);if(s.parsedType!==m.promise&&s.common.async===!1)return p(s,{code:l.invalid_type,expected:m.promise,received:s.parsedType}),y;const r=s.parsedType===m.promise?s.data:Promise.resolve(s.data);return N(r.then(n=>this._def.type.parseAsync(n,{path:s.path,errorMap:s.common.contextualErrorMap})))}}ve.create=(t,e)=>new ve({type:t,typeName:b.ZodPromise,...v(e)});class U extends w{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===b.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:s,ctx:r}=this._processInputParams(e),n=this._def.effect||null,i={addIssue:a=>{p(r,a),a.fatal?s.abort():s.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),n.type==="preprocess"){const a=n.transform(r.data,i);if(r.common.async)return Promise.resolve(a).then(async o=>{if(s.value==="aborted")return y;const d=await this._def.schema._parseAsync({data:o,path:r.path,parent:r});return d.status==="aborted"?y:d.status==="dirty"||s.value==="dirty"?ge(d.value):d});{if(s.value==="aborted")return y;const o=this._def.schema._parseSync({data:a,path:r.path,parent:r});return o.status==="aborted"?y:o.status==="dirty"||s.value==="dirty"?ge(o.value):o}}if(n.type==="refinement"){const a=o=>{const d=n.refinement(o,i);if(r.common.async)return Promise.resolve(d);if(d instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(r.common.async===!1){const o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?y:(o.status==="dirty"&&s.dirty(),a(o.value),{status:s.value,value:o.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>o.status==="aborted"?y:(o.status==="dirty"&&s.dirty(),a(o.value).then(()=>({status:s.value,value:o.value}))))}if(n.type==="transform")if(r.common.async===!1){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!ae(a))return a;const o=n.transform(a.value,i);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:s.value,value:o}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>ae(a)?Promise.resolve(n.transform(a.value,i)).then(o=>({status:s.value,value:o})):a);T.assertNever(n)}}U.create=(t,e,s)=>new U({schema:t,typeName:b.ZodEffects,effect:e,...v(s)});U.createWithPreprocess=(t,e,s)=>new U({schema:e,effect:{type:"preprocess",transform:t},typeName:b.ZodEffects,...v(s)});class J extends w{_parse(e){return this._getType(e)===m.undefined?N(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}J.create=(t,e)=>new J({innerType:t,typeName:b.ZodOptional,...v(e)});class re extends w{_parse(e){return this._getType(e)===m.null?N(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}re.create=(t,e)=>new re({innerType:t,typeName:b.ZodNullable,...v(e)});class Ze extends w{_parse(e){const{ctx:s}=this._processInputParams(e);let r=s.data;return s.parsedType===m.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:s.path,parent:s})}removeDefault(){return this._def.innerType}}Ze.create=(t,e)=>new Ze({innerType:t,typeName:b.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...v(e)});class Le extends w{_parse(e){const{ctx:s}=this._processInputParams(e),r={...s,common:{...s.common,issues:[]}},n=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Ie(n)?n.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new B(r.common.issues)},input:r.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new B(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Le.create=(t,e)=>new Le({innerType:t,typeName:b.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...v(e)});class rt extends w{_parse(e){if(this._getType(e)!==m.nan){const r=this._getOrReturnCtx(e);return p(r,{code:l.invalid_type,expected:m.nan,received:r.parsedType}),y}return{status:"valid",value:e.data}}}rt.create=t=>new rt({typeName:b.ZodNaN,...v(t)});const Gs=Symbol("zod_brand");class xt extends w{_parse(e){const{ctx:s}=this._processInputParams(e),r=s.data;return this._def.type._parse({data:r,path:s.path,parent:s})}unwrap(){return this._def.type}}class Ve extends w{_parse(e){const{status:s,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?y:i.status==="dirty"?(s.dirty(),ge(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const n=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return n.status==="aborted"?y:n.status==="dirty"?(s.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:r.path,parent:r})}}static create(e,s){return new Ve({in:e,out:s,typeName:b.ZodPipeline})}}class $e extends w{_parse(e){const s=this._def.innerType._parse(e),r=n=>(ae(n)&&(n.value=Object.freeze(n.value)),n);return Ie(s)?s.then(n=>r(n)):r(s)}unwrap(){return this._def.innerType}}$e.create=(t,e)=>new $e({innerType:t,typeName:b.ZodReadonly,...v(e)});function jt(t,e){const s=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof s=="string"?{message:s}:s}function Qt(t,e={},s){return t?ye.create().superRefine((r,n)=>{var i,a;const o=t(r);if(o instanceof Promise)return o.then(d=>{var c,u;if(!d){const g=jt(e,r),k=(u=(c=g.fatal)!==null&&c!==void 0?c:s)!==null&&u!==void 0?u:!0;n.addIssue({code:"custom",...g,fatal:k})}});if(!o){const d=jt(e,r),c=(a=(i=d.fatal)!==null&&i!==void 0?i:s)!==null&&a!==void 0?a:!0;n.addIssue({code:"custom",...d,fatal:c})}}):ye.create()}const Xs={object:C.lazycreate};var b;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(b||(b={}));const Qs=(t,e={message:`Input not instance of ${t.name}`})=>Qt(s=>s instanceof t,e),es=L.create,ts=ee.create,er=rt.create,tr=te.create,ss=Re.create,sr=oe.create,rr=et.create,nr=Ae.create,ir=Oe.create,ar=ye.create,or=ie.create,cr=X.create,dr=tt.create,ur=z.create,hr=C.create,lr=C.strictCreate,fr=Me.create,pr=it.create,gr=Ne.create,mr=H.create,_r=Pe.create,br=st.create,yr=ce.create,vr=_e.create,Sr=je.create,wr=Be.create,xr=se.create,Tr=De.create,kr=ve.create,Bt=U.create,Er=J.create,Cr=re.create,Ir=U.createWithPreprocess,Rr=Ve.create,Ar=()=>es().optional(),Or=()=>ts().optional(),Mr=()=>ss().optional(),Nr={string:t=>L.create({...t,coerce:!0}),number:t=>ee.create({...t,coerce:!0}),boolean:t=>Re.create({...t,coerce:!0}),bigint:t=>te.create({...t,coerce:!0}),date:t=>oe.create({...t,coerce:!0})},Pr=y;var j=Object.freeze({__proto__:null,defaultErrorMap:be,setErrorMap:Is,getErrorMap:Ge,makeIssue:Xe,EMPTY_PATH:Rs,addIssueToContext:p,ParseStatus:M,INVALID:y,DIRTY:ge,OK:N,isAborted:_t,isDirty:bt,isValid:ae,isAsync:Ie,get util(){return T},get objectUtil(){return mt},ZodParsedType:m,getParsedType:G,ZodType:w,datetimeRegex:Gt,ZodString:L,ZodNumber:ee,ZodBigInt:te,ZodBoolean:Re,ZodDate:oe,ZodSymbol:et,ZodUndefined:Ae,ZodNull:Oe,ZodAny:ye,ZodUnknown:ie,ZodNever:X,ZodVoid:tt,ZodArray:z,ZodObject:C,ZodUnion:Me,ZodDiscriminatedUnion:it,ZodIntersection:Ne,ZodTuple:H,ZodRecord:Pe,ZodMap:st,ZodSet:ce,ZodFunction:_e,ZodLazy:je,ZodLiteral:Be,ZodEnum:se,ZodNativeEnum:De,ZodPromise:ve,ZodEffects:U,ZodTransformer:U,ZodOptional:J,ZodNullable:re,ZodDefault:Ze,ZodCatch:Le,ZodNaN:rt,BRAND:Gs,ZodBranded:xt,ZodPipeline:Ve,ZodReadonly:$e,custom:Qt,Schema:w,ZodSchema:w,late:Xs,get ZodFirstPartyTypeKind(){return b},coerce:Nr,any:ar,array:ur,bigint:tr,boolean:ss,date:sr,discriminatedUnion:pr,effect:Bt,enum:xr,function:vr,instanceof:Qs,intersection:gr,lazy:Sr,literal:wr,map:br,nan:er,nativeEnum:Tr,never:cr,null:ir,nullable:Cr,number:ts,object:hr,oboolean:Mr,onumber:Or,optional:Er,ostring:Ar,pipeline:Rr,preprocess:Ir,promise:kr,record:_r,set:yr,strictObject:lr,string:es,symbol:rr,transformer:Bt,tuple:mr,undefined:nr,union:fr,unknown:or,void:dr,NEVER:Pr,ZodIssueCode:l,quotelessJson:Cs,ZodError:B});j.object({maxTokens:j.number().int().positive().optional(),temperature:j.number().optional(),topP:j.number().optional(),presencePenalty:j.number().optional(),frequencyPenalty:j.number().optional(),seed:j.number().int().optional(),headers:j.record(j.string().optional()).optional()});j.object({apiKey:j.string().optional(),baseUrl:j.string().optional(),modelName:j.string().optional()});var jr=t=>Array.from(t).map(s=>s.getModelContext()).sort((s,r)=>(r.priority??0)-(s.priority??0)).reduce((s,r)=>{var n;if(r.system&&(s.system?s.system+=`
23
15
 
24
- ${r.system}`:s.system=r.system),r.tools)for(const[i,o]of Object.entries(r.tools)){const c=(n=s.tools)==null?void 0:n[i];if(c&&c!==o)throw new Error(`You tried to define a tool with the name ${i}, but it already exists.`);s.tools||(s.tools={}),s.tools[i]=o}return r.config&&(s.config={...s.config,...r.config}),r.callSettings&&(s.callSettings={...s.callSettings,...r.callSettings}),s},{}),Yn=class{constructor(){h(this,"_providers",new Set);h(this,"_subscribers",new Set)}getModelContext(){return Wn(this._providers)}registerModelContextProvider(t){var s;this._providers.add(t);const e=(s=t.subscribe)==null?void 0:s.call(t,()=>{this.notifySubscribers()});return this.notifySubscribers(),()=>{this._providers.delete(t),e==null||e(),this.notifySubscribers()}}notifySubscribers(){for(const t of this._subscribers)t()}subscribe(t){return this._subscribers.add(t),()=>this._subscribers.delete(t)}},Jn=class{constructor(){h(this,"_contextProvider",new Yn)}registerModelContextProvider(t){return this._contextProvider.registerModelContextProvider(t)}},qn=class{constructor(){h(this,"_subscribers",new Set)}subscribe(t){return this._subscribers.add(t),()=>this._subscribers.delete(t)}waitForUpdate(){return new Promise(t=>{const e=this.subscribe(()=>{e(),t()})})}_notifySubscribers(){const t=[];for(const e of this._subscribers)try{e()}catch(s){t.push(s)}if(t.length>0)throw t.length===1?t[0]:new AggregateError(t)}},Kn=t=>t.status.type==="complete",Fs=class extends qn{constructor(){super(...arguments);h(this,"isEditing",!0);h(this,"_attachments",[]);h(this,"_text","");h(this,"_role","user");h(this,"_runConfig",{});h(this,"_eventSubscribers",new Map)}getAttachmentAccept(){var e;return((e=this.getAttachmentAdapter())==null?void 0:e.accept)??"*"}get attachments(){return this._attachments}setAttachments(e){this._attachments=e,this._notifySubscribers()}get isEmpty(){return!this.text.trim()&&!this.attachments.length}get text(){return this._text}get role(){return this._role}get runConfig(){return this._runConfig}setText(e){this._text!==e&&(this._text=e,this._notifySubscribers())}setRole(e){this._role!==e&&(this._role=e,this._notifySubscribers())}setRunConfig(e){this._runConfig!==e&&(this._runConfig=e,this._notifySubscribers())}_emptyTextAndAttachments(){this._attachments=[],this._text="",this._notifySubscribers()}async _onClearAttachments(){const e=this.getAttachmentAdapter();e&&await Promise.all(this._attachments.map(s=>e.remove(s)))}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 e=this._onClearAttachments();this._emptyTextAndAttachments(),await e}async clearAttachments(){const e=this._onClearAttachments();this.setAttachments([]),await e}async send(){const e=this.getAttachmentAdapter(),s=e&&this.attachments.length>0?await Promise.all(this.attachments.map(async n=>Kn(n)?n:await e.send(n))):[],r={role:this.role,content:this.text?[{type:"text",text:this.text}]:[],attachments:s,runConfig:this.runConfig};this._emptyTextAndAttachments(),this.handleSend(r),this._notifyEventSubscribers("send")}cancel(){this.handleCancel()}async addAttachment(e){const s=this.getAttachmentAdapter();if(!s)throw new Error("Attachments are not supported");const r=i=>{const o=this._attachments.findIndex(c=>c.id===i.id);o!==-1?this._attachments=[...this._attachments.slice(0,o),i,...this._attachments.slice(o+1)]:(this._attachments=[...this._attachments,i],this._notifyEventSubscribers("attachment_add")),this._notifySubscribers()},n=s.add({file:e});if(Symbol.asyncIterator in n)for await(const i of n)r(i);else r(await n);this._notifyEventSubscribers("attachment_add"),this._notifySubscribers()}async removeAttachment(e){const s=this.getAttachmentAdapter();if(!s)throw new Error("Attachments are not supported");const r=this._attachments.findIndex(i=>i.id===e);if(r===-1)throw new Error("Attachment not found");const n=this._attachments[r];await s.remove(n),this._attachments=[...this._attachments.slice(0,r),...this._attachments.slice(r+1)],this._notifySubscribers()}_notifyEventSubscribers(e){const s=this._eventSubscribers.get(e);if(s)for(const r of s)r()}unstable_on(e,s){const r=this._eventSubscribers.get(e);return r?r.add(s):this._eventSubscribers.set(e,new Set([s])),()=>{const n=this._eventSubscribers.get(e);n&&n.delete(s)}}},Hn=class extends Fs{constructor(e){super();h(this,"_canCancel",!1);this.runtime=e,this.connect()}get canCancel(){return this._canCancel}get attachments(){return super.attachments}getAttachmentAdapter(){var e;return(e=this.runtime.adapters)==null?void 0:e.attachments}connect(){return this.runtime.subscribe(()=>{this.canCancel!==this.runtime.capabilities.cancel&&(this._canCancel=this.runtime.capabilities.cancel,this._notifySubscribers())})}async handleSend(e){var s;this.runtime.append({...e,parentId:((s=this.runtime.messages.at(-1))==null?void 0:s.id)??null,sourceId:null})}async handleCancel(){this.runtime.cancelRun()}};let Gn=(t,e=21)=>(s=e)=>{let r="",n=s|0;for(;n--;)r+=t[Math.random()*t.length|0];return r};var Qe=Gn("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7),Xn="__optimistic__",Qn=()=>`${Xn}${Qe()}`,ei=(t,{id:e=Qe(),status:s={type:"complete",reason:"unknown"},attachments:r=[]}={})=>{const n={id:e,createdAt:new Date},i=t.role;switch(i){case"assistant":return{...n,role:i,content:t.content.map(o=>o.type==="tool-call"?{...o,argsText:JSON.stringify(o.args)}:o),status:s,metadata:{unstable_annotations:[],unstable_data:[],steps:[],custom:{}}};case"user":return{...n,role:i,content:t.content,attachments:r,metadata:{custom:{}}};case"system":return{...n,role:i,content:t.content,metadata:{custom:{}}};default:{const o=i;throw new Error(`Unknown message role: ${o}`)}}},Vs=Object.freeze({type:"running"}),Us=Object.freeze({type:"complete",reason:"unknown"}),ti=t=>t===Vs||t===Us,zs=(t,e)=>t&&e?Vs:Us,Me={exports:{}};const si=typeof Buffer<"u",Ss=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,ws=/"(?: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 Ws(t,e,s){s==null&&e!==null&&typeof e=="object"&&(s=e,e=void 0),si&&Buffer.isBuffer(t)&&(t=t.toString()),t&&t.charCodeAt(0)===65279&&(t=t.slice(1));const r=JSON.parse(t,e);if(r===null||typeof r!="object")return r;const n=s&&s.protoAction||"error",i=s&&s.constructorAction||"error";if(n==="ignore"&&i==="ignore")return r;if(n!=="ignore"&&i!=="ignore"){if(Ss.test(t)===!1&&ws.test(t)===!1)return r}else if(n!=="ignore"&&i==="ignore"){if(Ss.test(t)===!1)return r}else if(ws.test(t)===!1)return r;return Ys(r,{protoAction:n,constructorAction:i,safe:s&&s.safe})}function Ys(t,{protoAction:e="error",constructorAction:s="error",safe:r}={}){let n=[t];for(;n.length;){const i=n;n=[];for(const o of i){if(e!=="ignore"&&Object.prototype.hasOwnProperty.call(o,"__proto__")){if(r===!0)return null;if(e==="error")throw new SyntaxError("Object contains forbidden prototype property");delete o.__proto__}if(s!=="ignore"&&Object.prototype.hasOwnProperty.call(o,"constructor")&&Object.prototype.hasOwnProperty.call(o.constructor,"prototype")){if(r===!0)return null;if(s==="error")throw new SyntaxError("Object contains forbidden prototype property");delete o.constructor}for(const c in o){const d=o[c];d&&typeof d=="object"&&n.push(d)}}}return t}function zt(t,e,s){const{stackTraceLimit:r}=Error;Error.stackTraceLimit=0;try{return Ws(t,e,s)}finally{Error.stackTraceLimit=r}}function ri(t,e){const{stackTraceLimit:s}=Error;Error.stackTraceLimit=0;try{return Ws(t,e,{safe:!0})}catch{return null}finally{Error.stackTraceLimit=s}}Me.exports=zt;Me.exports.default=zt;Me.exports.parse=zt;Me.exports.safeParse=ri;Me.exports.scan=Ys;var ni=Me.exports;const xs=Nr(ni);function ii(t){const e=["ROOT"];let s=-1,r=null;function n(u,l,g){switch(u){case'"':{s=l,e.pop(),e.push(g),e.push("INSIDE_STRING");break}case"f":case"t":case"n":{s=l,r=l,e.pop(),e.push(g),e.push("INSIDE_LITERAL");break}case"-":{e.pop(),e.push(g),e.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{s=l,e.pop(),e.push(g),e.push("INSIDE_NUMBER");break}case"{":{s=l,e.pop(),e.push(g),e.push("INSIDE_OBJECT_START");break}case"[":{s=l,e.pop(),e.push(g),e.push("INSIDE_ARRAY_START");break}}}function i(u,l){switch(u){case",":{e.pop(),e.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{s=l,e.pop();break}}}function o(u,l){switch(u){case",":{e.pop(),e.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{s=l,e.pop();break}}}for(let u=0;u<t.length;u++){const l=t[u];switch(e[e.length-1]){case"ROOT":n(l,u,"FINISH");break;case"INSIDE_OBJECT_START":{switch(l){case'"':{e.pop(),e.push("INSIDE_OBJECT_KEY");break}case"}":{s=u,e.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(l){case'"':{e.pop(),e.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(l){case'"':{e.pop(),e.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(l){case":":{e.pop(),e.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{n(l,u,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{i(l,u);break}case"INSIDE_STRING":{switch(l){case'"':{e.pop(),s=u;break}case"\\":{e.push("INSIDE_STRING_ESCAPE");break}default:s=u}break}case"INSIDE_ARRAY_START":{switch(l){case"]":{s=u,e.pop();break}default:{s=u,n(l,u,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(l){case",":{e.pop(),e.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{s=u,e.pop();break}default:{s=u;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{n(l,u,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{e.pop(),s=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":{s=u;break}case"e":case"E":case"-":case".":break;case",":{e.pop(),e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&o(l,u),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&i(l,u);break}case"}":{e.pop(),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&i(l,u);break}case"]":{e.pop(),e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&o(l,u);break}default:{e.pop();break}}break}case"INSIDE_LITERAL":{const I=t.substring(r,u+1);!"false".startsWith(I)&&!"true".startsWith(I)&&!"null".startsWith(I)?(e.pop(),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?i(l,u):e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&o(l,u)):s=u;break}}}let c=t.slice(0,s+1),d=0;for(let u=e.length-1;u>=0;u--)switch(e[u]){case"INSIDE_STRING":{c+='"',d++;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+="}",d++;break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{c+="]",d++;break}case"INSIDE_LITERAL":{const g=t.substring(r,t.length);"true".startsWith(g)?c+="true".slice(g.length):"false".startsWith(g)?c+="false".slice(g.length):"null".startsWith(g)&&(c+="null".slice(g.length))}}return[c,d]}function Js(t,e){function s(r){const n=T.useContext(t);if(!(r!=null&&r.optional)&&!n)throw new Error(`This component must be used within ${e}.`);return n}return s}function qs(t,e){function s(n){const i=t(n);return i?i[e]:null}function r(n){let i=!1,o;typeof n=="function"?o=n:n&&typeof n=="object"&&(i=!!n.optional,o=n.selector);const c=s({optional:i});return c?o?c(o):c():null}return{[e]:r,[`${e}Store`]:s}}var et=t=>{var s;const e=t;e.__isBound||((s=e.__internal_bindMethods)==null||s.call(e),e.__isBound=!0)},Ks=T.createContext(null),ai=Js(Ks,"AssistantRuntimeProvider"),{useToolUIs:ya,useToolUIsStore:Sa}=qs(ai,"useToolUIs");const Ts=t=>{let e;const s=new Set,r=(u,l)=>{const g=typeof u=="function"?u(e):u;if(!Object.is(g,e)){const I=e;e=l??(typeof g!="object"||g===null)?g:Object.assign({},e,g),s.forEach(N=>N(e,I))}},n=()=>e,c={setState:r,getState:n,getInitialState:()=>d,subscribe:u=>(s.add(u),()=>s.delete(u))},d=e=t(r,n,c);return c},oi=t=>t?Ts(t):Ts,ci=t=>t;function ui(t,e=ci){const s=T.useSyncExternalStore(t.subscribe,()=>e(t.getState()),()=>e(t.getInitialState()));return T.useDebugValue(s),s}const Es=t=>{const e=oi(t),s=r=>ui(e,r);return Object.assign(s,e),s},rt=t=>t?Es(t):Es;var di=()=>rt(t=>{const e=new Map;return Object.freeze({getToolUI:s=>{const r=e.get(s),n=r==null?void 0:r.at(-1);return n||null},setToolUI:(s,r)=>{let n=e.get(s);return n||(n=[],e.set(s,n)),n.push(r),t({}),()=>{const i=n.indexOf(r);i!==-1&&n.splice(i,1),i===n.length&&t({})}}})}),li=T.createContext(null),xt=t=>t,hi=T.createContext(null),fi=t=>{const[e]=T.useState(()=>rt(()=>t));return T.useEffect(()=>{et(t),xt(e).setState(t,!0)},[t,e]),e},pi=({runtime:t,children:e})=>{const s=fi(t),[r]=T.useState(()=>({useThreadListItemRuntime:s}));return H.jsx(hi.Provider,{value:r,children:e})},gi=()=>{const t=new Set;return rt(()=>({isAtBottom:!0,scrollToBottom:()=>{for(const e of t)e()},onScrollToBottom:e=>(t.add(e),()=>{t.delete(e)})}))},Hs=T.createContext(null),mi=Js(Hs,"ThreadPrimitive.Viewport"),{useThreadViewport:wa,useThreadViewportStore:_i}=qs(mi,"useThreadViewport"),bi=()=>{const t=_i({optional:!0}),[e]=T.useState(()=>gi());return T.useEffect(()=>t==null?void 0:t.getState().onScrollToBottom(()=>{e.getState().scrollToBottom()}),[t,e]),T.useEffect(()=>{if(t)return e.subscribe(s=>{t.getState().isAtBottom!==s.isAtBottom&&xt(t).setState({isAtBottom:s.isAtBottom})})},[e,t]),e},vi=({children:t})=>{const e=bi(),[s]=T.useState(()=>({useThreadViewport:e}));return H.jsx(Hs.Provider,{value:s,children:t})},yi=t=>{const[e]=T.useState(()=>rt(()=>t));return T.useEffect(()=>{et(t),et(t.composer),xt(e).setState(t,!0)},[t,e]),e},Si=({children:t,listItemRuntime:e,runtime:s})=>{const r=yi(s),[n]=T.useState(()=>({useThreadRuntime:r}));return H.jsx(pi,{runtime:e,children:H.jsx(li.Provider,{value:n,children:H.jsx(vi,{children:t})})})},wi=t=>{const[e]=T.useState(()=>rt(()=>t));return T.useEffect(()=>{et(t),et(t.threads),xt(e).setState(t,!0)},[t,e]),e},xi=()=>T.useMemo(()=>di(),[]),Ti=t=>{var e;return(e=t._core)==null?void 0:e.RenderComponent},Ei=({children:t,runtime:e})=>{const s=wi(e),r=xi(),[n]=T.useState(()=>({useToolUIs:r,useAssistantRuntime:s})),i=Ti(e);return H.jsxs(Ks.Provider,{value:n,children:[i&&H.jsx(i,{}),H.jsx(Si,{runtime:e.thread,listItemRuntime:e.threads.mainItem,children:t})]})},ki=T.memo(Ei),ks=class{constructor(t,e,s){this.contentBinding=t,this.messageApi=e,this.threadApi=s}get path(){return this.contentBinding.path}__internal_bindMethods(){this.addToolResult=this.addToolResult.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this)}getState(){return this.contentBinding.getState()}addToolResult(t){const e=this.contentBinding.getState();if(!e)throw new Error("Content part is not available");if(e.type!=="tool-call")throw new Error("Tried to add tool result to non-tool content 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 s=this.messageApi.getState();if(!s)throw new Error("Message is not available");const r=e.toolName,n=e.toolCallId;this.threadApi.getState().addToolResult({messageId:s.id,toolName:r,toolCallId:n,result:t})}subscribe(t){return this.contentBinding.subscribe(t)}},Ci=Symbol("partial-json-count"),Ri=t=>{try{return xs.parse(t)}catch{try{const[e,s]=ii(t),r=xs.parse(e);return r[Ci]=s,r}catch{return}}},Gs=(t,e,s)=>{const{role:r,id:n,createdAt:i,attachments:o,status:c,metadata:d}=t,u={id:n??e,createdAt:i??new Date},l=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;if(r!=="user"&&o)throw new Error("attachments are only supported for user messages");if(r!=="assistant"&&c)throw new Error("status is only supported for assistant messages");if(r!=="assistant"&&(d!=null&&d.steps))throw new Error("metadata.steps is only supported for assistant messages");switch(r){case"assistant":return{...u,role:r,content:l.map(g=>{const I=g.type;switch(I){case"text":case"reasoning":return g.text.trim().length===0?null:g;case"file":case"source":return g;case"tool-call":return g.args?{...g,toolCallId:g.toolCallId??"tool-"+Qe(),args:g.args,argsText:JSON.stringify(g.args)}:{...g,toolCallId:g.toolCallId??"tool-"+Qe(),args:g.args??Ri(g.argsText??"{}"),argsText:g.argsText??""};default:{const N=I;throw new Error(`Unsupported assistant content part type: ${N}`)}}}).filter(g=>!!g),status:c??s,metadata:{unstable_annotations:(d==null?void 0:d.unstable_annotations)??[],unstable_data:(d==null?void 0:d.unstable_data)??[],custom:(d==null?void 0:d.custom)??{},steps:(d==null?void 0:d.steps)??[]}};case"user":return{...u,role:r,content:l.map(g=>{const I=g.type;switch(I){case"text":case"image":case"audio":case"file":return g;default:{const N=I;throw new Error(`Unsupported user content part type: ${N}`)}}}),attachments:o??[],metadata:{custom:(d==null?void 0:d.custom)??{}}};case"system":if(l.length!==1||l[0].type!=="text")throw new Error("System messages must have exactly one text content part.");return{...u,role:r,content:l,metadata:{custom:(d==null?void 0:d.custom)??{}}};default:{const g=r;throw new Error(`Unknown message role: ${g}`)}}},Ii={fromArray:t=>{const e=t.map(s=>Gs(s,Qe(),zs(!1,!1)));return{messages:e.map((s,r)=>({parentId:r>0?e[r-1].id:null,message:s}))}}},ft=t=>t.next?ft(t.next):"current"in t?t:null,Ai=class{constructor(t){h(this,"_value",null);this.func=t}get value(){return this._value===null&&(this._value=this.func()),this._value}dirty(){this._value=null}},Oi=class{constructor(){h(this,"messages",new Map);h(this,"head",null);h(this,"root",{children:[],next:null});h(this,"_messages",new Ai(()=>{var e;const t=new Array(((e=this.head)==null?void 0:e.level)??0);for(let s=this.head;s;s=s.prev)t[s.level]=s.current;return t}))}performOp(t,e,s){const r=e.prev??this.root,n=t??this.root;if(!(s==="relink"&&r===n)){if(s!=="link"&&(r.children=r.children.filter(i=>i!==e.current.id),r.next===e)){const i=r.children.at(-1),o=i?this.messages.get(i):null;if(o===void 0)throw new Error("MessageRepository(performOp/cut): Fallback sibling message not found. This is likely an internal bug in assistant-ui.");r.next=o}if(s!=="cut"){for(let i=t;i;i=i.prev)if(i.current.id===e.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.");n.children=[...n.children,e.current.id],(ft(e)===this.head||n.next===null)&&(n.next=e),e.prev=t}}}get headId(){var t;return((t=this.head)==null?void 0:t.current.id)??null}getMessages(){return this._messages.value}addOrUpdateMessage(t,e){const s=this.messages.get(e.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(s){s.current=e,this.performOp(r,s,"relink"),this._messages.dirty();return}const n={prev:r,current:e,next:null,children:[],level:r?r.level+1:0};this.messages.set(e.id,n),this.performOp(r,n,"link"),this.head===r&&(this.head=n),this._messages.dirty()}getMessage(t){var s;const e=this.messages.get(t);if(!e)throw new Error("MessageRepository(updateMessage): Message not found. This is likely an internal bug in assistant-ui.");return{parentId:((s=e.prev)==null?void 0:s.current.id)??null,message:e.current}}appendOptimisticMessage(t,e){let s;do s=Qn();while(this.messages.has(s));return this.addOrUpdateMessage(t,ei(e,{id:s,status:{type:"running"}})),s}deleteMessage(t,e){const s=this.messages.get(t);if(!s)throw new Error("MessageRepository(deleteMessage): Optimistic message not found. This is likely an internal bug in assistant-ui.");const r=e===void 0?s.prev:e===null?null:this.messages.get(e);if(r===void 0)throw new Error("MessageRepository(deleteMessage): Replacement not found. This is likely an internal bug in assistant-ui.");for(const n of s.children){const i=this.messages.get(n);if(!i)throw new Error("MessageRepository(deleteMessage): Child message not found. This is likely an internal bug in assistant-ui.");this.performOp(r,i,"relink")}this.performOp(null,s,"cut"),this.messages.delete(t),this.head===s&&(this.head=ft(r??this.root)),this._messages.dirty()}getBranches(t){const e=this.messages.get(t);if(!e)throw new Error("MessageRepository(getBranches): Message not found. This is likely an internal bug in assistant-ui.");const{children:s}=e.prev??this.root;return s}switchToBranch(t){const e=this.messages.get(t);if(!e)throw new Error("MessageRepository(switchToBranch): Branch not found. This is likely an internal bug in assistant-ui.");const s=e.prev??this.root;s.next=e,this.head=ft(e),this._messages.dirty()}resetHead(t){if(t===null){this.head=null,this._messages.dirty();return}const e=this.messages.get(t);if(!e)throw new Error("MessageRepository(resetHead): Branch not found. This is likely an internal bug in assistant-ui.");this.head=e;for(let s=e;s;s=s.prev)s.prev&&(s.prev.next=s);this._messages.dirty()}clear(){this.messages.clear(),this.head=null,this.root={children:[],next:null},this._messages.dirty()}export(){var e,s;const t=[];for(const[,r]of this.messages)t.push({message:r.current,parentId:((e=r.prev)==null?void 0:e.current.id)??null});return{headId:((s=this.head)==null?void 0:s.current.id)??null,messages:t}}import({headId:t,messages:e}){var s;for(const{message:r,parentId:n}of e)this.addOrUpdateMessage(n,r);this.resetHead(t??((s=e.at(-1))==null?void 0:s.message.id)??null)}},Tt=class{constructor(){h(this,"_subscriptions",new Set);h(this,"_connection")}get isConnected(){return!!this._connection}notifySubscribers(){for(const t of this._subscriptions)t()}_updateConnection(){var t;if(this._subscriptions.size>0){if(this._connection)return;this._connection=this._connect()}else(t=this._connection)==null||t.call(this),this._connection=void 0}subscribe(t){return this._subscriptions.add(t),this._updateConnection(),()=>{this._subscriptions.delete(t),this._updateConnection()}}},Q=Symbol("skip-update"),Wt=class extends Tt{constructor(e){super();h(this,"_previousStateDirty",!0);h(this,"_previousState");h(this,"getState",()=>{if(!this.isConnected||this._previousStateDirty){const e=this.binding.getState();e!==Q&&(this._previousState=e),this._previousStateDirty=!1}if(this._previousState===void 0)throw new Error("Entry not available in the store");return this._previousState});this.binding=e}get path(){return this.binding.path}_connect(){const e=()=>{this._previousStateDirty=!0,this.notifySubscribers()};return this.binding.subscribe(e)}},dt=class{constructor(t,e){this._core=t,this._threadListBinding=e}get path(){return this._core.path}__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)}getState(){return this._core.getState()}switchTo(){const t=this._core.getState();return this._threadListBinding.switchToThread(t.id)}rename(t){const e=this._core.getState();return this._threadListBinding.rename(e.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,e){let s=this._core.getState().isMain;return this.subscribe(()=>{const r=this._core.getState().isMain;s!==r&&(s=r,!(t==="switched-to"&&!r)&&(t==="switched-away"&&r||e()))})}subscribe(t){return this._core.subscribe(t)}};function Mi(t,e){if(t===void 0&&e===void 0)return!0;if(t===void 0||e===void 0)return!1;for(const s of Object.keys(t)){const r=t[s],n=e[s];if(!Object.is(r,n))return!1}return!0}var K=class extends Tt{constructor(e){super();h(this,"_previousState");h(this,"getState",()=>(this.isConnected||this._syncState(),this._previousState));this.binding=e;const s=e.getState();if(s===Q)throw new Error("Entry not available in the store");this._previousState=s}get path(){return this.binding.path}_syncState(){const e=this.binding.getState();return e===Q||Mi(e,this._previousState)?!1:(this._previousState=e,!0)}_connect(){const e=()=>{this._syncState()&&this.notifySubscribers()};return this.binding.subscribe(e)}},Oe=Symbol("innerMessage"),Pi=t=>t[Oe],tt=t=>t.content.filter(s=>s.type==="text").map(s=>s.text).join(`
16
+ ${r.system}`:s.system=r.system),r.tools)for(const[i,a]of Object.entries(r.tools)){const o=(n=s.tools)==null?void 0:n[i];if(o&&o!==a)throw new Error(`You tried to define a tool with the name ${i}, but it already exists.`);s.tools||(s.tools={}),s.tools[i]=a}return r.config&&(s.config={...s.config,...r.config}),r.callSettings&&(s.callSettings={...s.callSettings,...r.callSettings}),s},{}),Br=class{constructor(){h(this,"_providers",new Set);h(this,"_subscribers",new Set)}getModelContext(){return jr(this._providers)}registerModelContextProvider(t){var s;this._providers.add(t);const e=(s=t.subscribe)==null?void 0:s.call(t,()=>{this.notifySubscribers()});return this.notifySubscribers(),()=>{this._providers.delete(t),e==null||e(),this.notifySubscribers()}}notifySubscribers(){for(const t of this._subscribers)t()}subscribe(t){return this._subscribers.add(t),()=>this._subscribers.delete(t)}},Dr=class{constructor(){h(this,"_contextProvider",new Br)}registerModelContextProvider(t){return this._contextProvider.registerModelContextProvider(t)}},Zr=class{constructor(){h(this,"_subscribers",new Set)}subscribe(t){return this._subscribers.add(t),()=>this._subscribers.delete(t)}waitForUpdate(){return new Promise(t=>{const e=this.subscribe(()=>{e(),t()})})}_notifySubscribers(){const t=[];for(const e of this._subscribers)try{e()}catch(s){t.push(s)}if(t.length>0)throw t.length===1?t[0]:new AggregateError(t)}},Lr=t=>t.status.type==="complete",rs=class extends Zr{constructor(){super(...arguments);h(this,"isEditing",!0);h(this,"_attachments",[]);h(this,"_text","");h(this,"_role","user");h(this,"_runConfig",{});h(this,"_eventSubscribers",new Map)}getAttachmentAccept(){var e;return((e=this.getAttachmentAdapter())==null?void 0:e.accept)??"*"}get attachments(){return this._attachments}setAttachments(e){this._attachments=e,this._notifySubscribers()}get isEmpty(){return!this.text.trim()&&!this.attachments.length}get text(){return this._text}get role(){return this._role}get runConfig(){return this._runConfig}setText(e){this._text!==e&&(this._text=e,this._notifySubscribers())}setRole(e){this._role!==e&&(this._role=e,this._notifySubscribers())}setRunConfig(e){this._runConfig!==e&&(this._runConfig=e,this._notifySubscribers())}_emptyTextAndAttachments(){this._attachments=[],this._text="",this._notifySubscribers()}async _onClearAttachments(){const e=this.getAttachmentAdapter();e&&await Promise.all(this._attachments.map(s=>e.remove(s)))}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 e=this._onClearAttachments();this._emptyTextAndAttachments(),await e}async clearAttachments(){const e=this._onClearAttachments();this.setAttachments([]),await e}async send(){const e=this.getAttachmentAdapter(),s=e&&this.attachments.length>0?await Promise.all(this.attachments.map(async n=>Lr(n)?n:await e.send(n))):[],r={role:this.role,content:this.text?[{type:"text",text:this.text}]:[],attachments:s,runConfig:this.runConfig};this._emptyTextAndAttachments(),this.handleSend(r),this._notifyEventSubscribers("send")}cancel(){this.handleCancel()}async addAttachment(e){const s=this.getAttachmentAdapter();if(!s)throw new Error("Attachments are not supported");const r=i=>{const a=this._attachments.findIndex(o=>o.id===i.id);a!==-1?this._attachments=[...this._attachments.slice(0,a),i,...this._attachments.slice(a+1)]:(this._attachments=[...this._attachments,i],this._notifyEventSubscribers("attachment_add")),this._notifySubscribers()},n=s.add({file:e});if(Symbol.asyncIterator in n)for await(const i of n)r(i);else r(await n);this._notifyEventSubscribers("attachment_add"),this._notifySubscribers()}async removeAttachment(e){const s=this.getAttachmentAdapter();if(!s)throw new Error("Attachments are not supported");const r=this._attachments.findIndex(i=>i.id===e);if(r===-1)throw new Error("Attachment not found");const n=this._attachments[r];await s.remove(n),this._attachments=[...this._attachments.slice(0,r),...this._attachments.slice(r+1)],this._notifySubscribers()}_notifyEventSubscribers(e){const s=this._eventSubscribers.get(e);if(s)for(const r of s)r()}unstable_on(e,s){const r=this._eventSubscribers.get(e);return r?r.add(s):this._eventSubscribers.set(e,new Set([s])),()=>{const n=this._eventSubscribers.get(e);n&&n.delete(s)}}},$r=class extends rs{constructor(e){super();h(this,"_canCancel",!1);this.runtime=e,this.connect()}get canCancel(){return this._canCancel}get attachments(){return super.attachments}getAttachmentAdapter(){var e;return(e=this.runtime.adapters)==null?void 0:e.attachments}connect(){return this.runtime.subscribe(()=>{this.canCancel!==this.runtime.capabilities.cancel&&(this._canCancel=this.runtime.capabilities.cancel,this._notifySubscribers())})}async handleSend(e){var s;this.runtime.append({...e,parentId:((s=this.runtime.messages.at(-1))==null?void 0:s.id)??null,sourceId:null})}async handleCancel(){this.runtime.cancelRun()}};let Fr=(t,e=21)=>(s=e)=>{let r="",n=s|0;for(;n--;)r+=t[Math.random()*t.length|0];return r};var Fe=Fr("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7),zr="__optimistic__",Ur=()=>`${zr}${Fe()}`,Vr=(t,{id:e=Fe(),status:s={type:"complete",reason:"unknown"},attachments:r=[]}={})=>{const n={id:e,createdAt:new Date},i=t.role;switch(i){case"assistant":return{...n,role:i,content:t.content.map(a=>a.type==="tool-call"?{...a,argsText:JSON.stringify(a.args)}:a),status:s,metadata:{unstable_annotations:[],unstable_data:[],steps:[],custom:{}}};case"user":return{...n,role:i,content:t.content,attachments:r,metadata:{custom:{}}};case"system":return{...n,role:i,content:t.content,metadata:{custom:{}}};default:{const a=i;throw new Error(`Unknown message role: ${a}`)}}},ns=Object.freeze({type:"running"}),is=Object.freeze({type:"complete",reason:"unknown"}),Wr=t=>t===ns||t===is,as=(t,e)=>t&&e?ns:is,we={exports:{}};const Yr=typeof Buffer<"u",Dt=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,Zt=/"(?: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 os(t,e,s){s==null&&e!==null&&typeof e=="object"&&(s=e,e=void 0),Yr&&Buffer.isBuffer(t)&&(t=t.toString()),t&&t.charCodeAt(0)===65279&&(t=t.slice(1));const r=JSON.parse(t,e);if(r===null||typeof r!="object")return r;const n=s&&s.protoAction||"error",i=s&&s.constructorAction||"error";if(n==="ignore"&&i==="ignore")return r;if(n!=="ignore"&&i!=="ignore"){if(Dt.test(t)===!1&&Zt.test(t)===!1)return r}else if(n!=="ignore"&&i==="ignore"){if(Dt.test(t)===!1)return r}else if(Zt.test(t)===!1)return r;return cs(r,{protoAction:n,constructorAction:i,safe:s&&s.safe})}function cs(t,{protoAction:e="error",constructorAction:s="error",safe:r}={}){let n=[t];for(;n.length;){const i=n;n=[];for(const a of i){if(e!=="ignore"&&Object.prototype.hasOwnProperty.call(a,"__proto__")){if(r===!0)return null;if(e==="error")throw new SyntaxError("Object contains forbidden prototype property");delete a.__proto__}if(s!=="ignore"&&Object.prototype.hasOwnProperty.call(a,"constructor")&&Object.prototype.hasOwnProperty.call(a.constructor,"prototype")){if(r===!0)return null;if(s==="error")throw new SyntaxError("Object contains forbidden prototype property");delete a.constructor}for(const o in a){const d=a[o];d&&typeof d=="object"&&n.push(d)}}}return t}function Tt(t,e,s){const{stackTraceLimit:r}=Error;Error.stackTraceLimit=0;try{return os(t,e,s)}finally{Error.stackTraceLimit=r}}function Jr(t,e){const{stackTraceLimit:s}=Error;Error.stackTraceLimit=0;try{return os(t,e,{safe:!0})}catch{return null}finally{Error.stackTraceLimit=s}}we.exports=Tt;we.exports.default=Tt;we.exports.parse=Tt;we.exports.safeParse=Jr;we.exports.scan=cs;var qr=we.exports;const Lt=ks(qr);function Hr(t){const e=["ROOT"];let s=-1,r=null;function n(c,u,g){switch(c){case'"':{s=u,e.pop(),e.push(g),e.push("INSIDE_STRING");break}case"f":case"t":case"n":{s=u,r=u,e.pop(),e.push(g),e.push("INSIDE_LITERAL");break}case"-":{e.pop(),e.push(g),e.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{s=u,e.pop(),e.push(g),e.push("INSIDE_NUMBER");break}case"{":{s=u,e.pop(),e.push(g),e.push("INSIDE_OBJECT_START");break}case"[":{s=u,e.pop(),e.push(g),e.push("INSIDE_ARRAY_START");break}}}function i(c,u){switch(c){case",":{e.pop(),e.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{s=u,e.pop();break}}}function a(c,u){switch(c){case",":{e.pop(),e.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{s=u,e.pop();break}}}for(let c=0;c<t.length;c++){const u=t[c];switch(e[e.length-1]){case"ROOT":n(u,c,"FINISH");break;case"INSIDE_OBJECT_START":{switch(u){case'"':{e.pop(),e.push("INSIDE_OBJECT_KEY");break}case"}":{s=c,e.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(u){case'"':{e.pop(),e.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(u){case'"':{e.pop(),e.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(u){case":":{e.pop(),e.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{n(u,c,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{i(u,c);break}case"INSIDE_STRING":{switch(u){case'"':{e.pop(),s=c;break}case"\\":{e.push("INSIDE_STRING_ESCAPE");break}default:s=c}break}case"INSIDE_ARRAY_START":{switch(u){case"]":{s=c,e.pop();break}default:{s=c,n(u,c,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(u){case",":{e.pop(),e.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{s=c,e.pop();break}default:{s=c;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{n(u,c,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{e.pop(),s=c;break}case"INSIDE_NUMBER":{switch(u){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{s=c;break}case"e":case"E":case"-":case".":break;case",":{e.pop(),e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(u,c),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&i(u,c);break}case"}":{e.pop(),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&i(u,c);break}case"]":{e.pop(),e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(u,c);break}default:{e.pop();break}}break}case"INSIDE_LITERAL":{const k=t.substring(r,c+1);!"false".startsWith(k)&&!"true".startsWith(k)&&!"null".startsWith(k)?(e.pop(),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?i(u,c):e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(u,c)):s=c;break}}}let o=t.slice(0,s+1),d=0;for(let c=e.length-1;c>=0;c--)switch(e[c]){case"INSIDE_STRING":{o+='"',d++;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":{o+="}",d++;break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{o+="]",d++;break}case"INSIDE_LITERAL":{const g=t.substring(r,t.length);"true".startsWith(g)?o+="true".slice(g.length):"false".startsWith(g)?o+="false".slice(g.length):"null".startsWith(g)&&(o+="null".slice(g.length))}}return[o,d]}function ds(t,e){function s(r){const n=S.useContext(t);if(!(r!=null&&r.optional)&&!n)throw new Error(`This component must be used within ${e}.`);return n}return s}function us(t,e){function s(n){const i=t(n);return i?i[e]:null}function r(n){let i=!1,a;typeof n=="function"?a=n:n&&typeof n=="object"&&(i=!!n.optional,a=n.selector);const o=s({optional:i});return o?a?o(a):o():null}return{[e]:r,[`${e}Store`]:s}}var ze=t=>{var s;const e=t;e.__isBound||((s=e.__internal_bindMethods)==null||s.call(e),e.__isBound=!0)},hs=S.createContext(null),Kr=ds(hs,"AssistantRuntimeProvider"),{useToolUIs:hi,useToolUIsStore:li}=us(Kr,"useToolUIs");const $t=t=>{let e;const s=new Set,r=(c,u)=>{const g=typeof c=="function"?c(e):c;if(!Object.is(g,e)){const k=e;e=u??(typeof g!="object"||g===null)?g:Object.assign({},e,g),s.forEach(I=>I(e,k))}},n=()=>e,o={setState:r,getState:n,getInitialState:()=>d,subscribe:c=>(s.add(c),()=>s.delete(c))},d=e=t(r,n,o);return o},Gr=t=>t?$t(t):$t,Xr=t=>t;function Qr(t,e=Xr){const s=S.useSyncExternalStore(t.subscribe,()=>e(t.getState()),()=>e(t.getInitialState()));return S.useDebugValue(s),s}const Ft=t=>{const e=Gr(t),s=r=>Qr(e,r);return Object.assign(s,e),s},We=t=>t?Ft(t):Ft;var en=()=>We(t=>{const e=new Map;return Object.freeze({getToolUI:s=>{const r=e.get(s),n=r==null?void 0:r.at(-1);return n||null},setToolUI:(s,r)=>{let n=e.get(s);return n||(n=[],e.set(s,n)),n.push(r),t({}),()=>{const i=n.indexOf(r);i!==-1&&n.splice(i,1),i===n.length&&t({})}}})}),tn=S.createContext(null),at=t=>t,sn=S.createContext(null),rn=t=>{const[e]=S.useState(()=>We(()=>t));return S.useEffect(()=>{ze(t),at(e).setState(t,!0)},[t,e]),e},nn=({runtime:t,children:e})=>{const s=rn(t),[r]=S.useState(()=>({useThreadListItemRuntime:s}));return F.jsx(sn.Provider,{value:r,children:e})},an=()=>{const t=new Set;return We(()=>({isAtBottom:!0,scrollToBottom:()=>{for(const e of t)e()},onScrollToBottom:e=>(t.add(e),()=>{t.delete(e)})}))},ls=S.createContext(null),on=ds(ls,"ThreadPrimitive.Viewport"),{useThreadViewport:fi,useThreadViewportStore:cn}=us(on,"useThreadViewport"),dn=()=>{const t=cn({optional:!0}),[e]=S.useState(()=>an());return S.useEffect(()=>t==null?void 0:t.getState().onScrollToBottom(()=>{e.getState().scrollToBottom()}),[t,e]),S.useEffect(()=>{if(t)return e.subscribe(s=>{t.getState().isAtBottom!==s.isAtBottom&&at(t).setState({isAtBottom:s.isAtBottom})})},[e,t]),e},un=({children:t})=>{const e=dn(),[s]=S.useState(()=>({useThreadViewport:e}));return F.jsx(ls.Provider,{value:s,children:t})},hn=t=>{const[e]=S.useState(()=>We(()=>t));return S.useEffect(()=>{ze(t),ze(t.composer),at(e).setState(t,!0)},[t,e]),e},ln=({children:t,listItemRuntime:e,runtime:s})=>{const r=hn(s),[n]=S.useState(()=>({useThreadRuntime:r}));return F.jsx(nn,{runtime:e,children:F.jsx(tn.Provider,{value:n,children:F.jsx(un,{children:t})})})},fn=t=>{const[e]=S.useState(()=>We(()=>t));return S.useEffect(()=>{ze(t),ze(t.threads),at(e).setState(t,!0)},[t,e]),e},pn=()=>S.useMemo(()=>en(),[]),gn=t=>{var e;return(e=t._core)==null?void 0:e.RenderComponent},mn=({children:t,runtime:e})=>{const s=fn(e),r=pn(),[n]=S.useState(()=>({useToolUIs:r,useAssistantRuntime:s})),i=gn(e);return F.jsxs(hs.Provider,{value:n,children:[i&&F.jsx(i,{}),F.jsx(ln,{runtime:e.thread,listItemRuntime:e.threads.mainItem,children:t})]})},_n=S.memo(mn),zt=class{constructor(t,e,s){this.contentBinding=t,this.messageApi=e,this.threadApi=s}get path(){return this.contentBinding.path}__internal_bindMethods(){this.addToolResult=this.addToolResult.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this)}getState(){return this.contentBinding.getState()}addToolResult(t){const e=this.contentBinding.getState();if(!e)throw new Error("Content part is not available");if(e.type!=="tool-call")throw new Error("Tried to add tool result to non-tool content 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 s=this.messageApi.getState();if(!s)throw new Error("Message is not available");const r=e.toolName,n=e.toolCallId;this.threadApi.getState().addToolResult({messageId:s.id,toolName:r,toolCallId:n,result:t})}subscribe(t){return this.contentBinding.subscribe(t)}},bn=Symbol("partial-json-count"),yn=t=>{try{return Lt.parse(t)}catch{try{const[e,s]=Hr(t),r=Lt.parse(e);return r[bn]=s,r}catch{return}}},fs=(t,e,s)=>{const{role:r,id:n,createdAt:i,attachments:a,status:o,metadata:d}=t,c={id:n??e,createdAt:i??new Date},u=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;if(r!=="user"&&a)throw new Error("attachments are only supported for user messages");if(r!=="assistant"&&o)throw new Error("status is only supported for assistant messages");if(r!=="assistant"&&(d!=null&&d.steps))throw new Error("metadata.steps is only supported for assistant messages");switch(r){case"assistant":return{...c,role:r,content:u.map(g=>{const k=g.type;switch(k){case"text":case"reasoning":return g.text.trim().length===0?null:g;case"file":case"source":return g;case"tool-call":return g.args?{...g,toolCallId:g.toolCallId??"tool-"+Fe(),args:g.args,argsText:JSON.stringify(g.args)}:{...g,toolCallId:g.toolCallId??"tool-"+Fe(),args:g.args??yn(g.argsText??"{}"),argsText:g.argsText??""};default:{const I=k;throw new Error(`Unsupported assistant content part type: ${I}`)}}}).filter(g=>!!g),status:o??s,metadata:{unstable_annotations:(d==null?void 0:d.unstable_annotations)??[],unstable_data:(d==null?void 0:d.unstable_data)??[],custom:(d==null?void 0:d.custom)??{},steps:(d==null?void 0:d.steps)??[]}};case"user":return{...c,role:r,content:u.map(g=>{const k=g.type;switch(k){case"text":case"image":case"audio":case"file":return g;default:{const I=k;throw new Error(`Unsupported user content part type: ${I}`)}}}),attachments:a??[],metadata:{custom:(d==null?void 0:d.custom)??{}}};case"system":if(u.length!==1||u[0].type!=="text")throw new Error("System messages must have exactly one text content part.");return{...c,role:r,content:u,metadata:{custom:(d==null?void 0:d.custom)??{}}};default:{const g=r;throw new Error(`Unknown message role: ${g}`)}}},vn={fromArray:t=>{const e=t.map(s=>fs(s,Fe(),as(!1,!1)));return{messages:e.map((s,r)=>({parentId:r>0?e[r-1].id:null,message:s}))}}},Ke=t=>t.next?Ke(t.next):"current"in t?t:null,Sn=class{constructor(t){h(this,"_value",null);this.func=t}get value(){return this._value===null&&(this._value=this.func()),this._value}dirty(){this._value=null}},wn=class{constructor(){h(this,"messages",new Map);h(this,"head",null);h(this,"root",{children:[],next:null});h(this,"_messages",new Sn(()=>{var e;const t=new Array(((e=this.head)==null?void 0:e.level)??0);for(let s=this.head;s;s=s.prev)t[s.level]=s.current;return t}))}performOp(t,e,s){const r=e.prev??this.root,n=t??this.root;if(!(s==="relink"&&r===n)){if(s!=="link"&&(r.children=r.children.filter(i=>i!==e.current.id),r.next===e)){const i=r.children.at(-1),a=i?this.messages.get(i):null;if(a===void 0)throw new Error("MessageRepository(performOp/cut): Fallback sibling message not found. This is likely an internal bug in assistant-ui.");r.next=a}if(s!=="cut"){for(let i=t;i;i=i.prev)if(i.current.id===e.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.");n.children=[...n.children,e.current.id],(Ke(e)===this.head||n.next===null)&&(n.next=e),e.prev=t}}}get headId(){var t;return((t=this.head)==null?void 0:t.current.id)??null}getMessages(){return this._messages.value}addOrUpdateMessage(t,e){const s=this.messages.get(e.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(s){s.current=e,this.performOp(r,s,"relink"),this._messages.dirty();return}const n={prev:r,current:e,next:null,children:[],level:r?r.level+1:0};this.messages.set(e.id,n),this.performOp(r,n,"link"),this.head===r&&(this.head=n),this._messages.dirty()}getMessage(t){var s;const e=this.messages.get(t);if(!e)throw new Error("MessageRepository(updateMessage): Message not found. This is likely an internal bug in assistant-ui.");return{parentId:((s=e.prev)==null?void 0:s.current.id)??null,message:e.current}}appendOptimisticMessage(t,e){let s;do s=Ur();while(this.messages.has(s));return this.addOrUpdateMessage(t,Vr(e,{id:s,status:{type:"running"}})),s}deleteMessage(t,e){const s=this.messages.get(t);if(!s)throw new Error("MessageRepository(deleteMessage): Optimistic message not found. This is likely an internal bug in assistant-ui.");const r=e===void 0?s.prev:e===null?null:this.messages.get(e);if(r===void 0)throw new Error("MessageRepository(deleteMessage): Replacement not found. This is likely an internal bug in assistant-ui.");for(const n of s.children){const i=this.messages.get(n);if(!i)throw new Error("MessageRepository(deleteMessage): Child message not found. This is likely an internal bug in assistant-ui.");this.performOp(r,i,"relink")}this.performOp(null,s,"cut"),this.messages.delete(t),this.head===s&&(this.head=Ke(r??this.root)),this._messages.dirty()}getBranches(t){const e=this.messages.get(t);if(!e)throw new Error("MessageRepository(getBranches): Message not found. This is likely an internal bug in assistant-ui.");const{children:s}=e.prev??this.root;return s}switchToBranch(t){const e=this.messages.get(t);if(!e)throw new Error("MessageRepository(switchToBranch): Branch not found. This is likely an internal bug in assistant-ui.");const s=e.prev??this.root;s.next=e,this.head=Ke(e),this._messages.dirty()}resetHead(t){if(t===null){this.head=null,this._messages.dirty();return}const e=this.messages.get(t);if(!e)throw new Error("MessageRepository(resetHead): Branch not found. This is likely an internal bug in assistant-ui.");this.head=e;for(let s=e;s;s=s.prev)s.prev&&(s.prev.next=s);this._messages.dirty()}clear(){this.messages.clear(),this.head=null,this.root={children:[],next:null},this._messages.dirty()}export(){var e,s;const t=[];for(const[,r]of this.messages)t.push({message:r.current,parentId:((e=r.prev)==null?void 0:e.current.id)??null});return{headId:((s=this.head)==null?void 0:s.current.id)??null,messages:t}}import({headId:t,messages:e}){var s;for(const{message:r,parentId:n}of e)this.addOrUpdateMessage(n,r);this.resetHead(t??((s=e.at(-1))==null?void 0:s.message.id)??null)}},ot=class{constructor(){h(this,"_subscriptions",new Set);h(this,"_connection")}get isConnected(){return!!this._connection}notifySubscribers(){for(const t of this._subscriptions)t()}_updateConnection(){var t;if(this._subscriptions.size>0){if(this._connection)return;this._connection=this._connect()}else(t=this._connection)==null||t.call(this),this._connection=void 0}subscribe(t){return this._subscriptions.add(t),this._updateConnection(),()=>{this._subscriptions.delete(t),this._updateConnection()}}},V=Symbol("skip-update"),kt=class extends ot{constructor(e){super();h(this,"_previousStateDirty",!0);h(this,"_previousState");h(this,"getState",()=>{if(!this.isConnected||this._previousStateDirty){const e=this.binding.getState();e!==V&&(this._previousState=e),this._previousStateDirty=!1}if(this._previousState===void 0)throw new Error("Entry not available in the store");return this._previousState});this.binding=e}get path(){return this.binding.path}_connect(){const e=()=>{this._previousStateDirty=!0,this.notifySubscribers()};return this.binding.subscribe(e)}},Je=class{constructor(t,e){this._core=t,this._threadListBinding=e}get path(){return this._core.path}__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)}getState(){return this._core.getState()}switchTo(){const t=this._core.getState();return this._threadListBinding.switchToThread(t.id)}rename(t){const e=this._core.getState();return this._threadListBinding.rename(e.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,e){let s=this._core.getState().isMain;return this.subscribe(()=>{const r=this._core.getState().isMain;s!==r&&(s=r,!(t==="switched-to"&&!r)&&(t==="switched-away"&&r||e()))})}subscribe(t){return this._core.subscribe(t)}};function xn(t,e){if(t===void 0&&e===void 0)return!0;if(t===void 0||e===void 0)return!1;for(const s of Object.keys(t)){const r=t[s],n=e[s];if(!Object.is(r,n))return!1}return!0}var $=class extends ot{constructor(e){super();h(this,"_previousState");h(this,"getState",()=>(this.isConnected||this._syncState(),this._previousState));this.binding=e;const s=e.getState();if(s===V)throw new Error("Entry not available in the store");this._previousState=s}get path(){return this.binding.path}_syncState(){const e=this.binding.getState();return e===V||xn(e,this._previousState)?!1:(this._previousState=e,!0)}_connect(){const e=()=>{this._syncState()&&this.notifySubscribers()};return this.binding.subscribe(e)}},Se=Symbol("innerMessage"),Tn=t=>t[Se],Ue=t=>t.content.filter(s=>s.type==="text").map(s=>s.text).join(`
25
17
 
26
- `),Xs=class{constructor(t){this._core=t}get path(){return this._core.path}__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)}},Qs=class extends Xs{constructor(t,e){super(t),this._composerApi=e}remove(){const t=this._composerApi.getState();if(!t)throw new Error("Composer is not available");return t.removeAttachment(this.getState().id)}},Ni=class extends Qs{get source(){return"thread-composer"}},ji=class extends Qs{get source(){return"edit-composer"}},Bi=class extends Xs{get source(){return"message"}constructor(t){super(t)}remove(){throw new Error("Message attachments cannot be removed")}},er=class extends Tt{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 e=this.config.binding.getState(),s=e==null?void 0:e.unstable_on(this.config.event,t);const r=()=>{var o;const i=this.config.binding.getState();i!==e&&(e=i,s==null||s(),s=(o=this.config.binding.getState())==null?void 0:o.unstable_on(this.config.event,t))},n=this.outerSubscribe(r);return()=>{n==null||n(),s==null||s()}}},tr=Object.freeze([]),sr=Object.freeze({}),Di=t=>Object.freeze({type:"thread",isEditing:(t==null?void 0:t.isEditing)??!1,canCancel:(t==null?void 0:t.canCancel)??!1,isEmpty:(t==null?void 0:t.isEmpty)??!0,attachments:(t==null?void 0:t.attachments)??tr,text:(t==null?void 0:t.text)??"",role:(t==null?void 0:t.role)??"user",runConfig:(t==null?void 0:t.runConfig)??sr,value:(t==null?void 0:t.text)??""}),Zi=t=>Object.freeze({type:"edit",isEditing:(t==null?void 0:t.isEditing)??!1,canCancel:(t==null?void 0:t.canCancel)??!1,isEmpty:(t==null?void 0:t.isEmpty)??!0,text:(t==null?void 0:t.text)??"",role:(t==null?void 0:t.role)??"user",attachments:(t==null?void 0:t.attachments)??tr,runConfig:(t==null?void 0:t.runConfig)??sr,value:(t==null?void 0:t.text)??""}),rr=class{constructor(t){h(this,"_eventSubscriptionSubjects",new Map);this._core=t}get path(){return this._core.path}__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.getAttachmentAccept=this.getAttachmentAccept.bind(this),this.getAttachmentByIndex=this.getAttachmentByIndex.bind(this),this.unstable_on=this.unstable_on.bind(this)}setText(t){const e=this._core.getState();if(!e)throw new Error("Composer is not available");e.setText(t)}setRunConfig(t){const e=this._core.getState();if(!e)throw new Error("Composer is not available");e.setRunConfig(t)}addAttachment(t){const e=this._core.getState();if(!e)throw new Error("Composer is not available");return e.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 e=this._core.getState();if(!e)throw new Error("Composer is not available");e.setRole(t)}subscribe(t){return this._core.subscribe(t)}unstable_on(t,e){let s=this._eventSubscriptionSubjects.get(t);return s||(s=new er({event:t,binding:this._core}),this._eventSubscriptionSubjects.set(t,s)),s.subscribe(e)}getAttachmentAccept(){const t=this._core.getState();if(!t)throw new Error("Composer is not available");return t.getAttachmentAccept()}},$i=class extends rr{constructor(e){const s=new Wt({path:e.path,getState:()=>Di(e.getState()),subscribe:r=>e.subscribe(r)});super({path:e.path,getState:()=>e.getState(),subscribe:r=>s.subscribe(r)});h(this,"_getState");this._getState=s.getState.bind(s)}get path(){return this._core.path}get type(){return"thread"}getState(){return this._getState()}getAttachmentByIndex(e){return new Ni(new K({path:{...this.path,attachmentSource:"thread-composer",attachmentSelector:{type:"index",index:e},ref:this.path.ref+`${this.path.ref}.attachments[${e}]`},getState:()=>{const r=this.getState().attachments[e];return r?{...r,source:"thread-composer"}:Q},subscribe:s=>this._core.subscribe(s)}),this._core)}},Li=class extends rr{constructor(e,s){const r=new Wt({path:e.path,getState:()=>Zi(e.getState()),subscribe:n=>e.subscribe(n)});super({path:e.path,getState:()=>e.getState(),subscribe:n=>r.subscribe(n)});h(this,"_getState");this._beginEdit=s,this._getState=r.getState.bind(r)}get path(){return this._core.path}get type(){return"edit"}__internal_bindMethods(){super.__internal_bindMethods(),this.beginEdit=this.beginEdit.bind(this)}getState(){return this._getState()}beginEdit(){this._beginEdit()}getAttachmentByIndex(e){return new ji(new K({path:{...this.path,attachmentSource:"edit-composer",attachmentSelector:{type:"index",index:e},ref:this.path.ref+`${this.path.ref}.attachments[${e}]`},getState:()=>{const r=this.getState().attachments[e];return r?{...r,source:"edit-composer"}:Q},subscribe:s=>this._core.subscribe(s)}),this._core)}},St=class extends Tt{constructor(t){super(),this.binding=t}get path(){return this.binding.path}getState(){return this.binding.getState()}outerSubscribe(t){return this.binding.subscribe(t)}_connect(){const t=()=>{this.notifySubscribers()};let e=this.binding.getState(),s=e==null?void 0:e.subscribe(t);const r=()=>{var o;const i=this.binding.getState();i!==e&&(e=i,s==null||s(),s=(o=this.binding.getState())==null?void 0:o.subscribe(t),t())},n=this.outerSubscribe(r);return()=>{n==null||n(),s==null||s()}}},lt=Object.freeze({type:"complete"}),Fi=(t,e,s)=>{if(t.role!=="assistant")return lt;if(s.type==="tool-call")return s.result?lt:t.status;const r=e===Math.max(0,t.content.length-1);return t.status.type==="requires-action"?lt:r?t.status:lt},Cs=(t,e)=>{const s=t.content[e];if(!s)return Q;const r=Fi(t,e,s);return Object.freeze({...s,[Oe]:s[Oe],status:r})},Vi=class{constructor(t,e){h(this,"composer");h(this,"_getEditComposerRuntimeCore",()=>this._threadBinding.getState().getEditComposer(this._core.getState().id));this._core=t,this._threadBinding=e,this.composer=new Li(new St({path:{...this.path,ref:this.path.ref+`${this.path.ref}.composer`,composerSource:"edit"},getState:this._getEditComposerRuntimeCore,subscribe:s=>this._threadBinding.subscribe(s)}),()=>this._threadBinding.getState().beginEdit(this._core.getState().id))}get path(){return this._core.path}__internal_bindMethods(){this.reload=this.reload.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.getContentPartByIndex=this.getContentPartByIndex.bind(this),this.getContentPartByToolCallId=this.getContentPartByToolCallId.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)}getState(){return this._core.getState()}reload(t={}){const e=this._getEditComposerRuntimeCore(),s=e??this._threadBinding.getState().composer,r=e??s,{runConfig:n=r.runConfig}=t,i=this._core.getState();if(i.role!=="assistant")throw new Error("Can only reload assistant messages");this._threadBinding.getState().startRun({parentId:i.parentId,sourceId:i.id,runConfig:n})}speak(){const t=this._core.getState();return this._threadBinding.getState().speak(t.id)}stopSpeaking(){var s;const t=this._core.getState();if(((s=this._threadBinding.getState().speech)==null?void 0:s.messageId)===t.id)this._threadBinding.getState().stopSpeaking();else throw new Error("Message is not being spoken")}submitFeedback({type:t}){const e=this._core.getState();this._threadBinding.getState().submitFeedback({messageId:e.id,type:t})}switchToBranch({position:t,branchId:e}){const s=this._core.getState();if(e&&t)throw new Error("May not specify both branchId and position");if(!e&&!t)throw new Error("Must specify either branchId or position");const n=this._threadBinding.getState().getBranches(s.id);let i=e;if(t==="previous"?i=n[s.branchNumber-2]:t==="next"&&(i=n[s.branchNumber]),!i)throw new Error("Branch not found");this._threadBinding.getState().switchToBranch(i)}unstable_getCopyText(){return tt(this.getState())}subscribe(t){return this._core.subscribe(t)}getContentPartByIndex(t){if(t<0)throw new Error("Content part index must be >= 0");return new ks(new K({path:{...this.path,ref:this.path.ref+`${this.path.ref}.content[${t}]`,contentPartSelector:{type:"index",index:t}},getState:()=>Cs(this.getState(),t),subscribe:e=>this._core.subscribe(e)}),this._core,this._threadBinding)}getContentPartByToolCallId(t){return new ks(new K({path:{...this.path,ref:this.path.ref+`${this.path.ref}.content[toolCallId=${JSON.stringify(t)}]`,contentPartSelector:{type:"toolCallId",toolCallId:t}},getState:()=>{const e=this._core.getState(),s=e.content.findIndex(r=>r.type==="tool-call"&&r.toolCallId===t);return s===-1?Q:Cs(e,s)},subscribe:e=>this._core.subscribe(e)}),this._core,this._threadBinding)}getAttachmentByIndex(t){return new Bi(new K({path:{...this.path,ref:this.path.ref+`${this.path.ref}.attachments[${t}]`,attachmentSource:"message",attachmentSelector:{type:"index",index:t}},getState:()=>{const e=this.getState().attachments,s=e==null?void 0:e[t];return s?{...s,source:"message"}:Q},subscribe:e=>this._core.subscribe(e)}))}},Ui=t=>({parentId:t.parentId??null,sourceId:t.sourceId??null,runConfig:t.runConfig??{},stream:t.stream}),zi=t=>({parentId:t.parentId??null,sourceId:t.sourceId??null,runConfig:t.runConfig??{}}),Wi=(t,e)=>{var s,r;return typeof e=="string"?{parentId:((s=t.at(-1))==null?void 0:s.id)??null,sourceId:null,runConfig:{},role:"user",content:[{type:"text",text:e}],attachments:[]}:e.role&&e.parentId&&e.attachments?e:{...e,parentId:e.parentId??((r=t.at(-1))==null?void 0:r.id)??null,sourceId:e.sourceId??null,role:e.role??"user",attachments:e.attachments??[]}},Yi=(t,e)=>{const s=t.messages.at(-1);return Object.freeze({threadId:e.id,metadata:e,capabilities:t.capabilities,isDisabled:t.isDisabled,isRunning:(s==null?void 0:s.role)!=="assistant"?!1:s.status.type==="running",messages:t.messages,suggestions:t.suggestions,extras:t.extras,speech:t.speech})},Ji=class{constructor(t,e){h(this,"_threadBinding");h(this,"composer");h(this,"_eventSubscriptionSubjects",new Map);const s=new K({path:t.path,getState:()=>Yi(t.getState(),e.getState()),subscribe:r=>{const n=t.subscribe(r),i=e.subscribe(r);return()=>{n(),i()}}});this._threadBinding={path:t.path,getState:()=>t.getState(),getStateState:()=>s.getState(),outerSubscribe:r=>t.outerSubscribe(r),subscribe:r=>t.subscribe(r)},this.composer=new $i(new St({path:{...this.path,ref:this.path.ref+`${this.path.ref}.composer`,composerSource:"thread"},getState:()=>this._threadBinding.getState().composer,subscribe:r=>this._threadBinding.subscribe(r)}))}get path(){return this._threadBinding.path}get __internal_threadBinding(){return this._threadBinding}__internal_bindMethods(){this.append=this.append.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.getMesssageByIndex=this.getMesssageByIndex.bind(this),this.getMesssageById=this.getMesssageById.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)}getState(){return this._threadBinding.getStateState()}append(t){this._threadBinding.getState().append(Wi(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 e=t===null||typeof t=="string"?{parentId:t}:t;return this._threadBinding.getState().startRun(zi(e))}unstable_resumeRun(t){return this._threadBinding.getState().resumeRun(Ui(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)}getMesssageByIndex(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}},()=>{var r;const e=this._threadBinding.getState().messages,s=e[t];if(s)return{message:s,parentId:((r=e[t-1])==null?void 0:r.id)??null}})}getMesssageById(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,e){return new Vi(new K({path:t,getState:()=>{var u;const{message:s,parentId:r}=e()??{},{messages:n,speech:i}=this._threadBinding.getState();if(!s||r===void 0)return Q;const o=this._threadBinding.getState(),c=o.getBranches(s.id),d=o.getSubmittedFeedback(s.id);return{...s,[Oe]:s[Oe],isLast:((u=n.at(-1))==null?void 0:u.id)===s.id,parentId:r,branchNumber:c.indexOf(s.id)+1,branchCount:c.length,speech:(i==null?void 0:i.messageId)===s.id?i:void 0,submittedFeedback:d}},subscribe:s=>this._threadBinding.subscribe(s)}),this._threadBinding)}unstable_on(t,e){let s=this._eventSubscriptionSubjects.get(t);return s||(s=new er({event:t,binding:this._threadBinding}),this._eventSubscriptionSubjects.set(t,s)),s.subscribe(e)}},qi=t=>({mainThreadId:t.mainThreadId,newThread:t.newThreadId,threads:t.threadIds,archivedThreads:t.archivedThreadIds}),ht=(t,e)=>{if(e===void 0)return Q;const s=t.getItemById(e);return s?{id:s.threadId,threadId:s.threadId,remoteId:s.remoteId,externalId:s.externalId,title:s.title,status:s.status,isMain:s.threadId===t.mainThreadId}:Q},Ki=class{constructor(t,e=Ji){h(this,"_getState");h(this,"_mainThreadListItemRuntime");h(this,"main");this._core=t,this._runtimeFactory=e;const s=new Wt({path:{},getState:()=>qi(t),subscribe:r=>t.subscribe(r)});this._getState=s.getState.bind(s),this._mainThreadListItemRuntime=new dt(new K({path:{ref:"threadItems[main]",threadSelector:{type:"main"}},getState:()=>ht(this._core,this._core.mainThreadId),subscribe:r=>this._core.subscribe(r)}),this._core),this.main=new e(new St({path:{ref:"threads.main",threadSelector:{type:"main"}},getState:()=>t.getMainThreadRuntimeCore(),subscribe:r=>t.subscribe(r)}),this._mainThreadListItemRuntime)}__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)}get mainItem(){return this._mainThreadListItemRuntime}getById(t){return new this._runtimeFactory(new St({path:{ref:"threads[threadId="+JSON.stringify(t)+"]",threadSelector:{type:"threadId",threadId:t}},getState:()=>this._core.getThreadRuntimeCore(t),subscribe:e=>this._core.subscribe(e)}),this.mainItem)}getItemByIndex(t){return new dt(new K({path:{ref:`threadItems[${t}]`,threadSelector:{type:"index",index:t}},getState:()=>ht(this._core,this._core.threadIds[t]),subscribe:e=>this._core.subscribe(e)}),this._core)}getArchivedItemByIndex(t){return new dt(new K({path:{ref:`archivedThreadItems[${t}]`,threadSelector:{type:"archiveIndex",index:t}},getState:()=>ht(this._core,this._core.archivedThreadIds[t]),subscribe:e=>this._core.subscribe(e)}),this._core)}getItemById(t){return new dt(new K({path:{ref:`threadItems[threadId=${t}]`,threadSelector:{type:"threadId",threadId:t}},getState:()=>ht(this._core,t),subscribe:e=>this._core.subscribe(e)}),this._core)}},_e=Object.freeze([]),ke="DEFAULT_THREAD_ID",Hi=Object.freeze([ke]),Gi=Object.freeze({threadId:ke,status:"regular"}),Xi=Promise.resolve(),Qi=class{constructor(t={},e){h(this,"_mainThreadId",ke);h(this,"_threads",Hi);h(this,"_archivedThreads",_e);h(this,"_mainThread");h(this,"_subscriptions",new Set);this.adapter=t,this.threadFactory=e,this._mainThread=this.threadFactory()}get newThreadId(){}get threadIds(){return this._threads}get archivedThreadIds(){return this._archivedThreads}getLoadThreadsPromise(){return Xi}get mainThreadId(){return this._mainThreadId}getMainThreadRuntimeCore(){return this._mainThread}getThreadRuntimeCore(){throw new Error("Method not implemented.")}getItemById(t){for(const e of this.adapter.threads??[])if(e.threadId===t)return e;for(const e of this.adapter.archivedThreads??[])if(e.threadId===t)return e;if(t===ke)return Gi}__internal_setAdapter(t){var d,u;const e=this.adapter;this.adapter=t;const s=t.threadId??ke,r=t.threads??_e,n=t.archivedThreads??_e,i=e.threadId??ke,o=e.threads??_e,c=e.archivedThreads??_e;i===s&&o===r&&c===n||(o!==r&&(this._threads=((d=this.adapter.threads)==null?void 0:d.map(l=>l.threadId))??_e),c!==n&&(this._archivedThreads=((u=this.adapter.archivedThreads)==null?void 0:u.map(l=>l.threadId))??_e),i!==s&&(this._mainThreadId=s,this._mainThread=this.threadFactory()),this._notifySubscribers())}async switchToThread(t){if(this._mainThreadId===t)return;const e=this.adapter.onSwitchToThread;if(!e)throw new Error("External store adapter does not support switching to thread");e(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,e){const s=this.adapter.onRename;if(!s)throw new Error("External store adapter does not support renaming");s(t,e)}async archive(t){const e=this.adapter.onArchive;if(!e)throw new Error("External store adapter does not support archiving");e(t)}async unarchive(t){const e=this.adapter.onUnarchive;if(!e)throw new Error("External store adapter does not support unarchiving");e(t)}async delete(t){const e=this.adapter.onDelete;if(!e)throw new Error("External store adapter does not support deleting");e(t)}initialize(){throw new Error("Method not implemented.")}generateTitle(){throw new Error("Method not implemented.")}subscribe(t){return this._subscriptions.add(t),()=>this._subscriptions.delete(t)}_notifySubscribers(){for(const t of this._subscriptions)t()}},Rs=class{constructor(){h(this,"cache",new WeakMap)}convertMessages(t,e){return t.map((s,r)=>{const n=this.cache.get(s),i=e(n,s,r);return this.cache.set(s,i),i})}},ea=class extends Fs{constructor(e,s,{parentId:r,message:n}){super();h(this,"_nonTextParts");h(this,"_previousText");h(this,"_parentId");h(this,"_sourceId");this.runtime=e,this.endEditCallback=s,this._parentId=r,this._sourceId=n.id,this._previousText=tt(n),this.setText(this._previousText),this.setRole(n.role),this.setAttachments(n.attachments??[]),this._nonTextParts=n.content.filter(i=>i.type!=="text"),this.setRunConfig({...e.composer.runConfig})}get canCancel(){return!0}getAttachmentAdapter(){var e;return(e=this.runtime.adapters)==null?void 0:e.attachments}async handleSend(e){tt(e)!==this._previousText&&this.runtime.append({...e,content:[...e.content,...this._nonTextParts],parentId:this._parentId,sourceId:this._sourceId}),this.handleCancel()}handleCancel(){this.endEditCallback(),this._notifySubscribers()}},ta=class{constructor(t){h(this,"_subscriptions",new Set);h(this,"_isInitialized",!1);h(this,"repository",new Oi);h(this,"composer",new Hn(this));h(this,"_editComposers",new Map);h(this,"_submittedFeedback",{});h(this,"_stopSpeaking");h(this,"speech");h(this,"_eventSubscribers",new Map);this._contextProvider=t}get messages(){return this.repository.getMessages()}getModelContext(){return this._contextProvider.getModelContext()}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 ea(this,()=>this._editComposers.delete(t),this.repository.getMessage(t))),this._notifySubscribers()}getMessageById(t){return this.repository.getMessage(t)}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 e=this._eventSubscribers.get(t);if(e)for(const s of e)s()}subscribe(t){return this._subscriptions.add(t),()=>this._subscriptions.delete(t)}getSubmittedFeedback(t){return this._submittedFeedback[t]}submitFeedback({messageId:t,type:e}){var n;const s=(n=this.adapters)==null?void 0:n.feedback;if(!s)throw new Error("Feedback adapter not configured");const{message:r}=this.repository.getMessage(t);s.submit({message:r,type:e}),this._submittedFeedback[t]={type:e},this._notifySubscribers()}speak(t){var i,o;const e=(i=this.adapters)==null?void 0:i.speech;if(!e)throw new Error("Speech adapter not configured");const{message:s}=this.repository.getMessage(t);(o=this._stopSpeaking)==null||o.call(this);const r=e.speak(tt(s)),n=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(),n(),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()}unstable_on(t,e){var r,n;if(t==="model-context-update")return((n=(r=this._contextProvider).subscribe)==null?void 0:n.call(r,e))??(()=>{});const s=this._eventSubscribers.get(t);return s?s.add(e):this._eventSubscribers.set(t,new Set([e])),()=>{this._eventSubscribers.get(t).delete(e)}}},sa=Object.freeze([]),ra=(t,e)=>{var s;return t&&((s=e[e.length-1])==null?void 0:s.role)!=="assistant"},na=class extends ta{constructor(e,s){super(e);h(this,"assistantOptimisticId",null);h(this,"_capabilities",{switchToBranch:!1,edit:!1,reload:!1,cancel:!1,unstable_copy:!1,speech:!1,attachments:!1,feedback:!1});h(this,"_messages");h(this,"isDisabled");h(this,"suggestions",[]);h(this,"extras");h(this,"_converter",new Rs);h(this,"_store");h(this,"updateMessages",e=>{var r,n,i,o;this._store.convertMessage!==void 0?(n=(r=this._store).setMessages)==null||n.call(r,e.flatMap(Pi).filter(c=>c!=null)):(o=(i=this._store).setMessages)==null||o.call(i,e)});this.__internal_setAdapter(s)}get capabilities(){return this._capabilities}get messages(){return this._messages}get adapters(){return this._store.adapters}beginEdit(e){if(!this._store.onEdit)throw new Error("Runtime does not support editing.");super.beginEdit(e)}__internal_setAdapter(e){var i,o,c,d,u,l;if(this._store===e)return;const s=e.isRunning??!1;this.isDisabled=e.isDisabled??!1;const r=this._store;if(this._store=e,this.extras=e.extras,this.suggestions=e.suggestions??sa,this._capabilities={switchToBranch:this._store.setMessages!==void 0,edit:this._store.onEdit!==void 0,reload:this._store.onReload!==void 0,cancel:this._store.onCancel!==void 0,speech:((i=this._store.adapters)==null?void 0:i.speech)!==void 0,unstable_copy:((o=this._store.unstable_capabilities)==null?void 0:o.copy)!==!1,attachments:!!((c=this._store.adapters)!=null&&c.attachments),feedback:!!((d=this._store.adapters)!=null&&d.feedback)},r){if(r.convertMessage!==e.convertMessage)this._converter=new Rs;else if(r.isRunning===e.isRunning&&r.messages===e.messages){this._notifySubscribers();return}}const n=e.convertMessage?this._converter.convertMessages(e.messages,(g,I,N)=>{if(!e.convertMessage)return I;const fe=N===e.messages.length-1,ee=zs(fe,s);if(g&&(g.role!=="assistant"||!ti(g.status)||g.status===ee))return g;const Pe=e.convertMessage(I,N),Y=Gs(Pe,N.toString(),ee);return Y[Oe]=I,Y}):e.messages;n.length>0&&this.ensureInitialized(),((r==null?void 0:r.isRunning)??e.isRunning!==!1??!1)&&(e.isRunning?this._notifyEventSubscribers("run-start"):this._notifyEventSubscribers("run-end"));for(let g=0;g<n.length;g++){const I=n[g],N=n[g-1];this.repository.addOrUpdateMessage((N==null?void 0:N.id)??null,I)}this.assistantOptimisticId&&(this.repository.deleteMessage(this.assistantOptimisticId),this.assistantOptimisticId=null),ra(s,n)&&(this.assistantOptimisticId=this.repository.appendOptimisticMessage(((u=n.at(-1))==null?void 0:u.id)??null,{role:"assistant",content:[]})),this.repository.resetHead(this.assistantOptimisticId??((l=n.at(-1))==null?void 0:l.id)??null),this._messages=this.repository.getMessages(),this._notifySubscribers()}switchToBranch(e){if(!this._store.setMessages)throw new Error("Runtime does not support switching branches.");this.repository.switchToBranch(e),this.updateMessages(this.repository.getMessages())}async append(e){var s;if(e.parentId!==(((s=this.messages.at(-1))==null?void 0:s.id)??null)){if(!this._store.onEdit)throw new Error("Runtime does not support editing messages.");await this._store.onEdit(e)}else await this._store.onNew(e)}async startRun(e){if(!this._store.onReload)throw new Error("Runtime does not support reloading messages.");await this._store.onReload(e.parentId,e)}async resumeRun(){throw new Error("Runtime does not support resuming runs.")}cancelRun(){var r;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 e=this.repository.getMessages();const s=e[e.length-1];(s==null?void 0:s.role)==="user"&&s.id===((r=e.at(-1))==null?void 0:r.id)?(this.repository.deleteMessage(s.id),this.composer.text.trim()||this.composer.setText(tt(s)),e=this.repository.getMessages()):this._notifySubscribers(),setTimeout(()=>{this.updateMessages(e)},0)}addToolResult(e){if(!this._store.onAddToolResult)throw new Error("Runtime does not support tool results.");this._store.onAddToolResult(e)}},Is=t=>{var e;return((e=t.adapters)==null?void 0:e.threadList)??{}},ia=class extends Jn{constructor(e){super();h(this,"threads");this.threads=new Qi(Is(e),()=>new na(this._contextProvider,e))}setAdapter(e){this.threads.__internal_setAdapter(Is(e)),this.threads.getMainThreadRuntimeCore().__internal_setAdapter(e)}},aa=T.createContext(null),oa=()=>T.useContext(aa),ca=t=>{const[e]=T.useState(()=>new ia(t));T.useEffect(()=>{e.setAdapter(t)});const{modelContext:s}=oa()??{};return T.useEffect(()=>{if(s)return e.registerModelContextProvider(s)},[s,e]),T.useMemo(()=>new ua(e),[e])},ua=class{constructor(t){h(this,"threads");h(this,"_thread");this._core=t,this.threads=new Ki(t.threads),this._thread=this.threads.main}get threadList(){return this.threads}__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(Ii.fromArray(t??[]))}};function da(t){return t.filter(e=>{var s;return e.finishReason==="stop"?e.text!==null&&((s=e.text)==null?void 0:s.trim())!=="":!0})}function la(t){const e=[];let s=null;for(const r of t)r.type==="reasoning"?(s!=null&&(e.push(s),s=null),e.push(r)):r.functionCalls?(s&&e.push(s),e.push(r),s=null):r.functionResponse?e[e.length-1]={...e[e.length-1],functionResponse:r.functionResponse}:s&&r.protocol===s.protocol&&(s.role===r.role||r.finishReason==="stop")?s.text+=r.text:(s&&e.push(s),s={...r});return s&&e.push(s),da(e)}function ha(t){var e;return t.role==="function"?{id:t.id,role:"assistant",status:(t==null?void 0:t.functionResponse)===null?{type:"running"}:{type:"complete",reason:"stop"},content:((e=t.functionCalls)==null?void 0:e.map(s=>{var r;return{type:"tool-call",toolName:s.name,toolCallId:s.id,args:s.args,result:(r=t.functionResponse)==null?void 0:r.result}}))??[]}:{id:t.id,role:t.role,content:t.type==="reasoning"?[{type:"reasoning",text:t.text}]:[{type:"text",text:t.text}]}}class Et{constructor(){h(this,"statusChangeCallbacks",[]);h(this,"messageCallbacks",[])}addStatusChangeListener(e){this.statusChangeCallbacks.push(e)}addMessageListener(e){this.messageCallbacks.push(e)}async syncSession(e){this.session=e}async notifyMessage(e){this.messageCallbacks.forEach(s=>s(e))}async notifyMessages(e){e.forEach(s=>{this.messageCallbacks.forEach(r=>r(s))})}async setSession(e){this.session=e}async setStatus(e){const s=this.status!==e;this.status=e,s&&this.statusChangeCallbacks.forEach(r=>r(e))}clearListeners(){this.statusChangeCallbacks=[],this.messageCallbacks=[]}}class Lt extends Et{constructor(s){super();h(this,"status");h(this,"autostart");h(this,"session");h(this,"config");h(this,"notify",!0);this.config=s,this.status="disconnected",this.autostart=!0}getName(){return"rest"}getPriority(){return 0}async connect(s){return this.setStatus("connected"),s}async disconnect(){this.setStatus("disconnected"),this.session=null}async syncSession(s){this.session=s}async send(s){const{apiUrl:r,apiKey:n,agentId:i}=this.config,o=this.session??"new",c=s,u=await(await fetch(`${r}/agents/${i}/sessions/${o}/messages`,{body:JSON.stringify({userMessage:c}),method:"POST",headers:{"Content-Type":"application/json","x-fox-apikey":n,"x-persona-apikey":n}})).json();this.notifyMessages(u.response.messages)}}class Ft extends Et{constructor(s){super();h(this,"status");h(this,"autostart");h(this,"session");h(this,"config");h(this,"webSocket");this.config=s,this.status="disconnected",this.autostart=!0,this.session=null,this.webSocket=null}getName(){return"websocket"}getPriority(){return 1}async syncSession(s){var r;(r=this.config.logger)==null||r.debug("Syncing session with WebSocket protocol:",s),this.session=s,this.webSocket&&this.status==="connected"&&(this.disconnect(),this.connect(s))}connect(s){var c;if(this.webSocket!==null&&this.status==="connected")return Promise.resolve(this.session);const r=s||this.session||"new";(c=this.config.logger)==null||c.debug("Connecting to WebSocket with sessionId:",r);const n=encodeURIComponent(this.config.apiKey),i=this.config.agentId,o=`${this.config.webSocketUrl}?sessionCode=${r}&agentId=${i}&apiKey=${n}`;return this.setStatus("connecting"),this.webSocket=new WebSocket(o),this.webSocket.addEventListener("open",()=>{this.setStatus("connected")}),this.webSocket.addEventListener("message",d=>{const u=JSON.parse(d.data);if(u.type!=="message")return;const l=u.payload;this.notifyMessage(l!=null&&l.thought?{role:"assistant",type:"reasoning",text:l.thought}:l)}),this.webSocket.addEventListener("close",()=>{var d;this.setStatus("disconnected"),this.webSocket=null,(d=this.config.logger)==null||d.warn("WebSocket connection closed")}),this.webSocket.addEventListener("error",d=>{var u;this.setStatus("disconnected"),this.webSocket=null,(u=this.config.logger)==null||u.error("WebSocket error",d)}),Promise.resolve(r)}disconnect(){var s;return(s=this.config.logger)==null||s.debug("Disconnecting WebSocket"),this.webSocket&&this.status==="connected"&&(this.webSocket.close(),this.setStatus("disconnected"),this.webSocket=null),Promise.resolve()}send(s){return this.webSocket&&this.status==="connected"?(this.webSocket.send(JSON.stringify({type:"request",payload:s})),Promise.resolve()):Promise.reject(new Error("WebSocket is not connected"))}}class fa{constructor(e){h(this,"config");h(this,"pc",null);h(this,"ws",null);h(this,"localStream",null);h(this,"remoteStream",new MediaStream);h(this,"audioCtx",null);h(this,"localAnalyser",null);h(this,"remoteAnalyser",null);h(this,"analyzerFrame",null);h(this,"dataChannel",null);h(this,"isConnected",!1);h(this,"visualizerCallbacks",[]);h(this,"messageCallbacks",[]);this.config=e}async connect(e){var s;if(!this.isConnected){this.isConnected=!0;try{this.localStream=await navigator.mediaDevices.getUserMedia({audio:!0})}catch(r){(s=this.config.logger)==null||s.error("Error accessing microphone:",r);return}this.pc=new RTCPeerConnection({iceServers:this.config.iceServers||[{urls:"stun:34.38.108.251:3478"},{urls:"turn:34.38.108.251:3478",username:"webrtc",credential:"webrtc"}]}),this.localStream.getTracks().forEach(r=>{this.pc.addTrack(r,this.localStream)}),this.pc.ontrack=r=>{r.streams[0].getTracks().forEach(i=>{this.remoteStream.addTrack(i)}),this.audioCtx||this._startAnalyzers();const n=new Audio;n.srcObject=this.remoteStream,n.play().catch(i=>{var o;(o=this.config.logger)==null||o.error("Error playing remote audio:",i)})},this.pc.onicecandidate=r=>{var n;r.candidate&&((n=this.ws)==null?void 0:n.readyState)===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"CANDIDATE",src:"client",payload:{candidate:r.candidate}}))},this.pc.ondatachannel=r=>{const n=r.channel;n.onmessage=i=>{this.messageCallbacks.forEach(o=>{o(i)})}},this.ws=new WebSocket(this.config.webrtcUrl||"wss://persona.applica.guru/api/webrtc"),this.ws.onopen=async()=>{var o,c;const r=await this.pc.createOffer();await this.pc.setLocalDescription(r);const n={agentId:this.config.agentId,sessionCode:e};(o=this.config.logger)==null||o.debug("Opening connection to WebRTC server: ",n);const i={type:"OFFER",src:((c=crypto.randomUUID)==null?void 0:c.call(crypto))||"client_"+Date.now(),payload:{sdp:{sdp:r.sdp,type:r.type},connectionId:(Date.now()%1e6).toString(),metadata:n}};this.ws.send(JSON.stringify(i))},this.ws.onmessage=async r=>{var i;const n=JSON.parse(r.data);if(n.type==="ANSWER")await this.pc.setRemoteDescription(new RTCSessionDescription(n.payload.sdp));else if(n.type==="CANDIDATE")try{await this.pc.addIceCandidate(new RTCIceCandidate(n.payload.candidate))}catch(o){(i=this.config.logger)==null||i.error("Error adding ICE candidate:",o)}},this.ws.onclose=()=>{this._stopAnalyzers()}}}async disconnect(){var e;this.isConnected&&(this.isConnected=!1,((e=this.ws)==null?void 0:e.readyState)===WebSocket.OPEN&&this.ws.close(),this.pc&&this.pc.close(),this.localStream&&this.localStream.getTracks().forEach(s=>s.stop()),this.remoteStream=new MediaStream,this.audioCtx&&(await this.audioCtx.close(),this.audioCtx=null),this._stopAnalyzers())}addVisualizerCallback(e){this.visualizerCallbacks.push(e)}addMessageCallback(e){this.messageCallbacks.push(e)}createDataChannel(e="messages"){this.pc&&(this.dataChannel=this.pc.createDataChannel(e),this.dataChannel.onopen=()=>{var s;return(s=this.config.logger)==null?void 0:s.info("Data channel opened")},this.dataChannel.onmessage=s=>{this.messageCallbacks.forEach(r=>{r(s)})})}sendMessage(e){var s,r;if(!this.dataChannel){(s=this.config.logger)==null||s.warn("Data channel is not open, cannot send message");return}this.dataChannel.send(e),(r=this.config.logger)==null||r.info("Sent message:",e)}_startAnalyzers(){if(!this.localStream||!this.remoteStream||this.visualizerCallbacks.length===0)return;this.audioCtx=new(window.AudioContext||window.webkitAudioContext);const e=this.audioCtx.createMediaStreamSource(this.localStream),s=this.audioCtx.createMediaStreamSource(this.remoteStream);this.localAnalyser=this.audioCtx.createAnalyser(),this.remoteAnalyser=this.audioCtx.createAnalyser(),this.localAnalyser.fftSize=256,this.remoteAnalyser.fftSize=256,e.connect(this.localAnalyser),s.connect(this.remoteAnalyser);const r=()=>{if(!this.localAnalyser||!this.remoteAnalyser||this.visualizerCallbacks.length===0)return;const n=new Uint8Array(this.localAnalyser.frequencyBinCount),i=new Uint8Array(this.remoteAnalyser.frequencyBinCount);this.localAnalyser.getByteFrequencyData(n),this.remoteAnalyser.getByteFrequencyData(i);const o=n.reduce((d,u)=>d+u,0)/n.length,c=i.reduce((d,u)=>d+u,0)/i.length;this.visualizerCallbacks.length>0&&this.visualizerCallbacks.forEach(d=>{d({localAmplitude:o,remoteAmplitude:c})}),this.analyzerFrame=requestAnimationFrame(r)};this.analyzerFrame=requestAnimationFrame(r)}_stopAnalyzers(){this.analyzerFrame&&(cancelAnimationFrame(this.analyzerFrame),this.analyzerFrame=null),this.localAnalyser=null,this.remoteAnalyser=null}}class Vt extends Et{constructor(s){super();h(this,"status");h(this,"session");h(this,"autostart");h(this,"config");h(this,"webRTCClient");this.config=s,this.status="disconnected",this.session=null,this.autostart=(s==null?void 0:s.autostart)??!1,this.webRTCClient=new fa(s),this.webRTCClient.addMessageCallback(r=>{var i;(i=s.logger)==null||i.debug("Received data message:",r.data);const n=JSON.parse(r.data);n.type==="message"&&this.notifyMessage(n.payload)})}getName(){return"webrtc"}getPriority(){return 10}async syncSession(s){super.syncSession(s),this.status==="connected"&&(await this.disconnect(),await this.connect(s))}async connect(s){var r;return this.status==="connected"?Promise.resolve(this.session):(this.session=s||this.session||"new",this.setStatus("connecting"),(r=this.config.logger)==null||r.debug("Connecting to WebRTC with sessionId:",this.session),await this.webRTCClient.connect(this.session),this.setStatus("connected"),await this.webRTCClient.createDataChannel(),this.session)}async disconnect(){var s,r,n;if(this.status==="disconnected")return(s=this.config.logger)==null||s.warn("Already disconnected"),Promise.resolve();await this.webRTCClient.disconnect(),this.setStatus("disconnected"),(n=(r=this.config)==null?void 0:r.logger)==null||n.debug("Disconnected from WebRTC")}send(s){return this.status!=="connected"?Promise.reject(new Error("Not connected")):(this.webRTCClient.sendMessage(s),Promise.resolve())}}const Yt=T.createContext(void 0);function pa({dev:t=!1,protocols:e,logger:s,children:r,session:n="new",...i}){const[o,c]=T.useState(!1),[d,u]=T.useState([]),[l,g]=T.useState(n),[I,N]=T.useState(new Map),fe=T.useRef(!1),ee=T.useMemo(()=>{if(Array.isArray(e))return e;if(typeof e=="object"&&e!==null){const P=t?"localhost:8000":"persona.applica.guru/api",J=t?"http":"https",te=t?"ws":"wss";return Object.keys(e).map(V=>{switch(V){case"rest":const pe=e[V];return pe===!0?new Lt({apiUrl:`${J}://${P}`,apiKey:i.apiKey,agentId:i.agentId,logger:s}):new Lt(pe);case"webrtc":const nt=e[V];return nt===!0?new Vt({webrtcUrl:`${te}://${P}/webrtc`,apiKey:i.apiKey,agentId:i.agentId,logger:s}):new Vt(nt);case"websocket":const it=e[V];return it===!0?new Ft({webSocketUrl:`${te}://${P}/websocket`,apiKey:i.apiKey,agentId:i.agentId,logger:s}):new Ft(it);default:throw new Error(`Unknown protocol: ${V}`)}})}throw new Error("Invalid protocols configuration")},[]);T.useEffect(()=>{fe.current||(fe.current=!0,s==null||s.debug("Initializing protocols: ",ee.map(P=>P.getName())),ee.forEach(P=>{P.setSession(l),P.clearListeners(),P.addStatusChangeListener(J=>{s==null||s.debug(`${P.getName()} has notified new status: ${J}`),I.set(P.getName(),J),N(new Map(I))}),P.addMessageListener(J=>{u(te=>la([...te,{...J,protocol:P.getName()}]))}),P.autostart&&P.status==="disconnected"&&(s==null||s.debug(`Connecting to protocol: ${P.getName()}`),P.connect(l))}))},[l,ee,s,I]);const Pe=async P=>{var Ne;if(((Ne=P.content[0])==null?void 0:Ne.type)!=="text")throw new Error("Only text messages are supported");const J=P.content[0].text;u(V=>[...V,{role:"user",type:"text",text:J}]),c(!0);const te=ee.sort((V,pe)=>pe.getPriority()-V.getPriority()).find(V=>V.status==="connected");await(te==null?void 0:te.send(J)),c(!1)},Y=T.useCallback(()=>(c(!1),u([]),g("new"),Promise.resolve()),[]),D=T.useCallback(()=>Promise.resolve(),[]),kt=ca({isRunning:o,messages:d,convertMessage:ha,onNew:Pe,onCancel:Y,onReload:D});return H.jsx(Yt.Provider,{value:{protocols:ee,protocolsStatus:I},children:H.jsx(ki,{runtime:kt,children:r})})}function ga({children:t,...e}){return H.jsx(pa,{...e,children:t})}function ma(){const t=T.useContext(Yt);if(!t)throw new Error("usePersonaRuntime must be used within a PersonaRuntimeProvider");return t}function nr(t){const e=T.useContext(Yt);if(!e)throw new Error("usePersonaRuntimeProtocol must be used within a PersonaRuntimeProvider");const s=e.protocols.find(n=>n.getName()===t);if(!s)return null;const r=e.protocolsStatus.get(s.getName());return{...s,connect:s.connect.bind(s),disconnect:s.disconnect.bind(s),send:s.send.bind(s),setSession:s.setSession.bind(s),addStatusChangeListener:s.addStatusChangeListener.bind(s),addMessageListener:s.addMessageListener.bind(s),getName:s.getName.bind(s),getPriority:s.getPriority.bind(s),status:r||s.status}}function _a(){return nr("webrtc")}class ba{constructor(){h(this,"prefix","[Persona]")}log(e,...s){console.log(`${this.prefix} - ${e}`,...s)}info(e,...s){console.info(`${this.prefix} - ${e}`,...s)}warn(e,...s){console.warn(`${this.prefix} - ${e}`,...s)}error(e,...s){console.error(`${this.prefix} - ${e}`,...s)}debug(e,...s){console.debug(`${this.prefix} - ${e}`,...s)}}exports.PersonaConsoleLogger=ba;exports.PersonaProtocolBase=Et;exports.PersonaRESTProtocol=Lt;exports.PersonaRuntimeProvider=ga;exports.PersonaWebRTCProtocol=Vt;exports.PersonaWebSocketProtocol=Ft;exports.usePersonaRuntime=ma;exports.usePersonaRuntimeProtocol=nr;exports.usePersonaRuntimeWebRTCProtocol=_a;
18
+ `),ps=class{constructor(t){this._core=t}get path(){return this._core.path}__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)}},gs=class extends ps{constructor(t,e){super(t),this._composerApi=e}remove(){const t=this._composerApi.getState();if(!t)throw new Error("Composer is not available");return t.removeAttachment(this.getState().id)}},kn=class extends gs{get source(){return"thread-composer"}},En=class extends gs{get source(){return"edit-composer"}},Cn=class extends ps{get source(){return"message"}constructor(t){super(t)}remove(){throw new Error("Message attachments cannot be removed")}},ms=class extends ot{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 e=this.config.binding.getState(),s=e==null?void 0:e.unstable_on(this.config.event,t);const r=()=>{var a;const i=this.config.binding.getState();i!==e&&(e=i,s==null||s(),s=(a=this.config.binding.getState())==null?void 0:a.unstable_on(this.config.event,t))},n=this.outerSubscribe(r);return()=>{n==null||n(),s==null||s()}}},_s=Object.freeze([]),bs=Object.freeze({}),In=t=>Object.freeze({type:"thread",isEditing:(t==null?void 0:t.isEditing)??!1,canCancel:(t==null?void 0:t.canCancel)??!1,isEmpty:(t==null?void 0:t.isEmpty)??!0,attachments:(t==null?void 0:t.attachments)??_s,text:(t==null?void 0:t.text)??"",role:(t==null?void 0:t.role)??"user",runConfig:(t==null?void 0:t.runConfig)??bs,value:(t==null?void 0:t.text)??""}),Rn=t=>Object.freeze({type:"edit",isEditing:(t==null?void 0:t.isEditing)??!1,canCancel:(t==null?void 0:t.canCancel)??!1,isEmpty:(t==null?void 0:t.isEmpty)??!0,text:(t==null?void 0:t.text)??"",role:(t==null?void 0:t.role)??"user",attachments:(t==null?void 0:t.attachments)??_s,runConfig:(t==null?void 0:t.runConfig)??bs,value:(t==null?void 0:t.text)??""}),ys=class{constructor(t){h(this,"_eventSubscriptionSubjects",new Map);this._core=t}get path(){return this._core.path}__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.getAttachmentAccept=this.getAttachmentAccept.bind(this),this.getAttachmentByIndex=this.getAttachmentByIndex.bind(this),this.unstable_on=this.unstable_on.bind(this)}setText(t){const e=this._core.getState();if(!e)throw new Error("Composer is not available");e.setText(t)}setRunConfig(t){const e=this._core.getState();if(!e)throw new Error("Composer is not available");e.setRunConfig(t)}addAttachment(t){const e=this._core.getState();if(!e)throw new Error("Composer is not available");return e.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 e=this._core.getState();if(!e)throw new Error("Composer is not available");e.setRole(t)}subscribe(t){return this._core.subscribe(t)}unstable_on(t,e){let s=this._eventSubscriptionSubjects.get(t);return s||(s=new ms({event:t,binding:this._core}),this._eventSubscriptionSubjects.set(t,s)),s.subscribe(e)}getAttachmentAccept(){const t=this._core.getState();if(!t)throw new Error("Composer is not available");return t.getAttachmentAccept()}},An=class extends ys{constructor(e){const s=new kt({path:e.path,getState:()=>In(e.getState()),subscribe:r=>e.subscribe(r)});super({path:e.path,getState:()=>e.getState(),subscribe:r=>s.subscribe(r)});h(this,"_getState");this._getState=s.getState.bind(s)}get path(){return this._core.path}get type(){return"thread"}getState(){return this._getState()}getAttachmentByIndex(e){return new kn(new $({path:{...this.path,attachmentSource:"thread-composer",attachmentSelector:{type:"index",index:e},ref:this.path.ref+`${this.path.ref}.attachments[${e}]`},getState:()=>{const r=this.getState().attachments[e];return r?{...r,source:"thread-composer"}:V},subscribe:s=>this._core.subscribe(s)}),this._core)}},On=class extends ys{constructor(e,s){const r=new kt({path:e.path,getState:()=>Rn(e.getState()),subscribe:n=>e.subscribe(n)});super({path:e.path,getState:()=>e.getState(),subscribe:n=>r.subscribe(n)});h(this,"_getState");this._beginEdit=s,this._getState=r.getState.bind(r)}get path(){return this._core.path}get type(){return"edit"}__internal_bindMethods(){super.__internal_bindMethods(),this.beginEdit=this.beginEdit.bind(this)}getState(){return this._getState()}beginEdit(){this._beginEdit()}getAttachmentByIndex(e){return new En(new $({path:{...this.path,attachmentSource:"edit-composer",attachmentSelector:{type:"index",index:e},ref:this.path.ref+`${this.path.ref}.attachments[${e}]`},getState:()=>{const r=this.getState().attachments[e];return r?{...r,source:"edit-composer"}:V},subscribe:s=>this._core.subscribe(s)}),this._core)}},nt=class extends ot{constructor(t){super(),this.binding=t}get path(){return this.binding.path}getState(){return this.binding.getState()}outerSubscribe(t){return this.binding.subscribe(t)}_connect(){const t=()=>{this.notifySubscribers()};let e=this.binding.getState(),s=e==null?void 0:e.subscribe(t);const r=()=>{var a;const i=this.binding.getState();i!==e&&(e=i,s==null||s(),s=(a=this.binding.getState())==null?void 0:a.subscribe(t),t())},n=this.outerSubscribe(r);return()=>{n==null||n(),s==null||s()}}},qe=Object.freeze({type:"complete"}),Mn=(t,e,s)=>{if(t.role!=="assistant")return qe;if(s.type==="tool-call")return s.result?qe:t.status;const r=e===Math.max(0,t.content.length-1);return t.status.type==="requires-action"?qe:r?t.status:qe},Ut=(t,e)=>{const s=t.content[e];if(!s)return V;const r=Mn(t,e,s);return Object.freeze({...s,[Se]:s[Se],status:r})},Nn=class{constructor(t,e){h(this,"composer");h(this,"_getEditComposerRuntimeCore",()=>this._threadBinding.getState().getEditComposer(this._core.getState().id));this._core=t,this._threadBinding=e,this.composer=new On(new nt({path:{...this.path,ref:this.path.ref+`${this.path.ref}.composer`,composerSource:"edit"},getState:this._getEditComposerRuntimeCore,subscribe:s=>this._threadBinding.subscribe(s)}),()=>this._threadBinding.getState().beginEdit(this._core.getState().id))}get path(){return this._core.path}__internal_bindMethods(){this.reload=this.reload.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.getContentPartByIndex=this.getContentPartByIndex.bind(this),this.getContentPartByToolCallId=this.getContentPartByToolCallId.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)}getState(){return this._core.getState()}reload(t={}){const e=this._getEditComposerRuntimeCore(),s=e??this._threadBinding.getState().composer,r=e??s,{runConfig:n=r.runConfig}=t,i=this._core.getState();if(i.role!=="assistant")throw new Error("Can only reload assistant messages");this._threadBinding.getState().startRun({parentId:i.parentId,sourceId:i.id,runConfig:n})}speak(){const t=this._core.getState();return this._threadBinding.getState().speak(t.id)}stopSpeaking(){var s;const t=this._core.getState();if(((s=this._threadBinding.getState().speech)==null?void 0:s.messageId)===t.id)this._threadBinding.getState().stopSpeaking();else throw new Error("Message is not being spoken")}submitFeedback({type:t}){const e=this._core.getState();this._threadBinding.getState().submitFeedback({messageId:e.id,type:t})}switchToBranch({position:t,branchId:e}){const s=this._core.getState();if(e&&t)throw new Error("May not specify both branchId and position");if(!e&&!t)throw new Error("Must specify either branchId or position");const n=this._threadBinding.getState().getBranches(s.id);let i=e;if(t==="previous"?i=n[s.branchNumber-2]:t==="next"&&(i=n[s.branchNumber]),!i)throw new Error("Branch not found");this._threadBinding.getState().switchToBranch(i)}unstable_getCopyText(){return Ue(this.getState())}subscribe(t){return this._core.subscribe(t)}getContentPartByIndex(t){if(t<0)throw new Error("Content part index must be >= 0");return new zt(new $({path:{...this.path,ref:this.path.ref+`${this.path.ref}.content[${t}]`,contentPartSelector:{type:"index",index:t}},getState:()=>Ut(this.getState(),t),subscribe:e=>this._core.subscribe(e)}),this._core,this._threadBinding)}getContentPartByToolCallId(t){return new zt(new $({path:{...this.path,ref:this.path.ref+`${this.path.ref}.content[toolCallId=${JSON.stringify(t)}]`,contentPartSelector:{type:"toolCallId",toolCallId:t}},getState:()=>{const e=this._core.getState(),s=e.content.findIndex(r=>r.type==="tool-call"&&r.toolCallId===t);return s===-1?V:Ut(e,s)},subscribe:e=>this._core.subscribe(e)}),this._core,this._threadBinding)}getAttachmentByIndex(t){return new Cn(new $({path:{...this.path,ref:this.path.ref+`${this.path.ref}.attachments[${t}]`,attachmentSource:"message",attachmentSelector:{type:"index",index:t}},getState:()=>{const e=this.getState().attachments,s=e==null?void 0:e[t];return s?{...s,source:"message"}:V},subscribe:e=>this._core.subscribe(e)}))}},Pn=t=>({parentId:t.parentId??null,sourceId:t.sourceId??null,runConfig:t.runConfig??{},stream:t.stream}),jn=t=>({parentId:t.parentId??null,sourceId:t.sourceId??null,runConfig:t.runConfig??{}}),Bn=(t,e)=>{var s,r;return typeof e=="string"?{parentId:((s=t.at(-1))==null?void 0:s.id)??null,sourceId:null,runConfig:{},role:"user",content:[{type:"text",text:e}],attachments:[]}:e.role&&e.parentId&&e.attachments?e:{...e,parentId:e.parentId??((r=t.at(-1))==null?void 0:r.id)??null,sourceId:e.sourceId??null,role:e.role??"user",attachments:e.attachments??[]}},Dn=(t,e)=>{const s=t.messages.at(-1);return Object.freeze({threadId:e.id,metadata:e,capabilities:t.capabilities,isDisabled:t.isDisabled,isRunning:(s==null?void 0:s.role)!=="assistant"?!1:s.status.type==="running",messages:t.messages,suggestions:t.suggestions,extras:t.extras,speech:t.speech})},Zn=class{constructor(t,e){h(this,"_threadBinding");h(this,"composer");h(this,"_eventSubscriptionSubjects",new Map);const s=new $({path:t.path,getState:()=>Dn(t.getState(),e.getState()),subscribe:r=>{const n=t.subscribe(r),i=e.subscribe(r);return()=>{n(),i()}}});this._threadBinding={path:t.path,getState:()=>t.getState(),getStateState:()=>s.getState(),outerSubscribe:r=>t.outerSubscribe(r),subscribe:r=>t.subscribe(r)},this.composer=new An(new nt({path:{...this.path,ref:this.path.ref+`${this.path.ref}.composer`,composerSource:"thread"},getState:()=>this._threadBinding.getState().composer,subscribe:r=>this._threadBinding.subscribe(r)}))}get path(){return this._threadBinding.path}get __internal_threadBinding(){return this._threadBinding}__internal_bindMethods(){this.append=this.append.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.getMesssageByIndex=this.getMesssageByIndex.bind(this),this.getMesssageById=this.getMesssageById.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)}getState(){return this._threadBinding.getStateState()}append(t){this._threadBinding.getState().append(Bn(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 e=t===null||typeof t=="string"?{parentId:t}:t;return this._threadBinding.getState().startRun(jn(e))}unstable_resumeRun(t){return this._threadBinding.getState().resumeRun(Pn(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)}getMesssageByIndex(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}},()=>{var r;const e=this._threadBinding.getState().messages,s=e[t];if(s)return{message:s,parentId:((r=e[t-1])==null?void 0:r.id)??null}})}getMesssageById(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,e){return new Nn(new $({path:t,getState:()=>{var c;const{message:s,parentId:r}=e()??{},{messages:n,speech:i}=this._threadBinding.getState();if(!s||r===void 0)return V;const a=this._threadBinding.getState(),o=a.getBranches(s.id),d=a.getSubmittedFeedback(s.id);return{...s,[Se]:s[Se],isLast:((c=n.at(-1))==null?void 0:c.id)===s.id,parentId:r,branchNumber:o.indexOf(s.id)+1,branchCount:o.length,speech:(i==null?void 0:i.messageId)===s.id?i:void 0,submittedFeedback:d}},subscribe:s=>this._threadBinding.subscribe(s)}),this._threadBinding)}unstable_on(t,e){let s=this._eventSubscriptionSubjects.get(t);return s||(s=new ms({event:t,binding:this._threadBinding}),this._eventSubscriptionSubjects.set(t,s)),s.subscribe(e)}},Ln=t=>({mainThreadId:t.mainThreadId,newThread:t.newThreadId,threads:t.threadIds,archivedThreads:t.archivedThreadIds}),He=(t,e)=>{if(e===void 0)return V;const s=t.getItemById(e);return s?{id:s.threadId,threadId:s.threadId,remoteId:s.remoteId,externalId:s.externalId,title:s.title,status:s.status,isMain:s.threadId===t.mainThreadId}:V},$n=class{constructor(t,e=Zn){h(this,"_getState");h(this,"_mainThreadListItemRuntime");h(this,"main");this._core=t,this._runtimeFactory=e;const s=new kt({path:{},getState:()=>Ln(t),subscribe:r=>t.subscribe(r)});this._getState=s.getState.bind(s),this._mainThreadListItemRuntime=new Je(new $({path:{ref:"threadItems[main]",threadSelector:{type:"main"}},getState:()=>He(this._core,this._core.mainThreadId),subscribe:r=>this._core.subscribe(r)}),this._core),this.main=new e(new nt({path:{ref:"threads.main",threadSelector:{type:"main"}},getState:()=>t.getMainThreadRuntimeCore(),subscribe:r=>t.subscribe(r)}),this._mainThreadListItemRuntime)}__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)}get mainItem(){return this._mainThreadListItemRuntime}getById(t){return new this._runtimeFactory(new nt({path:{ref:"threads[threadId="+JSON.stringify(t)+"]",threadSelector:{type:"threadId",threadId:t}},getState:()=>this._core.getThreadRuntimeCore(t),subscribe:e=>this._core.subscribe(e)}),this.mainItem)}getItemByIndex(t){return new Je(new $({path:{ref:`threadItems[${t}]`,threadSelector:{type:"index",index:t}},getState:()=>He(this._core,this._core.threadIds[t]),subscribe:e=>this._core.subscribe(e)}),this._core)}getArchivedItemByIndex(t){return new Je(new $({path:{ref:`archivedThreadItems[${t}]`,threadSelector:{type:"archiveIndex",index:t}},getState:()=>He(this._core,this._core.archivedThreadIds[t]),subscribe:e=>this._core.subscribe(e)}),this._core)}getItemById(t){return new Je(new $({path:{ref:`threadItems[threadId=${t}]`,threadSelector:{type:"threadId",threadId:t}},getState:()=>He(this._core,t),subscribe:e=>this._core.subscribe(e)}),this._core)}},ne=Object.freeze([]),me="DEFAULT_THREAD_ID",Fn=Object.freeze([me]),zn=Object.freeze({threadId:me,status:"regular"}),Un=Promise.resolve(),Vn=class{constructor(t={},e){h(this,"_mainThreadId",me);h(this,"_threads",Fn);h(this,"_archivedThreads",ne);h(this,"_mainThread");h(this,"_subscriptions",new Set);this.adapter=t,this.threadFactory=e,this._mainThread=this.threadFactory()}get newThreadId(){}get threadIds(){return this._threads}get archivedThreadIds(){return this._archivedThreads}getLoadThreadsPromise(){return Un}get mainThreadId(){return this._mainThreadId}getMainThreadRuntimeCore(){return this._mainThread}getThreadRuntimeCore(){throw new Error("Method not implemented.")}getItemById(t){for(const e of this.adapter.threads??[])if(e.threadId===t)return e;for(const e of this.adapter.archivedThreads??[])if(e.threadId===t)return e;if(t===me)return zn}__internal_setAdapter(t){var d,c;const e=this.adapter;this.adapter=t;const s=t.threadId??me,r=t.threads??ne,n=t.archivedThreads??ne,i=e.threadId??me,a=e.threads??ne,o=e.archivedThreads??ne;i===s&&a===r&&o===n||(a!==r&&(this._threads=((d=this.adapter.threads)==null?void 0:d.map(u=>u.threadId))??ne),o!==n&&(this._archivedThreads=((c=this.adapter.archivedThreads)==null?void 0:c.map(u=>u.threadId))??ne),i!==s&&(this._mainThreadId=s,this._mainThread=this.threadFactory()),this._notifySubscribers())}async switchToThread(t){if(this._mainThreadId===t)return;const e=this.adapter.onSwitchToThread;if(!e)throw new Error("External store adapter does not support switching to thread");e(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,e){const s=this.adapter.onRename;if(!s)throw new Error("External store adapter does not support renaming");s(t,e)}async archive(t){const e=this.adapter.onArchive;if(!e)throw new Error("External store adapter does not support archiving");e(t)}async unarchive(t){const e=this.adapter.onUnarchive;if(!e)throw new Error("External store adapter does not support unarchiving");e(t)}async delete(t){const e=this.adapter.onDelete;if(!e)throw new Error("External store adapter does not support deleting");e(t)}initialize(){throw new Error("Method not implemented.")}generateTitle(){throw new Error("Method not implemented.")}subscribe(t){return this._subscriptions.add(t),()=>this._subscriptions.delete(t)}_notifySubscribers(){for(const t of this._subscriptions)t()}},Vt=class{constructor(){h(this,"cache",new WeakMap)}convertMessages(t,e){return t.map((s,r)=>{const n=this.cache.get(s),i=e(n,s,r);return this.cache.set(s,i),i})}},Wn=class extends rs{constructor(e,s,{parentId:r,message:n}){super();h(this,"_nonTextParts");h(this,"_previousText");h(this,"_parentId");h(this,"_sourceId");this.runtime=e,this.endEditCallback=s,this._parentId=r,this._sourceId=n.id,this._previousText=Ue(n),this.setText(this._previousText),this.setRole(n.role),this.setAttachments(n.attachments??[]),this._nonTextParts=n.content.filter(i=>i.type!=="text"),this.setRunConfig({...e.composer.runConfig})}get canCancel(){return!0}getAttachmentAdapter(){var e;return(e=this.runtime.adapters)==null?void 0:e.attachments}async handleSend(e){Ue(e)!==this._previousText&&this.runtime.append({...e,content:[...e.content,...this._nonTextParts],parentId:this._parentId,sourceId:this._sourceId}),this.handleCancel()}handleCancel(){this.endEditCallback(),this._notifySubscribers()}},Yn=class{constructor(t){h(this,"_subscriptions",new Set);h(this,"_isInitialized",!1);h(this,"repository",new wn);h(this,"composer",new $r(this));h(this,"_editComposers",new Map);h(this,"_submittedFeedback",{});h(this,"_stopSpeaking");h(this,"speech");h(this,"_eventSubscribers",new Map);this._contextProvider=t}get messages(){return this.repository.getMessages()}getModelContext(){return this._contextProvider.getModelContext()}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 Wn(this,()=>this._editComposers.delete(t),this.repository.getMessage(t))),this._notifySubscribers()}getMessageById(t){return this.repository.getMessage(t)}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 e=this._eventSubscribers.get(t);if(e)for(const s of e)s()}subscribe(t){return this._subscriptions.add(t),()=>this._subscriptions.delete(t)}getSubmittedFeedback(t){return this._submittedFeedback[t]}submitFeedback({messageId:t,type:e}){var n;const s=(n=this.adapters)==null?void 0:n.feedback;if(!s)throw new Error("Feedback adapter not configured");const{message:r}=this.repository.getMessage(t);s.submit({message:r,type:e}),this._submittedFeedback[t]={type:e},this._notifySubscribers()}speak(t){var i,a;const e=(i=this.adapters)==null?void 0:i.speech;if(!e)throw new Error("Speech adapter not configured");const{message:s}=this.repository.getMessage(t);(a=this._stopSpeaking)==null||a.call(this);const r=e.speak(Ue(s)),n=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(),n(),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()}unstable_on(t,e){var r,n;if(t==="model-context-update")return((n=(r=this._contextProvider).subscribe)==null?void 0:n.call(r,e))??(()=>{});const s=this._eventSubscribers.get(t);return s?s.add(e):this._eventSubscribers.set(t,new Set([e])),()=>{this._eventSubscribers.get(t).delete(e)}}},Jn=Object.freeze([]),qn=(t,e)=>{var s;return t&&((s=e[e.length-1])==null?void 0:s.role)!=="assistant"},Hn=class extends Yn{constructor(e,s){super(e);h(this,"assistantOptimisticId",null);h(this,"_capabilities",{switchToBranch:!1,edit:!1,reload:!1,cancel:!1,unstable_copy:!1,speech:!1,attachments:!1,feedback:!1});h(this,"_messages");h(this,"isDisabled");h(this,"suggestions",[]);h(this,"extras");h(this,"_converter",new Vt);h(this,"_store");h(this,"updateMessages",e=>{var r,n,i,a;this._store.convertMessage!==void 0?(n=(r=this._store).setMessages)==null||n.call(r,e.flatMap(Tn).filter(o=>o!=null)):(a=(i=this._store).setMessages)==null||a.call(i,e)});this.__internal_setAdapter(s)}get capabilities(){return this._capabilities}get messages(){return this._messages}get adapters(){return this._store.adapters}beginEdit(e){if(!this._store.onEdit)throw new Error("Runtime does not support editing.");super.beginEdit(e)}__internal_setAdapter(e){var i,a,o,d,c,u;if(this._store===e)return;const s=e.isRunning??!1;this.isDisabled=e.isDisabled??!1;const r=this._store;if(this._store=e,this.extras=e.extras,this.suggestions=e.suggestions??Jn,this._capabilities={switchToBranch:this._store.setMessages!==void 0,edit:this._store.onEdit!==void 0,reload:this._store.onReload!==void 0,cancel:this._store.onCancel!==void 0,speech:((i=this._store.adapters)==null?void 0:i.speech)!==void 0,unstable_copy:((a=this._store.unstable_capabilities)==null?void 0:a.copy)!==!1,attachments:!!((o=this._store.adapters)!=null&&o.attachments),feedback:!!((d=this._store.adapters)!=null&&d.feedback)},r){if(r.convertMessage!==e.convertMessage)this._converter=new Vt;else if(r.isRunning===e.isRunning&&r.messages===e.messages){this._notifySubscribers();return}}const n=e.convertMessage?this._converter.convertMessages(e.messages,(g,k,I)=>{if(!e.convertMessage)return k;const de=I===e.messages.length-1,D=as(de,s);if(g&&(g.role!=="assistant"||!Wr(g.status)||g.status===D))return g;const xe=e.convertMessage(k,I),ue=fs(xe,I.toString(),D);return ue[Se]=k,ue}):e.messages;n.length>0&&this.ensureInitialized(),((r==null?void 0:r.isRunning)??e.isRunning!==!1??!1)&&(e.isRunning?this._notifyEventSubscribers("run-start"):this._notifyEventSubscribers("run-end"));for(let g=0;g<n.length;g++){const k=n[g],I=n[g-1];this.repository.addOrUpdateMessage((I==null?void 0:I.id)??null,k)}this.assistantOptimisticId&&(this.repository.deleteMessage(this.assistantOptimisticId),this.assistantOptimisticId=null),qn(s,n)&&(this.assistantOptimisticId=this.repository.appendOptimisticMessage(((c=n.at(-1))==null?void 0:c.id)??null,{role:"assistant",content:[]})),this.repository.resetHead(this.assistantOptimisticId??((u=n.at(-1))==null?void 0:u.id)??null),this._messages=this.repository.getMessages(),this._notifySubscribers()}switchToBranch(e){if(!this._store.setMessages)throw new Error("Runtime does not support switching branches.");this.repository.switchToBranch(e),this.updateMessages(this.repository.getMessages())}async append(e){var s;if(e.parentId!==(((s=this.messages.at(-1))==null?void 0:s.id)??null)){if(!this._store.onEdit)throw new Error("Runtime does not support editing messages.");await this._store.onEdit(e)}else await this._store.onNew(e)}async startRun(e){if(!this._store.onReload)throw new Error("Runtime does not support reloading messages.");await this._store.onReload(e.parentId,e)}async resumeRun(){throw new Error("Runtime does not support resuming runs.")}cancelRun(){var r;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 e=this.repository.getMessages();const s=e[e.length-1];(s==null?void 0:s.role)==="user"&&s.id===((r=e.at(-1))==null?void 0:r.id)?(this.repository.deleteMessage(s.id),this.composer.text.trim()||this.composer.setText(Ue(s)),e=this.repository.getMessages()):this._notifySubscribers(),setTimeout(()=>{this.updateMessages(e)},0)}addToolResult(e){if(!this._store.onAddToolResult)throw new Error("Runtime does not support tool results.");this._store.onAddToolResult(e)}},Wt=t=>{var e;return((e=t.adapters)==null?void 0:e.threadList)??{}},Kn=class extends Dr{constructor(e){super();h(this,"threads");this.threads=new Vn(Wt(e),()=>new Hn(this._contextProvider,e))}setAdapter(e){this.threads.__internal_setAdapter(Wt(e)),this.threads.getMainThreadRuntimeCore().__internal_setAdapter(e)}},Gn=S.createContext(null),Xn=()=>S.useContext(Gn),Qn=t=>{const[e]=S.useState(()=>new Kn(t));S.useEffect(()=>{e.setAdapter(t)});const{modelContext:s}=Xn()??{};return S.useEffect(()=>{if(s)return e.registerModelContextProvider(s)},[s,e]),S.useMemo(()=>new ei(e),[e])},ei=class{constructor(t){h(this,"threads");h(this,"_thread");this._core=t,this.threads=new $n(t.threads),this._thread=this.threads.main}get threadList(){return this.threads}__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(vn.fromArray(t??[]))}};function ti(t){return t.filter(e=>{var s;return e.finishReason==="stop"?e.text!==null&&((s=e.text)==null?void 0:s.trim())!=="":!0})}function si(t){const e=[];let s=null;for(const r of t)r.type==="reasoning"?(s!=null&&(e.push(s),s=null),e.push(r)):r.functionCalls?(s&&e.push(s),e.push(r),s=null):r.functionResponse?e[e.length-1]={...e[e.length-1],functionResponse:r.functionResponse}:s&&r.protocol===s.protocol&&(s.role===r.role||r.finishReason==="stop")?s.text+=r.text:(s&&e.push(s),s={...r});return s&&e.push(s),ti(e)}function ri(t){var e;return t.role==="function"?{id:t.id,role:"assistant",status:(t==null?void 0:t.functionResponse)===null?{type:"running"}:{type:"complete",reason:"stop"},content:((e=t.functionCalls)==null?void 0:e.map(s=>{var r;return{type:"tool-call",toolName:s.name,toolCallId:s.id,args:s.args,result:(r=t.functionResponse)==null?void 0:r.result}}))??[]}:{id:t.id,role:t.role,content:t.type==="reasoning"?[{type:"reasoning",text:t.text}]:[{type:"text",text:t.text}]}}class ct{constructor(){h(this,"statusChangeCallbacks",[]);h(this,"messageCallbacks",[])}addStatusChangeListener(e){this.statusChangeCallbacks.push(e)}addMessageListener(e){this.messageCallbacks.push(e)}async syncSession(e){this.session=e}async notifyMessage(e){this.messageCallbacks.forEach(s=>s(e))}async notifyMessages(e){e.forEach(s=>{this.messageCallbacks.forEach(r=>r(s))})}async setSession(e){this.session=e}async setStatus(e){const s=this.status!==e;this.status=e,s&&this.statusChangeCallbacks.forEach(r=>r(e))}clearListeners(){this.statusChangeCallbacks=[],this.messageCallbacks=[]}}class vt extends ct{constructor(s){super();h(this,"status");h(this,"autostart");h(this,"session");h(this,"config");h(this,"notify",!0);this.config=s,this.status="disconnected",this.autostart=!0}getName(){return"rest"}getPriority(){return 0}async connect(s){return this.setStatus("connected"),s}async disconnect(){this.setStatus("disconnected"),this.session=null}async syncSession(s){this.session=s}async send(s){const{apiUrl:r,apiKey:n,agentId:i}=this.config,a=this.session??"new",o=s,c=await(await fetch(`${r}/agents/${i}/sessions/${a}/messages`,{body:JSON.stringify({userMessage:o}),method:"POST",headers:{"Content-Type":"application/json","x-fox-apikey":n,"x-persona-apikey":n}})).json();this.notifyMessages(c.response.messages)}}class St extends ct{constructor(s){super();h(this,"status");h(this,"autostart");h(this,"session");h(this,"config");h(this,"webSocket");this.config=s,this.status="disconnected",this.autostart=!0,this.session=null,this.webSocket=null}getName(){return"websocket"}getPriority(){return 1}async syncSession(s){var r;(r=this.config.logger)==null||r.debug("Syncing session with WebSocket protocol:",s),this.session=s,this.webSocket&&this.status==="connected"&&(this.disconnect(),this.connect(s))}connect(s){var o;if(this.webSocket!==null&&this.status==="connected")return Promise.resolve(this.session);const r=s||this.session||"new";(o=this.config.logger)==null||o.debug("Connecting to WebSocket with sessionId:",r);const n=encodeURIComponent(this.config.apiKey),i=this.config.agentId,a=`${this.config.webSocketUrl}?sessionCode=${r}&agentId=${i}&apiKey=${n}`;return this.setStatus("connecting"),this.webSocket=new WebSocket(a),this.webSocket.addEventListener("open",()=>{this.setStatus("connected")}),this.webSocket.addEventListener("message",d=>{const c=JSON.parse(d.data);if(c.type!=="message")return;const u=c.payload;this.notifyMessage(u!=null&&u.thought?{role:"assistant",type:"reasoning",text:u.thought}:u)}),this.webSocket.addEventListener("close",()=>{var d;this.setStatus("disconnected"),this.webSocket=null,(d=this.config.logger)==null||d.warn("WebSocket connection closed")}),this.webSocket.addEventListener("error",d=>{var c;this.setStatus("disconnected"),this.webSocket=null,(c=this.config.logger)==null||c.error("WebSocket error",d)}),Promise.resolve(r)}disconnect(){var s;return(s=this.config.logger)==null||s.debug("Disconnecting WebSocket"),this.webSocket&&this.status==="connected"&&(this.webSocket.close(),this.setStatus("disconnected"),this.webSocket=null),Promise.resolve()}send(s){return this.webSocket&&this.status==="connected"?(this.webSocket.send(JSON.stringify({type:"request",payload:s})),Promise.resolve()):Promise.reject(new Error("WebSocket is not connected"))}}class ni{constructor(e){h(this,"config");h(this,"pc",null);h(this,"ws",null);h(this,"localStream",null);h(this,"remoteStream",new MediaStream);h(this,"audioCtx",null);h(this,"localAnalyser",null);h(this,"remoteAnalyser",null);h(this,"analyzerFrame",null);h(this,"dataChannel",null);h(this,"isConnected",!1);h(this,"visualizerCallbacks",[]);h(this,"messageCallbacks",[]);this.config=e}async connect(e){var s;if(!this.isConnected){this.isConnected=!0;try{this.localStream=await navigator.mediaDevices.getUserMedia({audio:!0})}catch(r){(s=this.config.logger)==null||s.error("Error accessing microphone:",r);return}this.pc=new RTCPeerConnection({iceServers:this.config.iceServers||[{urls:"stun:34.38.108.251:3478"},{urls:"turn:34.38.108.251:3478",username:"webrtc",credential:"webrtc"}]}),this.localStream.getTracks().forEach(r=>{this.pc.addTrack(r,this.localStream)}),this.pc.ontrack=r=>{r.streams[0].getTracks().forEach(i=>{this.remoteStream.addTrack(i)}),this.audioCtx||this._startAnalyzers();const n=new Audio;n.srcObject=this.remoteStream,n.play().catch(i=>{var a;(a=this.config.logger)==null||a.error("Error playing remote audio:",i)})},this.pc.onicecandidate=r=>{var n;r.candidate&&((n=this.ws)==null?void 0:n.readyState)===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"CANDIDATE",src:"client",payload:{candidate:r.candidate}}))},this.pc.ondatachannel=r=>{const n=r.channel;n.onmessage=i=>{this.messageCallbacks.forEach(a=>{a(i)})}},this.ws=new WebSocket(this.config.webrtcUrl||"wss://persona.applica.guru/api/webrtc"),this.ws.onopen=async()=>{var a,o;const r=await this.pc.createOffer();await this.pc.setLocalDescription(r);const n={agentId:this.config.agentId,sessionCode:e};(a=this.config.logger)==null||a.debug("Opening connection to WebRTC server: ",n);const i={type:"OFFER",src:((o=crypto.randomUUID)==null?void 0:o.call(crypto))||"client_"+Date.now(),payload:{sdp:{sdp:r.sdp,type:r.type},connectionId:(Date.now()%1e6).toString(),metadata:n}};this.ws.send(JSON.stringify(i))},this.ws.onmessage=async r=>{var i;const n=JSON.parse(r.data);if(n.type==="ANSWER")await this.pc.setRemoteDescription(new RTCSessionDescription(n.payload.sdp));else if(n.type==="CANDIDATE")try{await this.pc.addIceCandidate(new RTCIceCandidate(n.payload.candidate))}catch(a){(i=this.config.logger)==null||i.error("Error adding ICE candidate:",a)}},this.ws.onclose=()=>{this._stopAnalyzers()}}}async disconnect(){var e;this.isConnected&&(this.isConnected=!1,((e=this.ws)==null?void 0:e.readyState)===WebSocket.OPEN&&this.ws.close(),this.pc&&this.pc.close(),this.localStream&&this.localStream.getTracks().forEach(s=>s.stop()),this.remoteStream=new MediaStream,this.audioCtx&&(await this.audioCtx.close(),this.audioCtx=null),this._stopAnalyzers())}addVisualizerCallback(e){this.visualizerCallbacks.push(e)}addMessageCallback(e){this.messageCallbacks.push(e)}createDataChannel(e="messages"){this.pc&&(this.dataChannel=this.pc.createDataChannel(e),this.dataChannel.onopen=()=>{var s;return(s=this.config.logger)==null?void 0:s.info("Data channel opened")},this.dataChannel.onmessage=s=>{this.messageCallbacks.forEach(r=>{r(s)})})}sendMessage(e){var s,r;if(!this.dataChannel){(s=this.config.logger)==null||s.warn("Data channel is not open, cannot send message");return}this.dataChannel.send(e),(r=this.config.logger)==null||r.info("Sent message:",e)}_startAnalyzers(){if(!this.localStream||!this.remoteStream||this.visualizerCallbacks.length===0)return;this.audioCtx=new(window.AudioContext||window.webkitAudioContext);const e=this.audioCtx.createMediaStreamSource(this.localStream),s=this.audioCtx.createMediaStreamSource(this.remoteStream);this.localAnalyser=this.audioCtx.createAnalyser(),this.remoteAnalyser=this.audioCtx.createAnalyser(),this.localAnalyser.fftSize=256,this.remoteAnalyser.fftSize=256,e.connect(this.localAnalyser),s.connect(this.remoteAnalyser);const r=()=>{if(!this.localAnalyser||!this.remoteAnalyser||this.visualizerCallbacks.length===0)return;const n=new Uint8Array(this.localAnalyser.frequencyBinCount),i=new Uint8Array(this.remoteAnalyser.frequencyBinCount);this.localAnalyser.getByteFrequencyData(n),this.remoteAnalyser.getByteFrequencyData(i);const a=n.reduce((d,c)=>d+c,0)/n.length,o=i.reduce((d,c)=>d+c,0)/i.length;this.visualizerCallbacks.length>0&&this.visualizerCallbacks.forEach(d=>{d({localAmplitude:a,remoteAmplitude:o})}),this.analyzerFrame=requestAnimationFrame(r)};this.analyzerFrame=requestAnimationFrame(r)}_stopAnalyzers(){this.analyzerFrame&&(cancelAnimationFrame(this.analyzerFrame),this.analyzerFrame=null),this.localAnalyser=null,this.remoteAnalyser=null}}class wt extends ct{constructor(s){super();h(this,"status");h(this,"session");h(this,"autostart");h(this,"config");h(this,"webRTCClient");this.config=s,this.status="disconnected",this.session=null,this.autostart=(s==null?void 0:s.autostart)??!1,this.webRTCClient=new ni(s),this.webRTCClient.addMessageCallback(r=>{var i;(i=s.logger)==null||i.debug("Received data message:",r.data);const n=JSON.parse(r.data);n.type==="message"&&this.notifyMessage(n.payload)})}getName(){return"webrtc"}getPriority(){return 10}async syncSession(s){super.syncSession(s),this.status==="connected"&&(await this.disconnect(),await this.connect(s))}async connect(s){var r;return this.status==="connected"?Promise.resolve(this.session):(this.session=s||this.session||"new",this.setStatus("connecting"),(r=this.config.logger)==null||r.debug("Connecting to WebRTC with sessionId:",this.session),await this.webRTCClient.connect(this.session),this.setStatus("connected"),await this.webRTCClient.createDataChannel(),this.session)}async disconnect(){var s,r,n;if(this.status==="disconnected")return(s=this.config.logger)==null||s.warn("Already disconnected"),Promise.resolve();await this.webRTCClient.disconnect(),this.setStatus("disconnected"),(n=(r=this.config)==null?void 0:r.logger)==null||n.debug("Disconnected from WebRTC")}send(s){return this.status!=="connected"?Promise.reject(new Error("Not connected")):(this.webRTCClient.sendMessage(s),Promise.resolve())}}const Et=S.createContext(void 0);function ii({dev:t=!1,protocols:e,logger:s,children:r,session:n="new",...i}){const[a,o]=S.useState(!1),[d,c]=S.useState([]),[u,g]=S.useState(n),[k,I]=S.useState(new Map),de=S.useRef(!1),D=S.useMemo(()=>{if(Array.isArray(e))return e;if(typeof e=="object"&&e!==null){const R=t?"localhost:8000":"persona.applica.guru/api",Z=t?"http":"https",W=t?"ws":"wss";return Object.keys(e).map(P=>{switch(P){case"rest":const he=e[P];return he===!0?new vt({apiUrl:`${Z}://${R}`,apiKey:i.apiKey,agentId:i.agentId,logger:s}):new vt(he);case"webrtc":const Ye=e[P];return Ye===!0?new wt({webrtcUrl:`${W}://${R}/webrtc`,apiKey:i.apiKey,agentId:i.agentId,logger:s}):new wt(Ye);case"websocket":const le=e[P];return le===!0?new St({webSocketUrl:`${W}://${R}/websocket`,apiKey:i.apiKey,agentId:i.agentId,logger:s}):new St(le);default:throw new Error(`Unknown protocol: ${P}`)}})}throw new Error("Invalid protocols configuration")},[]);S.useEffect(()=>{de.current||(de.current=!0,s==null||s.debug("Initializing protocols: ",D.map(R=>R.getName())),D.forEach(R=>{R.setSession(u),R.clearListeners(),R.addStatusChangeListener(Z=>{s==null||s.debug(`${R.getName()} has notified new status: ${Z}`),k.set(R.getName(),Z),I(new Map(k))}),R.addMessageListener(Z=>{c(W=>si([...W,{...Z,protocol:R.getName()}]))}),R.autostart&&R.status==="disconnected"&&(s==null||s.debug(`Connecting to protocol: ${R.getName()}`),R.connect(u))}))},[u,D,s,k]);const xe=async R=>{var Te;if(((Te=R.content[0])==null?void 0:Te.type)!=="text")throw new Error("Only text messages are supported");const Z=R.content[0].text;c(P=>[...P,{role:"user",type:"text",text:Z}]),o(!0);const W=D.sort((P,he)=>he.getPriority()-P.getPriority()).find(P=>P.status==="connected");await(W==null?void 0:W.send(Z)),o(!1)},ue=S.useCallback(()=>(o(!1),c([]),g("new"),Promise.resolve()),[]),dt=S.useCallback(()=>Promise.resolve(),[]),ut=Qn({isRunning:a,messages:d,convertMessage:ri,onNew:xe,onCancel:ue,onReload:dt});return F.jsx(Et.Provider,{value:{protocols:D,protocolsStatus:k},children:F.jsx(_n,{runtime:ut,children:r})})}function ai({children:t,...e}){return F.jsx(ii,{...e,children:t})}function oi(){const t=S.useContext(Et);if(!t)throw new Error("usePersonaRuntime must be used within a PersonaRuntimeProvider");return t}function vs(t){const e=S.useContext(Et);if(!e)throw new Error("usePersonaRuntimeProtocol must be used within a PersonaRuntimeProvider");const s=e.protocols.find(n=>n.getName()===t);if(!s)return null;const r=e.protocolsStatus.get(s.getName());return{...s,connect:s.connect.bind(s),disconnect:s.disconnect.bind(s),send:s.send.bind(s),setSession:s.setSession.bind(s),addStatusChangeListener:s.addStatusChangeListener.bind(s),addMessageListener:s.addMessageListener.bind(s),getName:s.getName.bind(s),getPriority:s.getPriority.bind(s),status:r||s.status}}function ci(){return vs("webrtc")}class di{constructor(){h(this,"prefix","[Persona]")}log(e,...s){console.log(`${this.prefix} - ${e}`,...s)}info(e,...s){console.info(`${this.prefix} - ${e}`,...s)}warn(e,...s){console.warn(`${this.prefix} - ${e}`,...s)}error(e,...s){console.error(`${this.prefix} - ${e}`,...s)}debug(e,...s){console.debug(`${this.prefix} - ${e}`,...s)}}exports.PersonaConsoleLogger=di;exports.PersonaProtocolBase=ct;exports.PersonaRESTProtocol=vt;exports.PersonaRuntimeProvider=ai;exports.PersonaWebRTCProtocol=wt;exports.PersonaWebSocketProtocol=St;exports.usePersonaRuntime=oi;exports.usePersonaRuntimeProtocol=vs;exports.usePersonaRuntimeWebRTCProtocol=ci;
27
19
  //# sourceMappingURL=bundle.cjs.js.map