@merit-systems/echo-react-sdk 1.0.15 → 1.0.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/echo-react-sdk.umd.js +2 -2
- package/dist/echo-react-sdk.umd.js.map +1 -1
- package/dist/index.cjs +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +6 -8
- package/dist/index.js +2382 -30
- package/dist/index.js.map +1 -1
- package/package.json +5 -3
package/dist/index.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";Object.create;var e,t=Object.defineProperty,n=(Object.getOwnPropertyDescriptor,Object.getOwnPropertyNames,Object.getPrototypeOf,Object.prototype.hasOwnProperty,(e,n,r)=>((e,n,r)=>n in e?t(e,n,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[n]=r)(e,"symbol"!=typeof n?n+"":n,r));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("react/jsx-runtime"),i=require("react");class o extends Error{}function s(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return function(e){return decodeURIComponent(atob(e).replace(/(.)/g,((e,t)=>{let n=t.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n="0"+n),"%"+n})))}(t)}catch(n){return atob(t)}}o.prototype.name="InvalidTokenError";var a,u,l,c={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},d=(e=>(e[e.NONE=0]="NONE",e[e.ERROR=1]="ERROR",e[e.WARN=2]="WARN",e[e.INFO=3]="INFO",e[e.DEBUG=4]="DEBUG",e))(d||{});(l=d||(d={})).reset=function(){a=3,u=c},l.setLevel=function(e){if(!(0<=e&&e<=4))throw new Error("Invalid log level");a=e},l.setLogger=function(e){u=e};var p=class e{constructor(e){this._name=e}debug(...t){a>=4&&u.debug(e._format(this._name,this._method),...t)}info(...t){a>=3&&u.info(e._format(this._name,this._method),...t)}warn(...t){a>=2&&u.warn(e._format(this._name,this._method),...t)}error(...t){a>=1&&u.error(e._format(this._name,this._method),...t)}throw(e){throw this.error(e),e}create(e){const t=Object.create(this);return t._method=e,t.debug("begin"),t}static createStatic(t,n){const r=new e(`${t}.${n}`);return r.debug("begin"),r}static _format(e,t){const n=`[${e}]`;return t?`${n} ${t}:`:n}static debug(t,...n){a>=4&&u.debug(e._format(t),...n)}static info(t,...n){a>=3&&u.info(e._format(t),...n)}static warn(t,...n){a>=2&&u.warn(e._format(t),...n)}static error(t,...n){a>=1&&u.error(e._format(t),...n)}};d.reset();var m=class{static decode(e){try{return function(e,t){if("string"!=typeof e)throw new o("Invalid token specified: must be a string");t||(t={});const n=!0===t.header?0:1,r=e.split(".")[n];if("string"!=typeof r)throw new o(`Invalid token specified: missing part #${n+1}`);let i;try{i=s(r)}catch(a){throw new o(`Invalid token specified: invalid base64 for part #${n+1} (${a.message})`)}try{return JSON.parse(i)}catch(a){throw new o(`Invalid token specified: invalid json for part #${n+1} (${a.message})`)}}(e)}catch(t){throw p.error("JwtUtils.decode",t),t}}static async generateSignedJwt(e,t,n){const r=`${f.encodeBase64Url((new TextEncoder).encode(JSON.stringify(e)))}.${f.encodeBase64Url((new TextEncoder).encode(JSON.stringify(t)))}`,i=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,(new TextEncoder).encode(r));return`${r}.${f.encodeBase64Url(new Uint8Array(i))}`}},h=e=>btoa([...new Uint8Array(e)].map((e=>String.fromCharCode(e))).join("")),g=class e{static _randomWord(){const e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}static generateUUIDv4(){return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(t=>(+t^e._randomWord()&15>>+t/4).toString(16))).replace(/-/g,"")}static generateCodeVerifier(){return e.generateUUIDv4()+e.generateUUIDv4()+e.generateUUIDv4()}static async generateCodeChallenge(e){if(!crypto.subtle)throw new Error("Crypto.subtle is available only in secure contexts (HTTPS).");try{const t=(new TextEncoder).encode(e),n=await crypto.subtle.digest("SHA-256",t);return h(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(t){throw p.error("CryptoUtils.generateCodeChallenge",t),t}}static generateBasicAuth(e,t){const n=(new TextEncoder).encode([e,t].join(":"));return h(n)}static async hash(e,t){const n=(new TextEncoder).encode(t),r=await crypto.subtle.digest(e,n);return new Uint8Array(r)}static async customCalculateJwkThumbprint(t){let n;switch(t.kty){case"RSA":n={e:t.e,kty:t.kty,n:t.n};break;case"EC":n={crv:t.crv,kty:t.kty,x:t.x,y:t.y};break;case"OKP":n={crv:t.crv,kty:t.kty,x:t.x};break;case"oct":n={crv:t.k,kty:t.kty};break;default:throw new Error("Unknown jwk type")}const r=await e.hash("SHA-256",JSON.stringify(n));return e.encodeBase64Url(r)}static async generateDPoPProof({url:t,accessToken:n,httpMethod:r,keyPair:i,nonce:o}){let s,a;const u={jti:window.crypto.randomUUID(),htm:null!=r?r:"GET",htu:t,iat:Math.floor(Date.now()/1e3)};n&&(s=await e.hash("SHA-256",n),a=e.encodeBase64Url(s),u.ath=a),o&&(u.nonce=o);try{const e=await crypto.subtle.exportKey("jwk",i.publicKey),t={alg:"ES256",typ:"dpop+jwt",jwk:{crv:e.crv,kty:e.kty,x:e.x,y:e.y}};return await m.generateSignedJwt(t,u,i.privateKey)}catch(l){throw l instanceof TypeError?new Error(`Error exporting dpop public key: ${l.message}`):l}}static async generateDPoPJkt(t){try{const n=await crypto.subtle.exportKey("jwk",t.publicKey);return await e.customCalculateJwkThumbprint(n)}catch(n){throw n instanceof TypeError?new Error(`Could not retrieve dpop keys from storage: ${n.message}`):n}}static async generateDPoPKeys(){return await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign","verify"])}};g.encodeBase64Url=e=>h(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");var f=g,v=class{constructor(e){this._name=e,this._callbacks=[],this._logger=new p(`Event('${this._name}')`)}addHandler(e){return this._callbacks.push(e),()=>this.removeHandler(e)}removeHandler(e){const t=this._callbacks.lastIndexOf(e);t>=0&&this._callbacks.splice(t,1)}async raise(...e){this._logger.debug("raise:",...e);for(const t of this._callbacks)await t(...e)}},y=class{static center({...e}){var t;return null==e.width&&(e.width=null!=(t=[800,720,600,480].find((e=>e<=window.outerWidth/1.618)))?t:360),null!=e.left||(e.left=Math.max(0,Math.round(window.screenX+(window.outerWidth-e.width)/2))),null!=e.height&&(null!=e.top||(e.top=Math.max(0,Math.round(window.screenY+(window.outerHeight-e.height)/2)))),e}static serialize(e){return Object.entries(e).filter((([,e])=>null!=e)).map((([e,t])=>`${e}=${"boolean"!=typeof t?t:t?"yes":"no"}`)).join(",")}},_=class e extends v{constructor(){super(...arguments),this._logger=new p(`Timer('${this._name}')`),this._timerHandle=null,this._expiration=0,this._callback=()=>{const t=this._expiration-e.getEpochTime();this._logger.debug("timer completes in",t),this._expiration<=e.getEpochTime()&&(this.cancel(),super.raise())}}static getEpochTime(){return Math.floor(Date.now()/1e3)}init(t){const n=this._logger.create("init");t=Math.max(Math.floor(t),1);const r=e.getEpochTime()+t;if(this.expiration===r&&this._timerHandle)return void n.debug("skipping since already initialized for expiration at",this.expiration);this.cancel(),n.debug("using duration",t),this._expiration=r;const i=Math.min(t,5);this._timerHandle=setInterval(this._callback,1e3*i)}get expiration(){return this._expiration}cancel(){this._logger.create("cancel"),this._timerHandle&&(clearInterval(this._timerHandle),this._timerHandle=null)}},b=class{static readParams(e,t="query"){if(!e)throw new TypeError("Invalid URL");const n=new URL(e,"http://127.0.0.1")["fragment"===t?"hash":"search"];return new URLSearchParams(n.slice(1))}},w=";",k=class extends Error{constructor(e,t){var n,r,i;if(super(e.error_description||e.error||""),this.form=t,this.name="ErrorResponse",!e.error)throw p.error("ErrorResponse","No error passed"),new Error("No error passed");this.error=e.error,this.error_description=null!=(n=e.error_description)?n:null,this.error_uri=null!=(r=e.error_uri)?r:null,this.state=e.userState,this.session_state=null!=(i=e.session_state)?i:null,this.url_state=e.url_state}},x=class extends Error{constructor(e){super(e),this.name="ErrorTimeout"}},I=class{constructor(e){this._logger=new p("AccessTokenEvents"),this._expiringTimer=new _("Access token expiring"),this._expiredTimer=new _("Access token expired"),this._expiringNotificationTimeInSeconds=e.expiringNotificationTimeInSeconds}async load(e){const t=this._logger.create("load");if(e.access_token&&void 0!==e.expires_in){const n=e.expires_in;if(t.debug("access token present, remaining duration:",n),n>0){let e=n-this._expiringNotificationTimeInSeconds;e<=0&&(e=1),t.debug("registering expiring timer, raising in",e,"seconds"),this._expiringTimer.init(e)}else t.debug("canceling existing expiring timer because we're past expiration."),this._expiringTimer.cancel();const r=n+1;t.debug("registering expired timer, raising in",r,"seconds"),this._expiredTimer.init(r)}else this._expiringTimer.cancel(),this._expiredTimer.cancel()}async unload(){this._logger.debug("unload: canceling existing access token timers"),this._expiringTimer.cancel(),this._expiredTimer.cancel()}addAccessTokenExpiring(e){return this._expiringTimer.addHandler(e)}removeAccessTokenExpiring(e){this._expiringTimer.removeHandler(e)}addAccessTokenExpired(e){return this._expiredTimer.addHandler(e)}removeAccessTokenExpired(e){this._expiredTimer.removeHandler(e)}},S=class{constructor(e,t,n,r,i){this._callback=e,this._client_id=t,this._intervalInSeconds=r,this._stopOnError=i,this._logger=new p("CheckSessionIFrame"),this._timer=null,this._session_state=null,this._message=e=>{e.origin===this._frame_origin&&e.source===this._frame.contentWindow&&("error"===e.data?(this._logger.error("error message from check session op iframe"),this._stopOnError&&this.stop()):"changed"===e.data?(this._logger.debug("changed message from check session op iframe"),this.stop(),this._callback()):this._logger.debug(e.data+" message from check session op iframe"))};const o=new URL(n);this._frame_origin=o.origin,this._frame=window.document.createElement("iframe"),this._frame.style.visibility="hidden",this._frame.style.position="fixed",this._frame.style.left="-1000px",this._frame.style.top="0",this._frame.width="0",this._frame.height="0",this._frame.src=o.href}load(){return new Promise((e=>{this._frame.onload=()=>{e()},window.document.body.appendChild(this._frame),window.addEventListener("message",this._message,!1)}))}start(e){if(this._session_state===e)return;this._logger.create("start"),this.stop(),this._session_state=e;const t=()=>{this._frame.contentWindow&&this._session_state&&this._frame.contentWindow.postMessage(this._client_id+" "+this._session_state,this._frame_origin)};t(),this._timer=setInterval(t,1e3*this._intervalInSeconds)}stop(){this._logger.create("stop"),this._session_state=null,this._timer&&(clearInterval(this._timer),this._timer=null)}},$=class{constructor(){this._logger=new p("InMemoryWebStorage"),this._data={}}clear(){this._logger.create("clear"),this._data={}}getItem(e){return this._logger.create(`getItem('${e}')`),this._data[e]}setItem(e,t){this._logger.create(`setItem('${e}')`),this._data[e]=t}removeItem(e){this._logger.create(`removeItem('${e}')`),delete this._data[e]}get length(){return Object.getOwnPropertyNames(this._data).length}key(e){return Object.getOwnPropertyNames(this._data)[e]}},E=class extends Error{constructor(e,t){super(t),this.name="ErrorDPoPNonce",this.nonce=e}},T=class{constructor(e=[],t=null,n={}){this._jwtHandler=t,this._extraHeaders=n,this._logger=new p("JsonService"),this._contentTypes=[],this._contentTypes.push(...e,"application/json"),t&&this._contentTypes.push("application/jwt")}async fetchWithTimeout(e,t={}){const{timeoutInSeconds:n,...r}=t;if(!n)return await fetch(e,r);const i=new AbortController,o=setTimeout((()=>i.abort()),1e3*n);try{return await fetch(e,{...t,signal:i.signal})}catch(s){if(s instanceof DOMException&&"AbortError"===s.name)throw new x("Network timed out");throw s}finally{clearTimeout(o)}}async getJson(e,{token:t,credentials:n,timeoutInSeconds:r}={}){const i=this._logger.create("getJson"),o={Accept:this._contentTypes.join(", ")};let s;t&&(i.debug("token passed, setting Authorization header"),o.Authorization="Bearer "+t),this._appendExtraHeaders(o);try{i.debug("url:",e),s=await this.fetchWithTimeout(e,{method:"GET",headers:o,timeoutInSeconds:r,credentials:n})}catch(l){throw i.error("Network Error"),l}i.debug("HTTP response received, status",s.status);const a=s.headers.get("Content-Type");if(a&&!this._contentTypes.find((e=>a.startsWith(e)))&&i.throw(new Error(`Invalid response Content-Type: ${null!=a?a:"undefined"}, from URL: ${e}`)),s.ok&&this._jwtHandler&&(null==a?void 0:a.startsWith("application/jwt")))return await this._jwtHandler(await s.text());let u;try{u=await s.json()}catch(l){if(i.error("Error parsing JSON response",l),s.ok)throw l;throw new Error(`${s.statusText} (${s.status})`)}if(!s.ok){if(i.error("Error from server:",u),u.error)throw new k(u);throw new Error(`${s.statusText} (${s.status}): ${JSON.stringify(u)}`)}return u}async postForm(e,{body:t,basicAuth:n,timeoutInSeconds:r,initCredentials:i,extraHeaders:o}){const s=this._logger.create("postForm"),a={Accept:this._contentTypes.join(", "),"Content-Type":"application/x-www-form-urlencoded",...o};let u;void 0!==n&&(a.Authorization="Basic "+n),this._appendExtraHeaders(a);try{s.debug("url:",e),u=await this.fetchWithTimeout(e,{method:"POST",headers:a,body:t,timeoutInSeconds:r,credentials:i})}catch(p){throw s.error("Network error"),p}s.debug("HTTP response received, status",u.status);const l=u.headers.get("Content-Type");if(l&&!this._contentTypes.find((e=>l.startsWith(e))))throw new Error(`Invalid response Content-Type: ${null!=l?l:"undefined"}, from URL: ${e}`);const c=await u.text();let d={};if(c)try{d=JSON.parse(c)}catch(p){if(s.error("Error parsing JSON response",p),u.ok)throw p;throw new Error(`${u.statusText} (${u.status})`)}if(!u.ok){if(s.error("Error from server:",d),u.headers.has("dpop-nonce")){const e=u.headers.get("dpop-nonce");throw new E(e,`${JSON.stringify(d)}`)}if(d.error)throw new k(d,t);throw new Error(`${u.statusText} (${u.status}): ${JSON.stringify(d)}`)}return d}_appendExtraHeaders(e){const t=this._logger.create("appendExtraHeaders"),n=Object.keys(this._extraHeaders),r=["accept","content-type"],i=["authorization"];0!==n.length&&n.forEach((n=>{if(r.includes(n.toLocaleLowerCase()))return void t.warn("Protected header could not be set",n,r);if(i.includes(n.toLocaleLowerCase())&&Object.keys(e).includes(n))return void t.warn("Header could not be overridden",n,i);const o="function"==typeof this._extraHeaders[n]?this._extraHeaders[n]():this._extraHeaders[n];o&&""!==o&&(e[n]=o)}))}},O=class{constructor(e){this._settings=e,this._logger=new p("MetadataService"),this._signingKeys=null,this._metadata=null,this._metadataUrl=this._settings.metadataUrl,this._jsonService=new T(["application/jwk-set+json"],null,this._settings.extraHeaders),this._settings.signingKeys&&(this._logger.debug("using signingKeys from settings"),this._signingKeys=this._settings.signingKeys),this._settings.metadata&&(this._logger.debug("using metadata from settings"),this._metadata=this._settings.metadata),this._settings.fetchRequestCredentials&&(this._logger.debug("using fetchRequestCredentials from settings"),this._fetchRequestCredentials=this._settings.fetchRequestCredentials)}resetSigningKeys(){this._signingKeys=null}async getMetadata(){const e=this._logger.create("getMetadata");if(this._metadata)return e.debug("using cached values"),this._metadata;if(!this._metadataUrl)throw e.throw(new Error("No authority or metadataUrl configured on settings")),null;e.debug("getting metadata from",this._metadataUrl);const t=await this._jsonService.getJson(this._metadataUrl,{credentials:this._fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return e.debug("merging remote JSON with seed metadata"),this._metadata=Object.assign({},t,this._settings.metadataSeed),this._metadata}getIssuer(){return this._getMetadataProperty("issuer")}getAuthorizationEndpoint(){return this._getMetadataProperty("authorization_endpoint")}getUserInfoEndpoint(){return this._getMetadataProperty("userinfo_endpoint")}getTokenEndpoint(e=!0){return this._getMetadataProperty("token_endpoint",e)}getCheckSessionIframe(){return this._getMetadataProperty("check_session_iframe",!0)}getEndSessionEndpoint(){return this._getMetadataProperty("end_session_endpoint",!0)}getRevocationEndpoint(e=!0){return this._getMetadataProperty("revocation_endpoint",e)}getKeysEndpoint(e=!0){return this._getMetadataProperty("jwks_uri",e)}async _getMetadataProperty(e,t=!1){const n=this._logger.create(`_getMetadataProperty('${e}')`),r=await this.getMetadata();if(n.debug("resolved"),void 0===r[e]){if(!0===t)return void n.warn("Metadata does not contain optional property");n.throw(new Error("Metadata does not contain property "+e))}return r[e]}async getSigningKeys(){const e=this._logger.create("getSigningKeys");if(this._signingKeys)return e.debug("returning signingKeys from cache"),this._signingKeys;const t=await this.getKeysEndpoint(!1);e.debug("got jwks_uri",t);const n=await this._jsonService.getJson(t,{timeoutInSeconds:this._settings.requestTimeoutInSeconds});if(e.debug("got key set",n),!Array.isArray(n.keys))throw e.throw(new Error("Missing keys on keyset")),null;return this._signingKeys=n.keys,this._signingKeys}},N=class{constructor({prefix:e="oidc.",store:t=localStorage}={}){this._logger=new p("WebStorageStateStore"),this._store=t,this._prefix=e}async set(e,t){this._logger.create(`set('${e}')`),e=this._prefix+e,await this._store.setItem(e,t)}async get(e){this._logger.create(`get('${e}')`),e=this._prefix+e;return await this._store.getItem(e)}async remove(e){this._logger.create(`remove('${e}')`),e=this._prefix+e;const t=await this._store.getItem(e);return await this._store.removeItem(e),t}async getAllKeys(){this._logger.create("getAllKeys");const e=await this._store.length,t=[];for(let n=0;n<e;n++){const e=await this._store.key(n);e&&0===e.indexOf(this._prefix)&&t.push(e.substr(this._prefix.length))}return t}},C=class{constructor({authority:e,metadataUrl:t,metadata:n,signingKeys:r,metadataSeed:i,client_id:o,client_secret:s,response_type:a="code",scope:u="openid",redirect_uri:l,post_logout_redirect_uri:c,client_authentication:d="client_secret_post",prompt:p,display:m,max_age:h,ui_locales:g,acr_values:f,resource:v,response_mode:y,filterProtocolClaims:_=!0,loadUserInfo:b=!1,requestTimeoutInSeconds:w,staleStateAgeInSeconds:k=900,mergeClaimsStrategy:x={array:"replace"},disablePKCE:I=!1,stateStore:S,revokeTokenAdditionalContentTypes:E,fetchRequestCredentials:T,refreshTokenAllowedScope:O,extraQueryParams:C={},extraTokenParams:A={},extraHeaders:P={},dpop:R,omitScopeWhenRequesting:U=!1}){var j;if(this.authority=e,t?this.metadataUrl=t:(this.metadataUrl=e,e&&(this.metadataUrl.endsWith("/")||(this.metadataUrl+="/"),this.metadataUrl+=".well-known/openid-configuration")),this.metadata=n,this.metadataSeed=i,this.signingKeys=r,this.client_id=o,this.client_secret=s,this.response_type=a,this.scope=u,this.redirect_uri=l,this.post_logout_redirect_uri=c,this.client_authentication=d,this.prompt=p,this.display=m,this.max_age=h,this.ui_locales=g,this.acr_values=f,this.resource=v,this.response_mode=y,this.filterProtocolClaims=null==_||_,this.loadUserInfo=!!b,this.staleStateAgeInSeconds=k,this.mergeClaimsStrategy=x,this.omitScopeWhenRequesting=U,this.disablePKCE=!!I,this.revokeTokenAdditionalContentTypes=E,this.fetchRequestCredentials=T||"same-origin",this.requestTimeoutInSeconds=w,S)this.stateStore=S;else{const e="undefined"!=typeof window?window.localStorage:new $;this.stateStore=new N({store:e})}if(this.refreshTokenAllowedScope=O,this.extraQueryParams=C,this.extraTokenParams=A,this.extraHeaders=P,this.dpop=R,this.dpop&&!(null==(j=this.dpop)?void 0:j.store))throw new Error("A DPoPStore is required when dpop is enabled")}},A=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new p("UserInfoService"),this._getClaimsFromJwt=async e=>{const t=this._logger.create("_getClaimsFromJwt");try{const n=m.decode(e);return t.debug("JWT decoding successful"),n}catch(n){throw t.error("Error parsing JWT response"),n}},this._jsonService=new T(void 0,this._getClaimsFromJwt,this._settings.extraHeaders)}async getClaims(e){const t=this._logger.create("getClaims");e||this._logger.throw(new Error("No token passed"));const n=await this._metadataService.getUserInfoEndpoint();t.debug("got userinfo url",n);const r=await this._jsonService.getJson(n,{token:e,credentials:this._settings.fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return t.debug("got claims",r),r}},P=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new p("TokenClient"),this._jsonService=new T(this._settings.revokeTokenAdditionalContentTypes,null,this._settings.extraHeaders)}async exchangeCode({grant_type:e="authorization_code",redirect_uri:t=this._settings.redirect_uri,client_id:n=this._settings.client_id,client_secret:r=this._settings.client_secret,extraHeaders:i,...o}){const s=this._logger.create("exchangeCode");n||s.throw(new Error("A client_id is required")),t||s.throw(new Error("A redirect_uri is required")),o.code||s.throw(new Error("A code is required"));const a=new URLSearchParams({grant_type:e,redirect_uri:t});for(const[d,p]of Object.entries(o))null!=p&&a.set(d,p);let u;switch(this._settings.client_authentication){case"client_secret_basic":if(null==r)throw s.throw(new Error("A client_secret is required")),null;u=f.generateBasicAuth(n,r);break;case"client_secret_post":a.append("client_id",n),r&&a.append("client_secret",r)}const l=await this._metadataService.getTokenEndpoint(!1);s.debug("got token endpoint");const c=await this._jsonService.postForm(l,{body:a,basicAuth:u,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:i});return s.debug("got response"),c}async exchangeCredentials({grant_type:e="password",client_id:t=this._settings.client_id,client_secret:n=this._settings.client_secret,scope:r=this._settings.scope,...i}){const o=this._logger.create("exchangeCredentials");t||o.throw(new Error("A client_id is required"));const s=new URLSearchParams({grant_type:e});this._settings.omitScopeWhenRequesting||s.set("scope",r);for(const[c,d]of Object.entries(i))null!=d&&s.set(c,d);let a;switch(this._settings.client_authentication){case"client_secret_basic":if(null==n)throw o.throw(new Error("A client_secret is required")),null;a=f.generateBasicAuth(t,n);break;case"client_secret_post":s.append("client_id",t),n&&s.append("client_secret",n)}const u=await this._metadataService.getTokenEndpoint(!1);o.debug("got token endpoint");const l=await this._jsonService.postForm(u,{body:s,basicAuth:a,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials});return o.debug("got response"),l}async exchangeRefreshToken({grant_type:e="refresh_token",client_id:t=this._settings.client_id,client_secret:n=this._settings.client_secret,timeoutInSeconds:r,extraHeaders:i,...o}){const s=this._logger.create("exchangeRefreshToken");t||s.throw(new Error("A client_id is required")),o.refresh_token||s.throw(new Error("A refresh_token is required"));const a=new URLSearchParams({grant_type:e});for(const[d,p]of Object.entries(o))Array.isArray(p)?p.forEach((e=>a.append(d,e))):null!=p&&a.set(d,p);let u;switch(this._settings.client_authentication){case"client_secret_basic":if(null==n)throw s.throw(new Error("A client_secret is required")),null;u=f.generateBasicAuth(t,n);break;case"client_secret_post":a.append("client_id",t),n&&a.append("client_secret",n)}const l=await this._metadataService.getTokenEndpoint(!1);s.debug("got token endpoint");const c=await this._jsonService.postForm(l,{body:a,basicAuth:u,timeoutInSeconds:r,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:i});return s.debug("got response"),c}async revoke(e){var t;const n=this._logger.create("revoke");e.token||n.throw(new Error("A token is required"));const r=await this._metadataService.getRevocationEndpoint(!1);n.debug(`got revocation endpoint, revoking ${null!=(t=e.token_type_hint)?t:"default token type"}`);const i=new URLSearchParams;for(const[o,s]of Object.entries(e))null!=s&&i.set(o,s);i.set("client_id",this._settings.client_id),this._settings.client_secret&&i.set("client_secret",this._settings.client_secret),await this._jsonService.postForm(r,{body:i,timeoutInSeconds:this._settings.requestTimeoutInSeconds}),n.debug("got response")}},R=class{constructor(e,t,n){this._settings=e,this._metadataService=t,this._claimsService=n,this._logger=new p("ResponseValidator"),this._userInfoService=new A(this._settings,this._metadataService),this._tokenClient=new P(this._settings,this._metadataService)}async validateSigninResponse(e,t,n){const r=this._logger.create("validateSigninResponse");this._processSigninState(e,t),r.debug("state processed"),await this._processCode(e,t,n),r.debug("code processed"),e.isOpenId&&this._validateIdTokenAttributes(e),r.debug("tokens validated"),await this._processClaims(e,null==t?void 0:t.skipUserInfo,e.isOpenId),r.debug("claims processed")}async validateCredentialsResponse(e,t){const n=this._logger.create("validateCredentialsResponse"),r=e.isOpenId&&!!e.id_token;r&&this._validateIdTokenAttributes(e),n.debug("tokens validated"),await this._processClaims(e,t,r),n.debug("claims processed")}async validateRefreshResponse(e,t){const n=this._logger.create("validateRefreshResponse");e.userState=t.data,null!=e.session_state||(e.session_state=t.session_state),null!=e.scope||(e.scope=t.scope),e.isOpenId&&e.id_token&&(this._validateIdTokenAttributes(e,t.id_token),n.debug("ID Token validated")),e.id_token||(e.id_token=t.id_token,e.profile=t.profile);const r=e.isOpenId&&!!e.id_token;await this._processClaims(e,!1,r),n.debug("claims processed")}validateSignoutResponse(e,t){const n=this._logger.create("validateSignoutResponse");if(t.id!==e.state&&n.throw(new Error("State does not match")),n.debug("state validated"),e.userState=t.data,e.error)throw n.warn("Response was error",e.error),new k(e)}_processSigninState(e,t){const n=this._logger.create("_processSigninState");if(t.id!==e.state&&n.throw(new Error("State does not match")),t.client_id||n.throw(new Error("No client_id on state")),t.authority||n.throw(new Error("No authority on state")),this._settings.authority!==t.authority&&n.throw(new Error("authority mismatch on settings vs. signin state")),this._settings.client_id&&this._settings.client_id!==t.client_id&&n.throw(new Error("client_id mismatch on settings vs. signin state")),n.debug("state validated"),e.userState=t.data,e.url_state=t.url_state,null!=e.scope||(e.scope=t.scope),e.error)throw n.warn("Response was error",e.error),new k(e);t.code_verifier&&!e.code&&n.throw(new Error("Expected code in response"))}async _processClaims(e,t=!1,n=!0){const r=this._logger.create("_processClaims");if(e.profile=this._claimsService.filterProtocolClaims(e.profile),t||!this._settings.loadUserInfo||!e.access_token)return void r.debug("not loading user info");r.debug("loading user info");const i=await this._userInfoService.getClaims(e.access_token);r.debug("user info claims received from user info endpoint"),n&&i.sub!==e.profile.sub&&r.throw(new Error("subject from UserInfo response does not match subject in ID Token")),e.profile=this._claimsService.mergeClaims(e.profile,this._claimsService.filterProtocolClaims(i)),r.debug("user info claims received, updated profile:",e.profile)}async _processCode(e,t,n){const r=this._logger.create("_processCode");if(e.code){r.debug("Validating code");const i=await this._tokenClient.exchangeCode({client_id:t.client_id,client_secret:t.client_secret,code:e.code,redirect_uri:t.redirect_uri,code_verifier:t.code_verifier,extraHeaders:n,...t.extraTokenParams});Object.assign(e,i)}else r.debug("No code to process")}_validateIdTokenAttributes(e,t){var n;const r=this._logger.create("_validateIdTokenAttributes");r.debug("decoding ID Token JWT");const i=m.decode(null!=(n=e.id_token)?n:"");if(i.sub||r.throw(new Error("ID Token is missing a subject claim")),t){const e=m.decode(t);i.sub!==e.sub&&r.throw(new Error("sub in id_token does not match current sub")),i.auth_time&&i.auth_time!==e.auth_time&&r.throw(new Error("auth_time in id_token does not match original auth_time")),i.azp&&i.azp!==e.azp&&r.throw(new Error("azp in id_token does not match original azp")),!i.azp&&e.azp&&r.throw(new Error("azp not in id_token, but present in original id_token"))}e.profile=i}},U=class e{constructor(e){this.id=e.id||f.generateUUIDv4(),this.data=e.data,e.created&&e.created>0?this.created=e.created:this.created=_.getEpochTime(),this.request_type=e.request_type,this.url_state=e.url_state}toStorageString(){return new p("State").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state})}static fromStorageString(t){return p.createStatic("State","fromStorageString"),Promise.resolve(new e(JSON.parse(t)))}static async clearStaleState(t,n){const r=p.createStatic("State","clearStaleState"),i=_.getEpochTime()-n,o=await t.getAllKeys();r.debug("got keys",o);for(let a=0;a<o.length;a++){const n=o[a],u=await t.get(n);let l=!1;if(u)try{const t=await e.fromStorageString(u);r.debug("got item from key:",n,t.created),t.created<=i&&(l=!0)}catch(s){r.error("Error parsing state for key:",n,s),l=!0}else r.debug("no item in storage for key:",n),l=!0;l&&(r.debug("removed item for key:",n),t.remove(n))}}},j=class e extends U{constructor(e){super(e),this.code_verifier=e.code_verifier,this.code_challenge=e.code_challenge,this.authority=e.authority,this.client_id=e.client_id,this.redirect_uri=e.redirect_uri,this.scope=e.scope,this.client_secret=e.client_secret,this.extraTokenParams=e.extraTokenParams,this.response_mode=e.response_mode,this.skipUserInfo=e.skipUserInfo}static async create(t){const n=!0===t.code_verifier?f.generateCodeVerifier():t.code_verifier||void 0,r=n?await f.generateCodeChallenge(n):void 0;return new e({...t,code_verifier:n,code_challenge:r})}toStorageString(){return new p("SigninState").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state,code_verifier:this.code_verifier,authority:this.authority,client_id:this.client_id,redirect_uri:this.redirect_uri,scope:this.scope,client_secret:this.client_secret,extraTokenParams:this.extraTokenParams,response_mode:this.response_mode,skipUserInfo:this.skipUserInfo})}static fromStorageString(t){p.createStatic("SigninState","fromStorageString");const n=JSON.parse(t);return e.create(n)}},z=class e{constructor(e){this.url=e.url,this.state=e.state}static async create({url:t,authority:n,client_id:r,redirect_uri:i,response_type:o,scope:s,state_data:a,response_mode:u,request_type:l,client_secret:c,nonce:d,url_state:p,resource:m,skipUserInfo:h,extraQueryParams:g,extraTokenParams:f,disablePKCE:v,dpopJkt:y,omitScopeWhenRequesting:_,...b}){if(!t)throw this._logger.error("create: No url passed"),new Error("url");if(!r)throw this._logger.error("create: No client_id passed"),new Error("client_id");if(!i)throw this._logger.error("create: No redirect_uri passed"),new Error("redirect_uri");if(!o)throw this._logger.error("create: No response_type passed"),new Error("response_type");if(!s)throw this._logger.error("create: No scope passed"),new Error("scope");if(!n)throw this._logger.error("create: No authority passed"),new Error("authority");const k=await j.create({data:a,request_type:l,url_state:p,code_verifier:!v,client_id:r,authority:n,redirect_uri:i,response_mode:u,client_secret:c,scope:s,extraTokenParams:f,skipUserInfo:h}),x=new URL(t);x.searchParams.append("client_id",r),x.searchParams.append("redirect_uri",i),x.searchParams.append("response_type",o),_||x.searchParams.append("scope",s),d&&x.searchParams.append("nonce",d),y&&x.searchParams.append("dpop_jkt",y);let I=k.id;if(p&&(I=`${I}${w}${p}`),x.searchParams.append("state",I),k.code_challenge&&(x.searchParams.append("code_challenge",k.code_challenge),x.searchParams.append("code_challenge_method","S256")),m){(Array.isArray(m)?m:[m]).forEach((e=>x.searchParams.append("resource",e)))}for(const[e,w]of Object.entries({response_mode:u,...b,...g}))null!=w&&x.searchParams.append(e,w.toString());return new e({url:x.href,state:k})}};z._logger=new p("SigninRequest");var D=z,M=class{constructor(e){if(this.access_token="",this.token_type="",this.profile={},this.state=e.get("state"),this.session_state=e.get("session_state"),this.state){const e=decodeURIComponent(this.state).split(w);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(w))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri"),this.code=e.get("code")}get expires_in(){if(void 0!==this.expires_at)return this.expires_at-_.getEpochTime()}set expires_in(e){"string"==typeof e&&(e=Number(e)),void 0!==e&&e>=0&&(this.expires_at=Math.floor(e)+_.getEpochTime())}get isOpenId(){var e;return(null==(e=this.scope)?void 0:e.split(" ").includes("openid"))||!!this.id_token}},L=class{constructor({url:e,state_data:t,id_token_hint:n,post_logout_redirect_uri:r,extraQueryParams:i,request_type:o,client_id:s,url_state:a}){if(this._logger=new p("SignoutRequest"),!e)throw this._logger.error("ctor: No url passed"),new Error("url");const u=new URL(e);if(n&&u.searchParams.append("id_token_hint",n),s&&u.searchParams.append("client_id",s),r&&(u.searchParams.append("post_logout_redirect_uri",r),t||a)){this.state=new U({data:t,request_type:o,url_state:a});let e=this.state.id;a&&(e=`${e}${w}${a}`),u.searchParams.append("state",e)}for(const[l,c]of Object.entries({...i}))null!=c&&u.searchParams.append(l,c.toString());this.url=u.href}},Z=class{constructor(e){if(this.state=e.get("state"),this.state){const e=decodeURIComponent(this.state).split(w);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(w))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri")}},q=["nbf","jti","auth_time","nonce","acr","amr","azp","at_hash"],F=["sub","iss","aud","exp","iat"],W=class{constructor(e){this._settings=e,this._logger=new p("ClaimsService")}filterProtocolClaims(e){const t={...e};if(this._settings.filterProtocolClaims){let e;e=Array.isArray(this._settings.filterProtocolClaims)?this._settings.filterProtocolClaims:q;for(const n of e)F.includes(n)||delete t[n]}return t}mergeClaims(e,t){const n={...e};for(const[r,i]of Object.entries(t))if(n[r]!==i)if(Array.isArray(n[r])||Array.isArray(i))if("replace"==this._settings.mergeClaimsStrategy.array)n[r]=i;else{const e=Array.isArray(n[r])?n[r]:[n[r]];for(const t of Array.isArray(i)?i:[i])e.includes(t)||e.push(t);n[r]=e}else"object"==typeof n[r]&&"object"==typeof i?n[r]=this.mergeClaims(n[r],i):n[r]=i;return n}},J=class{constructor(e,t){this.keys=e,this.nonce=t}},B=class{constructor(e,t){this._logger=new p("OidcClient"),this.settings=e instanceof C?e:new C(e),this.metadataService=null!=t?t:new O(this.settings),this._claimsService=new W(this.settings),this._validator=new R(this.settings,this.metadataService,this._claimsService),this._tokenClient=new P(this.settings,this.metadataService)}async createSigninRequest({state:e,request:t,request_uri:n,request_type:r,id_token_hint:i,login_hint:o,skipUserInfo:s,nonce:a,url_state:u,response_type:l=this.settings.response_type,scope:c=this.settings.scope,redirect_uri:d=this.settings.redirect_uri,prompt:p=this.settings.prompt,display:m=this.settings.display,max_age:h=this.settings.max_age,ui_locales:g=this.settings.ui_locales,acr_values:f=this.settings.acr_values,resource:v=this.settings.resource,response_mode:y=this.settings.response_mode,extraQueryParams:_=this.settings.extraQueryParams,extraTokenParams:b=this.settings.extraTokenParams,dpopJkt:w,omitScopeWhenRequesting:k=this.settings.omitScopeWhenRequesting}){const x=this._logger.create("createSigninRequest");if("code"!==l)throw new Error("Only the Authorization Code flow (with PKCE) is supported");const I=await this.metadataService.getAuthorizationEndpoint();x.debug("Received authorization endpoint",I);const S=await D.create({url:I,authority:this.settings.authority,client_id:this.settings.client_id,redirect_uri:d,response_type:l,scope:c,state_data:e,url_state:u,prompt:p,display:m,max_age:h,ui_locales:g,id_token_hint:i,login_hint:o,acr_values:f,dpopJkt:w,resource:v,request:t,request_uri:n,extraQueryParams:_,extraTokenParams:b,request_type:r,response_mode:y,client_secret:this.settings.client_secret,skipUserInfo:s,nonce:a,disablePKCE:this.settings.disablePKCE,omitScopeWhenRequesting:k});await this.clearStaleState();const $=S.state;return await this.settings.stateStore.set($.id,$.toStorageString()),S}async readSigninResponseState(e,t=!1){const n=this._logger.create("readSigninResponseState"),r=new M(b.readParams(e,this.settings.response_mode));if(!r.state)throw n.throw(new Error("No state in response")),null;const i=await this.settings.stateStore[t?"remove":"get"](r.state);if(!i)throw n.throw(new Error("No matching state found in storage")),null;return{state:await j.fromStorageString(i),response:r}}async processSigninResponse(e,t,n=!0){const r=this._logger.create("processSigninResponse"),{state:i,response:o}=await this.readSigninResponseState(e,n);if(r.debug("received state from storage; validating response"),this.settings.dpop&&this.settings.dpop.store){const e=await this.getDpopProof(this.settings.dpop.store);t={...t,DPoP:e}}try{await this._validator.validateSigninResponse(o,i,t)}catch(s){if(!(s instanceof E&&this.settings.dpop))throw s;{const e=await this.getDpopProof(this.settings.dpop.store,s.nonce);t.DPoP=e,await this._validator.validateSigninResponse(o,i,t)}}return o}async getDpopProof(e,t){let n,r;return(await e.getAllKeys()).includes(this.settings.client_id)?(r=await e.get(this.settings.client_id),r.nonce!==t&&t&&(r.nonce=t,await e.set(this.settings.client_id,r))):(n=await f.generateDPoPKeys(),r=new J(n,t),await e.set(this.settings.client_id,r)),await f.generateDPoPProof({url:await this.metadataService.getTokenEndpoint(!1),httpMethod:"POST",keyPair:r.keys,nonce:r.nonce})}async processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:n=!1,extraTokenParams:r={}}){const i=await this._tokenClient.exchangeCredentials({username:e,password:t,...r}),o=new M(new URLSearchParams);return Object.assign(o,i),await this._validator.validateCredentialsResponse(o,n),o}async useRefreshToken({state:e,redirect_uri:t,resource:n,timeoutInSeconds:r,extraHeaders:i,extraTokenParams:o}){var s;const a=this._logger.create("useRefreshToken");let u,l;if(void 0===this.settings.refreshTokenAllowedScope)u=e.scope;else{const t=this.settings.refreshTokenAllowedScope.split(" ");u=((null==(s=e.scope)?void 0:s.split(" "))||[]).filter((e=>t.includes(e))).join(" ")}if(this.settings.dpop&&this.settings.dpop.store){const e=await this.getDpopProof(this.settings.dpop.store);i={...i,DPoP:e}}try{l=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:u,redirect_uri:t,resource:n,timeoutInSeconds:r,extraHeaders:i,...o})}catch(d){if(!(d instanceof E&&this.settings.dpop))throw d;i.DPoP=await this.getDpopProof(this.settings.dpop.store,d.nonce),l=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:u,redirect_uri:t,resource:n,timeoutInSeconds:r,extraHeaders:i,...o})}const c=new M(new URLSearchParams);return Object.assign(c,l),a.debug("validating response",c),await this._validator.validateRefreshResponse(c,{...e,scope:u}),c}async createSignoutRequest({state:e,id_token_hint:t,client_id:n,request_type:r,url_state:i,post_logout_redirect_uri:o=this.settings.post_logout_redirect_uri,extraQueryParams:s=this.settings.extraQueryParams}={}){const a=this._logger.create("createSignoutRequest"),u=await this.metadataService.getEndSessionEndpoint();if(!u)throw a.throw(new Error("No end session endpoint")),null;a.debug("Received end session endpoint",u),n||!o||t||(n=this.settings.client_id);const l=new L({url:u,id_token_hint:t,client_id:n,post_logout_redirect_uri:o,state_data:e,extraQueryParams:s,request_type:r,url_state:i});await this.clearStaleState();const c=l.state;return c&&(a.debug("Signout request has state to persist"),await this.settings.stateStore.set(c.id,c.toStorageString())),l}async readSignoutResponseState(e,t=!1){const n=this._logger.create("readSignoutResponseState"),r=new Z(b.readParams(e,this.settings.response_mode));if(!r.state){if(n.debug("No state in response"),r.error)throw n.warn("Response was error:",r.error),new k(r);return{state:void 0,response:r}}const i=await this.settings.stateStore[t?"remove":"get"](r.state);if(!i)throw n.throw(new Error("No matching state found in storage")),null;return{state:await U.fromStorageString(i),response:r}}async processSignoutResponse(e){const t=this._logger.create("processSignoutResponse"),{state:n,response:r}=await this.readSignoutResponseState(e,!0);return n?(t.debug("Received state from storage; validating response"),this._validator.validateSignoutResponse(r,n)):t.debug("No state from storage; skipping response validation"),r}clearStaleState(){return this._logger.create("clearStaleState"),U.clearStaleState(this.settings.stateStore,this.settings.staleStateAgeInSeconds)}async revokeToken(e,t){return this._logger.create("revokeToken"),await this._tokenClient.revoke({token:e,token_type_hint:t})}},H=class{constructor(e){this._userManager=e,this._logger=new p("SessionMonitor"),this._start=async e=>{const t=e.session_state;if(!t)return;const n=this._logger.create("_start");if(e.profile?(this._sub=e.profile.sub,n.debug("session_state",t,", sub",this._sub)):(this._sub=void 0,n.debug("session_state",t,", anonymous user")),this._checkSessionIFrame)this._checkSessionIFrame.start(t);else try{const e=await this._userManager.metadataService.getCheckSessionIframe();if(e){n.debug("initializing check session iframe");const r=this._userManager.settings.client_id,i=this._userManager.settings.checkSessionIntervalInSeconds,o=this._userManager.settings.stopCheckSessionOnError,s=new S(this._callback,r,e,i,o);await s.load(),this._checkSessionIFrame=s,s.start(t)}else n.warn("no check session iframe found in the metadata")}catch(r){n.error("Error from getCheckSessionIframe:",r instanceof Error?r.message:r)}},this._stop=()=>{const e=this._logger.create("_stop");if(this._sub=void 0,this._checkSessionIFrame&&this._checkSessionIFrame.stop(),this._userManager.settings.monitorAnonymousSession){const t=setInterval((async()=>{clearInterval(t);try{const e=await this._userManager.querySessionStatus();if(e){const t={session_state:e.session_state,profile:e.sub?{sub:e.sub}:null};this._start(t)}}catch(n){e.error("error from querySessionStatus",n instanceof Error?n.message:n)}}),1e3)}},this._callback=async()=>{const e=this._logger.create("_callback");try{const t=await this._userManager.querySessionStatus();let n=!0;t&&this._checkSessionIFrame?t.sub===this._sub?(n=!1,this._checkSessionIFrame.start(t.session_state),e.debug("same sub still logged in at OP, session state has changed, restarting check session iframe; session_state",t.session_state),await this._userManager.events._raiseUserSessionChanged()):e.debug("different subject signed into OP",t.sub):e.debug("subject no longer signed into OP"),n?this._sub?await this._userManager.events._raiseUserSignedOut():await this._userManager.events._raiseUserSignedIn():e.debug("no change in session detected, no event to raise")}catch(t){this._sub&&(e.debug("Error calling queryCurrentSigninSession; raising signed out event",t),await this._userManager.events._raiseUserSignedOut())}},e||this._logger.throw(new Error("No user manager passed")),this._userManager.events.addUserLoaded(this._start),this._userManager.events.addUserUnloaded(this._stop),this._init().catch((e=>{this._logger.error(e)}))}async _init(){this._logger.create("_init");const e=await this._userManager.getUser();if(e)this._start(e);else if(this._userManager.settings.monitorAnonymousSession){const e=await this._userManager.querySessionStatus();if(e){const t={session_state:e.session_state,profile:e.sub?{sub:e.sub}:null};this._start(t)}}}},V=class e{constructor(e){var t;this.id_token=e.id_token,this.session_state=null!=(t=e.session_state)?t:null,this.access_token=e.access_token,this.refresh_token=e.refresh_token,this.token_type=e.token_type,this.scope=e.scope,this.profile=e.profile,this.expires_at=e.expires_at,this.state=e.userState,this.url_state=e.url_state}get expires_in(){if(void 0!==this.expires_at)return this.expires_at-_.getEpochTime()}set expires_in(e){void 0!==e&&(this.expires_at=Math.floor(e)+_.getEpochTime())}get expired(){const e=this.expires_in;if(void 0!==e)return e<=0}get scopes(){var e,t;return null!=(t=null==(e=this.scope)?void 0:e.split(" "))?t:[]}toStorageString(){return new p("User").create("toStorageString"),JSON.stringify({id_token:this.id_token,session_state:this.session_state,access_token:this.access_token,refresh_token:this.refresh_token,token_type:this.token_type,scope:this.scope,profile:this.profile,expires_at:this.expires_at})}static fromStorageString(t){return p.createStatic("User","fromStorageString"),new e(JSON.parse(t))}},K="oidc-client",G=class{constructor(){this._abort=new v("Window navigation aborted"),this._disposeHandlers=new Set,this._window=null}async navigate(e){const t=this._logger.create("navigate");if(!this._window)throw new Error("Attempted to navigate on a disposed window");t.debug("setting URL in window"),this._window.location.replace(e.url);const{url:n,keepOpen:r}=await new Promise(((n,r)=>{const i=i=>{var o;const s=i.data,a=null!=(o=e.scriptOrigin)?o:window.location.origin;if(i.origin===a&&(null==s?void 0:s.source)===K){try{const n=b.readParams(s.url,e.response_mode).get("state");if(n||t.warn("no state found in response url"),i.source!==this._window&&n!==e.state)return}catch{this._dispose(),r(new Error("Invalid response from window"))}n(s)}};window.addEventListener("message",i,!1),this._disposeHandlers.add((()=>window.removeEventListener("message",i,!1)));const o=new BroadcastChannel(`oidc-client-popup-${e.state}`);o.addEventListener("message",i,!1),this._disposeHandlers.add((()=>o.close())),this._disposeHandlers.add(this._abort.addHandler((e=>{this._dispose(),r(e)})))}));return t.debug("got response from window"),this._dispose(),r||this.close(),{url:n}}_dispose(){this._logger.create("_dispose");for(const e of this._disposeHandlers)e();this._disposeHandlers.clear()}static _notifyParent(e,t,n=!1,r=window.location.origin){const i={source:K,url:t,keepOpen:n},o=new p("_notifyParent");if(e)o.debug("With parent. Using parent.postMessage."),e.postMessage(i,r);else{o.debug("No parent. Using BroadcastChannel.");const e=new URL(t).searchParams.get("state");if(!e)throw new Error("No parent and no state in URL. Can't complete notification.");const n=new BroadcastChannel(`oidc-client-popup-${e}`);n.postMessage(i),n.close()}}},Y={location:!1,toolbar:!1,height:640,closePopupWindowAfterInSeconds:-1},X="_blank",Q=60,ee=2,te=class extends C{constructor(e){const{popup_redirect_uri:t=e.redirect_uri,popup_post_logout_redirect_uri:n=e.post_logout_redirect_uri,popupWindowFeatures:r=Y,popupWindowTarget:i=X,redirectMethod:o="assign",redirectTarget:s="self",iframeNotifyParentOrigin:a=e.iframeNotifyParentOrigin,iframeScriptOrigin:u=e.iframeScriptOrigin,requestTimeoutInSeconds:l,silent_redirect_uri:c=e.redirect_uri,silentRequestTimeoutInSeconds:d,automaticSilentRenew:p=!0,validateSubOnSilentRenew:m=!0,includeIdTokenInSilentRenew:h=!1,monitorSession:g=!1,monitorAnonymousSession:f=!1,checkSessionIntervalInSeconds:v=ee,query_status_response_type:y="code",stopCheckSessionOnError:_=!0,revokeTokenTypes:b=["access_token","refresh_token"],revokeTokensOnSignout:w=!1,includeIdTokenInSilentSignout:k=!1,accessTokenExpiringNotificationTimeInSeconds:x=Q,userStore:I}=e;if(super(e),this.popup_redirect_uri=t,this.popup_post_logout_redirect_uri=n,this.popupWindowFeatures=r,this.popupWindowTarget=i,this.redirectMethod=o,this.redirectTarget=s,this.iframeNotifyParentOrigin=a,this.iframeScriptOrigin=u,this.silent_redirect_uri=c,this.silentRequestTimeoutInSeconds=d||l||10,this.automaticSilentRenew=p,this.validateSubOnSilentRenew=m,this.includeIdTokenInSilentRenew=h,this.monitorSession=g,this.monitorAnonymousSession=f,this.checkSessionIntervalInSeconds=v,this.stopCheckSessionOnError=_,this.query_status_response_type=y,this.revokeTokenTypes=b,this.revokeTokensOnSignout=w,this.includeIdTokenInSilentSignout=k,this.accessTokenExpiringNotificationTimeInSeconds=x,I)this.userStore=I;else{const e="undefined"!=typeof window?window.sessionStorage:new $;this.userStore=new N({store:e})}}},ne=class e extends G{constructor({silentRequestTimeoutInSeconds:t=10}){super(),this._logger=new p("IFrameWindow"),this._timeoutInSeconds=t,this._frame=e.createHiddenIframe(),this._window=this._frame.contentWindow}static createHiddenIframe(){const e=window.document.createElement("iframe");return e.style.visibility="hidden",e.style.position="fixed",e.style.left="-1000px",e.style.top="0",e.width="0",e.height="0",window.document.body.appendChild(e),e}async navigate(e){this._logger.debug("navigate: Using timeout of:",this._timeoutInSeconds);const t=setTimeout((()=>{this._abort.raise(new x("IFrame timed out without a response"))}),1e3*this._timeoutInSeconds);return this._disposeHandlers.add((()=>clearTimeout(t))),await super.navigate(e)}close(){var e;this._frame&&(this._frame.parentNode&&(this._frame.addEventListener("load",(e=>{var t;const n=e.target;null==(t=n.parentNode)||t.removeChild(n),this._abort.raise(new Error("IFrame removed from DOM"))}),!0),null==(e=this._frame.contentWindow)||e.location.replace("about:blank")),this._frame=null),this._window=null}static notifyParent(e,t){return super._notifyParent(window.parent,e,!1,t)}},re=class{constructor(e){this._settings=e,this._logger=new p("IFrameNavigator")}async prepare({silentRequestTimeoutInSeconds:e=this._settings.silentRequestTimeoutInSeconds}){return new ne({silentRequestTimeoutInSeconds:e})}async callback(e){this._logger.create("callback"),ne.notifyParent(e,this._settings.iframeNotifyParentOrigin)}},ie=class extends G{constructor({popupWindowTarget:e=X,popupWindowFeatures:t={},popupSignal:n}){super(),this._logger=new p("PopupWindow");const r=y.center({...Y,...t});this._window=window.open(void 0,e,y.serialize(r)),n&&n.addEventListener("abort",(()=>{var e;this._abort.raise(new Error(null!=(e=n.reason)?e:"Popup aborted"))})),t.closePopupWindowAfterInSeconds&&t.closePopupWindowAfterInSeconds>0&&setTimeout((()=>{this._window&&"boolean"==typeof this._window.closed&&!this._window.closed?this.close():this._abort.raise(new Error("Popup blocked by user"))}),1e3*t.closePopupWindowAfterInSeconds)}async navigate(e){var t;null==(t=this._window)||t.focus();const n=setInterval((()=>{this._window&&!this._window.closed||(this._logger.debug("Popup closed by user or isolated by redirect"),r(),this._disposeHandlers.delete(r))}),500),r=()=>clearInterval(n);return this._disposeHandlers.add(r),await super.navigate(e)}close(){this._window&&(this._window.closed||(this._window.close(),this._abort.raise(new Error("Popup closed")))),this._window=null}static notifyOpener(e,t){super._notifyParent(window.opener,e,t),t||window.opener||window.close()}},oe=class{constructor(e){this._settings=e,this._logger=new p("PopupNavigator")}async prepare({popupWindowFeatures:e=this._settings.popupWindowFeatures,popupWindowTarget:t=this._settings.popupWindowTarget,popupSignal:n}){return new ie({popupWindowFeatures:e,popupWindowTarget:t,popupSignal:n})}async callback(e,{keepOpen:t=!1}){this._logger.create("callback"),ie.notifyOpener(e,t)}},se=class{constructor(e){this._settings=e,this._logger=new p("RedirectNavigator")}async prepare({redirectMethod:e=this._settings.redirectMethod,redirectTarget:t=this._settings.redirectTarget}){var n;this._logger.create("prepare");let r=window.self;"top"===t&&(r=null!=(n=window.top)?n:window.self);const i=r.location[e].bind(r.location);let o;return{navigate:async e=>{this._logger.create("navigate");const t=new Promise(((e,t)=>{o=t}));return i(e.url),await t},close:()=>{this._logger.create("close"),null==o||o(new Error("Redirect aborted")),r.stop()}}}async callback(){}},ae=class extends I{constructor(e){super({expiringNotificationTimeInSeconds:e.accessTokenExpiringNotificationTimeInSeconds}),this._logger=new p("UserManagerEvents"),this._userLoaded=new v("User loaded"),this._userUnloaded=new v("User unloaded"),this._silentRenewError=new v("Silent renew error"),this._userSignedIn=new v("User signed in"),this._userSignedOut=new v("User signed out"),this._userSessionChanged=new v("User session changed")}async load(e,t=!0){await super.load(e),t&&await this._userLoaded.raise(e)}async unload(){await super.unload(),await this._userUnloaded.raise()}addUserLoaded(e){return this._userLoaded.addHandler(e)}removeUserLoaded(e){return this._userLoaded.removeHandler(e)}addUserUnloaded(e){return this._userUnloaded.addHandler(e)}removeUserUnloaded(e){return this._userUnloaded.removeHandler(e)}addSilentRenewError(e){return this._silentRenewError.addHandler(e)}removeSilentRenewError(e){return this._silentRenewError.removeHandler(e)}async _raiseSilentRenewError(e){await this._silentRenewError.raise(e)}addUserSignedIn(e){return this._userSignedIn.addHandler(e)}removeUserSignedIn(e){this._userSignedIn.removeHandler(e)}async _raiseUserSignedIn(){await this._userSignedIn.raise()}addUserSignedOut(e){return this._userSignedOut.addHandler(e)}removeUserSignedOut(e){this._userSignedOut.removeHandler(e)}async _raiseUserSignedOut(){await this._userSignedOut.raise()}addUserSessionChanged(e){return this._userSessionChanged.addHandler(e)}removeUserSessionChanged(e){this._userSessionChanged.removeHandler(e)}async _raiseUserSessionChanged(){await this._userSessionChanged.raise()}},ue=class{constructor(e){this._userManager=e,this._logger=new p("SilentRenewService"),this._isStarted=!1,this._retryTimer=new _("Retry Silent Renew"),this._tokenExpiring=async()=>{const e=this._logger.create("_tokenExpiring");try{await this._userManager.signinSilent(),e.debug("silent token renewal successful")}catch(t){if(t instanceof x)return e.warn("ErrorTimeout from signinSilent:",t,"retry in 5s"),void this._retryTimer.init(5);e.error("Error from signinSilent:",t),await this._userManager.events._raiseSilentRenewError(t)}}}async start(){const e=this._logger.create("start");if(!this._isStarted){this._isStarted=!0,this._userManager.events.addAccessTokenExpiring(this._tokenExpiring),this._retryTimer.addHandler(this._tokenExpiring);try{await this._userManager.getUser()}catch(t){e.error("getUser error",t)}}}stop(){this._isStarted&&(this._retryTimer.cancel(),this._retryTimer.removeHandler(this._tokenExpiring),this._userManager.events.removeAccessTokenExpiring(this._tokenExpiring),this._isStarted=!1)}},le=class{constructor(e){this.refresh_token=e.refresh_token,this.id_token=e.id_token,this.session_state=e.session_state,this.scope=e.scope,this.profile=e.profile,this.data=e.state}},ce=class{constructor(e,t,n,r){this._logger=new p("UserManager"),this.settings=new te(e),this._client=new B(e),this._redirectNavigator=null!=t?t:new se(this.settings),this._popupNavigator=null!=n?n:new oe(this.settings),this._iframeNavigator=null!=r?r:new re(this.settings),this._events=new ae(this.settings),this._silentRenewService=new ue(this),this.settings.automaticSilentRenew&&this.startSilentRenew(),this._sessionMonitor=null,this.settings.monitorSession&&(this._sessionMonitor=new H(this))}get events(){return this._events}get metadataService(){return this._client.metadataService}async getUser(e=!1){const t=this._logger.create("getUser"),n=await this._loadUser();return n?(t.info("user loaded"),await this._events.load(n,e),n):(t.info("user not found in storage"),null)}async removeUser(){const e=this._logger.create("removeUser");await this.storeUser(null),e.info("user removed from storage"),await this._events.unload()}async signinRedirect(e={}){var t;this._logger.create("signinRedirect");const{redirectMethod:n,...r}=e;let i;(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(i=await this.generateDPoPJkt(this.settings.dpop));const o=await this._redirectNavigator.prepare({redirectMethod:n});await this._signinStart({request_type:"si:r",dpopJkt:i,...r},o)}async signinRedirectCallback(e=window.location.href){const t=this._logger.create("signinRedirectCallback"),n=await this._signinEnd(e);return n.profile&&n.profile.sub?t.info("success, signed in subject",n.profile.sub):t.info("no subject"),n}async signinResourceOwnerCredentials({username:e,password:t,skipUserInfo:n=!1}){const r=this._logger.create("signinResourceOwnerCredential"),i=await this._client.processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:n,extraTokenParams:this.settings.extraTokenParams});r.debug("got signin response");const o=await this._buildUser(i);return o.profile&&o.profile.sub?r.info("success, signed in subject",o.profile.sub):r.info("no subject"),o}async signinPopup(e={}){var t;const n=this._logger.create("signinPopup");let r;(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(r=await this.generateDPoPJkt(this.settings.dpop));const{popupWindowFeatures:i,popupWindowTarget:o,popupSignal:s,...a}=e,u=this.settings.popup_redirect_uri;u||n.throw(new Error("No popup_redirect_uri configured"));const l=await this._popupNavigator.prepare({popupWindowFeatures:i,popupWindowTarget:o,popupSignal:s}),c=await this._signin({request_type:"si:p",redirect_uri:u,display:"popup",dpopJkt:r,...a},l);return c&&(c.profile&&c.profile.sub?n.info("success, signed in subject",c.profile.sub):n.info("no subject")),c}async signinPopupCallback(e=window.location.href,t=!1){const n=this._logger.create("signinPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),n.info("success")}async signinSilent(e={}){var t,n;const r=this._logger.create("signinSilent"),{silentRequestTimeoutInSeconds:i,...o}=e;let s,a=await this._loadUser();if(null==a?void 0:a.refresh_token){r.debug("using refresh token");const e=new le(a);return await this._useRefreshToken({state:e,redirect_uri:o.redirect_uri,resource:o.resource,extraTokenParams:o.extraTokenParams,timeoutInSeconds:i})}(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(s=await this.generateDPoPJkt(this.settings.dpop));const u=this.settings.silent_redirect_uri;let l;u||r.throw(new Error("No silent_redirect_uri configured")),a&&this.settings.validateSubOnSilentRenew&&(r.debug("subject prior to silent renew:",a.profile.sub),l=a.profile.sub);const c=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:i});return a=await this._signin({request_type:"si:s",redirect_uri:u,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?null==a?void 0:a.id_token:void 0,dpopJkt:s,...o},c,l),a&&((null==(n=a.profile)?void 0:n.sub)?r.info("success, signed in subject",a.profile.sub):r.info("no subject")),a}async _useRefreshToken(e){const t=await this._client.useRefreshToken({timeoutInSeconds:this.settings.silentRequestTimeoutInSeconds,...e}),n=new V({...e.state,...t});return await this.storeUser(n),await this._events.load(n),n}async signinSilentCallback(e=window.location.href){const t=this._logger.create("signinSilentCallback");await this._iframeNavigator.callback(e),t.info("success")}async signinCallback(e=window.location.href){const{state:t}=await this._client.readSigninResponseState(e);switch(t.request_type){case"si:r":return await this.signinRedirectCallback(e);case"si:p":await this.signinPopupCallback(e);break;case"si:s":await this.signinSilentCallback(e);break;default:throw new Error("invalid response_type in state")}}async signoutCallback(e=window.location.href,t=!1){const{state:n}=await this._client.readSignoutResponseState(e);if(n)switch(n.request_type){case"so:r":return await this.signoutRedirectCallback(e);case"so:p":await this.signoutPopupCallback(e,t);break;case"so:s":await this.signoutSilentCallback(e);break;default:throw new Error("invalid response_type in state")}}async querySessionStatus(e={}){const t=this._logger.create("querySessionStatus"),{silentRequestTimeoutInSeconds:n,...r}=e,i=this.settings.silent_redirect_uri;i||t.throw(new Error("No silent_redirect_uri configured"));const o=await this._loadUser(),s=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:n}),a=await this._signinStart({request_type:"si:s",redirect_uri:i,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?null==o?void 0:o.id_token:void 0,response_type:this.settings.query_status_response_type,scope:"openid",skipUserInfo:!0,...r},s);try{const e={},n=await this._client.processSigninResponse(a.url,e);return t.debug("got signin response"),n.session_state&&n.profile.sub?(t.info("success for subject",n.profile.sub),{session_state:n.session_state,sub:n.profile.sub}):(t.info("success, user not authenticated"),null)}catch(u){if(this.settings.monitorAnonymousSession&&u instanceof k)switch(u.error){case"login_required":case"consent_required":case"interaction_required":case"account_selection_required":return t.info("success for anonymous user"),{session_state:u.session_state}}throw u}}async _signin(e,t,n){const r=await this._signinStart(e,t);return await this._signinEnd(r.url,n)}async _signinStart(e,t){const n=this._logger.create("_signinStart");try{const r=await this._client.createSigninRequest(e);return n.debug("got signin request"),await t.navigate({url:r.url,state:r.state.id,response_mode:r.state.response_mode,scriptOrigin:this.settings.iframeScriptOrigin})}catch(r){throw n.debug("error after preparing navigator, closing navigator window"),t.close(),r}}async _signinEnd(e,t){const n=this._logger.create("_signinEnd"),r=await this._client.processSigninResponse(e,{});n.debug("got signin response");return await this._buildUser(r,t)}async _buildUser(e,t){const n=this._logger.create("_buildUser"),r=new V(e);if(t){if(t!==r.profile.sub)throw n.debug("current user does not match user returned from signin. sub from signin:",r.profile.sub),new k({...e,error:"login_required"});n.debug("current user matches user returned from signin")}return await this.storeUser(r),n.debug("user stored"),await this._events.load(r),r}async signoutRedirect(e={}){const t=this._logger.create("signoutRedirect"),{redirectMethod:n,...r}=e,i=await this._redirectNavigator.prepare({redirectMethod:n});await this._signoutStart({request_type:"so:r",post_logout_redirect_uri:this.settings.post_logout_redirect_uri,...r},i),t.info("success")}async signoutRedirectCallback(e=window.location.href){const t=this._logger.create("signoutRedirectCallback"),n=await this._signoutEnd(e);return t.info("success"),n}async signoutPopup(e={}){const t=this._logger.create("signoutPopup"),{popupWindowFeatures:n,popupWindowTarget:r,popupSignal:i,...o}=e,s=this.settings.popup_post_logout_redirect_uri,a=await this._popupNavigator.prepare({popupWindowFeatures:n,popupWindowTarget:r,popupSignal:i});await this._signout({request_type:"so:p",post_logout_redirect_uri:s,state:null==s?void 0:{},...o},a),t.info("success")}async signoutPopupCallback(e=window.location.href,t=!1){const n=this._logger.create("signoutPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),n.info("success")}async _signout(e,t){const n=await this._signoutStart(e,t);return await this._signoutEnd(n.url)}async _signoutStart(e={},t){var n;const r=this._logger.create("_signoutStart");try{const i=await this._loadUser();r.debug("loaded current user from storage"),this.settings.revokeTokensOnSignout&&await this._revokeInternal(i);const o=e.id_token_hint||i&&i.id_token;o&&(r.debug("setting id_token_hint in signout request"),e.id_token_hint=o),await this.removeUser(),r.debug("user removed, creating signout request");const s=await this._client.createSignoutRequest(e);return r.debug("got signout request"),await t.navigate({url:s.url,state:null==(n=s.state)?void 0:n.id,scriptOrigin:this.settings.iframeScriptOrigin})}catch(i){throw r.debug("error after preparing navigator, closing navigator window"),t.close(),i}}async _signoutEnd(e){const t=this._logger.create("_signoutEnd"),n=await this._client.processSignoutResponse(e);return t.debug("got signout response"),n}async signoutSilent(e={}){var t;const n=this._logger.create("signoutSilent"),{silentRequestTimeoutInSeconds:r,...i}=e,o=this.settings.includeIdTokenInSilentSignout?null==(t=await this._loadUser())?void 0:t.id_token:void 0,s=this.settings.popup_post_logout_redirect_uri,a=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:r});await this._signout({request_type:"so:s",post_logout_redirect_uri:s,id_token_hint:o,...i},a),n.info("success")}async signoutSilentCallback(e=window.location.href){const t=this._logger.create("signoutSilentCallback");await this._iframeNavigator.callback(e),t.info("success")}async revokeTokens(e){const t=await this._loadUser();await this._revokeInternal(t,e)}async _revokeInternal(e,t=this.settings.revokeTokenTypes){const n=this._logger.create("_revokeInternal");if(!e)return;const r=t.filter((t=>"string"==typeof e[t]));if(r.length){for(const t of r)await this._client.revokeToken(e[t],t),n.info(`${t} revoked successfully`),"access_token"!==t&&(e[t]=null);await this.storeUser(e),n.debug("user stored"),await this._events.load(e)}else n.debug("no need to revoke due to no token(s)")}startSilentRenew(){this._logger.create("startSilentRenew"),this._silentRenewService.start()}stopSilentRenew(){this._silentRenewService.stop()}get _userStoreKey(){return`user:${this.settings.authority}:${this.settings.client_id}`}async _loadUser(){const e=this._logger.create("_loadUser"),t=await this.settings.userStore.get(this._userStoreKey);return t?(e.debug("user storageString loaded"),V.fromStorageString(t)):(e.debug("no user storageString"),null)}async storeUser(e){const t=this._logger.create("storeUser");if(e){t.debug("storing user");const n=e.toStorageString();await this.settings.userStore.set(this._userStoreKey,n)}else this._logger.debug("removing user"),await this.settings.userStore.remove(this._userStoreKey),this.settings.dpop&&await this.settings.dpop.store.remove(this.settings.client_id)}async clearStaleState(){await this._client.clearStaleState()}async dpopProof(e,t,n,r){var i,o;const s=await(null==(o=null==(i=this.settings.dpop)?void 0:i.store)?void 0:o.get(this.settings.client_id));if(s)return await f.generateDPoPProof({url:e,accessToken:null==t?void 0:t.access_token,httpMethod:n,keyPair:s.keys,nonce:r})}async generateDPoPJkt(e){let t=await e.store.get(this.settings.client_id);if(!t){const n=await f.generateDPoPKeys();t=new J(n),await e.store.set(this.settings.client_id,t)}return await f.generateDPoPJkt(t.keys)}},de=i.createContext(void 0);de.displayName="AuthContext";var pe={isLoading:!0,isAuthenticated:!1},me=(e,t)=>{switch(t.type){case"INITIALISED":case"USER_LOADED":return{...e,user:t.user,isLoading:!1,isAuthenticated:!!t.user&&!t.user.expired,error:void 0};case"USER_SIGNED_OUT":case"USER_UNLOADED":return{...e,user:void 0,isAuthenticated:!1};case"NAVIGATOR_INIT":return{...e,isLoading:!0,activeNavigator:t.method};case"NAVIGATOR_CLOSE":return{...e,isLoading:!1,activeNavigator:void 0};case"ERROR":{const n=t.error;return n.toString=()=>`${n.name}: ${n.message}`,{...e,isLoading:!1,error:n}}default:{const n=new TypeError(`unknown type ${t.type}`),r={name:n.name,message:n.message,innerError:n,stack:n.stack,source:"unknown",toString:()=>`${r.name}: ${r.message}`};return{...e,isLoading:!1,error:r}}}},he=ye("signinCallback","Sign-in failed"),ge=ye("signoutCallback","Sign-out failed"),fe=ye("renewSilent","Renew silent failed");function ve(e,t){return{name:_e(e,"name",(()=>"Error")),message:_e(e,"message",(()=>t)),stack:_e(e,"stack",(()=>(new Error).stack)),innerError:e}}function ye(e,t){return n=>({...ve(n,t),source:e})}function _e(e,t,n){if(e&&"object"==typeof e){const n=e[t];if("string"==typeof n)return n}return n()}var be,we=["clearStaleState","querySessionStatus","revokeTokens","startSilentRenew","stopSilentRenew"],ke=["signinPopup","signinSilent","signinRedirect","signinResourceOwnerCredentials","signoutPopup","signoutRedirect","signoutSilent"],xe=e=>()=>{throw new Error(`UserManager#${e} was called from an unsupported context. If this is a server-rendered page, defer this call with useEffect() or pass a custom UserManager implementation.`)},Ie="undefined"==typeof window?null:ce,Se=e=>{const{children:t,onSigninCallback:n,skipSigninCallback:r,matchSignoutCallback:o,onSignoutCallback:s,onRemoveUser:a,userManager:u=null,...l}=e,[c]=i.useState((()=>null!=u?u:Ie?new Ie(l):{settings:l})),[d,p]=i.useReducer(me,pe),m=i.useMemo((()=>Object.assign({settings:c.settings,events:c.events},Object.fromEntries(we.map((e=>{var t,n;return[e,null!=(n=null==(t=c[e])?void 0:t.bind(c))?n:xe(e)]}))),Object.fromEntries(ke.map((e=>[e,c[e]?async t=>{p({type:"NAVIGATOR_INIT",method:e});try{return await c[e](t)}catch(n){return p({type:"ERROR",error:{...ve(n,`Unknown error while executing ${e}(...).`),source:e,args:t}}),null}finally{p({type:"NAVIGATOR_CLOSE"})}}:xe(e)]))))),[c]),h=i.useRef(!1);i.useEffect((()=>{c&&!h.current&&(h.current=!0,(async()=>{try{let e=null;((e=window.location)=>{let t=new URLSearchParams(e.search);return!!((t.get("code")||t.get("error"))&&t.get("state")||(t=new URLSearchParams(e.hash.replace("#","?")),(t.get("code")||t.get("error"))&&t.get("state")))})()&&!r&&(e=await c.signinCallback(),n&&await n(e)),e=e||await c.getUser(),p({type:"INITIALISED",user:e})}catch(e){p({type:"ERROR",error:he(e)})}try{if(o&&o(c.settings)){const e=await c.signoutCallback();s&&await s(e)}}catch(e){p({type:"ERROR",error:ge(e)})}})())}),[c,r,n,s,o]),i.useEffect((()=>{if(!c)return;const e=e=>{p({type:"USER_LOADED",user:e})};c.events.addUserLoaded(e);const t=()=>{p({type:"USER_UNLOADED"})};c.events.addUserUnloaded(t);const n=()=>{p({type:"USER_SIGNED_OUT"})};c.events.addUserSignedOut(n);const r=e=>{p({type:"ERROR",error:fe(e)})};return c.events.addSilentRenewError(r),()=>{c.events.removeUserLoaded(e),c.events.removeUserUnloaded(t),c.events.removeUserSignedOut(n),c.events.removeSilentRenewError(r)}}),[c]);const g=i.useCallback((async()=>{await c.removeUser(),a&&await a()}),[c,a]),f=i.useMemo((()=>({...d,...m,removeUser:g})),[d,m,g]);return i.createElement(de.Provider,{value:f},t)},$e=()=>{const e=i.useContext(de);return e||console.warn("AuthProvider context is undefined, please verify you are calling useAuth() as child of a <AuthProvider> component."),e},Ee="vercel.ai.error",Te=Symbol.for(Ee),Oe=class e extends Error{constructor({name:e,message:t,cause:n}){super(t),this[be]=!0,this.name=e,this.cause=n}static isInstance(t){return e.hasMarker(t,Ee)}static hasMarker(e,t){const n=Symbol.for(t);return null!=e&&"object"==typeof e&&n in e&&"boolean"==typeof e[n]&&!0===e[n]}};be=Te;var Ne,Ce=Oe,Ae="AI_APICallError",Pe=`vercel.ai.error.${Ae}`,Re=Symbol.for(Pe),Ue=class extends Ce{constructor({message:e,url:t,requestBodyValues:n,statusCode:r,responseHeaders:i,responseBody:o,cause:s,isRetryable:a=null!=r&&(408===r||409===r||429===r||r>=500),data:u}){super({name:Ae,message:e,cause:s}),this[Ne]=!0,this.url=t,this.requestBodyValues=n,this.statusCode=r,this.responseHeaders=i,this.responseBody=o,this.isRetryable=a,this.data=u}static isInstance(e){return Ce.hasMarker(e,Pe)}};Ne=Re;var je,ze="AI_EmptyResponseBodyError",De=`vercel.ai.error.${ze}`,Me=Symbol.for(De),Le=class extends Ce{constructor({message:e="Empty response body"}={}){super({name:ze,message:e}),this[je]=!0}static isInstance(e){return Ce.hasMarker(e,De)}};function Ze(e){return null==e?"unknown error":"string"==typeof e?e:e instanceof Error?e.message:JSON.stringify(e)}je=Me;var qe,Fe="AI_InvalidArgumentError",We=`vercel.ai.error.${Fe}`,Je=Symbol.for(We),Be=class extends Ce{constructor({message:e,cause:t,argument:n}){super({name:Fe,message:e,cause:t}),this[qe]=!0,this.argument=n}static isInstance(e){return Ce.hasMarker(e,We)}};qe=Je;var He,Ve="AI_InvalidPromptError",Ke=`vercel.ai.error.${Ve}`,Ge=Symbol.for(Ke),Ye=class extends Ce{constructor({prompt:e,message:t,cause:n}){super({name:Ve,message:`Invalid prompt: ${t}`,cause:n}),this[He]=!0,this.prompt=e}static isInstance(e){return Ce.hasMarker(e,Ke)}};He=Ge;var Xe,Qe="AI_InvalidResponseDataError",et=`vercel.ai.error.${Qe}`,tt=Symbol.for(et),nt=class extends Ce{constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:Qe,message:t}),this[Xe]=!0,this.data=e}static isInstance(e){return Ce.hasMarker(e,et)}};Xe=tt;var rt,it="AI_JSONParseError",ot=`vercel.ai.error.${it}`,st=Symbol.for(ot),at=class extends Ce{constructor({text:e,cause:t}){super({name:it,message:`JSON parsing failed: Text: ${e}.\nError message: ${Ze(t)}`,cause:t}),this[rt]=!0,this.text=e}static isInstance(e){return Ce.hasMarker(e,ot)}};rt=st;var ut,lt="AI_LoadAPIKeyError",ct=`vercel.ai.error.${lt}`,dt=Symbol.for(ct),pt=class extends Ce{constructor({message:e}){super({name:lt,message:e}),this[ut]=!0}static isInstance(e){return Ce.hasMarker(e,ct)}};ut=dt;var mt,ht="AI_NoSuchModelError",gt=`vercel.ai.error.${ht}`,ft=Symbol.for(gt),vt=class extends Ce{constructor({errorName:e=ht,modelId:t,modelType:n,message:r=`No such ${n}: ${t}`}){super({name:e,message:r}),this[mt]=!0,this.modelId=t,this.modelType=n}static isInstance(e){return Ce.hasMarker(e,gt)}};mt=ft;var yt,_t="AI_TooManyEmbeddingValuesForCallError",bt=`vercel.ai.error.${_t}`,wt=Symbol.for(bt),kt=class extends Ce{constructor(e){super({name:_t,message:`Too many values for a single embedding call. The ${e.provider} model "${e.modelId}" can only embed up to ${e.maxEmbeddingsPerCall} values per call, but ${e.values.length} values were provided.`}),this[yt]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return Ce.hasMarker(e,bt)}};yt=wt;var xt,It="AI_TypeValidationError",St=`vercel.ai.error.${It}`,$t=Symbol.for(St);xt=$t;var Et,Tt=class e extends Ce{constructor({value:e,cause:t}){super({name:It,message:`Type validation failed: Value: ${JSON.stringify(e)}.\nError message: ${Ze(t)}`,cause:t}),this[xt]=!0,this.value=e}static isInstance(e){return Ce.hasMarker(e,St)}static wrap({value:t,cause:n}){return e.isInstance(n)&&n.value===t?n:new e({value:t,cause:n})}},Ot="AI_UnsupportedFunctionalityError",Nt=`vercel.ai.error.${Ot}`,Ct=Symbol.for(Nt),At=class extends Ce{constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:Ot,message:t}),this[Et]=!0,this.functionality=e}static isInstance(e){return Ce.hasMarker(e,Nt)}};Et=Ct;class Pt extends Error{constructor(e,t){super(e),this.name="ParseError",this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}}function Rt(e){}function Ut(e){if("function"==typeof e)throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=Rt,onError:n=Rt,onRetry:r=Rt,onComment:i}=e;let o,s="",a=!0,u="",l="";function c(e){if(""===e)return u.length>0&&t({id:o,event:l||void 0,data:u.endsWith("\n")?u.slice(0,-1):u}),o=void 0,u="",void(l="");if(e.startsWith(":"))return void(i&&i(e.slice(e.startsWith(": ")?2:1)));const n=e.indexOf(":");if(-1===n)d(e,"",e);else{const t=e.slice(0,n),r=" "===e[n+1]?2:1;d(t,e.slice(n+r),e)}}function d(e,t,i){switch(e){case"event":l=t;break;case"data":u=`${u}${t}\n`;break;case"id":o=t.includes("\0")?void 0:t;break;case"retry":/^\d+$/.test(t)?r(parseInt(t,10)):n(new Pt(`Invalid \`retry\` value: "${t}"`,{type:"invalid-retry",value:t,line:i}));break;default:n(new Pt(`Unknown field "${e.length>20?`${e.slice(0,20)}…`:e}"`,{type:"unknown-field",field:e,value:t,line:i}))}}return{feed:function(e){const t=a?e.replace(/^\xEF\xBB\xBF/,""):e,[n,r]=function(e){const t=[];let n="",r=0;for(;r<e.length;){const i=e.indexOf("\r",r),o=e.indexOf("\n",r);let s=-1;if(-1!==i&&-1!==o?s=Math.min(i,o):-1!==i?s=i===e.length-1?-1:i:-1!==o&&(s=o),-1===s){n=e.slice(r);break}{const n=e.slice(r,s);t.push(n),r=s+1,"\r"===e[r-1]&&"\n"===e[r]&&r++}}return[t,n]}(`${s}${t}`);for(const i of n)c(i);s=r,a=!1},reset:function(e={}){s&&e.consume&&c(s),a=!0,o=void 0,u="",l="",s=""}}}class jt extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let r;super({start(i){r=Ut({onEvent:e=>{i.enqueue(e)},onError(t){"terminate"===e?i.error(t):"function"==typeof e&&e(t)},onRetry:t,onComment:n})},transform(e){r.feed(e)}})}}const zt=Object.freeze({status:"aborted"});function Dt(e,t,n){function r(n,r){var i;Object.defineProperty(n,"_zod",{value:n._zod??{},enumerable:!1}),(i=n._zod).traits??(i.traits=new Set),n._zod.traits.add(e),t(n,r);for(const e in s.prototype)e in n||Object.defineProperty(n,e,{value:s.prototype[e].bind(n)});n._zod.constr=s,n._zod.def=r}const i=(null==n?void 0:n.Parent)??Object;class o extends i{}function s(e){var t;const i=(null==n?void 0:n.Parent)?new o:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(const n of i._zod.deferred)n();return i}return Object.defineProperty(o,"name",{value:e}),Object.defineProperty(s,"init",{value:r}),Object.defineProperty(s,Symbol.hasInstance,{value:t=>{var r,i;return!!((null==n?void 0:n.Parent)&&t instanceof n.Parent)||(null==(i=null==(r=null==t?void 0:t._zod)?void 0:r.traits)?void 0:i.has(e))}}),Object.defineProperty(s,"name",{value:e}),s}const Mt=Symbol("zod_brand");class Lt extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const Zt={};function qt(e){return e&&Object.assign(Zt,e),Zt}function Ft(e){const t=Object.values(e).filter((e=>"number"==typeof e));return Object.entries(e).filter((([e,n])=>-1===t.indexOf(+e))).map((([e,t])=>t))}function Wt(e,t="|"){return e.map((e=>mn(e))).join(t)}function Jt(e,t){return"bigint"==typeof t?t.toString():t}function Bt(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Ht(e){return null==e}function Vt(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function Kt(e,t){const n=(e.toString().split(".")[1]||"").length,r=t.toString();let i=(r.split(".")[1]||"").length;if(0===i&&/\d?e-\d?/.test(r)){const e=r.match(/\d?e-(\d?)/);(null==e?void 0:e[1])&&(i=Number.parseInt(e[1]))}const o=n>i?n:i;return Number.parseInt(e.toFixed(o).replace(".",""))%Number.parseInt(t.toFixed(o).replace(".",""))/10**o}const Gt=Symbol("evaluating");function Yt(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==Gt)return void 0===r&&(r=Gt,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Xt(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function Qt(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function en(...e){const t={};for(const n of e){const e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function tn(e){return JSON.stringify(e)}const nn="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function rn(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const on=Bt((()=>{var e;if("undefined"!=typeof navigator&&(null==(e=null==navigator?void 0:navigator.userAgent)?void 0:e.includes("Cloudflare")))return!1;try{return new Function(""),!0}catch(t){return!1}}));function sn(e){if(!1===rn(e))return!1;const t=e.constructor;if(void 0===t)return!0;const n=t.prototype;return!1!==rn(n)&&!1!==Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")}function an(e){return sn(e)?{...e}:e}const un=new Set(["string","number","symbol"]),ln=new Set(["string","number","bigint","boolean","symbol","undefined"]);function cn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function dn(e,t,n){const r=new e._zod.constr(t??e._zod.def);return t&&!(null==n?void 0:n.parent)||(r._zod.parent=e),r}function pn(e){const t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==(null==t?void 0:t.message)){if(void 0!==(null==t?void 0:t.error))throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,"string"==typeof t.error?{...t,error:()=>t.error}:t}function mn(e){return"bigint"==typeof e?e.toString()+"n":"string"==typeof e?`"${e}"`:`${e}`}function hn(e){return Object.keys(e).filter((t=>"optional"===e[t]._zod.optin&&"optional"===e[t]._zod.optout))}const gn={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},fn={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function vn(e,t){const n=e._zod.def;return dn(e,en(e._zod.def,{get shape(){const e={};for(const r in t){if(!(r in n.shape))throw new Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return Qt(this,"shape",e),e},checks:[]}))}function yn(e,t){const n=e._zod.def,r=en(e._zod.def,{get shape(){const r={...e._zod.def.shape};for(const e in t){if(!(e in n.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return Qt(this,"shape",r),r},checks:[]});return dn(e,r)}function _n(e,t){if(!sn(t))throw new Error("Invalid input to extend: expected a plain object");const n=en(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return Qt(this,"shape",n),n},checks:[]});return dn(e,n)}function bn(e,t){const n=en(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return Qt(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:[]});return dn(e,n)}function wn(e,t,n){const r=en(t._zod.def,{get shape(){const r=t._zod.def.shape,i={...r};if(n)for(const t in n){if(!(t in r))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:"optional",innerType:r[t]}):r[t])}else for(const t in r)i[t]=e?new e({type:"optional",innerType:r[t]}):r[t];return Qt(this,"shape",i),i},checks:[]});return dn(t,r)}function kn(e,t,n){const r=en(t._zod.def,{get shape(){const r=t._zod.def.shape,i={...r};if(n)for(const t in n){if(!(t in i))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:"nonoptional",innerType:r[t]}))}else for(const t in r)i[t]=new e({type:"nonoptional",innerType:r[t]});return Qt(this,"shape",i),i},checks:[]});return dn(t,r)}function xn(e,t=0){var n;for(let r=t;r<e.issues.length;r++)if(!0!==(null==(n=e.issues[r])?void 0:n.continue))return!0;return!1}function In(e,t){return t.map((t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t}))}function Sn(e){return"string"==typeof e?e:null==e?void 0:e.message}function $n(e,t,n){var r,i,o,s,a,u;const l={...e,path:e.path??[]};if(!e.message){const c=Sn(null==(o=null==(i=null==(r=e.inst)?void 0:r._zod.def)?void 0:i.error)?void 0:o.call(i,e))??Sn(null==(s=null==t?void 0:t.error)?void 0:s.call(t,e))??Sn(null==(a=n.customError)?void 0:a.call(n,e))??Sn(null==(u=n.localeError)?void 0:u.call(n,e))??"Invalid input";l.message=c}return delete l.inst,delete l.continue,(null==t?void 0:t.reportInput)||delete l.input,l}function En(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function Tn(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function On(...e){const[t,n,r]=e;return"string"==typeof t?{message:t,code:"custom",input:n,inst:r}:{...t}}const Nn=Object.freeze(Object.defineProperty({__proto__:null,BIGINT_FORMAT_RANGES:fn,Class:class{constructor(...e){}},NUMBER_FORMAT_RANGES:gn,aborted:xn,allowsEval:on,assert:function(e){},assertEqual:function(e){return e},assertIs:function(e){},assertNever:function(e){throw new Error},assertNotEqual:function(e){return e},assignProp:Qt,cached:Bt,captureStackTrace:nn,cleanEnum:function(e){return Object.entries(e).filter((([e,t])=>Number.isNaN(Number.parseInt(e,10)))).map((e=>e[1]))},cleanRegex:Vt,clone:dn,cloneDef:function(e){return en(e._zod.def)},createTransparentProxy:function(e){let t;return new Proxy({},{get:(n,r,i)=>(t??(t=e()),Reflect.get(t,r,i)),set:(n,r,i,o)=>(t??(t=e()),Reflect.set(t,r,i,o)),has:(n,r)=>(t??(t=e()),Reflect.has(t,r)),deleteProperty:(n,r)=>(t??(t=e()),Reflect.deleteProperty(t,r)),ownKeys:n=>(t??(t=e()),Reflect.ownKeys(t)),getOwnPropertyDescriptor:(n,r)=>(t??(t=e()),Reflect.getOwnPropertyDescriptor(t,r)),defineProperty:(n,r,i)=>(t??(t=e()),Reflect.defineProperty(t,r,i))})},defineLazy:Yt,esc:tn,escapeRegex:cn,extend:_n,finalizeIssue:$n,floatSafeRemainder:Kt,getElementAtPath:function(e,t){return t?t.reduce(((e,t)=>null==e?void 0:e[t]),e):e},getEnumValues:Ft,getLengthableOrigin:Tn,getParsedType:e=>{const t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":null===e?"null":e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?"promise":"undefined"!=typeof Map&&e instanceof Map?"map":"undefined"!=typeof Set&&e instanceof Set?"set":"undefined"!=typeof Date&&e instanceof Date?"date":"undefined"!=typeof File&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},getSizableOrigin:En,isObject:rn,isPlainObject:sn,issue:On,joinValues:Wt,jsonStringifyReplacer:Jt,merge:bn,mergeDefs:en,normalizeParams:pn,nullish:Ht,numKeys:function(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t},objectClone:Xt,omit:yn,optionalKeys:hn,partial:wn,pick:vn,prefixIssues:In,primitiveTypes:ln,promiseAllObject:function(e){const t=Object.keys(e),n=t.map((t=>e[t]));return Promise.all(n).then((e=>{const n={};for(let r=0;r<t.length;r++)n[t[r]]=e[r];return n}))},propertyKeyTypes:un,randomString:function(e=10){const t="abcdefghijklmnopqrstuvwxyz";let n="";for(let r=0;r<e;r++)n+=t[Math.floor(26*Math.random())];return n},required:kn,shallowClone:an,stringifyPrimitive:mn,unwrapMessage:Sn},Symbol.toStringTag,{value:"Module"})),Cn=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Jt,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},An=Dt("$ZodError",Cn),Pn=Dt("$ZodError",Cn,{Parent:Error});function Rn(e,t=e=>e.message){const n={},r=[];for(const i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function Un(e,t){const n=t||function(e){return e.message},r={_errors:[]},i=e=>{for(const t of e.issues)if("invalid_union"===t.code&&t.errors.length)t.errors.map((e=>i({issues:e})));else if("invalid_key"===t.code)i({issues:t.issues});else if("invalid_element"===t.code)i({issues:t.issues});else if(0===t.path.length)r._errors.push(n(t));else{let e=r,i=0;for(;i<t.path.length;){const r=t.path[i];i===t.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(n(t))):e[r]=e[r]||{_errors:[]},e=e[r],i++}}};return i(e),r}function jn(e,t){const n=t||function(e){return e.message},r={errors:[]},i=(e,t=[])=>{var o,s;for(const a of e.issues)if("invalid_union"===a.code&&a.errors.length)a.errors.map((e=>i({issues:e},a.path)));else if("invalid_key"===a.code)i({issues:a.issues},a.path);else if("invalid_element"===a.code)i({issues:a.issues},a.path);else{const e=[...t,...a.path];if(0===e.length){r.errors.push(n(a));continue}let i=r,u=0;for(;u<e.length;){const t=e[u],r=u===e.length-1;"string"==typeof t?(i.properties??(i.properties={}),(o=i.properties)[t]??(o[t]={errors:[]}),i=i.properties[t]):(i.items??(i.items=[]),(s=i.items)[t]??(s[t]={errors:[]}),i=i.items[t]),r&&i.errors.push(n(a)),u++}}};return i(e),r}function zn(e){const t=[],n=e.map((e=>"object"==typeof e?e.key:e));for(const r of n)"number"==typeof r?t.push(`[${r}]`):"symbol"==typeof r?t.push(`[${JSON.stringify(String(r))}]`):/[^\w$]/.test(r)?t.push(`[${JSON.stringify(r)}]`):(t.length&&t.push("."),t.push(r));return t.join("")}function Dn(e){var t;const n=[],r=[...e.issues].sort(((e,t)=>(e.path??[]).length-(t.path??[]).length));for(const i of r)n.push(`✖ ${i.message}`),(null==(t=i.path)?void 0:t.length)&&n.push(` → at ${zn(i.path)}`);return n.join("\n")}const Mn=e=>(t,n,r,i)=>{const o=r?Object.assign(r,{async:!1}):{async:!1},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new Lt;if(s.issues.length){const t=new((null==i?void 0:i.Err)??e)(s.issues.map((e=>$n(e,o,qt()))));throw nn(t,null==i?void 0:i.callee),t}return s.value},Ln=Mn(Pn),Zn=e=>async(t,n,r,i)=>{const o=r?Object.assign(r,{async:!0}):{async:!0};let s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){const t=new((null==i?void 0:i.Err)??e)(s.issues.map((e=>$n(e,o,qt()))));throw nn(t,null==i?void 0:i.callee),t}return s.value},qn=Zn(Pn),Fn=e=>(t,n,r)=>{const i=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},i);if(o instanceof Promise)throw new Lt;return o.issues.length?{success:!1,error:new(e??An)(o.issues.map((e=>$n(e,i,qt()))))}:{success:!0,data:o.value}},Wn=Fn(Pn),Jn=e=>async(t,n,r)=>{const i=r?Object.assign(r,{async:!0}):{async:!0};let o=t._zod.run({value:n,issues:[]},i);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map((e=>$n(e,i,qt()))))}:{success:!0,data:o.value}},Bn=Jn(Pn),Hn=/^[cC][^\s-]{8,}$/,Vn=/^[0-9a-z]+$/,Kn=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Gn=/^[0-9a-vA-V]{20}$/,Yn=/^[A-Za-z0-9]{27}$/,Xn=/^[a-zA-Z0-9_-]{21}$/,Qn=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,er=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,tr=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,nr=tr(4),rr=tr(6),ir=tr(7),or=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function sr(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}const ar=/^(?:(?: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])$/,ur=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,lr=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,cr=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,dr=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,pr=/^[A-Za-z0-9_-]*$/,mr=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,hr=/^\+(?:[0-9]){6,14}[0-9]$/,gr="(?:(?:\\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])))",fr=new RegExp(`^${gr}$`);function vr(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function yr(e){return new RegExp(`^${vr(e)}$`)}function _r(e){const t=vr({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${gr}T(?:${r})$`)}const br=e=>{const t=e?`[\\s\\S]{${(null==e?void 0:e.minimum)??0},${(null==e?void 0:e.maximum)??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},wr=/^\d+n?$/,kr=/^\d+$/,xr=/^-?\d+(?:\.\d+)?/i,Ir=/true|false/i,Sr=/null/i,$r=/undefined/i,Er=/^[^A-Z]*$/,Tr=/^[^a-z]*$/,Or=Object.freeze(Object.defineProperty({__proto__:null,base64:dr,base64url:pr,bigint:wr,boolean:Ir,browserEmail:/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,cidrv4:lr,cidrv6:cr,cuid:Hn,cuid2:Vn,date:fr,datetime:_r,domain:/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,duration:Qn,e164:hr,email:or,emoji:sr,extendedDuration:/^[-+]?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)?)??$/,guid:er,hostname:mr,html5Email:/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,idnEmail:/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,integer:kr,ipv4:ar,ipv6:ur,ksuid:Yn,lowercase:Er,nanoid:Xn,null:Sr,number:xr,rfc5322Email:/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,string:br,time:yr,ulid:Kn,undefined:$r,unicodeEmail:/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,uppercase:Tr,uuid:tr,uuid4:nr,uuid6:rr,uuid7:ir,xid:Gn},Symbol.toStringTag,{value:"Module"})),Nr=Dt("$ZodCheck",((e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])})),Cr={number:"number",bigint:"bigint",object:"date"},Ar=Dt("$ZodCheckLessThan",((e,t)=>{Nr.init(e,t);const n=Cr[typeof t.value];e._zod.onattach.push((e=>{const n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)})),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}})),Pr=Dt("$ZodCheckGreaterThan",((e,t)=>{Nr.init(e,t);const n=Cr[typeof t.value];e._zod.onattach.push((e=>{const n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)})),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}})),Rr=Dt("$ZodCheckMultipleOf",((e,t)=>{Nr.init(e,t),e._zod.onattach.push((e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)})),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof n.value?n.value%t.value===BigInt(0):0===Kt(n.value,t.value))||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}})),Ur=Dt("$ZodCheckNumberFormat",((e,t)=>{var n;Nr.init(e,t),t.format=t.format||"float64";const r=null==(n=t.format)?void 0:n.includes("int"),i=r?"int":"number",[o,s]=gn[t.format];e._zod.onattach.push((e=>{const n=e._zod.bag;n.format=t.format,n.minimum=o,n.maximum=s,r&&(n.pattern=kr)})),e._zod.check=n=>{const a=n.value;if(r){if(!Number.isInteger(a))return void n.issues.push({expected:i,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});if(!Number.isSafeInteger(a))return void(a>0?n.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:i,continue:!t.abort}):n.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:i,continue:!t.abort}))}a<o&&n.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),a>s&&n.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:e})}})),jr=Dt("$ZodCheckBigIntFormat",((e,t)=>{Nr.init(e,t);const[n,r]=fn[t.format];e._zod.onattach.push((e=>{const i=e._zod.bag;i.format=t.format,i.minimum=n,i.maximum=r})),e._zod.check=i=>{const o=i.value;o<n&&i.issues.push({origin:"bigint",input:o,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort}),o>r&&i.issues.push({origin:"bigint",input:o,code:"too_big",maximum:r,inst:e})}})),zr=Dt("$ZodCheckMaxSize",((e,t)=>{var n;Nr.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Ht(t)&&void 0!==t.size}),e._zod.onattach.push((e=>{const n=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(e._zod.bag.maximum=t.maximum)})),e._zod.check=n=>{const r=n.value;r.size<=t.maximum||n.issues.push({origin:En(r),code:"too_big",maximum:t.maximum,input:r,inst:e,continue:!t.abort})}})),Dr=Dt("$ZodCheckMinSize",((e,t)=>{var n;Nr.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Ht(t)&&void 0!==t.size}),e._zod.onattach.push((e=>{const n=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(e._zod.bag.minimum=t.minimum)})),e._zod.check=n=>{const r=n.value;r.size>=t.minimum||n.issues.push({origin:En(r),code:"too_small",minimum:t.minimum,input:r,inst:e,continue:!t.abort})}})),Mr=Dt("$ZodCheckSizeEquals",((e,t)=>{var n;Nr.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Ht(t)&&void 0!==t.size}),e._zod.onattach.push((e=>{const n=e._zod.bag;n.minimum=t.size,n.maximum=t.size,n.size=t.size})),e._zod.check=n=>{const r=n.value,i=r.size;if(i===t.size)return;const o=i>t.size;n.issues.push({origin:En(r),...o?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}})),Lr=Dt("$ZodCheckMaxLength",((e,t)=>{var n;Nr.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Ht(t)&&void 0!==t.length}),e._zod.onattach.push((e=>{const n=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(e._zod.bag.maximum=t.maximum)})),e._zod.check=n=>{const r=n.value;if(r.length<=t.maximum)return;const i=Tn(r);n.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}})),Zr=Dt("$ZodCheckMinLength",((e,t)=>{var n;Nr.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Ht(t)&&void 0!==t.length}),e._zod.onattach.push((e=>{const n=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(e._zod.bag.minimum=t.minimum)})),e._zod.check=n=>{const r=n.value;if(r.length>=t.minimum)return;const i=Tn(r);n.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}})),qr=Dt("$ZodCheckLengthEquals",((e,t)=>{var n;Nr.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Ht(t)&&void 0!==t.length}),e._zod.onattach.push((e=>{const n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length})),e._zod.check=n=>{const r=n.value,i=r.length;if(i===t.length)return;const o=Tn(r),s=i>t.length;n.issues.push({origin:o,...s?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}})),Fr=Dt("$ZodCheckStringFormat",((e,t)=>{var n,r;Nr.init(e,t),e._zod.onattach.push((e=>{const n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??(n.patterns=new Set),n.patterns.add(t.pattern))})),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})})),Wr=Dt("$ZodCheckRegex",((e,t)=>{Fr.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}})),Jr=Dt("$ZodCheckLowerCase",((e,t)=>{t.pattern??(t.pattern=Er),Fr.init(e,t)})),Br=Dt("$ZodCheckUpperCase",((e,t)=>{t.pattern??(t.pattern=Tr),Fr.init(e,t)})),Hr=Dt("$ZodCheckIncludes",((e,t)=>{Nr.init(e,t);const n=cn(t.includes),r=new RegExp("number"==typeof t.position?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push((e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)})),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}})),Vr=Dt("$ZodCheckStartsWith",((e,t)=>{Nr.init(e,t);const n=new RegExp(`^${cn(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push((e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)})),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}})),Kr=Dt("$ZodCheckEndsWith",((e,t)=>{Nr.init(e,t);const n=new RegExp(`.*${cn(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push((e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)})),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}));function Gr(e,t,n){e.issues.length&&t.issues.push(...In(n,e.issues))}const Yr=Dt("$ZodCheckProperty",((e,t)=>{Nr.init(e,t),e._zod.check=e=>{const n=t.schema._zod.run({value:e.value[t.property],issues:[]},{});if(n instanceof Promise)return n.then((n=>Gr(n,e,t.property)));Gr(n,e,t.property)}})),Xr=Dt("$ZodCheckMimeType",((e,t)=>{Nr.init(e,t);const n=new Set(t.mime);e._zod.onattach.push((e=>{e._zod.bag.mime=t.mime})),e._zod.check=r=>{n.has(r.value.type)||r.issues.push({code:"invalid_value",values:t.mime,input:r.value.type,inst:e,continue:!t.abort})}})),Qr=Dt("$ZodCheckOverwrite",((e,t)=>{Nr.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}));class ei{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e)return e(this,{execution:"sync"}),void e(this,{execution:"async"});const t=e.split("\n").filter((e=>e)),n=Math.min(...t.map((e=>e.length-e.trimStart().length))),r=t.map((e=>e.slice(n))).map((e=>" ".repeat(2*this.indent)+e));for(const i of r)this.content.push(i)}compile(){return new Function(...null==this?void 0:this.args,[...((null==this?void 0:this.content)??[""]).map((e=>` ${e}`))].join("\n"))}}const ti={major:4,minor:0,patch:17},ni=Dt("$ZodType",((e,t)=>{var n,r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=ti;const i=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&i.unshift(e);for(const o of i)for(const t of o._zod.onattach)t(e);if(0===i.length)(r=e._zod).deferred??(r.deferred=[]),null==(n=e._zod.deferred)||n.push((()=>{e._zod.run=e._zod.parse}));else{const t=(e,t,n)=>{let r,i=xn(e);for(const o of t){if(o._zod.def.when){if(!o._zod.def.when(e))continue}else if(i)continue;const t=e.issues.length,s=o._zod.check(e);if(s instanceof Promise&&!1===(null==n?void 0:n.async))throw new Lt;if(r||s instanceof Promise)r=(r??Promise.resolve()).then((async()=>{await s;e.issues.length!==t&&(i||(i=xn(e,t)))}));else{if(e.issues.length===t)continue;i||(i=xn(e,t))}}return r?r.then((()=>e)):e};e._zod.run=(n,r)=>{const o=e._zod.parse(n,r);if(o instanceof Promise){if(!1===r.async)throw new Lt;return o.then((e=>t(e,i,r)))}return t(o,i,r)}}e["~standard"]={validate:t=>{var n;try{const r=Wn(e,t);return r.success?{value:r.data}:{issues:null==(n=r.error)?void 0:n.issues}}catch(r){return Bn(e,t).then((e=>{var t;return e.success?{value:e.data}:{issues:null==(t=e.error)?void 0:t.issues}}))}},vendor:"zod",version:1}})),ri=Dt("$ZodString",((e,t)=>{var n;ni.init(e,t),e._zod.pattern=[...(null==(n=null==e?void 0:e._zod.bag)?void 0:n.patterns)??[]].pop()??br(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch(i){}return"string"==typeof n.value||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}})),ii=Dt("$ZodStringFormat",((e,t)=>{Fr.init(e,t),ri.init(e,t)})),oi=Dt("$ZodGUID",((e,t)=>{t.pattern??(t.pattern=er),ii.init(e,t)})),si=Dt("$ZodUUID",((e,t)=>{if(t.version){const e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=tr(e))}else t.pattern??(t.pattern=tr());ii.init(e,t)})),ai=Dt("$ZodEmail",((e,t)=>{t.pattern??(t.pattern=or),ii.init(e,t)})),ui=Dt("$ZodURL",((e,t)=>{ii.init(e,t),e._zod.check=n=>{try{const r=n.value.trim(),i=new URL(r);return t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:mr.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),void(t.normalize?n.value=i.href:n.value=r)}catch(r){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}})),li=Dt("$ZodEmoji",((e,t)=>{t.pattern??(t.pattern=sr()),ii.init(e,t)})),ci=Dt("$ZodNanoID",((e,t)=>{t.pattern??(t.pattern=Xn),ii.init(e,t)})),di=Dt("$ZodCUID",((e,t)=>{t.pattern??(t.pattern=Hn),ii.init(e,t)})),pi=Dt("$ZodCUID2",((e,t)=>{t.pattern??(t.pattern=Vn),ii.init(e,t)})),mi=Dt("$ZodULID",((e,t)=>{t.pattern??(t.pattern=Kn),ii.init(e,t)})),hi=Dt("$ZodXID",((e,t)=>{t.pattern??(t.pattern=Gn),ii.init(e,t)})),gi=Dt("$ZodKSUID",((e,t)=>{t.pattern??(t.pattern=Yn),ii.init(e,t)})),fi=Dt("$ZodISODateTime",((e,t)=>{t.pattern??(t.pattern=_r(t)),ii.init(e,t)})),vi=Dt("$ZodISODate",((e,t)=>{t.pattern??(t.pattern=fr),ii.init(e,t)})),yi=Dt("$ZodISOTime",((e,t)=>{t.pattern??(t.pattern=yr(t)),ii.init(e,t)})),_i=Dt("$ZodISODuration",((e,t)=>{t.pattern??(t.pattern=Qn),ii.init(e,t)})),bi=Dt("$ZodIPv4",((e,t)=>{t.pattern??(t.pattern=ar),ii.init(e,t),e._zod.onattach.push((e=>{e._zod.bag.format="ipv4"}))})),wi=Dt("$ZodIPv6",((e,t)=>{t.pattern??(t.pattern=ur),ii.init(e,t),e._zod.onattach.push((e=>{e._zod.bag.format="ipv6"})),e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}})),ki=Dt("$ZodCIDRv4",((e,t)=>{t.pattern??(t.pattern=lr),ii.init(e,t)})),xi=Dt("$ZodCIDRv6",((e,t)=>{t.pattern??(t.pattern=cr),ii.init(e,t),e._zod.check=n=>{const[r,i]=n.value.split("/");try{if(!i)throw new Error;const e=Number(i);if(`${e}`!==i)throw new Error;if(e<0||e>128)throw new Error;new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}}));function Ii(e){if(""===e)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const Si=Dt("$ZodBase64",((e,t)=>{t.pattern??(t.pattern=dr),ii.init(e,t),e._zod.onattach.push((e=>{e._zod.bag.contentEncoding="base64"})),e._zod.check=n=>{Ii(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}));function $i(e){if(!pr.test(e))return!1;const t=e.replace(/[-_]/g,(e=>"-"===e?"+":"/"));return Ii(t.padEnd(4*Math.ceil(t.length/4),"="))}const Ei=Dt("$ZodBase64URL",((e,t)=>{t.pattern??(t.pattern=pr),ii.init(e,t),e._zod.onattach.push((e=>{e._zod.bag.contentEncoding="base64url"})),e._zod.check=n=>{$i(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}})),Ti=Dt("$ZodE164",((e,t)=>{t.pattern??(t.pattern=hr),ii.init(e,t)}));function Oi(e,t=null){try{const n=e.split(".");if(3!==n.length)return!1;const[r]=n;if(!r)return!1;const i=JSON.parse(atob(r));return(!("typ"in i)||"JWT"===(null==i?void 0:i.typ))&&(!!i.alg&&(!t||"alg"in i&&i.alg===t))}catch{return!1}}const Ni=Dt("$ZodJWT",((e,t)=>{ii.init(e,t),e._zod.check=n=>{Oi(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}})),Ci=Dt("$ZodCustomStringFormat",((e,t)=>{ii.init(e,t),e._zod.check=n=>{t.fn(n.value)||n.issues.push({code:"invalid_format",format:t.format,input:n.value,inst:e,continue:!t.abort})}})),Ai=Dt("$ZodNumber",((e,t)=>{ni.init(e,t),e._zod.pattern=e._zod.bag.pattern??xr,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch(s){}const i=n.value;if("number"==typeof i&&!Number.isNaN(i)&&Number.isFinite(i))return n;const o="number"==typeof i?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...o?{received:o}:{}}),n}})),Pi=Dt("$ZodNumber",((e,t)=>{Ur.init(e,t),Ai.init(e,t)})),Ri=Dt("$ZodBoolean",((e,t)=>{ni.init(e,t),e._zod.pattern=Ir,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(o){}const i=n.value;return"boolean"==typeof i||n.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),n}})),Ui=Dt("$ZodBigInt",((e,t)=>{ni.init(e,t),e._zod.pattern=wr,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=BigInt(n.value)}catch(i){}return"bigint"==typeof n.value||n.issues.push({expected:"bigint",code:"invalid_type",input:n.value,inst:e}),n}})),ji=Dt("$ZodBigInt",((e,t)=>{jr.init(e,t),Ui.init(e,t)})),zi=Dt("$ZodSymbol",((e,t)=>{ni.init(e,t),e._zod.parse=(t,n)=>{const r=t.value;return"symbol"==typeof r||t.issues.push({expected:"symbol",code:"invalid_type",input:r,inst:e}),t}})),Di=Dt("$ZodUndefined",((e,t)=>{ni.init(e,t),e._zod.pattern=$r,e._zod.values=new Set([void 0]),e._zod.optin="optional",e._zod.optout="optional",e._zod.parse=(t,n)=>{const r=t.value;return void 0===r||t.issues.push({expected:"undefined",code:"invalid_type",input:r,inst:e}),t}})),Mi=Dt("$ZodNull",((e,t)=>{ni.init(e,t),e._zod.pattern=Sr,e._zod.values=new Set([null]),e._zod.parse=(t,n)=>{const r=t.value;return null===r||t.issues.push({expected:"null",code:"invalid_type",input:r,inst:e}),t}})),Li=Dt("$ZodAny",((e,t)=>{ni.init(e,t),e._zod.parse=e=>e})),Zi=Dt("$ZodUnknown",((e,t)=>{ni.init(e,t),e._zod.parse=e=>e})),qi=Dt("$ZodNever",((e,t)=>{ni.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)})),Fi=Dt("$ZodVoid",((e,t)=>{ni.init(e,t),e._zod.parse=(t,n)=>{const r=t.value;return void 0===r||t.issues.push({expected:"void",code:"invalid_type",input:r,inst:e}),t}})),Wi=Dt("$ZodDate",((e,t)=>{ni.init(e,t),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=new Date(n.value)}catch(s){}const i=n.value,o=i instanceof Date;return o&&!Number.isNaN(i.getTime())||n.issues.push({expected:"date",code:"invalid_type",input:i,...o?{received:"Invalid Date"}:{},inst:e}),n}}));function Ji(e,t,n){e.issues.length&&t.issues.push(...In(n,e.issues)),t.value[n]=e.value}const Bi=Dt("$ZodArray",((e,t)=>{ni.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),n;n.value=Array(i.length);const o=[];for(let e=0;e<i.length;e++){const s=i[e],a=t.element._zod.run({value:s,issues:[]},r);a instanceof Promise?o.push(a.then((t=>Ji(t,n,e)))):Ji(a,n,e)}return o.length?Promise.all(o).then((()=>n)):n}}));function Hi(e,t,n,r){e.issues.length&&t.issues.push(...In(n,e.issues)),void 0===e.value?n in r&&(t.value[n]=void 0):t.value[n]=e.value}const Vi=Dt("$ZodObject",((e,t)=>{ni.init(e,t);const n=Bt((()=>{const e=Object.keys(t.shape);for(const r of e)if(!t.shape[r]._zod.traits.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const n=hn(t.shape);return{shape:t.shape,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}}));Yt(e._zod,"propValues",(()=>{const e=t.shape,n={};for(const t in e){const r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(const e of r.values)n[t].add(e)}}return n}));let r;const i=rn,o=!Zt.jitless,s=o&&on.value,a=t.catchall;let u;e._zod.parse=(l,c)=>{u??(u=n.value);const d=l.value;if(!i(d))return l.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),l;const p=[];if(o&&s&&!1===(null==c?void 0:c.async)&&!0!==c.jitless)r||(r=(e=>{const t=new ei(["shape","payload","ctx"]),r=n.value,i=e=>{const t=tn(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");const o=Object.create(null);let s=0;for(const n of r.keys)o[n]="key_"+s++;t.write("const newResult = {}");for(const n of r.keys){const e=o[n],r=tn(n);t.write(`const ${e} = ${i(n)};`),t.write(`\n if (${e}.issues.length) {\n payload.issues = payload.issues.concat(${e}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${r}, ...iss.path] : [${r}]\n })));\n }\n \n if (${e}.value === undefined) {\n if (${r} in input) {\n newResult[${r}] = undefined;\n }\n } else {\n newResult[${r}] = ${e}.value;\n }\n `)}t.write("payload.value = newResult;"),t.write("return payload;");const a=t.compile();return(t,n)=>a(e,t,n)})(t.shape)),l=r(l,c);else{l.value={};const e=u.shape;for(const t of u.keys){const n=e[t]._zod.run({value:d[t],issues:[]},c);n instanceof Promise?p.push(n.then((e=>Hi(e,l,t,d)))):Hi(n,l,t,d)}}if(!a)return p.length?Promise.all(p).then((()=>l)):l;const m=[],h=u.keySet,g=a._zod,f=g.def.type;for(const e of Object.keys(d)){if(h.has(e))continue;if("never"===f){m.push(e);continue}const t=g.run({value:d[e],issues:[]},c);t instanceof Promise?p.push(t.then((t=>Hi(t,l,e,d)))):Hi(t,l,e,d)}return m.length&&l.issues.push({code:"unrecognized_keys",keys:m,input:d,inst:e}),p.length?Promise.all(p).then((()=>l)):l}}));function Ki(e,t,n,r){for(const o of e)if(0===o.issues.length)return t.value=o.value,t;const i=e.filter((e=>!xn(e)));return 1===i.length?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map((e=>e.issues.map((e=>$n(e,r,qt())))))}),t)}const Gi=Dt("$ZodUnion",((e,t)=>{ni.init(e,t),Yt(e._zod,"optin",(()=>t.options.some((e=>"optional"===e._zod.optin))?"optional":void 0)),Yt(e._zod,"optout",(()=>t.options.some((e=>"optional"===e._zod.optout))?"optional":void 0)),Yt(e._zod,"values",(()=>{if(t.options.every((e=>e._zod.values)))return new Set(t.options.flatMap((e=>Array.from(e._zod.values))))})),Yt(e._zod,"pattern",(()=>{if(t.options.every((e=>e._zod.pattern))){const e=t.options.map((e=>e._zod.pattern));return new RegExp(`^(${e.map((e=>Vt(e.source))).join("|")})$`)}}));const n=1===t.options.length,r=t.options[0]._zod.run;e._zod.parse=(i,o)=>{if(n)return r(i,o);let s=!1;const a=[];for(const e of t.options){const t=e._zod.run({value:i.value,issues:[]},o);if(t instanceof Promise)a.push(t),s=!0;else{if(0===t.issues.length)return t;a.push(t)}}return s?Promise.all(a).then((t=>Ki(t,i,e,o))):Ki(a,i,e,o)}})),Yi=Dt("$ZodDiscriminatedUnion",((e,t)=>{Gi.init(e,t);const n=e._zod.parse;Yt(e._zod,"propValues",(()=>{const e={};for(const n of t.options){const r=n._zod.propValues;if(!r||0===Object.keys(r).length)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(const[t,n]of Object.entries(r)){e[t]||(e[t]=new Set);for(const r of n)e[t].add(r)}}return e}));const r=Bt((()=>{var e;const n=t.options,r=new Map;for(const i of n){const n=null==(e=i._zod.propValues)?void 0:e[t.discriminator];if(!n||0===n.size)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(const e of n){if(r.has(e))throw new Error(`Duplicate discriminator value "${String(e)}"`);r.set(e,i)}}return r}));e._zod.parse=(i,o)=>{const s=i.value;if(!rn(s))return i.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),i;const a=r.value.get(null==s?void 0:s[t.discriminator]);return a?a._zod.run(i,o):t.unionFallback?n(i,o):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,input:s,path:[t.discriminator],inst:e}),i)}})),Xi=Dt("$ZodIntersection",((e,t)=>{ni.init(e,t),e._zod.parse=(e,n)=>{const r=e.value,i=t.left._zod.run({value:r,issues:[]},n),o=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||o instanceof Promise?Promise.all([i,o]).then((([t,n])=>eo(e,t,n))):eo(e,i,o)}}));function Qi(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(sn(e)&&sn(t)){const n=Object.keys(t),r=Object.keys(e).filter((e=>-1!==n.indexOf(e))),i={...e,...t};for(const o of r){const n=Qi(e[o],t[o]);if(!n.valid)return{valid:!1,mergeErrorPath:[o,...n.mergeErrorPath]};i[o]=n.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const i=Qi(e[r],t[r]);if(!i.valid)return{valid:!1,mergeErrorPath:[r,...i.mergeErrorPath]};n.push(i.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function eo(e,t,n){if(t.issues.length&&e.issues.push(...t.issues),n.issues.length&&e.issues.push(...n.issues),xn(e))return e;const r=Qi(t.value,n.value);if(!r.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return e.value=r.data,e}const to=Dt("$ZodTuple",((e,t)=>{ni.init(e,t);const n=t.items,r=n.length-[...n].reverse().findIndex((e=>"optional"!==e._zod.optin));e._zod.parse=(i,o)=>{const s=i.value;if(!Array.isArray(s))return i.issues.push({input:s,inst:e,expected:"tuple",code:"invalid_type"}),i;i.value=[];const a=[];if(!t.rest){const t=s.length>n.length,o=s.length<r-1;if(t||o)return i.issues.push({...t?{code:"too_big",maximum:n.length}:{code:"too_small",minimum:n.length},input:s,inst:e,origin:"array"}),i}let u=-1;for(const e of n){if(u++,u>=s.length&&u>=r)continue;const t=e._zod.run({value:s[u],issues:[]},o);t instanceof Promise?a.push(t.then((e=>no(e,i,u)))):no(t,i,u)}if(t.rest){const e=s.slice(n.length);for(const n of e){u++;const e=t.rest._zod.run({value:n,issues:[]},o);e instanceof Promise?a.push(e.then((e=>no(e,i,u)))):no(e,i,u)}}return a.length?Promise.all(a).then((()=>i)):i}}));function no(e,t,n){e.issues.length&&t.issues.push(...In(n,e.issues)),t.value[n]=e.value}const ro=Dt("$ZodRecord",((e,t)=>{ni.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;if(!sn(i))return n.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),n;const o=[];if(t.keyType._zod.values){const s=t.keyType._zod.values;n.value={};for(const e of s)if("string"==typeof e||"number"==typeof e||"symbol"==typeof e){const s=t.valueType._zod.run({value:i[e],issues:[]},r);s instanceof Promise?o.push(s.then((t=>{t.issues.length&&n.issues.push(...In(e,t.issues)),n.value[e]=t.value}))):(s.issues.length&&n.issues.push(...In(e,s.issues)),n.value[e]=s.value)}let a;for(const e in i)s.has(e)||(a=a??[],a.push(e));a&&a.length>0&&n.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:a})}else{n.value={};for(const s of Reflect.ownKeys(i)){if("__proto__"===s)continue;const a=t.keyType._zod.run({value:s,issues:[]},r);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:a.issues.map((e=>$n(e,r,qt()))),input:s,path:[s],inst:e}),n.value[a.value]=a.value;continue}const u=t.valueType._zod.run({value:i[s],issues:[]},r);u instanceof Promise?o.push(u.then((e=>{e.issues.length&&n.issues.push(...In(s,e.issues)),n.value[a.value]=e.value}))):(u.issues.length&&n.issues.push(...In(s,u.issues)),n.value[a.value]=u.value)}}return o.length?Promise.all(o).then((()=>n)):n}})),io=Dt("$ZodMap",((e,t)=>{ni.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;if(!(i instanceof Map))return n.issues.push({expected:"map",code:"invalid_type",input:i,inst:e}),n;const o=[];n.value=new Map;for(const[s,a]of i){const u=t.keyType._zod.run({value:s,issues:[]},r),l=t.valueType._zod.run({value:a,issues:[]},r);u instanceof Promise||l instanceof Promise?o.push(Promise.all([u,l]).then((([t,o])=>{oo(t,o,n,s,i,e,r)}))):oo(u,l,n,s,i,e,r)}return o.length?Promise.all(o).then((()=>n)):n}}));function oo(e,t,n,r,i,o,s){e.issues.length&&(un.has(typeof r)?n.issues.push(...In(r,e.issues)):n.issues.push({code:"invalid_key",origin:"map",input:i,inst:o,issues:e.issues.map((e=>$n(e,s,qt())))})),t.issues.length&&(un.has(typeof r)?n.issues.push(...In(r,t.issues)):n.issues.push({origin:"map",code:"invalid_element",input:i,inst:o,key:r,issues:t.issues.map((e=>$n(e,s,qt())))})),n.value.set(e.value,t.value)}const so=Dt("$ZodSet",((e,t)=>{ni.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;if(!(i instanceof Set))return n.issues.push({input:i,inst:e,expected:"set",code:"invalid_type"}),n;const o=[];n.value=new Set;for(const e of i){const i=t.valueType._zod.run({value:e,issues:[]},r);i instanceof Promise?o.push(i.then((e=>ao(e,n)))):ao(i,n)}return o.length?Promise.all(o).then((()=>n)):n}}));function ao(e,t){e.issues.length&&t.issues.push(...e.issues),t.value.add(e.value)}const uo=Dt("$ZodEnum",((e,t)=>{ni.init(e,t);const n=Ft(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter((e=>un.has(typeof e))).map((e=>"string"==typeof e?cn(e):e.toString())).join("|")})$`),e._zod.parse=(t,i)=>{const o=t.value;return r.has(o)||t.issues.push({code:"invalid_value",values:n,input:o,inst:e}),t}})),lo=Dt("$ZodLiteral",((e,t)=>{if(ni.init(e,t),0===t.values.length)throw new Error("Cannot create literal schema with no valid values");e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map((e=>"string"==typeof e?cn(e):e?cn(e.toString()):String(e))).join("|")})$`),e._zod.parse=(n,r)=>{const i=n.value;return e._zod.values.has(i)||n.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),n}})),co=Dt("$ZodFile",((e,t)=>{ni.init(e,t),e._zod.parse=(t,n)=>{const r=t.value;return r instanceof File||t.issues.push({expected:"file",code:"invalid_type",input:r,inst:e}),t}})),po=Dt("$ZodTransform",((e,t)=>{ni.init(e,t),e._zod.parse=(e,n)=>{const r=t.transform(e.value,e);if(n.async){return(r instanceof Promise?r:Promise.resolve(r)).then((t=>(e.value=t,e)))}if(r instanceof Promise)throw new Lt;return e.value=r,e}}));function mo(e,t){return e.issues.length&&void 0===t?{issues:[],value:void 0}:e}const ho=Dt("$ZodOptional",((e,t)=>{ni.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Yt(e._zod,"values",(()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0)),Yt(e._zod,"pattern",(()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${Vt(e.source)})?$`):void 0})),e._zod.parse=(e,n)=>{if("optional"===t.innerType._zod.optin){const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then((t=>mo(t,e.value))):mo(r,e.value)}return void 0===e.value?e:t.innerType._zod.run(e,n)}})),go=Dt("$ZodNullable",((e,t)=>{ni.init(e,t),Yt(e._zod,"optin",(()=>t.innerType._zod.optin)),Yt(e._zod,"optout",(()=>t.innerType._zod.optout)),Yt(e._zod,"pattern",(()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${Vt(e.source)}|null)$`):void 0})),Yt(e._zod,"values",(()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0)),e._zod.parse=(e,n)=>null===e.value?e:t.innerType._zod.run(e,n)})),fo=Dt("$ZodDefault",((e,t)=>{ni.init(e,t),e._zod.optin="optional",Yt(e._zod,"values",(()=>t.innerType._zod.values)),e._zod.parse=(e,n)=>{if(void 0===e.value)return e.value=t.defaultValue,e;const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then((e=>vo(e,t))):vo(r,t)}}));function vo(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}const yo=Dt("$ZodPrefault",((e,t)=>{ni.init(e,t),e._zod.optin="optional",Yt(e._zod,"values",(()=>t.innerType._zod.values)),e._zod.parse=(e,n)=>(void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))})),_o=Dt("$ZodNonOptional",((e,t)=>{ni.init(e,t),Yt(e._zod,"values",(()=>{const e=t.innerType._zod.values;return e?new Set([...e].filter((e=>void 0!==e))):void 0})),e._zod.parse=(n,r)=>{const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then((t=>bo(t,e))):bo(i,e)}}));function bo(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const wo=Dt("$ZodSuccess",((e,t)=>{ni.init(e,t),e._zod.parse=(e,n)=>{const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then((t=>(e.value=0===t.issues.length,e))):(e.value=0===r.issues.length,e)}})),ko=Dt("$ZodCatch",((e,t)=>{ni.init(e,t),Yt(e._zod,"optin",(()=>t.innerType._zod.optin)),Yt(e._zod,"optout",(()=>t.innerType._zod.optout)),Yt(e._zod,"values",(()=>t.innerType._zod.values)),e._zod.parse=(e,n)=>{const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then((r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map((e=>$n(e,n,qt())))},input:e.value}),e.issues=[]),e))):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map((e=>$n(e,n,qt())))},input:e.value}),e.issues=[]),e)}})),xo=Dt("$ZodNaN",((e,t)=>{ni.init(e,t),e._zod.parse=(t,n)=>("number"==typeof t.value&&Number.isNaN(t.value)||t.issues.push({input:t.value,inst:e,expected:"nan",code:"invalid_type"}),t)})),Io=Dt("$ZodPipe",((e,t)=>{ni.init(e,t),Yt(e._zod,"values",(()=>t.in._zod.values)),Yt(e._zod,"optin",(()=>t.in._zod.optin)),Yt(e._zod,"optout",(()=>t.out._zod.optout)),Yt(e._zod,"propValues",(()=>t.in._zod.propValues)),e._zod.parse=(e,n)=>{const r=t.in._zod.run(e,n);return r instanceof Promise?r.then((e=>So(e,t,n))):So(r,t,n)}}));function So(e,t,n){return e.issues.length?e:t.out._zod.run({value:e.value,issues:e.issues},n)}const $o=Dt("$ZodReadonly",((e,t)=>{ni.init(e,t),Yt(e._zod,"propValues",(()=>t.innerType._zod.propValues)),Yt(e._zod,"values",(()=>t.innerType._zod.values)),Yt(e._zod,"optin",(()=>t.innerType._zod.optin)),Yt(e._zod,"optout",(()=>t.innerType._zod.optout)),e._zod.parse=(e,n)=>{const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(Eo):Eo(r)}}));function Eo(e){return e.value=Object.freeze(e.value),e}const To=Dt("$ZodTemplateLiteral",((e,t)=>{ni.init(e,t);const n=[];for(const r of t.parts)if("object"==typeof r&&null!==r){if(!r._zod.pattern)throw new Error(`Invalid template literal part, no pattern found: ${[...r._zod.traits].shift()}`);const e=r._zod.pattern instanceof RegExp?r._zod.pattern.source:r._zod.pattern;if(!e)throw new Error(`Invalid template literal part: ${r._zod.traits}`);const t=e.startsWith("^")?1:0,i=e.endsWith("$")?e.length-1:e.length;n.push(e.slice(t,i))}else{if(null!==r&&!ln.has(typeof r))throw new Error(`Invalid template literal part: ${r}`);n.push(cn(`${r}`))}e._zod.pattern=new RegExp(`^${n.join("")}$`),e._zod.parse=(n,r)=>"string"!=typeof n.value?(n.issues.push({input:n.value,inst:e,expected:"template_literal",code:"invalid_type"}),n):(e._zod.pattern.lastIndex=0,e._zod.pattern.test(n.value)||n.issues.push({input:n.value,inst:e,code:"invalid_format",format:t.format??"template_literal",pattern:e._zod.pattern.source}),n)})),Oo=Dt("$ZodPromise",((e,t)=>{ni.init(e,t),e._zod.parse=(e,n)=>Promise.resolve(e.value).then((e=>t.innerType._zod.run({value:e,issues:[]},n)))})),No=Dt("$ZodLazy",((e,t)=>{ni.init(e,t),Yt(e._zod,"innerType",(()=>t.getter())),Yt(e._zod,"pattern",(()=>e._zod.innerType._zod.pattern)),Yt(e._zod,"propValues",(()=>e._zod.innerType._zod.propValues)),Yt(e._zod,"optin",(()=>e._zod.innerType._zod.optin??void 0)),Yt(e._zod,"optout",(()=>e._zod.innerType._zod.optout??void 0)),e._zod.parse=(t,n)=>e._zod.innerType._zod.run(t,n)})),Co=Dt("$ZodCustom",((e,t)=>{Nr.init(e,t),ni.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{const r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then((t=>Ao(t,n,r,e)));Ao(i,n,r,e)}}));function Ao(e,t,n,r){if(!e){const e={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(On(e))}}const Po=()=>{const e={string:{unit:"حرف",verb:"أن يحوي"},file:{unit:"بايت",verb:"أن يحوي"},array:{unit:"عنصر",verb:"أن يحوي"},set:{unit:"عنصر",verb:"أن يحوي"}};function t(t){return e[t]??null}const n={regex:"مدخل",email:"بريد إلكتروني",url:"رابط",emoji:"إيموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاريخ ووقت بمعيار ISO",date:"تاريخ بمعيار ISO",time:"وقت بمعيار ISO",duration:"مدة بمعيار ISO",ipv4:"عنوان IPv4",ipv6:"عنوان IPv6",cidrv4:"مدى عناوين بصيغة IPv4",cidrv6:"مدى عناوين بصيغة IPv6",base64:"نَص بترميز base64-encoded",base64url:"نَص بترميز base64url-encoded",json_string:"نَص على هيئة JSON",e164:"رقم هاتف بمعيار E.164",jwt:"JWT",template_literal:"مدخل"};return e=>{switch(e.code){case"invalid_type":return`مدخلات غير مقبولة: يفترض إدخال ${e.expected}، ولكن تم إدخال ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`مدخلات غير مقبولة: يفترض إدخال ${mn(e.values[0])}`:`اختيار غير مقبول: يتوقع انتقاء أحد هذه الخيارات: ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?` أكبر من اللازم: يفترض أن تكون ${e.origin??"القيمة"} ${n} ${e.maximum.toString()} ${r.unit??"عنصر"}`:`أكبر من اللازم: يفترض أن تكون ${e.origin??"القيمة"} ${n} ${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`أصغر من اللازم: يفترض لـ ${e.origin} أن يكون ${n} ${e.minimum.toString()} ${r.unit}`:`أصغر من اللازم: يفترض لـ ${e.origin} أن يكون ${n} ${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`نَص غير مقبول: يجب أن يبدأ بـ "${e.prefix}"`:"ends_with"===t.format?`نَص غير مقبول: يجب أن ينتهي بـ "${t.suffix}"`:"includes"===t.format?`نَص غير مقبول: يجب أن يتضمَّن "${t.includes}"`:"regex"===t.format?`نَص غير مقبول: يجب أن يطابق النمط ${t.pattern}`:`${n[t.format]??e.format} غير مقبول`}case"not_multiple_of":return`رقم غير مقبول: يجب أن يكون من مضاعفات ${e.divisor}`;case"unrecognized_keys":return`معرف${e.keys.length>1?"ات":""} غريب${e.keys.length>1?"ة":""}: ${Wt(e.keys,"، ")}`;case"invalid_key":return`معرف غير مقبول في ${e.origin}`;case"invalid_union":default:return"مدخل غير مقبول";case"invalid_element":return`مدخل غير مقبول في ${e.origin}`}}};const Ro=()=>{const e={string:{unit:"simvol",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"element",verb:"olmalıdır"},set:{unit:"element",verb:"olmalıdır"}};function t(t){return e[t]??null}const n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Yanlış dəyər: gözlənilən ${e.expected}, daxil olan ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Yanlış dəyər: gözlənilən ${mn(e.values[0])}`:`Yanlış seçim: aşağıdakılardan biri olmalıdır: ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Çox böyük: gözlənilən ${e.origin??"dəyər"} ${n}${e.maximum.toString()} ${r.unit??"element"}`:`Çox böyük: gözlənilən ${e.origin??"dəyər"} ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Çox kiçik: gözlənilən ${e.origin} ${n}${e.minimum.toString()} ${r.unit}`:`Çox kiçik: gözlənilən ${e.origin} ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Yanlış mətn: "${t.prefix}" ilə başlamalıdır`:"ends_with"===t.format?`Yanlış mətn: "${t.suffix}" ilə bitməlidir`:"includes"===t.format?`Yanlış mətn: "${t.includes}" daxil olmalıdır`:"regex"===t.format?`Yanlış mətn: ${t.pattern} şablonuna uyğun olmalıdır`:`Yanlış ${n[t.format]??e.format}`}case"not_multiple_of":return`Yanlış ədəd: ${e.divisor} ilə bölünə bilən olmalıdır`;case"unrecognized_keys":return`Tanınmayan açar${e.keys.length>1?"lar":""}: ${Wt(e.keys,", ")}`;case"invalid_key":return`${e.origin} daxilində yanlış açar`;case"invalid_union":default:return"Yanlış dəyər";case"invalid_element":return`${e.origin} daxilində yanlış dəyər`}}};function Uo(e,t,n,r){const i=Math.abs(e),o=i%10,s=i%100;return s>=11&&s<=19?r:1===o?t:o>=2&&o<=4?n:r}const jo=()=>{const e={string:{unit:{one:"сімвал",few:"сімвалы",many:"сімвалаў"},verb:"мець"},array:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},set:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},file:{unit:{one:"байт",few:"байты",many:"байтаў"},verb:"мець"}};function t(t){return e[t]??null}const n={regex:"увод",email:"email адрас",url:"URL",emoji:"эмодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата і час",date:"ISO дата",time:"ISO час",duration:"ISO працягласць",ipv4:"IPv4 адрас",ipv6:"IPv6 адрас",cidrv4:"IPv4 дыяпазон",cidrv6:"IPv6 дыяпазон",base64:"радок у фармаце base64",base64url:"радок у фармаце base64url",json_string:"JSON радок",e164:"нумар E.164",jwt:"JWT",template_literal:"увод"};return e=>{switch(e.code){case"invalid_type":return`Няправільны ўвод: чакаўся ${e.expected}, атрымана ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"лік";case"object":if(Array.isArray(e))return"масіў";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Няправільны ўвод: чакалася ${mn(e.values[0])}`:`Няправільны варыянт: чакаўся адзін з ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);if(r){const t=Uo(Number(e.maximum),r.unit.one,r.unit.few,r.unit.many);return`Занадта вялікі: чакалася, што ${e.origin??"значэнне"} павінна ${r.verb} ${n}${e.maximum.toString()} ${t}`}return`Занадта вялікі: чакалася, што ${e.origin??"значэнне"} павінна быць ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);if(r){const t=Uo(Number(e.minimum),r.unit.one,r.unit.few,r.unit.many);return`Занадта малы: чакалася, што ${e.origin} павінна ${r.verb} ${n}${e.minimum.toString()} ${t}`}return`Занадта малы: чакалася, што ${e.origin} павінна быць ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Няправільны радок: павінен пачынацца з "${t.prefix}"`:"ends_with"===t.format?`Няправільны радок: павінен заканчвацца на "${t.suffix}"`:"includes"===t.format?`Няправільны радок: павінен змяшчаць "${t.includes}"`:"regex"===t.format?`Няправільны радок: павінен адпавядаць шаблону ${t.pattern}`:`Няправільны ${n[t.format]??e.format}`}case"not_multiple_of":return`Няправільны лік: павінен быць кратным ${e.divisor}`;case"unrecognized_keys":return`Нераспазнаны ${e.keys.length>1?"ключы":"ключ"}: ${Wt(e.keys,", ")}`;case"invalid_key":return`Няправільны ключ у ${e.origin}`;case"invalid_union":default:return"Няправільны ўвод";case"invalid_element":return`Няправільнае значэнне ў ${e.origin}`}}};const zo=()=>{const e={string:{unit:"caràcters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function t(t){return e[t]??null}const n={regex:"entrada",email:"adreça electrònica",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i hora ISO",date:"data ISO",time:"hora ISO",duration:"durada ISO",ipv4:"adreça IPv4",ipv6:"adreça IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"};return e=>{switch(e.code){case"invalid_type":return`Tipus invàlid: s'esperava ${e.expected}, s'ha rebut ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Valor invàlid: s'esperava ${mn(e.values[0])}`:`Opció invàlida: s'esperava una de ${Wt(e.values," o ")}`;case"too_big":{const n=e.inclusive?"com a màxim":"menys de",r=t(e.origin);return r?`Massa gran: s'esperava que ${e.origin??"el valor"} contingués ${n} ${e.maximum.toString()} ${r.unit??"elements"}`:`Massa gran: s'esperava que ${e.origin??"el valor"} fos ${n} ${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?"com a mínim":"més de",r=t(e.origin);return r?`Massa petit: s'esperava que ${e.origin} contingués ${n} ${e.minimum.toString()} ${r.unit}`:`Massa petit: s'esperava que ${e.origin} fos ${n} ${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Format invàlid: ha de començar amb "${t.prefix}"`:"ends_with"===t.format?`Format invàlid: ha d'acabar amb "${t.suffix}"`:"includes"===t.format?`Format invàlid: ha d'incloure "${t.includes}"`:"regex"===t.format?`Format invàlid: ha de coincidir amb el patró ${t.pattern}`:`Format invàlid per a ${n[t.format]??e.format}`}case"not_multiple_of":return`Número invàlid: ha de ser múltiple de ${e.divisor}`;case"unrecognized_keys":return`Clau${e.keys.length>1?"s":""} no reconeguda${e.keys.length>1?"s":""}: ${Wt(e.keys,", ")}`;case"invalid_key":return`Clau invàlida a ${e.origin}`;case"invalid_union":default:return"Entrada invàlida";case"invalid_element":return`Element invàlid a ${e.origin}`}}};const Do=()=>{const e={string:{unit:"znaků",verb:"mít"},file:{unit:"bajtů",verb:"mít"},array:{unit:"prvků",verb:"mít"},set:{unit:"prvků",verb:"mít"}};function t(t){return e[t]??null}const n={regex:"regulární výraz",email:"e-mailová adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"datum a čas ve formátu ISO",date:"datum ve formátu ISO",time:"čas ve formátu ISO",duration:"doba trvání ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"řetězec zakódovaný ve formátu base64",base64url:"řetězec zakódovaný ve formátu base64url",json_string:"řetězec ve formátu JSON",e164:"číslo E.164",jwt:"JWT",template_literal:"vstup"};return e=>{switch(e.code){case"invalid_type":return`Neplatný vstup: očekáváno ${e.expected}, obdrženo ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"číslo";case"string":return"řetězec";case"boolean":return"boolean";case"bigint":return"bigint";case"function":return"funkce";case"symbol":return"symbol";case"undefined":return"undefined";case"object":if(Array.isArray(e))return"pole";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Neplatný vstup: očekáváno ${mn(e.values[0])}`:`Neplatná možnost: očekávána jedna z hodnot ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Hodnota je příliš velká: ${e.origin??"hodnota"} musí mít ${n}${e.maximum.toString()} ${r.unit??"prvků"}`:`Hodnota je příliš velká: ${e.origin??"hodnota"} musí být ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Hodnota je příliš malá: ${e.origin??"hodnota"} musí mít ${n}${e.minimum.toString()} ${r.unit??"prvků"}`:`Hodnota je příliš malá: ${e.origin??"hodnota"} musí být ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Neplatný řetězec: musí začínat na "${t.prefix}"`:"ends_with"===t.format?`Neplatný řetězec: musí končit na "${t.suffix}"`:"includes"===t.format?`Neplatný řetězec: musí obsahovat "${t.includes}"`:"regex"===t.format?`Neplatný řetězec: musí odpovídat vzoru ${t.pattern}`:`Neplatný formát ${n[t.format]??e.format}`}case"not_multiple_of":return`Neplatné číslo: musí být násobkem ${e.divisor}`;case"unrecognized_keys":return`Neznámé klíče: ${Wt(e.keys,", ")}`;case"invalid_key":return`Neplatný klíč v ${e.origin}`;case"invalid_union":default:return"Neplatný vstup";case"invalid_element":return`Neplatná hodnota v ${e.origin}`}}};const Mo=()=>{const e={string:{unit:"tegn",verb:"havde"},file:{unit:"bytes",verb:"havde"},array:{unit:"elementer",verb:"indeholdt"},set:{unit:"elementer",verb:"indeholdt"}},t={string:"streng",number:"tal",boolean:"boolean",array:"liste",object:"objekt",set:"sæt",file:"fil"};function n(t){return e[t]??null}function r(e){return t[e]??e}const i={regex:"input",email:"e-mailadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslæt",date:"ISO-dato",time:"ISO-klokkeslæt",duration:"ISO-varighed",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodet streng",base64url:"base64url-kodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Ugyldigt input: forventede ${r(e.expected)}, fik ${r((e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"tal";case"object":return Array.isArray(e)?"liste":null===e?"null":Object.getPrototypeOf(e)!==Object.prototype&&e.constructor?e.constructor.name:"objekt"}return t})(e.input))}`;case"invalid_value":return 1===e.values.length?`Ugyldig værdi: forventede ${mn(e.values[0])}`:`Ugyldigt valg: forventede en af følgende ${Wt(e.values,"|")}`;case"too_big":{const t=e.inclusive?"<=":"<",i=n(e.origin),o=r(e.origin);return i?`For stor: forventede ${o??"value"} ${i.verb} ${t} ${e.maximum.toString()} ${i.unit??"elementer"}`:`For stor: forventede ${o??"value"} havde ${t} ${e.maximum.toString()}`}case"too_small":{const t=e.inclusive?">=":">",i=n(e.origin),o=r(e.origin);return i?`For lille: forventede ${o} ${i.verb} ${t} ${e.minimum.toString()} ${i.unit}`:`For lille: forventede ${o} havde ${t} ${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Ugyldig streng: skal starte med "${t.prefix}"`:"ends_with"===t.format?`Ugyldig streng: skal ende med "${t.suffix}"`:"includes"===t.format?`Ugyldig streng: skal indeholde "${t.includes}"`:"regex"===t.format?`Ugyldig streng: skal matche mønsteret ${t.pattern}`:`Ugyldig ${i[t.format]??e.format}`}case"not_multiple_of":return`Ugyldigt tal: skal være deleligt med ${e.divisor}`;case"unrecognized_keys":return`${e.keys.length>1?"Ukendte nøgler":"Ukendt nøgle"}: ${Wt(e.keys,", ")}`;case"invalid_key":return`Ugyldig nøgle i ${e.origin}`;case"invalid_union":return"Ugyldigt input: matcher ingen af de tilladte typer";case"invalid_element":return`Ugyldig værdi i ${e.origin}`;default:return"Ugyldigt input"}}};const Lo=()=>{const e={string:{unit:"Zeichen",verb:"zu haben"},file:{unit:"Bytes",verb:"zu haben"},array:{unit:"Elemente",verb:"zu haben"},set:{unit:"Elemente",verb:"zu haben"}};function t(t){return e[t]??null}const n={regex:"Eingabe",email:"E-Mail-Adresse",url:"URL",emoji:"Emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-Datum und -Uhrzeit",date:"ISO-Datum",time:"ISO-Uhrzeit",duration:"ISO-Dauer",ipv4:"IPv4-Adresse",ipv6:"IPv6-Adresse",cidrv4:"IPv4-Bereich",cidrv6:"IPv6-Bereich",base64:"Base64-codierter String",base64url:"Base64-URL-codierter String",json_string:"JSON-String",e164:"E.164-Nummer",jwt:"JWT",template_literal:"Eingabe"};return e=>{switch(e.code){case"invalid_type":return`Ungültige Eingabe: erwartet ${e.expected}, erhalten ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"Zahl";case"object":if(Array.isArray(e))return"Array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Ungültige Eingabe: erwartet ${mn(e.values[0])}`:`Ungültige Option: erwartet eine von ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Zu groß: erwartet, dass ${e.origin??"Wert"} ${n}${e.maximum.toString()} ${r.unit??"Elemente"} hat`:`Zu groß: erwartet, dass ${e.origin??"Wert"} ${n}${e.maximum.toString()} ist`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Zu klein: erwartet, dass ${e.origin} ${n}${e.minimum.toString()} ${r.unit} hat`:`Zu klein: erwartet, dass ${e.origin} ${n}${e.minimum.toString()} ist`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Ungültiger String: muss mit "${t.prefix}" beginnen`:"ends_with"===t.format?`Ungültiger String: muss mit "${t.suffix}" enden`:"includes"===t.format?`Ungültiger String: muss "${t.includes}" enthalten`:"regex"===t.format?`Ungültiger String: muss dem Muster ${t.pattern} entsprechen`:`Ungültig: ${n[t.format]??e.format}`}case"not_multiple_of":return`Ungültige Zahl: muss ein Vielfaches von ${e.divisor} sein`;case"unrecognized_keys":return`${e.keys.length>1?"Unbekannte Schlüssel":"Unbekannter Schlüssel"}: ${Wt(e.keys,", ")}`;case"invalid_key":return`Ungültiger Schlüssel in ${e.origin}`;case"invalid_union":default:return"Ungültige Eingabe";case"invalid_element":return`Ungültiger Wert in ${e.origin}`}}};const Zo=()=>{const e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function t(t){return e[t]??null}const n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Invalid input: expected ${e.expected}, received ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Invalid input: expected ${mn(e.values[0])}`:`Invalid option: expected one of ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Too big: expected ${e.origin??"value"} to have ${n}${e.maximum.toString()} ${r.unit??"elements"}`:`Too big: expected ${e.origin??"value"} to be ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Too small: expected ${e.origin} to have ${n}${e.minimum.toString()} ${r.unit}`:`Too small: expected ${e.origin} to be ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Invalid string: must start with "${t.prefix}"`:"ends_with"===t.format?`Invalid string: must end with "${t.suffix}"`:"includes"===t.format?`Invalid string: must include "${t.includes}"`:"regex"===t.format?`Invalid string: must match pattern ${t.pattern}`:`Invalid ${n[t.format]??e.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${e.divisor}`;case"unrecognized_keys":return`Unrecognized key${e.keys.length>1?"s":""}: ${Wt(e.keys,", ")}`;case"invalid_key":return`Invalid key in ${e.origin}`;case"invalid_union":default:return"Invalid input";case"invalid_element":return`Invalid value in ${e.origin}`}}};function qo(){return{localeError:Zo()}}const Fo=()=>{const e={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function t(t){return e[t]??null}const n={regex:"enigo",email:"retadreso",url:"URL",emoji:"emoĝio",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datotempo",date:"ISO-dato",time:"ISO-tempo",duration:"ISO-daŭro",ipv4:"IPv4-adreso",ipv6:"IPv6-adreso",cidrv4:"IPv4-rango",cidrv6:"IPv6-rango",base64:"64-ume kodita karaktraro",base64url:"URL-64-ume kodita karaktraro",json_string:"JSON-karaktraro",e164:"E.164-nombro",jwt:"JWT",template_literal:"enigo"};return e=>{switch(e.code){case"invalid_type":return`Nevalida enigo: atendiĝis ${e.expected}, riceviĝis ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"nombro";case"object":if(Array.isArray(e))return"tabelo";if(null===e)return"senvalora";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Nevalida enigo: atendiĝis ${mn(e.values[0])}`:`Nevalida opcio: atendiĝis unu el ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Tro granda: atendiĝis ke ${e.origin??"valoro"} havu ${n}${e.maximum.toString()} ${r.unit??"elementojn"}`:`Tro granda: atendiĝis ke ${e.origin??"valoro"} havu ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Tro malgranda: atendiĝis ke ${e.origin} havu ${n}${e.minimum.toString()} ${r.unit}`:`Tro malgranda: atendiĝis ke ${e.origin} estu ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Nevalida karaktraro: devas komenciĝi per "${t.prefix}"`:"ends_with"===t.format?`Nevalida karaktraro: devas finiĝi per "${t.suffix}"`:"includes"===t.format?`Nevalida karaktraro: devas inkluzivi "${t.includes}"`:"regex"===t.format?`Nevalida karaktraro: devas kongrui kun la modelo ${t.pattern}`:`Nevalida ${n[t.format]??e.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${e.divisor}`;case"unrecognized_keys":return`Nekonata${e.keys.length>1?"j":""} ŝlosilo${e.keys.length>1?"j":""}: ${Wt(e.keys,", ")}`;case"invalid_key":return`Nevalida ŝlosilo en ${e.origin}`;case"invalid_union":default:return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${e.origin}`}}};const Wo=()=>{const e={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}};function t(t){return e[t]??null}const n={regex:"entrada",email:"dirección de correo electrónico",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"fecha y hora ISO",date:"fecha ISO",time:"hora ISO",duration:"duración ISO",ipv4:"dirección IPv4",ipv6:"dirección IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"};return e=>{switch(e.code){case"invalid_type":return`Entrada inválida: se esperaba ${e.expected}, recibido ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"número";case"object":if(Array.isArray(e))return"arreglo";if(null===e)return"nulo";if(Object.getPrototypeOf(e)!==Object.prototype)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Entrada inválida: se esperaba ${mn(e.values[0])}`:`Opción inválida: se esperaba una de ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Demasiado grande: se esperaba que ${e.origin??"valor"} tuviera ${n}${e.maximum.toString()} ${r.unit??"elementos"}`:`Demasiado grande: se esperaba que ${e.origin??"valor"} fuera ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Demasiado pequeño: se esperaba que ${e.origin} tuviera ${n}${e.minimum.toString()} ${r.unit}`:`Demasiado pequeño: se esperaba que ${e.origin} fuera ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Cadena inválida: debe comenzar con "${t.prefix}"`:"ends_with"===t.format?`Cadena inválida: debe terminar en "${t.suffix}"`:"includes"===t.format?`Cadena inválida: debe incluir "${t.includes}"`:"regex"===t.format?`Cadena inválida: debe coincidir con el patrón ${t.pattern}`:`Inválido ${n[t.format]??e.format}`}case"not_multiple_of":return`Número inválido: debe ser múltiplo de ${e.divisor}`;case"unrecognized_keys":return`Llave${e.keys.length>1?"s":""} desconocida${e.keys.length>1?"s":""}: ${Wt(e.keys,", ")}`;case"invalid_key":return`Llave inválida en ${e.origin}`;case"invalid_union":default:return"Entrada inválida";case"invalid_element":return`Valor inválido en ${e.origin}`}}};const Jo=()=>{const e={string:{unit:"کاراکتر",verb:"داشته باشد"},file:{unit:"بایت",verb:"داشته باشد"},array:{unit:"آیتم",verb:"داشته باشد"},set:{unit:"آیتم",verb:"داشته باشد"}};function t(t){return e[t]??null}const n={regex:"ورودی",email:"آدرس ایمیل",url:"URL",emoji:"ایموجی",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاریخ و زمان ایزو",date:"تاریخ ایزو",time:"زمان ایزو",duration:"مدت زمان ایزو",ipv4:"IPv4 آدرس",ipv6:"IPv6 آدرس",cidrv4:"IPv4 دامنه",cidrv6:"IPv6 دامنه",base64:"base64-encoded رشته",base64url:"base64url-encoded رشته",json_string:"JSON رشته",e164:"E.164 عدد",jwt:"JWT",template_literal:"ورودی"};return e=>{switch(e.code){case"invalid_type":return`ورودی نامعتبر: میبایست ${e.expected} میبود، ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"عدد";case"object":if(Array.isArray(e))return"آرایه";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)} دریافت شد`;case"invalid_value":return 1===e.values.length?`ورودی نامعتبر: میبایست ${mn(e.values[0])} میبود`:`گزینه نامعتبر: میبایست یکی از ${Wt(e.values,"|")} میبود`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`خیلی بزرگ: ${e.origin??"مقدار"} باید ${n}${e.maximum.toString()} ${r.unit??"عنصر"} باشد`:`خیلی بزرگ: ${e.origin??"مقدار"} باید ${n}${e.maximum.toString()} باشد`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`خیلی کوچک: ${e.origin} باید ${n}${e.minimum.toString()} ${r.unit} باشد`:`خیلی کوچک: ${e.origin} باید ${n}${e.minimum.toString()} باشد`}case"invalid_format":{const t=e;return"starts_with"===t.format?`رشته نامعتبر: باید با "${t.prefix}" شروع شود`:"ends_with"===t.format?`رشته نامعتبر: باید با "${t.suffix}" تمام شود`:"includes"===t.format?`رشته نامعتبر: باید شامل "${t.includes}" باشد`:"regex"===t.format?`رشته نامعتبر: باید با الگوی ${t.pattern} مطابقت داشته باشد`:`${n[t.format]??e.format} نامعتبر`}case"not_multiple_of":return`عدد نامعتبر: باید مضرب ${e.divisor} باشد`;case"unrecognized_keys":return`کلید${e.keys.length>1?"های":""} ناشناس: ${Wt(e.keys,", ")}`;case"invalid_key":return`کلید ناشناس در ${e.origin}`;case"invalid_union":default:return"ورودی نامعتبر";case"invalid_element":return`مقدار نامعتبر در ${e.origin}`}}};const Bo=()=>{const e={string:{unit:"merkkiä",subject:"merkkijonon"},file:{unit:"tavua",subject:"tiedoston"},array:{unit:"alkiota",subject:"listan"},set:{unit:"alkiota",subject:"joukon"},number:{unit:"",subject:"luvun"},bigint:{unit:"",subject:"suuren kokonaisluvun"},int:{unit:"",subject:"kokonaisluvun"},date:{unit:"",subject:"päivämäärän"}};function t(t){return e[t]??null}const n={regex:"säännöllinen lauseke",email:"sähköpostiosoite",url:"URL-osoite",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-aikaleima",date:"ISO-päivämäärä",time:"ISO-aika",duration:"ISO-kesto",ipv4:"IPv4-osoite",ipv6:"IPv6-osoite",cidrv4:"IPv4-alue",cidrv6:"IPv6-alue",base64:"base64-koodattu merkkijono",base64url:"base64url-koodattu merkkijono",json_string:"JSON-merkkijono",e164:"E.164-luku",jwt:"JWT",template_literal:"templaattimerkkijono"};return e=>{switch(e.code){case"invalid_type":return`Virheellinen tyyppi: odotettiin ${e.expected}, oli ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Virheellinen syöte: täytyy olla ${mn(e.values[0])}`:`Virheellinen valinta: täytyy olla yksi seuraavista: ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Liian suuri: ${r.subject} täytyy olla ${n}${e.maximum.toString()} ${r.unit}`.trim():`Liian suuri: arvon täytyy olla ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Liian pieni: ${r.subject} täytyy olla ${n}${e.minimum.toString()} ${r.unit}`.trim():`Liian pieni: arvon täytyy olla ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Virheellinen syöte: täytyy alkaa "${t.prefix}"`:"ends_with"===t.format?`Virheellinen syöte: täytyy loppua "${t.suffix}"`:"includes"===t.format?`Virheellinen syöte: täytyy sisältää "${t.includes}"`:"regex"===t.format?`Virheellinen syöte: täytyy vastata säännöllistä lauseketta ${t.pattern}`:`Virheellinen ${n[t.format]??e.format}`}case"not_multiple_of":return`Virheellinen luku: täytyy olla luvun ${e.divisor} monikerta`;case"unrecognized_keys":return`${e.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${Wt(e.keys,", ")}`;case"invalid_key":return"Virheellinen avain tietueessa";case"invalid_union":return"Virheellinen unioni";case"invalid_element":return"Virheellinen arvo joukossa";default:return"Virheellinen syöte"}}};const Ho=()=>{const e={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}};function t(t){return e[t]??null}const n={regex:"entrée",email:"adresse e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date et heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"};return e=>{switch(e.code){case"invalid_type":return`Entrée invalide : ${e.expected} attendu, ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"nombre";case"object":if(Array.isArray(e))return"tableau";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)} reçu`;case"invalid_value":return 1===e.values.length?`Entrée invalide : ${mn(e.values[0])} attendu`:`Option invalide : une valeur parmi ${Wt(e.values,"|")} attendue`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Trop grand : ${e.origin??"valeur"} doit ${r.verb} ${n}${e.maximum.toString()} ${r.unit??"élément(s)"}`:`Trop grand : ${e.origin??"valeur"} doit être ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Trop petit : ${e.origin} doit ${r.verb} ${n}${e.minimum.toString()} ${r.unit}`:`Trop petit : ${e.origin} doit être ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Chaîne invalide : doit commencer par "${t.prefix}"`:"ends_with"===t.format?`Chaîne invalide : doit se terminer par "${t.suffix}"`:"includes"===t.format?`Chaîne invalide : doit inclure "${t.includes}"`:"regex"===t.format?`Chaîne invalide : doit correspondre au modèle ${t.pattern}`:`${n[t.format]??e.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${e.divisor}`;case"unrecognized_keys":return`Clé${e.keys.length>1?"s":""} non reconnue${e.keys.length>1?"s":""} : ${Wt(e.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${e.origin}`;case"invalid_union":default:return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${e.origin}`}}};const Vo=()=>{const e={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}};function t(t){return e[t]??null}const n={regex:"entrée",email:"adresse courriel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date-heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"};return e=>{switch(e.code){case"invalid_type":return`Entrée invalide : attendu ${e.expected}, reçu ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Entrée invalide : attendu ${mn(e.values[0])}`:`Option invalide : attendu l'une des valeurs suivantes ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"≤":"<",r=t(e.origin);return r?`Trop grand : attendu que ${e.origin??"la valeur"} ait ${n}${e.maximum.toString()} ${r.unit}`:`Trop grand : attendu que ${e.origin??"la valeur"} soit ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?"≥":">",r=t(e.origin);return r?`Trop petit : attendu que ${e.origin} ait ${n}${e.minimum.toString()} ${r.unit}`:`Trop petit : attendu que ${e.origin} soit ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Chaîne invalide : doit commencer par "${t.prefix}"`:"ends_with"===t.format?`Chaîne invalide : doit se terminer par "${t.suffix}"`:"includes"===t.format?`Chaîne invalide : doit inclure "${t.includes}"`:"regex"===t.format?`Chaîne invalide : doit correspondre au motif ${t.pattern}`:`${n[t.format]??e.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${e.divisor}`;case"unrecognized_keys":return`Clé${e.keys.length>1?"s":""} non reconnue${e.keys.length>1?"s":""} : ${Wt(e.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${e.origin}`;case"invalid_union":default:return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${e.origin}`}}};const Ko=()=>{const e={string:{unit:"אותיות",verb:"לכלול"},file:{unit:"בייטים",verb:"לכלול"},array:{unit:"פריטים",verb:"לכלול"},set:{unit:"פריטים",verb:"לכלול"}};function t(t){return e[t]??null}const n={regex:"קלט",email:"כתובת אימייל",url:"כתובת רשת",emoji:"אימוג'י",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"תאריך וזמן ISO",date:"תאריך ISO",time:"זמן ISO",duration:"משך זמן ISO",ipv4:"כתובת IPv4",ipv6:"כתובת IPv6",cidrv4:"טווח IPv4",cidrv6:"טווח IPv6",base64:"מחרוזת בבסיס 64",base64url:"מחרוזת בבסיס 64 לכתובות רשת",json_string:"מחרוזת JSON",e164:"מספר E.164",jwt:"JWT",template_literal:"קלט"};return e=>{switch(e.code){case"invalid_type":return`קלט לא תקין: צריך ${e.expected}, התקבל ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`קלט לא תקין: צריך ${mn(e.values[0])}`:`קלט לא תקין: צריך אחת מהאפשרויות ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`גדול מדי: ${e.origin??"value"} צריך להיות ${n}${e.maximum.toString()} ${r.unit??"elements"}`:`גדול מדי: ${e.origin??"value"} צריך להיות ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`קטן מדי: ${e.origin} צריך להיות ${n}${e.minimum.toString()} ${r.unit}`:`קטן מדי: ${e.origin} צריך להיות ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`מחרוזת לא תקינה: חייבת להתחיל ב"${t.prefix}"`:"ends_with"===t.format?`מחרוזת לא תקינה: חייבת להסתיים ב "${t.suffix}"`:"includes"===t.format?`מחרוזת לא תקינה: חייבת לכלול "${t.includes}"`:"regex"===t.format?`מחרוזת לא תקינה: חייבת להתאים לתבנית ${t.pattern}`:`${n[t.format]??e.format} לא תקין`}case"not_multiple_of":return`מספר לא תקין: חייב להיות מכפלה של ${e.divisor}`;case"unrecognized_keys":return`מפתח${e.keys.length>1?"ות":""} לא מזוה${e.keys.length>1?"ים":"ה"}: ${Wt(e.keys,", ")}`;case"invalid_key":return`מפתח לא תקין ב${e.origin}`;case"invalid_union":default:return"קלט לא תקין";case"invalid_element":return`ערך לא תקין ב${e.origin}`}}};const Go=()=>{const e={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function t(t){return e[t]??null}const n={regex:"bemenet",email:"email cím",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO időbélyeg",date:"ISO dátum",time:"ISO idő",duration:"ISO időintervallum",ipv4:"IPv4 cím",ipv6:"IPv6 cím",cidrv4:"IPv4 tartomány",cidrv6:"IPv6 tartomány",base64:"base64-kódolt string",base64url:"base64url-kódolt string",json_string:"JSON string",e164:"E.164 szám",jwt:"JWT",template_literal:"bemenet"};return e=>{switch(e.code){case"invalid_type":return`Érvénytelen bemenet: a várt érték ${e.expected}, a kapott érték ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"szám";case"object":if(Array.isArray(e))return"tömb";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Érvénytelen bemenet: a várt érték ${mn(e.values[0])}`:`Érvénytelen opció: valamelyik érték várt ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Túl nagy: ${e.origin??"érték"} mérete túl nagy ${n}${e.maximum.toString()} ${r.unit??"elem"}`:`Túl nagy: a bemeneti érték ${e.origin??"érték"} túl nagy: ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Túl kicsi: a bemeneti érték ${e.origin} mérete túl kicsi ${n}${e.minimum.toString()} ${r.unit}`:`Túl kicsi: a bemeneti érték ${e.origin} túl kicsi ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Érvénytelen string: "${t.prefix}" értékkel kell kezdődnie`:"ends_with"===t.format?`Érvénytelen string: "${t.suffix}" értékkel kell végződnie`:"includes"===t.format?`Érvénytelen string: "${t.includes}" értéket kell tartalmaznia`:"regex"===t.format?`Érvénytelen string: ${t.pattern} mintának kell megfelelnie`:`Érvénytelen ${n[t.format]??e.format}`}case"not_multiple_of":return`Érvénytelen szám: ${e.divisor} többszörösének kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${e.keys.length>1?"s":""}: ${Wt(e.keys,", ")}`;case"invalid_key":return`Érvénytelen kulcs ${e.origin}`;case"invalid_union":default:return"Érvénytelen bemenet";case"invalid_element":return`Érvénytelen érték: ${e.origin}`}}};const Yo=()=>{const e={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function t(t){return e[t]??null}const n={regex:"input",email:"alamat email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tanggal dan waktu format ISO",date:"tanggal format ISO",time:"jam format ISO",duration:"durasi format ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"rentang alamat IPv4",cidrv6:"rentang alamat IPv6",base64:"string dengan enkode base64",base64url:"string dengan enkode base64url",json_string:"string JSON",e164:"angka E.164",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Input tidak valid: diharapkan ${e.expected}, diterima ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Input tidak valid: diharapkan ${mn(e.values[0])}`:`Pilihan tidak valid: diharapkan salah satu dari ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Terlalu besar: diharapkan ${e.origin??"value"} memiliki ${n}${e.maximum.toString()} ${r.unit??"elemen"}`:`Terlalu besar: diharapkan ${e.origin??"value"} menjadi ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Terlalu kecil: diharapkan ${e.origin} memiliki ${n}${e.minimum.toString()} ${r.unit}`:`Terlalu kecil: diharapkan ${e.origin} menjadi ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`String tidak valid: harus dimulai dengan "${t.prefix}"`:"ends_with"===t.format?`String tidak valid: harus berakhir dengan "${t.suffix}"`:"includes"===t.format?`String tidak valid: harus menyertakan "${t.includes}"`:"regex"===t.format?`String tidak valid: harus sesuai pola ${t.pattern}`:`${n[t.format]??e.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${e.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${e.keys.length>1?"s":""}: ${Wt(e.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${e.origin}`;case"invalid_union":default:return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${e.origin}`}}};const Xo=()=>{const e={string:{unit:"stafi",verb:"að hafa"},file:{unit:"bæti",verb:"að hafa"},array:{unit:"hluti",verb:"að hafa"},set:{unit:"hluti",verb:"að hafa"}};function t(t){return e[t]??null}const n={regex:"gildi",email:"netfang",url:"vefslóð",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dagsetning og tími",date:"ISO dagsetning",time:"ISO tími",duration:"ISO tímalengd",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded strengur",base64url:"base64url-encoded strengur",json_string:"JSON strengur",e164:"E.164 tölugildi",jwt:"JWT",template_literal:"gildi"};return e=>{switch(e.code){case"invalid_type":return`Rangt gildi: Þú slóst inn ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"númer";case"object":if(Array.isArray(e))return"fylki";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)} þar sem á að vera ${e.expected}`;case"invalid_value":return 1===e.values.length?`Rangt gildi: gert ráð fyrir ${mn(e.values[0])}`:`Ógilt val: má vera eitt af eftirfarandi ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Of stórt: gert er ráð fyrir að ${e.origin??"gildi"} hafi ${n}${e.maximum.toString()} ${r.unit??"hluti"}`:`Of stórt: gert er ráð fyrir að ${e.origin??"gildi"} sé ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Of lítið: gert er ráð fyrir að ${e.origin} hafi ${n}${e.minimum.toString()} ${r.unit}`:`Of lítið: gert er ráð fyrir að ${e.origin} sé ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Ógildur strengur: verður að byrja á "${t.prefix}"`:"ends_with"===t.format?`Ógildur strengur: verður að enda á "${t.suffix}"`:"includes"===t.format?`Ógildur strengur: verður að innihalda "${t.includes}"`:"regex"===t.format?`Ógildur strengur: verður að fylgja mynstri ${t.pattern}`:`Rangt ${n[t.format]??e.format}`}case"not_multiple_of":return`Röng tala: verður að vera margfeldi af ${e.divisor}`;case"unrecognized_keys":return`Óþekkt ${e.keys.length>1?"ir lyklar":"ur lykill"}: ${Wt(e.keys,", ")}`;case"invalid_key":return`Rangur lykill í ${e.origin}`;case"invalid_union":default:return"Rangt gildi";case"invalid_element":return`Rangt gildi í ${e.origin}`}}};const Qo=()=>{const e={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function t(t){return e[t]??null}const n={regex:"input",email:"indirizzo email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e ora ISO",date:"data ISO",time:"ora ISO",duration:"durata ISO",ipv4:"indirizzo IPv4",ipv6:"indirizzo IPv6",cidrv4:"intervallo IPv4",cidrv6:"intervallo IPv6",base64:"stringa codificata in base64",base64url:"URL codificata in base64",json_string:"stringa JSON",e164:"numero E.164",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Input non valido: atteso ${e.expected}, ricevuto ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"numero";case"object":if(Array.isArray(e))return"vettore";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Input non valido: atteso ${mn(e.values[0])}`:`Opzione non valida: atteso uno tra ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Troppo grande: ${e.origin??"valore"} deve avere ${n}${e.maximum.toString()} ${r.unit??"elementi"}`:`Troppo grande: ${e.origin??"valore"} deve essere ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Troppo piccolo: ${e.origin} deve avere ${n}${e.minimum.toString()} ${r.unit}`:`Troppo piccolo: ${e.origin} deve essere ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Stringa non valida: deve iniziare con "${t.prefix}"`:"ends_with"===t.format?`Stringa non valida: deve terminare con "${t.suffix}"`:"includes"===t.format?`Stringa non valida: deve includere "${t.includes}"`:"regex"===t.format?`Stringa non valida: deve corrispondere al pattern ${t.pattern}`:`Invalid ${n[t.format]??e.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${e.divisor}`;case"unrecognized_keys":return`Chiav${e.keys.length>1?"i":"e"} non riconosciut${e.keys.length>1?"e":"a"}: ${Wt(e.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${e.origin}`;case"invalid_union":default:return"Input non valido";case"invalid_element":return`Valore non valido in ${e.origin}`}}};const es=()=>{const e={string:{unit:"文字",verb:"である"},file:{unit:"バイト",verb:"である"},array:{unit:"要素",verb:"である"},set:{unit:"要素",verb:"である"}};function t(t){return e[t]??null}const n={regex:"入力値",email:"メールアドレス",url:"URL",emoji:"絵文字",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日時",date:"ISO日付",time:"ISO時刻",duration:"ISO期間",ipv4:"IPv4アドレス",ipv6:"IPv6アドレス",cidrv4:"IPv4範囲",cidrv6:"IPv6範囲",base64:"base64エンコード文字列",base64url:"base64urlエンコード文字列",json_string:"JSON文字列",e164:"E.164番号",jwt:"JWT",template_literal:"入力値"};return e=>{switch(e.code){case"invalid_type":return`無効な入力: ${e.expected}が期待されましたが、${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"数値";case"object":if(Array.isArray(e))return"配列";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}が入力されました`;case"invalid_value":return 1===e.values.length?`無効な入力: ${mn(e.values[0])}が期待されました`:`無効な選択: ${Wt(e.values,"、")}のいずれかである必要があります`;case"too_big":{const n=e.inclusive?"以下である":"より小さい",r=t(e.origin);return r?`大きすぎる値: ${e.origin??"値"}は${e.maximum.toString()}${r.unit??"要素"}${n}必要があります`:`大きすぎる値: ${e.origin??"値"}は${e.maximum.toString()}${n}必要があります`}case"too_small":{const n=e.inclusive?"以上である":"より大きい",r=t(e.origin);return r?`小さすぎる値: ${e.origin}は${e.minimum.toString()}${r.unit}${n}必要があります`:`小さすぎる値: ${e.origin}は${e.minimum.toString()}${n}必要があります`}case"invalid_format":{const t=e;return"starts_with"===t.format?`無効な文字列: "${t.prefix}"で始まる必要があります`:"ends_with"===t.format?`無効な文字列: "${t.suffix}"で終わる必要があります`:"includes"===t.format?`無効な文字列: "${t.includes}"を含む必要があります`:"regex"===t.format?`無効な文字列: パターン${t.pattern}に一致する必要があります`:`無効な${n[t.format]??e.format}`}case"not_multiple_of":return`無効な数値: ${e.divisor}の倍数である必要があります`;case"unrecognized_keys":return`認識されていないキー${e.keys.length>1?"群":""}: ${Wt(e.keys,"、")}`;case"invalid_key":return`${e.origin}内の無効なキー`;case"invalid_union":default:return"無効な入力";case"invalid_element":return`${e.origin}内の無効な値`}}};const ts=()=>{const e={string:{unit:"តួអក្សរ",verb:"គួរមាន"},file:{unit:"បៃ",verb:"គួរមាន"},array:{unit:"ធាតុ",verb:"គួរមាន"},set:{unit:"ធាតុ",verb:"គួរមាន"}};function t(t){return e[t]??null}const n={regex:"ទិន្នន័យបញ្ចូល",email:"អាសយដ្ឋានអ៊ីមែល",url:"URL",emoji:"សញ្ញាអារម្មណ៍",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"កាលបរិច្ឆេទ និងម៉ោង ISO",date:"កាលបរិច្ឆេទ ISO",time:"ម៉ោង ISO",duration:"រយៈពេល ISO",ipv4:"អាសយដ្ឋាន IPv4",ipv6:"អាសយដ្ឋាន IPv6",cidrv4:"ដែនអាសយដ្ឋាន IPv4",cidrv6:"ដែនអាសយដ្ឋាន IPv6",base64:"ខ្សែអក្សរអ៊ិកូដ base64",base64url:"ខ្សែអក្សរអ៊ិកូដ base64url",json_string:"ខ្សែអក្សរ JSON",e164:"លេខ E.164",jwt:"JWT",template_literal:"ទិន្នន័យបញ្ចូល"};return e=>{switch(e.code){case"invalid_type":return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${e.expected} ប៉ុន្តែទទួលបាន ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"មិនមែនជាលេខ (NaN)":"លេខ";case"object":if(Array.isArray(e))return"អារេ (Array)";if(null===e)return"គ្មានតម្លៃ (null)";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${mn(e.values[0])}`:`ជម្រើសមិនត្រឹមត្រូវ៖ ត្រូវជាមួយក្នុងចំណោម ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`ធំពេក៖ ត្រូវការ ${e.origin??"តម្លៃ"} ${n} ${e.maximum.toString()} ${r.unit??"ធាតុ"}`:`ធំពេក៖ ត្រូវការ ${e.origin??"តម្លៃ"} ${n} ${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`តូចពេក៖ ត្រូវការ ${e.origin} ${n} ${e.minimum.toString()} ${r.unit}`:`តូចពេក៖ ត្រូវការ ${e.origin} ${n} ${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវចាប់ផ្តើមដោយ "${t.prefix}"`:"ends_with"===t.format?`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវបញ្ចប់ដោយ "${t.suffix}"`:"includes"===t.format?`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវមាន "${t.includes}"`:"regex"===t.format?`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវតែផ្គូផ្គងនឹងទម្រង់ដែលបានកំណត់ ${t.pattern}`:`មិនត្រឹមត្រូវ៖ ${n[t.format]??e.format}`}case"not_multiple_of":return`លេខមិនត្រឹមត្រូវ៖ ត្រូវតែជាពហុគុណនៃ ${e.divisor}`;case"unrecognized_keys":return`រកឃើញសោមិនស្គាល់៖ ${Wt(e.keys,", ")}`;case"invalid_key":return`សោមិនត្រឹមត្រូវនៅក្នុង ${e.origin}`;case"invalid_union":default:return"ទិន្នន័យមិនត្រឹមត្រូវ";case"invalid_element":return`ទិន្នន័យមិនត្រឹមត្រូវនៅក្នុង ${e.origin}`}}};const ns=()=>{const e={string:{unit:"문자",verb:"to have"},file:{unit:"바이트",verb:"to have"},array:{unit:"개",verb:"to have"},set:{unit:"개",verb:"to have"}};function t(t){return e[t]??null}const n={regex:"입력",email:"이메일 주소",url:"URL",emoji:"이모지",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 날짜시간",date:"ISO 날짜",time:"ISO 시간",duration:"ISO 기간",ipv4:"IPv4 주소",ipv6:"IPv6 주소",cidrv4:"IPv4 범위",cidrv6:"IPv6 범위",base64:"base64 인코딩 문자열",base64url:"base64url 인코딩 문자열",json_string:"JSON 문자열",e164:"E.164 번호",jwt:"JWT",template_literal:"입력"};return e=>{switch(e.code){case"invalid_type":return`잘못된 입력: 예상 타입은 ${e.expected}, 받은 타입은 ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}입니다`;case"invalid_value":return 1===e.values.length?`잘못된 입력: 값은 ${mn(e.values[0])} 이어야 합니다`:`잘못된 옵션: ${Wt(e.values,"또는 ")} 중 하나여야 합니다`;case"too_big":{const n=e.inclusive?"이하":"미만",r="미만"===n?"이어야 합니다":"여야 합니다",i=t(e.origin),o=(null==i?void 0:i.unit)??"요소";return i?`${e.origin??"값"}이 너무 큽니다: ${e.maximum.toString()}${o} ${n}${r}`:`${e.origin??"값"}이 너무 큽니다: ${e.maximum.toString()} ${n}${r}`}case"too_small":{const n=e.inclusive?"이상":"초과",r="이상"===n?"이어야 합니다":"여야 합니다",i=t(e.origin),o=(null==i?void 0:i.unit)??"요소";return i?`${e.origin??"값"}이 너무 작습니다: ${e.minimum.toString()}${o} ${n}${r}`:`${e.origin??"값"}이 너무 작습니다: ${e.minimum.toString()} ${n}${r}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`잘못된 문자열: "${t.prefix}"(으)로 시작해야 합니다`:"ends_with"===t.format?`잘못된 문자열: "${t.suffix}"(으)로 끝나야 합니다`:"includes"===t.format?`잘못된 문자열: "${t.includes}"을(를) 포함해야 합니다`:"regex"===t.format?`잘못된 문자열: 정규식 ${t.pattern} 패턴과 일치해야 합니다`:`잘못된 ${n[t.format]??e.format}`}case"not_multiple_of":return`잘못된 숫자: ${e.divisor}의 배수여야 합니다`;case"unrecognized_keys":return`인식할 수 없는 키: ${Wt(e.keys,", ")}`;case"invalid_key":return`잘못된 키: ${e.origin}`;case"invalid_union":default:return"잘못된 입력";case"invalid_element":return`잘못된 값: ${e.origin}`}}};const rs=()=>{const e={string:{unit:"знаци",verb:"да имаат"},file:{unit:"бајти",verb:"да имаат"},array:{unit:"ставки",verb:"да имаат"},set:{unit:"ставки",verb:"да имаат"}};function t(t){return e[t]??null}const n={regex:"внес",email:"адреса на е-пошта",url:"URL",emoji:"емоџи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO датум и време",date:"ISO датум",time:"ISO време",duration:"ISO времетраење",ipv4:"IPv4 адреса",ipv6:"IPv6 адреса",cidrv4:"IPv4 опсег",cidrv6:"IPv6 опсег",base64:"base64-енкодирана низа",base64url:"base64url-енкодирана низа",json_string:"JSON низа",e164:"E.164 број",jwt:"JWT",template_literal:"внес"};return e=>{switch(e.code){case"invalid_type":return`Грешен внес: се очекува ${e.expected}, примено ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"број";case"object":if(Array.isArray(e))return"низа";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Invalid input: expected ${mn(e.values[0])}`:`Грешана опција: се очекува една ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Премногу голем: се очекува ${e.origin??"вредноста"} да има ${n}${e.maximum.toString()} ${r.unit??"елементи"}`:`Премногу голем: се очекува ${e.origin??"вредноста"} да биде ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Премногу мал: се очекува ${e.origin} да има ${n}${e.minimum.toString()} ${r.unit}`:`Премногу мал: се очекува ${e.origin} да биде ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Неважечка низа: мора да започнува со "${t.prefix}"`:"ends_with"===t.format?`Неважечка низа: мора да завршува со "${t.suffix}"`:"includes"===t.format?`Неважечка низа: мора да вклучува "${t.includes}"`:"regex"===t.format?`Неважечка низа: мора да одгоара на патернот ${t.pattern}`:`Invalid ${n[t.format]??e.format}`}case"not_multiple_of":return`Грешен број: мора да биде делив со ${e.divisor}`;case"unrecognized_keys":return`${e.keys.length>1?"Непрепознаени клучеви":"Непрепознаен клуч"}: ${Wt(e.keys,", ")}`;case"invalid_key":return`Грешен клуч во ${e.origin}`;case"invalid_union":default:return"Грешен внес";case"invalid_element":return`Грешна вредност во ${e.origin}`}}};const is=()=>{const e={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function t(t){return e[t]??null}const n={regex:"input",email:"alamat e-mel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tarikh masa ISO",date:"tarikh ISO",time:"masa ISO",duration:"tempoh ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"julat IPv4",cidrv6:"julat IPv6",base64:"string dikodkan base64",base64url:"string dikodkan base64url",json_string:"string JSON",e164:"nombor E.164",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Input tidak sah: dijangka ${e.expected}, diterima ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"nombor";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Input tidak sah: dijangka ${mn(e.values[0])}`:`Pilihan tidak sah: dijangka salah satu daripada ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Terlalu besar: dijangka ${e.origin??"nilai"} ${r.verb} ${n}${e.maximum.toString()} ${r.unit??"elemen"}`:`Terlalu besar: dijangka ${e.origin??"nilai"} adalah ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Terlalu kecil: dijangka ${e.origin} ${r.verb} ${n}${e.minimum.toString()} ${r.unit}`:`Terlalu kecil: dijangka ${e.origin} adalah ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`String tidak sah: mesti bermula dengan "${t.prefix}"`:"ends_with"===t.format?`String tidak sah: mesti berakhir dengan "${t.suffix}"`:"includes"===t.format?`String tidak sah: mesti mengandungi "${t.includes}"`:"regex"===t.format?`String tidak sah: mesti sepadan dengan corak ${t.pattern}`:`${n[t.format]??e.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${e.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${Wt(e.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${e.origin}`;case"invalid_union":default:return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${e.origin}`}}};const os=()=>{const e={string:{unit:"tekens"},file:{unit:"bytes"},array:{unit:"elementen"},set:{unit:"elementen"}};function t(t){return e[t]??null}const n={regex:"invoer",email:"emailadres",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum en tijd",date:"ISO datum",time:"ISO tijd",duration:"ISO duur",ipv4:"IPv4-adres",ipv6:"IPv6-adres",cidrv4:"IPv4-bereik",cidrv6:"IPv6-bereik",base64:"base64-gecodeerde tekst",base64url:"base64 URL-gecodeerde tekst",json_string:"JSON string",e164:"E.164-nummer",jwt:"JWT",template_literal:"invoer"};return e=>{switch(e.code){case"invalid_type":return`Ongeldige invoer: verwacht ${e.expected}, ontving ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"getal";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Ongeldige invoer: verwacht ${mn(e.values[0])}`:`Ongeldige optie: verwacht één van ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Te lang: verwacht dat ${e.origin??"waarde"} ${n}${e.maximum.toString()} ${r.unit??"elementen"} bevat`:`Te lang: verwacht dat ${e.origin??"waarde"} ${n}${e.maximum.toString()} is`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Te kort: verwacht dat ${e.origin} ${n}${e.minimum.toString()} ${r.unit} bevat`:`Te kort: verwacht dat ${e.origin} ${n}${e.minimum.toString()} is`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Ongeldige tekst: moet met "${t.prefix}" beginnen`:"ends_with"===t.format?`Ongeldige tekst: moet op "${t.suffix}" eindigen`:"includes"===t.format?`Ongeldige tekst: moet "${t.includes}" bevatten`:"regex"===t.format?`Ongeldige tekst: moet overeenkomen met patroon ${t.pattern}`:`Ongeldig: ${n[t.format]??e.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${e.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${e.keys.length>1?"s":""}: ${Wt(e.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${e.origin}`;case"invalid_union":default:return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${e.origin}`}}};const ss=()=>{const e={string:{unit:"tegn",verb:"å ha"},file:{unit:"bytes",verb:"å ha"},array:{unit:"elementer",verb:"å inneholde"},set:{unit:"elementer",verb:"å inneholde"}};function t(t){return e[t]??null}const n={regex:"input",email:"e-postadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varighet",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkodet streng",base64url:"base64url-enkodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Ugyldig input: forventet ${e.expected}, fikk ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"tall";case"object":if(Array.isArray(e))return"liste";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Ugyldig verdi: forventet ${mn(e.values[0])}`:`Ugyldig valg: forventet en av ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`For stor(t): forventet ${e.origin??"value"} til å ha ${n}${e.maximum.toString()} ${r.unit??"elementer"}`:`For stor(t): forventet ${e.origin??"value"} til å ha ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`For lite(n): forventet ${e.origin} til å ha ${n}${e.minimum.toString()} ${r.unit}`:`For lite(n): forventet ${e.origin} til å ha ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Ugyldig streng: må starte med "${t.prefix}"`:"ends_with"===t.format?`Ugyldig streng: må ende med "${t.suffix}"`:"includes"===t.format?`Ugyldig streng: må inneholde "${t.includes}"`:"regex"===t.format?`Ugyldig streng: må matche mønsteret ${t.pattern}`:`Ugyldig ${n[t.format]??e.format}`}case"not_multiple_of":return`Ugyldig tall: må være et multiplum av ${e.divisor}`;case"unrecognized_keys":return`${e.keys.length>1?"Ukjente nøkler":"Ukjent nøkkel"}: ${Wt(e.keys,", ")}`;case"invalid_key":return`Ugyldig nøkkel i ${e.origin}`;case"invalid_union":default:return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${e.origin}`}}};const as=()=>{const e={string:{unit:"harf",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"unsur",verb:"olmalıdır"},set:{unit:"unsur",verb:"olmalıdır"}};function t(t){return e[t]??null}const n={regex:"giren",email:"epostagâh",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO hengâmı",date:"ISO tarihi",time:"ISO zamanı",duration:"ISO müddeti",ipv4:"IPv4 nişânı",ipv6:"IPv6 nişânı",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-şifreli metin",base64url:"base64url-şifreli metin",json_string:"JSON metin",e164:"E.164 sayısı",jwt:"JWT",template_literal:"giren"};return e=>{switch(e.code){case"invalid_type":return`Fâsit giren: umulan ${e.expected}, alınan ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"numara";case"object":if(Array.isArray(e))return"saf";if(null===e)return"gayb";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Fâsit giren: umulan ${mn(e.values[0])}`:`Fâsit tercih: mûteberler ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Fazla büyük: ${e.origin??"value"}, ${n}${e.maximum.toString()} ${r.unit??"elements"} sahip olmalıydı.`:`Fazla büyük: ${e.origin??"value"}, ${n}${e.maximum.toString()} olmalıydı.`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Fazla küçük: ${e.origin}, ${n}${e.minimum.toString()} ${r.unit} sahip olmalıydı.`:`Fazla küçük: ${e.origin}, ${n}${e.minimum.toString()} olmalıydı.`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Fâsit metin: "${t.prefix}" ile başlamalı.`:"ends_with"===t.format?`Fâsit metin: "${t.suffix}" ile bitmeli.`:"includes"===t.format?`Fâsit metin: "${t.includes}" ihtivâ etmeli.`:"regex"===t.format?`Fâsit metin: ${t.pattern} nakşına uymalı.`:`Fâsit ${n[t.format]??e.format}`}case"not_multiple_of":return`Fâsit sayı: ${e.divisor} katı olmalıydı.`;case"unrecognized_keys":return`Tanınmayan anahtar ${e.keys.length>1?"s":""}: ${Wt(e.keys,", ")}`;case"invalid_key":return`${e.origin} için tanınmayan anahtar var.`;case"invalid_union":return"Giren tanınamadı.";case"invalid_element":return`${e.origin} için tanınmayan kıymet var.`;default:return"Kıymet tanınamadı."}}};const us=()=>{const e={string:{unit:"توکي",verb:"ولري"},file:{unit:"بایټس",verb:"ولري"},array:{unit:"توکي",verb:"ولري"},set:{unit:"توکي",verb:"ولري"}};function t(t){return e[t]??null}const n={regex:"ورودي",email:"بریښنالیک",url:"یو آر ال",emoji:"ایموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"نیټه او وخت",date:"نېټه",time:"وخت",duration:"موده",ipv4:"د IPv4 پته",ipv6:"د IPv6 پته",cidrv4:"د IPv4 ساحه",cidrv6:"د IPv6 ساحه",base64:"base64-encoded متن",base64url:"base64url-encoded متن",json_string:"JSON متن",e164:"د E.164 شمېره",jwt:"JWT",template_literal:"ورودي"};return e=>{switch(e.code){case"invalid_type":return`ناسم ورودي: باید ${e.expected} وای, مګر ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"عدد";case"object":if(Array.isArray(e))return"ارې";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)} ترلاسه شو`;case"invalid_value":return 1===e.values.length?`ناسم ورودي: باید ${mn(e.values[0])} وای`:`ناسم انتخاب: باید یو له ${Wt(e.values,"|")} څخه وای`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`ډیر لوی: ${e.origin??"ارزښت"} باید ${n}${e.maximum.toString()} ${r.unit??"عنصرونه"} ولري`:`ډیر لوی: ${e.origin??"ارزښت"} باید ${n}${e.maximum.toString()} وي`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`ډیر کوچنی: ${e.origin} باید ${n}${e.minimum.toString()} ${r.unit} ولري`:`ډیر کوچنی: ${e.origin} باید ${n}${e.minimum.toString()} وي`}case"invalid_format":{const t=e;return"starts_with"===t.format?`ناسم متن: باید د "${t.prefix}" سره پیل شي`:"ends_with"===t.format?`ناسم متن: باید د "${t.suffix}" سره پای ته ورسيږي`:"includes"===t.format?`ناسم متن: باید "${t.includes}" ولري`:"regex"===t.format?`ناسم متن: باید د ${t.pattern} سره مطابقت ولري`:`${n[t.format]??e.format} ناسم دی`}case"not_multiple_of":return`ناسم عدد: باید د ${e.divisor} مضرب وي`;case"unrecognized_keys":return`ناسم ${e.keys.length>1?"کلیډونه":"کلیډ"}: ${Wt(e.keys,", ")}`;case"invalid_key":return`ناسم کلیډ په ${e.origin} کې`;case"invalid_union":default:return"ناسمه ورودي";case"invalid_element":return`ناسم عنصر په ${e.origin} کې`}}};const ls=()=>{const e={string:{unit:"znaków",verb:"mieć"},file:{unit:"bajtów",verb:"mieć"},array:{unit:"elementów",verb:"mieć"},set:{unit:"elementów",verb:"mieć"}};function t(t){return e[t]??null}const n={regex:"wyrażenie",email:"adres email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i godzina w formacie ISO",date:"data w formacie ISO",time:"godzina w formacie ISO",duration:"czas trwania ISO",ipv4:"adres IPv4",ipv6:"adres IPv6",cidrv4:"zakres IPv4",cidrv6:"zakres IPv6",base64:"ciąg znaków zakodowany w formacie base64",base64url:"ciąg znaków zakodowany w formacie base64url",json_string:"ciąg znaków w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wejście"};return e=>{switch(e.code){case"invalid_type":return`Nieprawidłowe dane wejściowe: oczekiwano ${e.expected}, otrzymano ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"liczba";case"object":if(Array.isArray(e))return"tablica";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Nieprawidłowe dane wejściowe: oczekiwano ${mn(e.values[0])}`:`Nieprawidłowa opcja: oczekiwano jednej z wartości ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Za duża wartość: oczekiwano, że ${e.origin??"wartość"} będzie mieć ${n}${e.maximum.toString()} ${r.unit??"elementów"}`:`Zbyt duż(y/a/e): oczekiwano, że ${e.origin??"wartość"} będzie wynosić ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Za mała wartość: oczekiwano, że ${e.origin??"wartość"} będzie mieć ${n}${e.minimum.toString()} ${r.unit??"elementów"}`:`Zbyt mał(y/a/e): oczekiwano, że ${e.origin??"wartość"} będzie wynosić ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Nieprawidłowy ciąg znaków: musi zaczynać się od "${t.prefix}"`:"ends_with"===t.format?`Nieprawidłowy ciąg znaków: musi kończyć się na "${t.suffix}"`:"includes"===t.format?`Nieprawidłowy ciąg znaków: musi zawierać "${t.includes}"`:"regex"===t.format?`Nieprawidłowy ciąg znaków: musi odpowiadać wzorcowi ${t.pattern}`:`Nieprawidłow(y/a/e) ${n[t.format]??e.format}`}case"not_multiple_of":return`Nieprawidłowa liczba: musi być wielokrotnością ${e.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${e.keys.length>1?"s":""}: ${Wt(e.keys,", ")}`;case"invalid_key":return`Nieprawidłowy klucz w ${e.origin}`;case"invalid_union":default:return"Nieprawidłowe dane wejściowe";case"invalid_element":return`Nieprawidłowa wartość w ${e.origin}`}}};const cs=()=>{const e={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function t(t){return e[t]??null}const n={regex:"padrão",email:"endereço de e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e hora ISO",date:"data ISO",time:"hora ISO",duration:"duração ISO",ipv4:"endereço IPv4",ipv6:"endereço IPv6",cidrv4:"faixa de IPv4",cidrv6:"faixa de IPv6",base64:"texto codificado em base64",base64url:"URL codificada em base64",json_string:"texto JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"};return e=>{switch(e.code){case"invalid_type":return`Tipo inválido: esperado ${e.expected}, recebido ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"número";case"object":if(Array.isArray(e))return"array";if(null===e)return"nulo";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Entrada inválida: esperado ${mn(e.values[0])}`:`Opção inválida: esperada uma das ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Muito grande: esperado que ${e.origin??"valor"} tivesse ${n}${e.maximum.toString()} ${r.unit??"elementos"}`:`Muito grande: esperado que ${e.origin??"valor"} fosse ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Muito pequeno: esperado que ${e.origin} tivesse ${n}${e.minimum.toString()} ${r.unit}`:`Muito pequeno: esperado que ${e.origin} fosse ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Texto inválido: deve começar com "${t.prefix}"`:"ends_with"===t.format?`Texto inválido: deve terminar com "${t.suffix}"`:"includes"===t.format?`Texto inválido: deve incluir "${t.includes}"`:"regex"===t.format?`Texto inválido: deve corresponder ao padrão ${t.pattern}`:`${n[t.format]??e.format} inválido`}case"not_multiple_of":return`Número inválido: deve ser múltiplo de ${e.divisor}`;case"unrecognized_keys":return`Chave${e.keys.length>1?"s":""} desconhecida${e.keys.length>1?"s":""}: ${Wt(e.keys,", ")}`;case"invalid_key":return`Chave inválida em ${e.origin}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido em ${e.origin}`;default:return"Campo inválido"}}};function ds(e,t,n,r){const i=Math.abs(e),o=i%10,s=i%100;return s>=11&&s<=19?r:1===o?t:o>=2&&o<=4?n:r}const ps=()=>{const e={string:{unit:{one:"символ",few:"символа",many:"символов"},verb:"иметь"},file:{unit:{one:"байт",few:"байта",many:"байт"},verb:"иметь"},array:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"},set:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"}};function t(t){return e[t]??null}const n={regex:"ввод",email:"email адрес",url:"URL",emoji:"эмодзи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата и время",date:"ISO дата",time:"ISO время",duration:"ISO длительность",ipv4:"IPv4 адрес",ipv6:"IPv6 адрес",cidrv4:"IPv4 диапазон",cidrv6:"IPv6 диапазон",base64:"строка в формате base64",base64url:"строка в формате base64url",json_string:"JSON строка",e164:"номер E.164",jwt:"JWT",template_literal:"ввод"};return e=>{switch(e.code){case"invalid_type":return`Неверный ввод: ожидалось ${e.expected}, получено ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"число";case"object":if(Array.isArray(e))return"массив";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Неверный ввод: ожидалось ${mn(e.values[0])}`:`Неверный вариант: ожидалось одно из ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);if(r){const t=ds(Number(e.maximum),r.unit.one,r.unit.few,r.unit.many);return`Слишком большое значение: ожидалось, что ${e.origin??"значение"} будет иметь ${n}${e.maximum.toString()} ${t}`}return`Слишком большое значение: ожидалось, что ${e.origin??"значение"} будет ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);if(r){const t=ds(Number(e.minimum),r.unit.one,r.unit.few,r.unit.many);return`Слишком маленькое значение: ожидалось, что ${e.origin} будет иметь ${n}${e.minimum.toString()} ${t}`}return`Слишком маленькое значение: ожидалось, что ${e.origin} будет ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Неверная строка: должна начинаться с "${t.prefix}"`:"ends_with"===t.format?`Неверная строка: должна заканчиваться на "${t.suffix}"`:"includes"===t.format?`Неверная строка: должна содержать "${t.includes}"`:"regex"===t.format?`Неверная строка: должна соответствовать шаблону ${t.pattern}`:`Неверный ${n[t.format]??e.format}`}case"not_multiple_of":return`Неверное число: должно быть кратным ${e.divisor}`;case"unrecognized_keys":return`Нераспознанн${e.keys.length>1?"ые":"ый"} ключ${e.keys.length>1?"и":""}: ${Wt(e.keys,", ")}`;case"invalid_key":return`Неверный ключ в ${e.origin}`;case"invalid_union":default:return"Неверные входные данные";case"invalid_element":return`Неверное значение в ${e.origin}`}}};const ms=()=>{const e={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function t(t){return e[t]??null}const n={regex:"vnos",email:"e-poštni naslov",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum in čas",date:"ISO datum",time:"ISO čas",duration:"ISO trajanje",ipv4:"IPv4 naslov",ipv6:"IPv6 naslov",cidrv4:"obseg IPv4",cidrv6:"obseg IPv6",base64:"base64 kodiran niz",base64url:"base64url kodiran niz",json_string:"JSON niz",e164:"E.164 številka",jwt:"JWT",template_literal:"vnos"};return e=>{switch(e.code){case"invalid_type":return`Neveljaven vnos: pričakovano ${e.expected}, prejeto ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"število";case"object":if(Array.isArray(e))return"tabela";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Neveljaven vnos: pričakovano ${mn(e.values[0])}`:`Neveljavna možnost: pričakovano eno izmed ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Preveliko: pričakovano, da bo ${e.origin??"vrednost"} imelo ${n}${e.maximum.toString()} ${r.unit??"elementov"}`:`Preveliko: pričakovano, da bo ${e.origin??"vrednost"} ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Premajhno: pričakovano, da bo ${e.origin} imelo ${n}${e.minimum.toString()} ${r.unit}`:`Premajhno: pričakovano, da bo ${e.origin} ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Neveljaven niz: mora se začeti z "${t.prefix}"`:"ends_with"===t.format?`Neveljaven niz: mora se končati z "${t.suffix}"`:"includes"===t.format?`Neveljaven niz: mora vsebovati "${t.includes}"`:"regex"===t.format?`Neveljaven niz: mora ustrezati vzorcu ${t.pattern}`:`Neveljaven ${n[t.format]??e.format}`}case"not_multiple_of":return`Neveljavno število: mora biti večkratnik ${e.divisor}`;case"unrecognized_keys":return`Neprepoznan${e.keys.length>1?"i ključi":" ključ"}: ${Wt(e.keys,", ")}`;case"invalid_key":return`Neveljaven ključ v ${e.origin}`;case"invalid_union":default:return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${e.origin}`}}};const hs=()=>{const e={string:{unit:"tecken",verb:"att ha"},file:{unit:"bytes",verb:"att ha"},array:{unit:"objekt",verb:"att innehålla"},set:{unit:"objekt",verb:"att innehålla"}};function t(t){return e[t]??null}const n={regex:"reguljärt uttryck",email:"e-postadress",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datum och tid",date:"ISO-datum",time:"ISO-tid",duration:"ISO-varaktighet",ipv4:"IPv4-intervall",ipv6:"IPv6-intervall",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodad sträng",base64url:"base64url-kodad sträng",json_string:"JSON-sträng",e164:"E.164-nummer",jwt:"JWT",template_literal:"mall-literal"};return e=>{switch(e.code){case"invalid_type":return`Ogiltig inmatning: förväntat ${e.expected}, fick ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"antal";case"object":if(Array.isArray(e))return"lista";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Ogiltig inmatning: förväntat ${mn(e.values[0])}`:`Ogiltigt val: förväntade en av ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`För stor(t): förväntade ${e.origin??"värdet"} att ha ${n}${e.maximum.toString()} ${r.unit??"element"}`:`För stor(t): förväntat ${e.origin??"värdet"} att ha ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`För lite(t): förväntade ${e.origin??"värdet"} att ha ${n}${e.minimum.toString()} ${r.unit}`:`För lite(t): förväntade ${e.origin??"värdet"} att ha ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Ogiltig sträng: måste börja med "${t.prefix}"`:"ends_with"===t.format?`Ogiltig sträng: måste sluta med "${t.suffix}"`:"includes"===t.format?`Ogiltig sträng: måste innehålla "${t.includes}"`:"regex"===t.format?`Ogiltig sträng: måste matcha mönstret "${t.pattern}"`:`Ogiltig(t) ${n[t.format]??e.format}`}case"not_multiple_of":return`Ogiltigt tal: måste vara en multipel av ${e.divisor}`;case"unrecognized_keys":return`${e.keys.length>1?"Okända nycklar":"Okänd nyckel"}: ${Wt(e.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${e.origin??"värdet"}`;case"invalid_union":default:return"Ogiltig input";case"invalid_element":return`Ogiltigt värde i ${e.origin??"värdet"}`}}};const gs=()=>{const e={string:{unit:"எழுத்துக்கள்",verb:"கொண்டிருக்க வேண்டும்"},file:{unit:"பைட்டுகள்",verb:"கொண்டிருக்க வேண்டும்"},array:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"},set:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"}};function t(t){return e[t]??null}const n={regex:"உள்ளீடு",email:"மின்னஞ்சல் முகவரி",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO தேதி நேரம்",date:"ISO தேதி",time:"ISO நேரம்",duration:"ISO கால அளவு",ipv4:"IPv4 முகவரி",ipv6:"IPv6 முகவரி",cidrv4:"IPv4 வரம்பு",cidrv6:"IPv6 வரம்பு",base64:"base64-encoded சரம்",base64url:"base64url-encoded சரம்",json_string:"JSON சரம்",e164:"E.164 எண்",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${e.expected}, பெறப்பட்டது ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"எண் அல்லாதது":"எண்";case"object":if(Array.isArray(e))return"அணி";if(null===e)return"வெறுமை";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${mn(e.values[0])}`:`தவறான விருப்பம்: எதிர்பார்க்கப்பட்டது ${Wt(e.values,"|")} இல் ஒன்று`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${e.origin??"மதிப்பு"} ${n}${e.maximum.toString()} ${r.unit??"உறுப்புகள்"} ஆக இருக்க வேண்டும்`:`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${e.origin??"மதிப்பு"} ${n}${e.maximum.toString()} ஆக இருக்க வேண்டும்`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${e.origin} ${n}${e.minimum.toString()} ${r.unit} ஆக இருக்க வேண்டும்`:`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${e.origin} ${n}${e.minimum.toString()} ஆக இருக்க வேண்டும்`}case"invalid_format":{const t=e;return"starts_with"===t.format?`தவறான சரம்: "${t.prefix}" இல் தொடங்க வேண்டும்`:"ends_with"===t.format?`தவறான சரம்: "${t.suffix}" இல் முடிவடைய வேண்டும்`:"includes"===t.format?`தவறான சரம்: "${t.includes}" ஐ உள்ளடக்க வேண்டும்`:"regex"===t.format?`தவறான சரம்: ${t.pattern} முறைபாட்டுடன் பொருந்த வேண்டும்`:`தவறான ${n[t.format]??e.format}`}case"not_multiple_of":return`தவறான எண்: ${e.divisor} இன் பலமாக இருக்க வேண்டும்`;case"unrecognized_keys":return`அடையாளம் தெரியாத விசை${e.keys.length>1?"கள்":""}: ${Wt(e.keys,", ")}`;case"invalid_key":return`${e.origin} இல் தவறான விசை`;case"invalid_union":default:return"தவறான உள்ளீடு";case"invalid_element":return`${e.origin} இல் தவறான மதிப்பு`}}};const fs=()=>{const e={string:{unit:"ตัวอักษร",verb:"ควรมี"},file:{unit:"ไบต์",verb:"ควรมี"},array:{unit:"รายการ",verb:"ควรมี"},set:{unit:"รายการ",verb:"ควรมี"}};function t(t){return e[t]??null}const n={regex:"ข้อมูลที่ป้อน",email:"ที่อยู่อีเมล",url:"URL",emoji:"อิโมจิ",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"วันที่เวลาแบบ ISO",date:"วันที่แบบ ISO",time:"เวลาแบบ ISO",duration:"ช่วงเวลาแบบ ISO",ipv4:"ที่อยู่ IPv4",ipv6:"ที่อยู่ IPv6",cidrv4:"ช่วง IP แบบ IPv4",cidrv6:"ช่วง IP แบบ IPv6",base64:"ข้อความแบบ Base64",base64url:"ข้อความแบบ Base64 สำหรับ URL",json_string:"ข้อความแบบ JSON",e164:"เบอร์โทรศัพท์ระหว่างประเทศ (E.164)",jwt:"โทเคน JWT",template_literal:"ข้อมูลที่ป้อน"};return e=>{switch(e.code){case"invalid_type":return`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น ${e.expected} แต่ได้รับ ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"ไม่ใช่ตัวเลข (NaN)":"ตัวเลข";case"object":if(Array.isArray(e))return"อาร์เรย์ (Array)";if(null===e)return"ไม่มีค่า (null)";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`ค่าไม่ถูกต้อง: ควรเป็น ${mn(e.values[0])}`:`ตัวเลือกไม่ถูกต้อง: ควรเป็นหนึ่งใน ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"ไม่เกิน":"น้อยกว่า",r=t(e.origin);return r?`เกินกำหนด: ${e.origin??"ค่า"} ควรมี${n} ${e.maximum.toString()} ${r.unit??"รายการ"}`:`เกินกำหนด: ${e.origin??"ค่า"} ควรมี${n} ${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?"อย่างน้อย":"มากกว่า",r=t(e.origin);return r?`น้อยกว่ากำหนด: ${e.origin} ควรมี${n} ${e.minimum.toString()} ${r.unit}`:`น้อยกว่ากำหนด: ${e.origin} ควรมี${n} ${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`รูปแบบไม่ถูกต้อง: ข้อความต้องขึ้นต้นด้วย "${t.prefix}"`:"ends_with"===t.format?`รูปแบบไม่ถูกต้อง: ข้อความต้องลงท้ายด้วย "${t.suffix}"`:"includes"===t.format?`รูปแบบไม่ถูกต้อง: ข้อความต้องมี "${t.includes}" อยู่ในข้อความ`:"regex"===t.format?`รูปแบบไม่ถูกต้อง: ต้องตรงกับรูปแบบที่กำหนด ${t.pattern}`:`รูปแบบไม่ถูกต้อง: ${n[t.format]??e.format}`}case"not_multiple_of":return`ตัวเลขไม่ถูกต้อง: ต้องเป็นจำนวนที่หารด้วย ${e.divisor} ได้ลงตัว`;case"unrecognized_keys":return`พบคีย์ที่ไม่รู้จัก: ${Wt(e.keys,", ")}`;case"invalid_key":return`คีย์ไม่ถูกต้องใน ${e.origin}`;case"invalid_union":return"ข้อมูลไม่ถูกต้อง: ไม่ตรงกับรูปแบบยูเนียนที่กำหนดไว้";case"invalid_element":return`ข้อมูลไม่ถูกต้องใน ${e.origin}`;default:return"ข้อมูลไม่ถูกต้อง"}}};const vs=()=>{const e={string:{unit:"karakter",verb:"olmalı"},file:{unit:"bayt",verb:"olmalı"},array:{unit:"öğe",verb:"olmalı"},set:{unit:"öğe",verb:"olmalı"}};function t(t){return e[t]??null}const n={regex:"girdi",email:"e-posta adresi",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO tarih ve saat",date:"ISO tarih",time:"ISO saat",duration:"ISO süre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aralığı",cidrv6:"IPv6 aralığı",base64:"base64 ile şifrelenmiş metin",base64url:"base64url ile şifrelenmiş metin",json_string:"JSON dizesi",e164:"E.164 sayısı",jwt:"JWT",template_literal:"Şablon dizesi"};return e=>{switch(e.code){case"invalid_type":return`Geçersiz değer: beklenen ${e.expected}, alınan ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Geçersiz değer: beklenen ${mn(e.values[0])}`:`Geçersiz seçenek: aşağıdakilerden biri olmalı: ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Çok büyük: beklenen ${e.origin??"değer"} ${n}${e.maximum.toString()} ${r.unit??"öğe"}`:`Çok büyük: beklenen ${e.origin??"değer"} ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Çok küçük: beklenen ${e.origin} ${n}${e.minimum.toString()} ${r.unit}`:`Çok küçük: beklenen ${e.origin} ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Geçersiz metin: "${t.prefix}" ile başlamalı`:"ends_with"===t.format?`Geçersiz metin: "${t.suffix}" ile bitmeli`:"includes"===t.format?`Geçersiz metin: "${t.includes}" içermeli`:"regex"===t.format?`Geçersiz metin: ${t.pattern} desenine uymalı`:`Geçersiz ${n[t.format]??e.format}`}case"not_multiple_of":return`Geçersiz sayı: ${e.divisor} ile tam bölünebilmeli`;case"unrecognized_keys":return`Tanınmayan anahtar${e.keys.length>1?"lar":""}: ${Wt(e.keys,", ")}`;case"invalid_key":return`${e.origin} içinde geçersiz anahtar`;case"invalid_union":default:return"Geçersiz değer";case"invalid_element":return`${e.origin} içinde geçersiz değer`}}};const ys=()=>{const e={string:{unit:"символів",verb:"матиме"},file:{unit:"байтів",verb:"матиме"},array:{unit:"елементів",verb:"матиме"},set:{unit:"елементів",verb:"матиме"}};function t(t){return e[t]??null}const n={regex:"вхідні дані",email:"адреса електронної пошти",url:"URL",emoji:"емодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"дата та час ISO",date:"дата ISO",time:"час ISO",duration:"тривалість ISO",ipv4:"адреса IPv4",ipv6:"адреса IPv6",cidrv4:"діапазон IPv4",cidrv6:"діапазон IPv6",base64:"рядок у кодуванні base64",base64url:"рядок у кодуванні base64url",json_string:"рядок JSON",e164:"номер E.164",jwt:"JWT",template_literal:"вхідні дані"};return e=>{switch(e.code){case"invalid_type":return`Неправильні вхідні дані: очікується ${e.expected}, отримано ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"число";case"object":if(Array.isArray(e))return"масив";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Неправильні вхідні дані: очікується ${mn(e.values[0])}`:`Неправильна опція: очікується одне з ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Занадто велике: очікується, що ${e.origin??"значення"} ${r.verb} ${n}${e.maximum.toString()} ${r.unit??"елементів"}`:`Занадто велике: очікується, що ${e.origin??"значення"} буде ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Занадто мале: очікується, що ${e.origin} ${r.verb} ${n}${e.minimum.toString()} ${r.unit}`:`Занадто мале: очікується, що ${e.origin} буде ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Неправильний рядок: повинен починатися з "${t.prefix}"`:"ends_with"===t.format?`Неправильний рядок: повинен закінчуватися на "${t.suffix}"`:"includes"===t.format?`Неправильний рядок: повинен містити "${t.includes}"`:"regex"===t.format?`Неправильний рядок: повинен відповідати шаблону ${t.pattern}`:`Неправильний ${n[t.format]??e.format}`}case"not_multiple_of":return`Неправильне число: повинно бути кратним ${e.divisor}`;case"unrecognized_keys":return`Нерозпізнаний ключ${e.keys.length>1?"і":""}: ${Wt(e.keys,", ")}`;case"invalid_key":return`Неправильний ключ у ${e.origin}`;case"invalid_union":default:return"Неправильні вхідні дані";case"invalid_element":return`Неправильне значення у ${e.origin}`}}};const _s=()=>{const e={string:{unit:"حروف",verb:"ہونا"},file:{unit:"بائٹس",verb:"ہونا"},array:{unit:"آئٹمز",verb:"ہونا"},set:{unit:"آئٹمز",verb:"ہونا"}};function t(t){return e[t]??null}const n={regex:"ان پٹ",email:"ای میل ایڈریس",url:"یو آر ایل",emoji:"ایموجی",uuid:"یو یو آئی ڈی",uuidv4:"یو یو آئی ڈی وی 4",uuidv6:"یو یو آئی ڈی وی 6",nanoid:"نینو آئی ڈی",guid:"جی یو آئی ڈی",cuid:"سی یو آئی ڈی",cuid2:"سی یو آئی ڈی 2",ulid:"یو ایل آئی ڈی",xid:"ایکس آئی ڈی",ksuid:"کے ایس یو آئی ڈی",datetime:"آئی ایس او ڈیٹ ٹائم",date:"آئی ایس او تاریخ",time:"آئی ایس او وقت",duration:"آئی ایس او مدت",ipv4:"آئی پی وی 4 ایڈریس",ipv6:"آئی پی وی 6 ایڈریس",cidrv4:"آئی پی وی 4 رینج",cidrv6:"آئی پی وی 6 رینج",base64:"بیس 64 ان کوڈڈ سٹرنگ",base64url:"بیس 64 یو آر ایل ان کوڈڈ سٹرنگ",json_string:"جے ایس او این سٹرنگ",e164:"ای 164 نمبر",jwt:"جے ڈبلیو ٹی",template_literal:"ان پٹ"};return e=>{switch(e.code){case"invalid_type":return`غلط ان پٹ: ${e.expected} متوقع تھا، ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"نمبر";case"object":if(Array.isArray(e))return"آرے";if(null===e)return"نل";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)} موصول ہوا`;case"invalid_value":return 1===e.values.length?`غلط ان پٹ: ${mn(e.values[0])} متوقع تھا`:`غلط آپشن: ${Wt(e.values,"|")} میں سے ایک متوقع تھا`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`بہت بڑا: ${e.origin??"ویلیو"} کے ${n}${e.maximum.toString()} ${r.unit??"عناصر"} ہونے متوقع تھے`:`بہت بڑا: ${e.origin??"ویلیو"} کا ${n}${e.maximum.toString()} ہونا متوقع تھا`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`بہت چھوٹا: ${e.origin} کے ${n}${e.minimum.toString()} ${r.unit} ہونے متوقع تھے`:`بہت چھوٹا: ${e.origin} کا ${n}${e.minimum.toString()} ہونا متوقع تھا`}case"invalid_format":{const t=e;return"starts_with"===t.format?`غلط سٹرنگ: "${t.prefix}" سے شروع ہونا چاہیے`:"ends_with"===t.format?`غلط سٹرنگ: "${t.suffix}" پر ختم ہونا چاہیے`:"includes"===t.format?`غلط سٹرنگ: "${t.includes}" شامل ہونا چاہیے`:"regex"===t.format?`غلط سٹرنگ: پیٹرن ${t.pattern} سے میچ ہونا چاہیے`:`غلط ${n[t.format]??e.format}`}case"not_multiple_of":return`غلط نمبر: ${e.divisor} کا مضاعف ہونا چاہیے`;case"unrecognized_keys":return`غیر تسلیم شدہ کی${e.keys.length>1?"ز":""}: ${Wt(e.keys,"، ")}`;case"invalid_key":return`${e.origin} میں غلط کی`;case"invalid_union":default:return"غلط ان پٹ";case"invalid_element":return`${e.origin} میں غلط ویلیو`}}};const bs=()=>{const e={string:{unit:"ký tự",verb:"có"},file:{unit:"byte",verb:"có"},array:{unit:"phần tử",verb:"có"},set:{unit:"phần tử",verb:"có"}};function t(t){return e[t]??null}const n={regex:"đầu vào",email:"địa chỉ email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ngày giờ ISO",date:"ngày ISO",time:"giờ ISO",duration:"khoảng thời gian ISO",ipv4:"địa chỉ IPv4",ipv6:"địa chỉ IPv6",cidrv4:"dải IPv4",cidrv6:"dải IPv6",base64:"chuỗi mã hóa base64",base64url:"chuỗi mã hóa base64url",json_string:"chuỗi JSON",e164:"số E.164",jwt:"JWT",template_literal:"đầu vào"};return e=>{switch(e.code){case"invalid_type":return`Đầu vào không hợp lệ: mong đợi ${e.expected}, nhận được ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"số";case"object":if(Array.isArray(e))return"mảng";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Đầu vào không hợp lệ: mong đợi ${mn(e.values[0])}`:`Tùy chọn không hợp lệ: mong đợi một trong các giá trị ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Quá lớn: mong đợi ${e.origin??"giá trị"} ${r.verb} ${n}${e.maximum.toString()} ${r.unit??"phần tử"}`:`Quá lớn: mong đợi ${e.origin??"giá trị"} ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Quá nhỏ: mong đợi ${e.origin} ${r.verb} ${n}${e.minimum.toString()} ${r.unit}`:`Quá nhỏ: mong đợi ${e.origin} ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Chuỗi không hợp lệ: phải bắt đầu bằng "${t.prefix}"`:"ends_with"===t.format?`Chuỗi không hợp lệ: phải kết thúc bằng "${t.suffix}"`:"includes"===t.format?`Chuỗi không hợp lệ: phải bao gồm "${t.includes}"`:"regex"===t.format?`Chuỗi không hợp lệ: phải khớp với mẫu ${t.pattern}`:`${n[t.format]??e.format} không hợp lệ`}case"not_multiple_of":return`Số không hợp lệ: phải là bội số của ${e.divisor}`;case"unrecognized_keys":return`Khóa không được nhận dạng: ${Wt(e.keys,", ")}`;case"invalid_key":return`Khóa không hợp lệ trong ${e.origin}`;case"invalid_union":default:return"Đầu vào không hợp lệ";case"invalid_element":return`Giá trị không hợp lệ trong ${e.origin}`}}};const ws=()=>{const e={string:{unit:"字符",verb:"包含"},file:{unit:"字节",verb:"包含"},array:{unit:"项",verb:"包含"},set:{unit:"项",verb:"包含"}};function t(t){return e[t]??null}const n={regex:"输入",email:"电子邮件",url:"URL",emoji:"表情符号",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日期时间",date:"ISO日期",time:"ISO时间",duration:"ISO时长",ipv4:"IPv4地址",ipv6:"IPv6地址",cidrv4:"IPv4网段",cidrv6:"IPv6网段",base64:"base64编码字符串",base64url:"base64url编码字符串",json_string:"JSON字符串",e164:"E.164号码",jwt:"JWT",template_literal:"输入"};return e=>{switch(e.code){case"invalid_type":return`无效输入:期望 ${e.expected},实际接收 ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"非数字(NaN)":"数字";case"object":if(Array.isArray(e))return"数组";if(null===e)return"空值(null)";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`无效输入:期望 ${mn(e.values[0])}`:`无效选项:期望以下之一 ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`数值过大:期望 ${e.origin??"值"} ${n}${e.maximum.toString()} ${r.unit??"个元素"}`:`数值过大:期望 ${e.origin??"值"} ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`数值过小:期望 ${e.origin} ${n}${e.minimum.toString()} ${r.unit}`:`数值过小:期望 ${e.origin} ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`无效字符串:必须以 "${t.prefix}" 开头`:"ends_with"===t.format?`无效字符串:必须以 "${t.suffix}" 结尾`:"includes"===t.format?`无效字符串:必须包含 "${t.includes}"`:"regex"===t.format?`无效字符串:必须满足正则表达式 ${t.pattern}`:`无效${n[t.format]??e.format}`}case"not_multiple_of":return`无效数字:必须是 ${e.divisor} 的倍数`;case"unrecognized_keys":return`出现未知的键(key): ${Wt(e.keys,", ")}`;case"invalid_key":return`${e.origin} 中的键(key)无效`;case"invalid_union":default:return"无效输入";case"invalid_element":return`${e.origin} 中包含无效值(value)`}}};const ks=()=>{const e={string:{unit:"字元",verb:"擁有"},file:{unit:"位元組",verb:"擁有"},array:{unit:"項目",verb:"擁有"},set:{unit:"項目",verb:"擁有"}};function t(t){return e[t]??null}const n={regex:"輸入",email:"郵件地址",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 日期時間",date:"ISO 日期",time:"ISO 時間",duration:"ISO 期間",ipv4:"IPv4 位址",ipv6:"IPv6 位址",cidrv4:"IPv4 範圍",cidrv6:"IPv6 範圍",base64:"base64 編碼字串",base64url:"base64url 編碼字串",json_string:"JSON 字串",e164:"E.164 數值",jwt:"JWT",template_literal:"輸入"};return e=>{switch(e.code){case"invalid_type":return`無效的輸入值:預期為 ${e.expected},但收到 ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`無效的輸入值:預期為 ${mn(e.values[0])}`:`無效的選項:預期為以下其中之一 ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`數值過大:預期 ${e.origin??"值"} 應為 ${n}${e.maximum.toString()} ${r.unit??"個元素"}`:`數值過大:預期 ${e.origin??"值"} 應為 ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`數值過小:預期 ${e.origin} 應為 ${n}${e.minimum.toString()} ${r.unit}`:`數值過小:預期 ${e.origin} 應為 ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`無效的字串:必須以 "${t.prefix}" 開頭`:"ends_with"===t.format?`無效的字串:必須以 "${t.suffix}" 結尾`:"includes"===t.format?`無效的字串:必須包含 "${t.includes}"`:"regex"===t.format?`無效的字串:必須符合格式 ${t.pattern}`:`無效的 ${n[t.format]??e.format}`}case"not_multiple_of":return`無效的數字:必須為 ${e.divisor} 的倍數`;case"unrecognized_keys":return`無法識別的鍵值${e.keys.length>1?"們":""}:${Wt(e.keys,"、")}`;case"invalid_key":return`${e.origin} 中有無效的鍵值`;case"invalid_union":default:return"無效的輸入值";case"invalid_element":return`${e.origin} 中有無效的值`}}};const xs=()=>{const e={string:{unit:"àmi",verb:"ní"},file:{unit:"bytes",verb:"ní"},array:{unit:"nkan",verb:"ní"},set:{unit:"nkan",verb:"ní"}};function t(t){return e[t]??null}const n={regex:"ẹ̀rọ ìbáwọlé",email:"àdírẹ́sì ìmẹ́lì",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"àkókò ISO",date:"ọjọ́ ISO",time:"àkókò ISO",duration:"àkókò tó pé ISO",ipv4:"àdírẹ́sì IPv4",ipv6:"àdírẹ́sì IPv6",cidrv4:"àgbègbè IPv4",cidrv6:"àgbègbè IPv6",base64:"ọ̀rọ̀ tí a kọ́ ní base64",base64url:"ọ̀rọ̀ base64url",json_string:"ọ̀rọ̀ JSON",e164:"nọ́mbà E.164",jwt:"JWT",template_literal:"ẹ̀rọ ìbáwọlé"};return e=>{switch(e.code){case"invalid_type":return`Ìbáwọlé aṣìṣe: a ní láti fi ${e.expected}, àmọ̀ a rí ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"nọ́mbà";case"object":if(Array.isArray(e))return"akopọ";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Ìbáwọlé aṣìṣe: a ní láti fi ${mn(e.values[0])}`:`Àṣàyàn aṣìṣe: yan ọ̀kan lára ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Tó pọ̀ jù: a ní láti jẹ́ pé ${e.origin??"iye"} ${r.verb} ${n}${e.maximum} ${r.unit}`:`Tó pọ̀ jù: a ní láti jẹ́ ${n}${e.maximum}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Kéré ju: a ní láti jẹ́ pé ${e.origin} ${r.verb} ${n}${e.minimum} ${r.unit}`:`Kéré ju: a ní láti jẹ́ ${n}${e.minimum}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bẹ̀rẹ̀ pẹ̀lú "${t.prefix}"`:"ends_with"===t.format?`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ parí pẹ̀lú "${t.suffix}"`:"includes"===t.format?`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ ní "${t.includes}"`:"regex"===t.format?`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bá àpẹẹrẹ mu ${t.pattern}`:`Aṣìṣe: ${n[t.format]??e.format}`}case"not_multiple_of":return`Nọ́mbà aṣìṣe: gbọ́dọ̀ jẹ́ èyà pípín ti ${e.divisor}`;case"unrecognized_keys":return`Bọtìnì àìmọ̀: ${Wt(e.keys,", ")}`;case"invalid_key":return`Bọtìnì aṣìṣe nínú ${e.origin}`;case"invalid_union":default:return"Ìbáwọlé aṣìṣe";case"invalid_element":return`Iye aṣìṣe nínú ${e.origin}`}}};const Is=Object.freeze(Object.defineProperty({__proto__:null,ar:function(){return{localeError:Po()}},az:function(){return{localeError:Ro()}},be:function(){return{localeError:jo()}},ca:function(){return{localeError:zo()}},cs:function(){return{localeError:Do()}},da:function(){return{localeError:Mo()}},de:function(){return{localeError:Lo()}},en:qo,eo:function(){return{localeError:Fo()}},es:function(){return{localeError:Wo()}},fa:function(){return{localeError:Jo()}},fi:function(){return{localeError:Bo()}},fr:function(){return{localeError:Ho()}},frCA:function(){return{localeError:Vo()}},he:function(){return{localeError:Ko()}},hu:function(){return{localeError:Go()}},id:function(){return{localeError:Yo()}},is:function(){return{localeError:Xo()}},it:function(){return{localeError:Qo()}},ja:function(){return{localeError:es()}},kh:function(){return{localeError:ts()}},ko:function(){return{localeError:ns()}},mk:function(){return{localeError:rs()}},ms:function(){return{localeError:is()}},nl:function(){return{localeError:os()}},no:function(){return{localeError:ss()}},ota:function(){return{localeError:as()}},pl:function(){return{localeError:ls()}},ps:function(){return{localeError:us()}},pt:function(){return{localeError:cs()}},ru:function(){return{localeError:ps()}},sl:function(){return{localeError:ms()}},sv:function(){return{localeError:hs()}},ta:function(){return{localeError:gs()}},th:function(){return{localeError:fs()}},tr:function(){return{localeError:vs()}},ua:function(){return{localeError:ys()}},ur:function(){return{localeError:_s()}},vi:function(){return{localeError:bs()}},yo:function(){return{localeError:xs()}},zhCN:function(){return{localeError:ws()}},zhTW:function(){return{localeError:ks()}}},Symbol.toStringTag,{value:"Module"})),Ss=Symbol("ZodOutput"),$s=Symbol("ZodInput");class Es{constructor(){this._map=new Map,this._idmap=new Map}add(e,...t){const n=t[0];if(this._map.set(e,n),n&&"object"==typeof n&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const n={...this.get(t)??{}};delete n.id;const r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function Ts(){return new Es}const Os=Ts();function Ns(e,t){return new e({type:"string",...pn(t)})}function Cs(e,t){return new e({type:"string",coerce:!0,...pn(t)})}function As(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...pn(t)})}function Ps(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...pn(t)})}function Rs(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...pn(t)})}function Us(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...pn(t)})}function js(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...pn(t)})}function zs(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...pn(t)})}function Ds(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...pn(t)})}function Ms(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...pn(t)})}function Ls(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...pn(t)})}function Zs(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...pn(t)})}function qs(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...pn(t)})}function Fs(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...pn(t)})}function Ws(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...pn(t)})}function Js(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...pn(t)})}function Bs(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...pn(t)})}function Hs(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...pn(t)})}function Vs(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...pn(t)})}function Ks(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...pn(t)})}function Gs(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...pn(t)})}function Ys(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...pn(t)})}function Xs(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...pn(t)})}function Qs(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...pn(t)})}const ea={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function ta(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...pn(t)})}function na(e,t){return new e({type:"string",format:"date",check:"string_format",...pn(t)})}function ra(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...pn(t)})}function ia(e,t){return new e({type:"string",format:"duration",check:"string_format",...pn(t)})}function oa(e,t){return new e({type:"number",checks:[],...pn(t)})}function sa(e,t){return new e({type:"number",coerce:!0,checks:[],...pn(t)})}function aa(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...pn(t)})}function ua(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...pn(t)})}function la(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...pn(t)})}function ca(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...pn(t)})}function da(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...pn(t)})}function pa(e,t){return new e({type:"boolean",...pn(t)})}function ma(e,t){return new e({type:"boolean",coerce:!0,...pn(t)})}function ha(e,t){return new e({type:"bigint",...pn(t)})}function ga(e,t){return new e({type:"bigint",coerce:!0,...pn(t)})}function fa(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...pn(t)})}function va(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...pn(t)})}function ya(e,t){return new e({type:"symbol",...pn(t)})}function _a(e,t){return new e({type:"undefined",...pn(t)})}function ba(e,t){return new e({type:"null",...pn(t)})}function wa(e){return new e({type:"any"})}function ka(e){return new e({type:"unknown"})}function xa(e,t){return new e({type:"never",...pn(t)})}function Ia(e,t){return new e({type:"void",...pn(t)})}function Sa(e,t){return new e({type:"date",...pn(t)})}function $a(e,t){return new e({type:"date",coerce:!0,...pn(t)})}function Ea(e,t){return new e({type:"nan",...pn(t)})}function Ta(e,t){return new Ar({check:"less_than",...pn(t),value:e,inclusive:!1})}function Oa(e,t){return new Ar({check:"less_than",...pn(t),value:e,inclusive:!0})}function Na(e,t){return new Pr({check:"greater_than",...pn(t),value:e,inclusive:!1})}function Ca(e,t){return new Pr({check:"greater_than",...pn(t),value:e,inclusive:!0})}function Aa(e){return Na(0,e)}function Pa(e){return Ta(0,e)}function Ra(e){return Oa(0,e)}function Ua(e){return Ca(0,e)}function ja(e,t){return new Rr({check:"multiple_of",...pn(t),value:e})}function za(e,t){return new zr({check:"max_size",...pn(t),maximum:e})}function Da(e,t){return new Dr({check:"min_size",...pn(t),minimum:e})}function Ma(e,t){return new Mr({check:"size_equals",...pn(t),size:e})}function La(e,t){return new Lr({check:"max_length",...pn(t),maximum:e})}function Za(e,t){return new Zr({check:"min_length",...pn(t),minimum:e})}function qa(e,t){return new qr({check:"length_equals",...pn(t),length:e})}function Fa(e,t){return new Wr({check:"string_format",format:"regex",...pn(t),pattern:e})}function Wa(e){return new Jr({check:"string_format",format:"lowercase",...pn(e)})}function Ja(e){return new Br({check:"string_format",format:"uppercase",...pn(e)})}function Ba(e,t){return new Hr({check:"string_format",format:"includes",...pn(t),includes:e})}function Ha(e,t){return new Vr({check:"string_format",format:"starts_with",...pn(t),prefix:e})}function Va(e,t){return new Kr({check:"string_format",format:"ends_with",...pn(t),suffix:e})}function Ka(e,t,n){return new Yr({check:"property",property:e,schema:t,...pn(n)})}function Ga(e,t){return new Xr({check:"mime_type",mime:e,...pn(t)})}function Ya(e){return new Qr({check:"overwrite",tx:e})}function Xa(e){return Ya((t=>t.normalize(e)))}function Qa(){return Ya((e=>e.trim()))}function eu(){return Ya((e=>e.toLowerCase()))}function tu(){return Ya((e=>e.toUpperCase()))}function nu(e,t,n){return new e({type:"array",element:t,...pn(n)})}function ru(e,t,n,r){const i=n instanceof ni;return new e({type:"tuple",items:t,rest:i?n:null,...pn(i?r:n)})}function iu(e,t){return new e({type:"file",...pn(t)})}function ou(e,t,n){const r=pn(n);r.abort??(r.abort=!0);return new e({type:"custom",check:"custom",fn:t,...r})}function su(e,t,n){return new e({type:"custom",check:"custom",fn:t,...pn(n)})}function au(e){const t=uu((n=>(n.addIssue=e=>{if("string"==typeof e)n.issues.push(On(e,n.value,t._zod.def));else{const r=e;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=n.value),r.inst??(r.inst=t),r.continue??(r.continue=!t._zod.def.abort),n.issues.push(On(r))}},e(n.value,n))));return t}function uu(e,t){const n=new Nr({check:"custom",...pn(t)});return n._zod.check=e,n}function lu(e,t){const n=pn(t);let r=n.truthy??["true","1","yes","on","y","enabled"],i=n.falsy??["false","0","no","off","n","disabled"];"sensitive"!==n.case&&(r=r.map((e=>"string"==typeof e?e.toLowerCase():e)),i=i.map((e=>"string"==typeof e?e.toLowerCase():e)));const o=new Set(r),s=new Set(i),a=e.Pipe??Io,u=e.Boolean??Ri,l=e.String??ri,c=new(e.Transform??po)({type:"transform",transform:(e,t)=>{let r=e;return"sensitive"!==n.case&&(r=r.toLowerCase()),!!o.has(r)||!s.has(r)&&(t.issues.push({code:"invalid_value",expected:"stringbool",values:[...o,...s],input:t.value,inst:c,continue:!1}),{})},error:n.error}),d=new a({type:"pipe",in:new l({type:"string",error:n.error}),out:c,error:n.error});return new a({type:"pipe",in:d,out:new u({type:"boolean",error:n.error}),error:n.error})}function cu(e,t,n,r={}){const i=pn(r),o={...pn(r),check:"string_format",type:"string",format:t,fn:"function"==typeof n?n:e=>n.test(e),...i};n instanceof RegExp&&(o.pattern=n);return new e(o)}class du{constructor(e){this._def=e,this.def=e}implement(e){if("function"!=typeof e)throw new Error("implement() must be called with a function");const t=(...n)=>{const r=this._def.input?Ln(this._def.input,n,void 0,{callee:t}):n;if(!Array.isArray(r))throw new Error("Invalid arguments schema: not an array or tuple schema.");const i=e(...r);return this._def.output?Ln(this._def.output,i,void 0,{callee:t}):i};return t}implementAsync(e){if("function"!=typeof e)throw new Error("implement() must be called with a function");const t=async(...n)=>{const r=this._def.input?await qn(this._def.input,n,void 0,{callee:t}):n;if(!Array.isArray(r))throw new Error("Invalid arguments schema: not an array or tuple schema.");const i=await e(...r);return this._def.output?qn(this._def.output,i,void 0,{callee:t}):i};return t}input(...e){const t=this.constructor;return Array.isArray(e[0])?new t({type:"function",input:new to({type:"tuple",items:e[0],rest:e[1]}),output:this._def.output}):new t({type:"function",input:e[0],output:this._def.output})}output(e){return new(0,this.constructor)({type:"function",input:this._def.input,output:e})}}function pu(e){return new du({type:"function",input:Array.isArray(null==e?void 0:e.input)?ru(to,null==e?void 0:e.input):(null==e?void 0:e.input)??nu(Bi,ka(Zi)),output:(null==e?void 0:e.output)??ka(Zi)})}class mu{constructor(e){this.counter=0,this.metadataRegistry=(null==e?void 0:e.metadata)??Os,this.target=(null==e?void 0:e.target)??"draft-2020-12",this.unrepresentable=(null==e?void 0:e.unrepresentable)??"throw",this.override=(null==e?void 0:e.override)??(()=>{}),this.io=(null==e?void 0:e.io)??"output",this.seen=new Map}process(e,t={path:[],schemaPath:[]}){var n,r,i,o;const s=e._zod.def,a={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},u=this.seen.get(e);if(u){u.count++;return t.schemaPath.includes(e)&&(u.cycle=t.path),u.schema}const l={schema:{},count:1,cycle:void 0,path:t.path};this.seen.set(e,l);const c=null==(r=(n=e._zod).toJSONSchema)?void 0:r.call(n);if(c)l.schema=c;else{const n={...t,schemaPath:[...t.schemaPath,e],path:t.path},r=e._zod.parent;if(r)l.ref=r,this.process(r,n),this.seen.get(r).isParent=!0;else{const t=l.schema;switch(s.type){case"string":{const n=t;n.type="string";const{minimum:r,maximum:i,format:o,patterns:s,contentEncoding:u}=e._zod.bag;if("number"==typeof r&&(n.minLength=r),"number"==typeof i&&(n.maxLength=i),o&&(n.format=a[o]??o,""===n.format&&delete n.format),u&&(n.contentEncoding=u),s&&s.size>0){const e=[...s];1===e.length?n.pattern=e[0].source:e.length>1&&(l.schema.allOf=[...e.map((e=>({..."draft-7"===this.target||"draft-4"===this.target?{type:"string"}:{},pattern:e.source})))])}break}case"number":{const n=t,{minimum:r,maximum:i,format:o,multipleOf:s,exclusiveMaximum:a,exclusiveMinimum:u}=e._zod.bag;"string"==typeof o&&o.includes("int")?n.type="integer":n.type="number","number"==typeof u&&("draft-4"===this.target?(n.minimum=u,n.exclusiveMinimum=!0):n.exclusiveMinimum=u),"number"==typeof r&&(n.minimum=r,"number"==typeof u&&"draft-4"!==this.target&&(u>=r?delete n.minimum:delete n.exclusiveMinimum)),"number"==typeof a&&("draft-4"===this.target?(n.maximum=a,n.exclusiveMaximum=!0):n.exclusiveMaximum=a),"number"==typeof i&&(n.maximum=i,"number"==typeof a&&"draft-4"!==this.target&&(a<=i?delete n.maximum:delete n.exclusiveMaximum)),"number"==typeof s&&(n.multipleOf=s);break}case"boolean":t.type="boolean";break;case"bigint":if("throw"===this.unrepresentable)throw new Error("BigInt cannot be represented in JSON Schema");break;case"symbol":if("throw"===this.unrepresentable)throw new Error("Symbols cannot be represented in JSON Schema");break;case"null":t.type="null";break;case"any":case"unknown":break;case"undefined":if("throw"===this.unrepresentable)throw new Error("Undefined cannot be represented in JSON Schema");break;case"void":if("throw"===this.unrepresentable)throw new Error("Void cannot be represented in JSON Schema");break;case"never":t.not={};break;case"date":if("throw"===this.unrepresentable)throw new Error("Date cannot be represented in JSON Schema");break;case"array":{const r=t,{minimum:i,maximum:o}=e._zod.bag;"number"==typeof i&&(r.minItems=i),"number"==typeof o&&(r.maxItems=o),r.type="array",r.items=this.process(s.element,{...n,path:[...n.path,"items"]});break}case"object":{const e=t;e.type="object",e.properties={};const r=s.shape;for(const t in r)e.properties[t]=this.process(r[t],{...n,path:[...n.path,"properties",t]});const o=new Set(Object.keys(r)),a=new Set([...o].filter((e=>{const t=s.shape[e]._zod;return"input"===this.io?void 0===t.optin:void 0===t.optout})));a.size>0&&(e.required=Array.from(a)),"never"===(null==(i=s.catchall)?void 0:i._zod.def.type)?e.additionalProperties=!1:s.catchall?s.catchall&&(e.additionalProperties=this.process(s.catchall,{...n,path:[...n.path,"additionalProperties"]})):"output"===this.io&&(e.additionalProperties=!1);break}case"union":t.anyOf=s.options.map(((e,t)=>this.process(e,{...n,path:[...n.path,"anyOf",t]})));break;case"intersection":{const e=t,r=this.process(s.left,{...n,path:[...n.path,"allOf",0]}),i=this.process(s.right,{...n,path:[...n.path,"allOf",1]}),o=e=>"allOf"in e&&1===Object.keys(e).length,a=[...o(r)?r.allOf:[r],...o(i)?i.allOf:[i]];e.allOf=a;break}case"tuple":{const r=t;r.type="array";const i=s.items.map(((e,t)=>this.process(e,{...n,path:[...n.path,"prefixItems",t]})));if("draft-2020-12"===this.target?r.prefixItems=i:r.items=i,s.rest){const e=this.process(s.rest,{...n,path:[...n.path,"items"]});"draft-2020-12"===this.target?r.items=e:r.additionalItems=e}s.rest&&(r.items=this.process(s.rest,{...n,path:[...n.path,"items"]}));const{minimum:o,maximum:a}=e._zod.bag;"number"==typeof o&&(r.minItems=o),"number"==typeof a&&(r.maxItems=a);break}case"record":{const e=t;e.type="object","draft-4"!==this.target&&(e.propertyNames=this.process(s.keyType,{...n,path:[...n.path,"propertyNames"]})),e.additionalProperties=this.process(s.valueType,{...n,path:[...n.path,"additionalProperties"]});break}case"map":if("throw"===this.unrepresentable)throw new Error("Map cannot be represented in JSON Schema");break;case"set":if("throw"===this.unrepresentable)throw new Error("Set cannot be represented in JSON Schema");break;case"enum":{const e=t,n=Ft(s.entries);n.every((e=>"number"==typeof e))&&(e.type="number"),n.every((e=>"string"==typeof e))&&(e.type="string"),e.enum=n;break}case"literal":{const e=t,n=[];for(const t of s.values)if(void 0===t){if("throw"===this.unrepresentable)throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if("bigint"==typeof t){if("throw"===this.unrepresentable)throw new Error("BigInt literals cannot be represented in JSON Schema");n.push(Number(t))}else n.push(t);if(0===n.length);else if(1===n.length){const t=n[0];e.type=null===t?"null":typeof t,"draft-4"===this.target?e.enum=[t]:e.const=t}else n.every((e=>"number"==typeof e))&&(e.type="number"),n.every((e=>"string"==typeof e))&&(e.type="string"),n.every((e=>"boolean"==typeof e))&&(e.type="string"),n.every((e=>null===e))&&(e.type="null"),e.enum=n;break}case"file":{const n=t,r={type:"string",format:"binary",contentEncoding:"binary"},{minimum:i,maximum:o,mime:s}=e._zod.bag;void 0!==i&&(r.minLength=i),void 0!==o&&(r.maxLength=o),s?1===s.length?(r.contentMediaType=s[0],Object.assign(n,r)):n.anyOf=s.map((e=>({...r,contentMediaType:e}))):Object.assign(n,r);break}case"transform":if("throw"===this.unrepresentable)throw new Error("Transforms cannot be represented in JSON Schema");break;case"nullable":{const e=this.process(s.innerType,n);t.anyOf=[e,{type:"null"}];break}case"nonoptional":case"promise":case"optional":this.process(s.innerType,n),l.ref=s.innerType;break;case"success":t.type="boolean";break;case"default":this.process(s.innerType,n),l.ref=s.innerType,t.default=JSON.parse(JSON.stringify(s.defaultValue));break;case"prefault":this.process(s.innerType,n),l.ref=s.innerType,"input"===this.io&&(t._prefault=JSON.parse(JSON.stringify(s.defaultValue)));break;case"catch":{let e;this.process(s.innerType,n),l.ref=s.innerType;try{e=s.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}t.default=e;break}case"nan":if("throw"===this.unrepresentable)throw new Error("NaN cannot be represented in JSON Schema");break;case"template_literal":{const n=t,r=e._zod.pattern;if(!r)throw new Error("Pattern not found in template literal");n.type="string",n.pattern=r.source;break}case"pipe":{const e="input"===this.io?"transform"===s.in._zod.def.type?s.out:s.in:s.out;this.process(e,n),l.ref=e;break}case"readonly":this.process(s.innerType,n),l.ref=s.innerType,t.readOnly=!0;break;case"lazy":{const t=e._zod.innerType;this.process(t,n),l.ref=t;break}case"custom":if("throw"===this.unrepresentable)throw new Error("Custom types cannot be represented in JSON Schema")}}}const d=this.metadataRegistry.get(e);d&&Object.assign(l.schema,d),"input"===this.io&&gu(e)&&(delete l.schema.examples,delete l.schema.default),"input"===this.io&&l.schema._prefault&&((o=l.schema).default??(o.default=l.schema._prefault)),delete l.schema._prefault;return this.seen.get(e).schema}emit(e,t){var n,r,i,o,s,a;const u={cycles:(null==t?void 0:t.cycles)??"ref",reused:(null==t?void 0:t.reused)??"inline",external:(null==t?void 0:t.external)??void 0},l=this.seen.get(e);if(!l)throw new Error("Unprocessed schema. This is a bug in Zod.");const c=e=>{var t;const n="draft-2020-12"===this.target?"$defs":"definitions";if(u.external){const r=null==(t=u.external.registry.get(e[0]))?void 0:t.id,i=u.external.uri??(e=>e);if(r)return{ref:i(r)};const o=e[1].defId??e[1].schema.id??"schema"+this.counter++;return e[1].defId=o,{defId:o,ref:`${i("__shared")}#/${n}/${o}`}}if(e[1]===l)return{ref:"#"};const r=`#/${n}/`,i=e[1].schema.id??"__schema"+this.counter++;return{defId:i,ref:r+i}},d=e=>{if(e[1].schema.$ref)return;const t=e[1],{ref:n,defId:r}=c(e);t.def={...t.schema},r&&(t.defId=r);const i=t.schema;for(const o in i)delete i[o];i.$ref=n};if("throw"===u.cycles)for(const f of this.seen.entries()){const e=f[1];if(e.cycle)throw new Error(`Cycle detected: #/${null==(n=e.cycle)?void 0:n.join("/")}/<root>\n\nSet the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const f of this.seen.entries()){const t=f[1];if(e===f[0]){d(f);continue}if(u.external){const t=null==(r=u.external.registry.get(f[0]))?void 0:r.id;if(e!==f[0]&&t){d(f);continue}}(null==(i=this.metadataRegistry.get(f[0]))?void 0:i.id)?d(f):(t.cycle||t.count>1&&"ref"===u.reused)&&d(f)}const p=(e,t)=>{const n=this.seen.get(e),r=n.def??n.schema,i={...r};if(null===n.ref)return;const o=n.ref;if(n.ref=null,o){p(o,t);const e=this.seen.get(o).schema;!e.$ref||"draft-7"!==t.target&&"draft-4"!==t.target?(Object.assign(r,e),Object.assign(r,i)):(r.allOf=r.allOf??[],r.allOf.push(e))}n.isParent||this.override({zodSchema:e,jsonSchema:r,path:n.path??[]})};for(const f of[...this.seen.entries()].reverse())p(f[0],{target:this.target});const m={};if("draft-2020-12"===this.target?m.$schema="https://json-schema.org/draft/2020-12/schema":"draft-7"===this.target?m.$schema="http://json-schema.org/draft-07/schema#":"draft-4"===this.target?m.$schema="http://json-schema.org/draft-04/schema#":console.warn(`Invalid target: ${this.target}`),null==(o=u.external)?void 0:o.uri){const t=null==(s=u.external.registry.get(e))?void 0:s.id;if(!t)throw new Error("Schema is missing an `id` property");m.$id=u.external.uri(t)}Object.assign(m,l.def);const h=(null==(a=u.external)?void 0:a.defs)??{};for(const f of this.seen.entries()){const e=f[1];e.def&&e.defId&&(h[e.defId]=e.def)}u.external||Object.keys(h).length>0&&("draft-2020-12"===this.target?m.$defs=h:m.definitions=h);try{return JSON.parse(JSON.stringify(m))}catch(g){throw new Error("Error converting schema to JSON.")}}}function hu(e,t){if(e instanceof Es){const n=new mu(t),r={};for(const t of e._idmap.entries()){const[e,r]=t;n.process(r)}const i={},o={registry:e,uri:null==t?void 0:t.uri,defs:r};for(const s of e._idmap.entries()){const[e,r]=s;i[e]=n.emit(r,{...t,external:o})}if(Object.keys(r).length>0){const e="draft-2020-12"===n.target?"$defs":"definitions";i.__shared={[e]:r}}return{schemas:i}}const n=new mu(t);return n.process(e),n.emit(e,t)}function gu(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;switch(r.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":case"custom":case"success":case"catch":return!1;case"array":return gu(r.element,n);case"object":for(const e in r.shape)if(gu(r.shape[e],n))return!0;return!1;case"union":for(const e of r.options)if(gu(e,n))return!0;return!1;case"intersection":return gu(r.left,n)||gu(r.right,n);case"tuple":for(const e of r.items)if(gu(e,n))return!0;return!(!r.rest||!gu(r.rest,n));case"record":case"map":return gu(r.keyType,n)||gu(r.valueType,n);case"set":return gu(r.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":case"default":case"prefault":return gu(r.innerType,n);case"lazy":return gu(r.getter(),n);case"transform":return!0;case"pipe":return gu(r.in,n)||gu(r.out,n)}throw new Error(`Unknown schema type: ${r.type}`)}const fu=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"})),vu=Object.freeze(Object.defineProperty({__proto__:null,$ZodAny:Li,$ZodArray:Bi,$ZodAsyncError:Lt,$ZodBase64:Si,$ZodBase64URL:Ei,$ZodBigInt:Ui,$ZodBigIntFormat:ji,$ZodBoolean:Ri,$ZodCIDRv4:ki,$ZodCIDRv6:xi,$ZodCUID:di,$ZodCUID2:pi,$ZodCatch:ko,$ZodCheck:Nr,$ZodCheckBigIntFormat:jr,$ZodCheckEndsWith:Kr,$ZodCheckGreaterThan:Pr,$ZodCheckIncludes:Hr,$ZodCheckLengthEquals:qr,$ZodCheckLessThan:Ar,$ZodCheckLowerCase:Jr,$ZodCheckMaxLength:Lr,$ZodCheckMaxSize:zr,$ZodCheckMimeType:Xr,$ZodCheckMinLength:Zr,$ZodCheckMinSize:Dr,$ZodCheckMultipleOf:Rr,$ZodCheckNumberFormat:Ur,$ZodCheckOverwrite:Qr,$ZodCheckProperty:Yr,$ZodCheckRegex:Wr,$ZodCheckSizeEquals:Mr,$ZodCheckStartsWith:Vr,$ZodCheckStringFormat:Fr,$ZodCheckUpperCase:Br,$ZodCustom:Co,$ZodCustomStringFormat:Ci,$ZodDate:Wi,$ZodDefault:fo,$ZodDiscriminatedUnion:Yi,$ZodE164:Ti,$ZodEmail:ai,$ZodEmoji:li,$ZodEnum:uo,$ZodError:An,$ZodFile:co,$ZodFunction:du,$ZodGUID:oi,$ZodIPv4:bi,$ZodIPv6:wi,$ZodISODate:vi,$ZodISODateTime:fi,$ZodISODuration:_i,$ZodISOTime:yi,$ZodIntersection:Xi,$ZodJWT:Ni,$ZodKSUID:gi,$ZodLazy:No,$ZodLiteral:lo,$ZodMap:io,$ZodNaN:xo,$ZodNanoID:ci,$ZodNever:qi,$ZodNonOptional:_o,$ZodNull:Mi,$ZodNullable:go,$ZodNumber:Ai,$ZodNumberFormat:Pi,$ZodObject:Vi,$ZodOptional:ho,$ZodPipe:Io,$ZodPrefault:yo,$ZodPromise:Oo,$ZodReadonly:$o,$ZodRealError:Pn,$ZodRecord:ro,$ZodRegistry:Es,$ZodSet:so,$ZodString:ri,$ZodStringFormat:ii,$ZodSuccess:wo,$ZodSymbol:zi,$ZodTemplateLiteral:To,$ZodTransform:po,$ZodTuple:to,$ZodType:ni,$ZodULID:mi,$ZodURL:ui,$ZodUUID:si,$ZodUndefined:Di,$ZodUnion:Gi,$ZodUnknown:Zi,$ZodVoid:Fi,$ZodXID:hi,$brand:Mt,$constructor:Dt,$input:$s,$output:Ss,Doc:ei,JSONSchema:fu,JSONSchemaGenerator:mu,NEVER:zt,TimePrecision:ea,_any:wa,_array:nu,_base64:Gs,_base64url:Ys,_bigint:ha,_boolean:pa,_catch:function(e,t,n){return new e({type:"catch",innerType:t,catchValue:"function"==typeof n?n:()=>n})},_check:uu,_cidrv4:Vs,_cidrv6:Ks,_coercedBigint:ga,_coercedBoolean:ma,_coercedDate:$a,_coercedNumber:sa,_coercedString:Cs,_cuid:Zs,_cuid2:qs,_custom:ou,_date:Sa,_default:function(e,t,n){return new e({type:"default",innerType:t,get defaultValue(){return"function"==typeof n?n():an(n)}})},_discriminatedUnion:function(e,t,n,r){return new e({type:"union",options:n,discriminator:t,...pn(r)})},_e164:Xs,_email:As,_emoji:Ms,_endsWith:Va,_enum:function(e,t,n){return new e({type:"enum",entries:Array.isArray(t)?Object.fromEntries(t.map((e=>[e,e]))):t,...pn(n)})},_file:iu,_float32:ua,_float64:la,_gt:Na,_gte:Ca,_guid:Ps,_includes:Ba,_int:aa,_int32:ca,_int64:fa,_intersection:function(e,t,n){return new e({type:"intersection",left:t,right:n})},_ipv4:Bs,_ipv6:Hs,_isoDate:na,_isoDateTime:ta,_isoDuration:ia,_isoTime:ra,_jwt:Qs,_ksuid:Js,_lazy:function(e,t){return new e({type:"lazy",getter:t})},_length:qa,_literal:function(e,t,n){return new e({type:"literal",values:Array.isArray(t)?t:[t],...pn(n)})},_lowercase:Wa,_lt:Ta,_lte:Oa,_map:function(e,t,n,r){return new e({type:"map",keyType:t,valueType:n,...pn(r)})},_max:Oa,_maxLength:La,_maxSize:za,_mime:Ga,_min:Ca,_minLength:Za,_minSize:Da,_multipleOf:ja,_nan:Ea,_nanoid:Ls,_nativeEnum:function(e,t,n){return new e({type:"enum",entries:t,...pn(n)})},_negative:Pa,_never:xa,_nonnegative:Ua,_nonoptional:function(e,t,n){return new e({type:"nonoptional",innerType:t,...pn(n)})},_nonpositive:Ra,_normalize:Xa,_null:ba,_nullable:function(e,t){return new e({type:"nullable",innerType:t})},_number:oa,_optional:function(e,t){return new e({type:"optional",innerType:t})},_overwrite:Ya,_parse:Mn,_parseAsync:Zn,_pipe:function(e,t,n){return new e({type:"pipe",in:t,out:n})},_positive:Aa,_promise:function(e,t){return new e({type:"promise",innerType:t})},_property:Ka,_readonly:function(e,t){return new e({type:"readonly",innerType:t})},_record:function(e,t,n,r){return new e({type:"record",keyType:t,valueType:n,...pn(r)})},_refine:su,_regex:Fa,_safeParse:Fn,_safeParseAsync:Jn,_set:function(e,t,n){return new e({type:"set",valueType:t,...pn(n)})},_size:Ma,_startsWith:Ha,_string:Ns,_stringFormat:cu,_stringbool:lu,_success:function(e,t){return new e({type:"success",innerType:t})},_superRefine:au,_symbol:ya,_templateLiteral:function(e,t,n){return new e({type:"template_literal",parts:t,...pn(n)})},_toLowerCase:eu,_toUpperCase:tu,_transform:function(e,t){return new e({type:"transform",transform:t})},_trim:Qa,_tuple:ru,_uint32:da,_uint64:va,_ulid:Fs,_undefined:_a,_union:function(e,t,n){return new e({type:"union",options:t,...pn(n)})},_unknown:ka,_uppercase:Ja,_url:Ds,_uuid:Rs,_uuidv4:Us,_uuidv6:js,_uuidv7:zs,_void:Ia,_xid:Ws,clone:dn,config:qt,flattenError:Rn,formatError:Un,function:pu,globalConfig:Zt,globalRegistry:Os,isValidBase64:Ii,isValidBase64URL:$i,isValidJWT:Oi,locales:Is,parse:Ln,parseAsync:qn,prettifyError:Dn,regexes:Or,registry:Ts,safeParse:Wn,safeParseAsync:Bn,toDotPath:zn,toJSONSchema:hu,treeifyError:jn,util:Nn,version:ti},Symbol.toStringTag,{value:"Module"})),yu=Dt("ZodISODateTime",((e,t)=>{fi.init(e,t),Du.init(e,t)}));function _u(e){return ta(yu,e)}const bu=Dt("ZodISODate",((e,t)=>{vi.init(e,t),Du.init(e,t)}));function wu(e){return na(bu,e)}const ku=Dt("ZodISOTime",((e,t)=>{yi.init(e,t),Du.init(e,t)}));function xu(e){return ra(ku,e)}const Iu=Dt("ZodISODuration",((e,t)=>{_i.init(e,t),Du.init(e,t)}));function Su(e){return ia(Iu,e)}const $u=Object.freeze(Object.defineProperty({__proto__:null,ZodISODate:bu,ZodISODateTime:yu,ZodISODuration:Iu,ZodISOTime:ku,date:wu,datetime:_u,duration:Su,time:xu},Symbol.toStringTag,{value:"Module"})),Eu=(e,t)=>{An.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>Un(e,t)},flatten:{value:t=>Rn(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Jt,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Jt,2)}},isEmpty:{get:()=>0===e.issues.length}})},Tu=Dt("ZodError",Eu),Ou=Dt("ZodError",Eu,{Parent:Error}),Nu=Mn(Ou),Cu=Zn(Ou),Au=Fn(Ou),Pu=Jn(Ou),Ru=Dt("ZodType",((e,t)=>(ni.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map((e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e))]}),e.clone=(t,n)=>dn(e,t,n),e.brand=()=>e,e.register=(t,n)=>(t.add(e,n),e),e.parse=(t,n)=>Nu(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Au(e,t,n),e.parseAsync=async(t,n)=>Cu(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Pu(e,t,n),e.spa=e.safeParseAsync,e.refine=(t,n)=>e.check(wc(t,n)),e.superRefine=t=>e.check(kc(t)),e.overwrite=t=>e.check(Ya(t)),e.optional=()=>Xl(e),e.nullable=()=>ec(e),e.nullish=()=>Xl(ec(e)),e.nonoptional=t=>sc(e,t),e.array=()=>El(e),e.or=t=>Pl([e,t]),e.and=t=>zl(e,t),e.transform=t=>pc(e,Gl(t)),e.default=t=>nc(e,t),e.prefault=t=>ic(e,t),e.catch=t=>lc(e,t),e.pipe=t=>pc(e,t),e.readonly=()=>hc(e),e.describe=t=>{const n=e.clone();return Os.add(n,{description:t}),n},Object.defineProperty(e,"description",{get(){var t;return null==(t=Os.get(e))?void 0:t.description},configurable:!0}),e.meta=(...t)=>{if(0===t.length)return Os.get(e);const n=e.clone();return Os.add(n,t[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e))),Uu=Dt("_ZodString",((e,t)=>{ri.init(e,t),Ru.init(e,t);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...t)=>e.check(Fa(...t)),e.includes=(...t)=>e.check(Ba(...t)),e.startsWith=(...t)=>e.check(Ha(...t)),e.endsWith=(...t)=>e.check(Va(...t)),e.min=(...t)=>e.check(Za(...t)),e.max=(...t)=>e.check(La(...t)),e.length=(...t)=>e.check(qa(...t)),e.nonempty=(...t)=>e.check(Za(1,...t)),e.lowercase=t=>e.check(Wa(t)),e.uppercase=t=>e.check(Ja(t)),e.trim=()=>e.check(Qa()),e.normalize=(...t)=>e.check(Xa(...t)),e.toLowerCase=()=>e.check(eu()),e.toUpperCase=()=>e.check(tu())})),ju=Dt("ZodString",((e,t)=>{ri.init(e,t),Uu.init(e,t),e.email=t=>e.check(As(Mu,t)),e.url=t=>e.check(Ds(qu,t)),e.jwt=t=>e.check(Qs(il,t)),e.emoji=t=>e.check(Ms(Fu,t)),e.guid=t=>e.check(Ps(Lu,t)),e.uuid=t=>e.check(Rs(Zu,t)),e.uuidv4=t=>e.check(Us(Zu,t)),e.uuidv6=t=>e.check(js(Zu,t)),e.uuidv7=t=>e.check(zs(Zu,t)),e.nanoid=t=>e.check(Ls(Wu,t)),e.guid=t=>e.check(Ps(Lu,t)),e.cuid=t=>e.check(Zs(Ju,t)),e.cuid2=t=>e.check(qs(Bu,t)),e.ulid=t=>e.check(Fs(Hu,t)),e.base64=t=>e.check(Gs(el,t)),e.base64url=t=>e.check(Ys(nl,t)),e.xid=t=>e.check(Ws(Vu,t)),e.ksuid=t=>e.check(Js(Ku,t)),e.ipv4=t=>e.check(Bs(Gu,t)),e.ipv6=t=>e.check(Hs(Yu,t)),e.cidrv4=t=>e.check(Vs(Xu,t)),e.cidrv6=t=>e.check(Ks(Qu,t)),e.e164=t=>e.check(Xs(rl,t)),e.datetime=t=>e.check(_u(t)),e.date=t=>e.check(wu(t)),e.time=t=>e.check(xu(t)),e.duration=t=>e.check(Su(t))}));function zu(e){return Ns(ju,e)}const Du=Dt("ZodStringFormat",((e,t)=>{ii.init(e,t),Uu.init(e,t)})),Mu=Dt("ZodEmail",((e,t)=>{ai.init(e,t),Du.init(e,t)}));const Lu=Dt("ZodGUID",((e,t)=>{oi.init(e,t),Du.init(e,t)}));const Zu=Dt("ZodUUID",((e,t)=>{si.init(e,t),Du.init(e,t)}));const qu=Dt("ZodURL",((e,t)=>{ui.init(e,t),Du.init(e,t)}));const Fu=Dt("ZodEmoji",((e,t)=>{li.init(e,t),Du.init(e,t)}));const Wu=Dt("ZodNanoID",((e,t)=>{ci.init(e,t),Du.init(e,t)}));const Ju=Dt("ZodCUID",((e,t)=>{di.init(e,t),Du.init(e,t)}));const Bu=Dt("ZodCUID2",((e,t)=>{pi.init(e,t),Du.init(e,t)}));const Hu=Dt("ZodULID",((e,t)=>{mi.init(e,t),Du.init(e,t)}));const Vu=Dt("ZodXID",((e,t)=>{hi.init(e,t),Du.init(e,t)}));const Ku=Dt("ZodKSUID",((e,t)=>{gi.init(e,t),Du.init(e,t)}));const Gu=Dt("ZodIPv4",((e,t)=>{bi.init(e,t),Du.init(e,t)}));const Yu=Dt("ZodIPv6",((e,t)=>{wi.init(e,t),Du.init(e,t)}));const Xu=Dt("ZodCIDRv4",((e,t)=>{ki.init(e,t),Du.init(e,t)}));const Qu=Dt("ZodCIDRv6",((e,t)=>{xi.init(e,t),Du.init(e,t)}));const el=Dt("ZodBase64",((e,t)=>{Si.init(e,t),Du.init(e,t)}));function tl(e){return Gs(el,e)}const nl=Dt("ZodBase64URL",((e,t)=>{Ei.init(e,t),Du.init(e,t)}));const rl=Dt("ZodE164",((e,t)=>{Ti.init(e,t),Du.init(e,t)}));const il=Dt("ZodJWT",((e,t)=>{Ni.init(e,t),Du.init(e,t)}));const ol=Dt("ZodCustomStringFormat",((e,t)=>{Ci.init(e,t),Du.init(e,t)}));const sl=Dt("ZodNumber",((e,t)=>{Ai.init(e,t),Ru.init(e,t),e.gt=(t,n)=>e.check(Na(t,n)),e.gte=(t,n)=>e.check(Ca(t,n)),e.min=(t,n)=>e.check(Ca(t,n)),e.lt=(t,n)=>e.check(Ta(t,n)),e.lte=(t,n)=>e.check(Oa(t,n)),e.max=(t,n)=>e.check(Oa(t,n)),e.int=t=>e.check(ll(t)),e.safe=t=>e.check(ll(t)),e.positive=t=>e.check(Na(0,t)),e.nonnegative=t=>e.check(Ca(0,t)),e.negative=t=>e.check(Ta(0,t)),e.nonpositive=t=>e.check(Oa(0,t)),e.multipleOf=(t,n)=>e.check(ja(t,n)),e.step=(t,n)=>e.check(ja(t,n)),e.finite=()=>e;const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null}));function al(e){return oa(sl,e)}const ul=Dt("ZodNumberFormat",((e,t)=>{Pi.init(e,t),sl.init(e,t)}));function ll(e){return aa(ul,e)}const cl=Dt("ZodBoolean",((e,t)=>{Ri.init(e,t),Ru.init(e,t)}));function dl(e){return pa(cl,e)}const pl=Dt("ZodBigInt",((e,t)=>{Ui.init(e,t),Ru.init(e,t),e.gte=(t,n)=>e.check(Ca(t,n)),e.min=(t,n)=>e.check(Ca(t,n)),e.gt=(t,n)=>e.check(Na(t,n)),e.gte=(t,n)=>e.check(Ca(t,n)),e.min=(t,n)=>e.check(Ca(t,n)),e.lt=(t,n)=>e.check(Ta(t,n)),e.lte=(t,n)=>e.check(Oa(t,n)),e.max=(t,n)=>e.check(Oa(t,n)),e.positive=t=>e.check(Na(BigInt(0),t)),e.negative=t=>e.check(Ta(BigInt(0),t)),e.nonpositive=t=>e.check(Oa(BigInt(0),t)),e.nonnegative=t=>e.check(Ca(BigInt(0),t)),e.multipleOf=(t,n)=>e.check(ja(t,n));const n=e._zod.bag;e.minValue=n.minimum??null,e.maxValue=n.maximum??null,e.format=n.format??null}));const ml=Dt("ZodBigIntFormat",((e,t)=>{ji.init(e,t),pl.init(e,t)}));const hl=Dt("ZodSymbol",((e,t)=>{zi.init(e,t),Ru.init(e,t)}));const gl=Dt("ZodUndefined",((e,t)=>{Di.init(e,t),Ru.init(e,t)}));const fl=Dt("ZodNull",((e,t)=>{Mi.init(e,t),Ru.init(e,t)}));function vl(e){return ba(fl,e)}const yl=Dt("ZodAny",((e,t)=>{Li.init(e,t),Ru.init(e,t)}));function _l(){return wa(yl)}const bl=Dt("ZodUnknown",((e,t)=>{Zi.init(e,t),Ru.init(e,t)}));function wl(){return ka(bl)}const kl=Dt("ZodNever",((e,t)=>{qi.init(e,t),Ru.init(e,t)}));function xl(e){return xa(kl,e)}const Il=Dt("ZodVoid",((e,t)=>{Fi.init(e,t),Ru.init(e,t)}));const Sl=Dt("ZodDate",((e,t)=>{Wi.init(e,t),Ru.init(e,t),e.min=(t,n)=>e.check(Ca(t,n)),e.max=(t,n)=>e.check(Oa(t,n));const n=e._zod.bag;e.minDate=n.minimum?new Date(n.minimum):null,e.maxDate=n.maximum?new Date(n.maximum):null}));const $l=Dt("ZodArray",((e,t)=>{Bi.init(e,t),Ru.init(e,t),e.element=t.element,e.min=(t,n)=>e.check(Za(t,n)),e.nonempty=t=>e.check(Za(1,t)),e.max=(t,n)=>e.check(La(t,n)),e.length=(t,n)=>e.check(qa(t,n)),e.unwrap=()=>e.element}));function El(e,t){return nu($l,e,t)}const Tl=Dt("ZodObject",((e,t)=>{Vi.init(e,t),Ru.init(e,t),Yt(e,"shape",(()=>t.shape)),e.keyof=()=>Jl(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:wl()}),e.loose=()=>e.clone({...e._zod.def,catchall:wl()}),e.strict=()=>e.clone({...e._zod.def,catchall:xl()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>_n(e,t),e.merge=t=>bn(e,t),e.pick=t=>vn(e,t),e.omit=t=>yn(e,t),e.partial=(...t)=>wn(Yl,e,t[0]),e.required=(...t)=>kn(oc,e,t[0])}));function Ol(e,t){const n={type:"object",get shape(){return Qt(this,"shape",e?Xt(e):{}),this.shape},...pn(t)};return new Tl(n)}function Nl(e,t){return new Tl({type:"object",get shape(){return Qt(this,"shape",Xt(e)),this.shape},catchall:xl(),...pn(t)})}function Cl(e,t){return new Tl({type:"object",get shape(){return Qt(this,"shape",Xt(e)),this.shape},catchall:wl(),...pn(t)})}const Al=Dt("ZodUnion",((e,t)=>{Gi.init(e,t),Ru.init(e,t),e.options=t.options}));function Pl(e,t){return new Al({type:"union",options:e,...pn(t)})}const Rl=Dt("ZodDiscriminatedUnion",((e,t)=>{Al.init(e,t),Yi.init(e,t)}));function Ul(e,t,n){return new Rl({type:"union",options:t,discriminator:e,...pn(n)})}const jl=Dt("ZodIntersection",((e,t)=>{Xi.init(e,t),Ru.init(e,t)}));function zl(e,t){return new jl({type:"intersection",left:e,right:t})}const Dl=Dt("ZodTuple",((e,t)=>{to.init(e,t),Ru.init(e,t),e.rest=t=>e.clone({...e._zod.def,rest:t})}));function Ml(e,t,n){const r=t instanceof ni;return new Dl({type:"tuple",items:e,rest:r?t:null,...pn(r?n:t)})}const Ll=Dt("ZodRecord",((e,t)=>{ro.init(e,t),Ru.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType}));function Zl(e,t,n){return new Ll({type:"record",keyType:e,valueType:t,...pn(n)})}const ql=Dt("ZodMap",((e,t)=>{io.init(e,t),Ru.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType}));const Fl=Dt("ZodSet",((e,t)=>{so.init(e,t),Ru.init(e,t),e.min=(...t)=>e.check(Da(...t)),e.nonempty=t=>e.check(Da(1,t)),e.max=(...t)=>e.check(za(...t)),e.size=(...t)=>e.check(Ma(...t))}));const Wl=Dt("ZodEnum",((e,t)=>{uo.init(e,t),Ru.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{const i={};for(const o of e){if(!n.has(o))throw new Error(`Key ${o} not found in enum`);i[o]=t.entries[o]}return new Wl({...t,checks:[],...pn(r),entries:i})},e.exclude=(e,r)=>{const i={...t.entries};for(const t of e){if(!n.has(t))throw new Error(`Key ${t} not found in enum`);delete i[t]}return new Wl({...t,checks:[],...pn(r),entries:i})}}));function Jl(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map((e=>[e,e]))):e;return new Wl({type:"enum",entries:n,...pn(t)})}const Bl=Dt("ZodLiteral",((e,t)=>{lo.init(e,t),Ru.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})}));function Hl(e,t){return new Bl({type:"literal",values:Array.isArray(e)?e:[e],...pn(t)})}const Vl=Dt("ZodFile",((e,t)=>{co.init(e,t),Ru.init(e,t),e.min=(t,n)=>e.check(Da(t,n)),e.max=(t,n)=>e.check(za(t,n)),e.mime=(t,n)=>e.check(Ga(Array.isArray(t)?t:[t],n))}));const Kl=Dt("ZodTransform",((e,t)=>{po.init(e,t),Ru.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=r=>{if("string"==typeof r)n.issues.push(On(r,n.value,t));else{const t=r;t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=n.value),t.inst??(t.inst=e),n.issues.push(On(t))}};const i=t.transform(n.value,n);return i instanceof Promise?i.then((e=>(n.value=e,n))):(n.value=i,n)}}));function Gl(e){return new Kl({type:"transform",transform:e})}const Yl=Dt("ZodOptional",((e,t)=>{ho.init(e,t),Ru.init(e,t),e.unwrap=()=>e._zod.def.innerType}));function Xl(e){return new Yl({type:"optional",innerType:e})}const Ql=Dt("ZodNullable",((e,t)=>{go.init(e,t),Ru.init(e,t),e.unwrap=()=>e._zod.def.innerType}));function ec(e){return new Ql({type:"nullable",innerType:e})}const tc=Dt("ZodDefault",((e,t)=>{fo.init(e,t),Ru.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap}));function nc(e,t){return new tc({type:"default",innerType:e,get defaultValue(){return"function"==typeof t?t():an(t)}})}const rc=Dt("ZodPrefault",((e,t)=>{yo.init(e,t),Ru.init(e,t),e.unwrap=()=>e._zod.def.innerType}));function ic(e,t){return new rc({type:"prefault",innerType:e,get defaultValue(){return"function"==typeof t?t():an(t)}})}const oc=Dt("ZodNonOptional",((e,t)=>{_o.init(e,t),Ru.init(e,t),e.unwrap=()=>e._zod.def.innerType}));function sc(e,t){return new oc({type:"nonoptional",innerType:e,...pn(t)})}const ac=Dt("ZodSuccess",((e,t)=>{wo.init(e,t),Ru.init(e,t),e.unwrap=()=>e._zod.def.innerType}));const uc=Dt("ZodCatch",((e,t)=>{ko.init(e,t),Ru.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap}));function lc(e,t){return new uc({type:"catch",innerType:e,catchValue:"function"==typeof t?t:()=>t})}const cc=Dt("ZodNaN",((e,t)=>{xo.init(e,t),Ru.init(e,t)}));const dc=Dt("ZodPipe",((e,t)=>{Io.init(e,t),Ru.init(e,t),e.in=t.in,e.out=t.out}));function pc(e,t){return new dc({type:"pipe",in:e,out:t})}const mc=Dt("ZodReadonly",((e,t)=>{$o.init(e,t),Ru.init(e,t),e.unwrap=()=>e._zod.def.innerType}));function hc(e){return new mc({type:"readonly",innerType:e})}const gc=Dt("ZodTemplateLiteral",((e,t)=>{To.init(e,t),Ru.init(e,t)}));const fc=Dt("ZodLazy",((e,t)=>{No.init(e,t),Ru.init(e,t),e.unwrap=()=>e._zod.def.getter()}));function vc(e){return new fc({type:"lazy",getter:e})}const yc=Dt("ZodPromise",((e,t)=>{Oo.init(e,t),Ru.init(e,t),e.unwrap=()=>e._zod.def.innerType}));const _c=Dt("ZodCustom",((e,t)=>{Co.init(e,t),Ru.init(e,t)}));function bc(e,t){return ou(_c,e??(()=>!0),t)}function wc(e,t={}){return su(_c,e,t)}function kc(e){return au(e)}function xc(e,t={error:`Input not instance of ${e.name}`}){const n=new _c({type:"custom",check:"custom",fn:t=>t instanceof e,abort:!0,...pn(t)});return n._zod.bag.Class=e,n}var Ic;function Sc(e){return sa(sl,e)}Ic||(Ic={});const $c=Object.freeze(Object.defineProperty({__proto__:null,bigint:function(e){return ga(pl,e)},boolean:function(e){return ma(cl,e)},date:function(e){return $a(Sl,e)},number:Sc,string:function(e){return Cs(ju,e)}},Symbol.toStringTag,{value:"Module"}));qt(qo());const Ec=Object.freeze(Object.defineProperty({__proto__:null,$brand:Mt,$input:$s,$output:Ss,NEVER:zt,TimePrecision:ea,ZodAny:yl,ZodArray:$l,ZodBase64:el,ZodBase64URL:nl,ZodBigInt:pl,ZodBigIntFormat:ml,ZodBoolean:cl,ZodCIDRv4:Xu,ZodCIDRv6:Qu,ZodCUID:Ju,ZodCUID2:Bu,ZodCatch:uc,ZodCustom:_c,ZodCustomStringFormat:ol,ZodDate:Sl,ZodDefault:tc,ZodDiscriminatedUnion:Rl,ZodE164:rl,ZodEmail:Mu,ZodEmoji:Fu,ZodEnum:Wl,ZodError:Tu,ZodFile:Vl,get ZodFirstPartyTypeKind(){return Ic},ZodGUID:Lu,ZodIPv4:Gu,ZodIPv6:Yu,ZodISODate:bu,ZodISODateTime:yu,ZodISODuration:Iu,ZodISOTime:ku,ZodIntersection:jl,ZodIssueCode:{invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"},ZodJWT:il,ZodKSUID:Ku,ZodLazy:fc,ZodLiteral:Bl,ZodMap:ql,ZodNaN:cc,ZodNanoID:Wu,ZodNever:kl,ZodNonOptional:oc,ZodNull:fl,ZodNullable:Ql,ZodNumber:sl,ZodNumberFormat:ul,ZodObject:Tl,ZodOptional:Yl,ZodPipe:dc,ZodPrefault:rc,ZodPromise:yc,ZodReadonly:mc,ZodRealError:Ou,ZodRecord:Ll,ZodSet:Fl,ZodString:ju,ZodStringFormat:Du,ZodSuccess:ac,ZodSymbol:hl,ZodTemplateLiteral:gc,ZodTransform:Kl,ZodTuple:Dl,ZodType:Ru,ZodULID:Hu,ZodURL:qu,ZodUUID:Zu,ZodUndefined:gl,ZodUnion:Al,ZodUnknown:bl,ZodVoid:Il,ZodXID:Vu,_ZodString:Uu,_default:nc,any:_l,array:El,base64:tl,base64url:function(e){return Ys(nl,e)},bigint:function(e){return ha(pl,e)},boolean:dl,catch:lc,check:function(e){const t=new Nr({check:"custom"});return t._zod.check=e,t},cidrv4:function(e){return Vs(Xu,e)},cidrv6:function(e){return Ks(Qu,e)},clone:dn,coerce:$c,config:qt,core:vu,cuid:function(e){return Zs(Ju,e)},cuid2:function(e){return qs(Bu,e)},custom:bc,date:function(e){return Sa(Sl,e)},discriminatedUnion:Ul,e164:function(e){return Xs(rl,e)},email:function(e){return As(Mu,e)},emoji:function(e){return Ms(Fu,e)},endsWith:Va,enum:Jl,file:function(e){return iu(Vl,e)},flattenError:Rn,float32:function(e){return ua(ul,e)},float64:function(e){return la(ul,e)},formatError:Un,function:pu,getErrorMap:function(){return qt().customError},globalRegistry:Os,gt:Na,gte:Ca,guid:function(e){return Ps(Lu,e)},hostname:function(e){return cu(ol,"hostname",mr,e)},includes:Ba,instanceof:xc,int:ll,int32:function(e){return ca(ul,e)},int64:function(e){return fa(ml,e)},intersection:zl,ipv4:function(e){return Bs(Gu,e)},ipv6:function(e){return Hs(Yu,e)},iso:$u,json:function(e){const t=vc((()=>Pl([zu(e),al(),dl(),vl(),El(t),Zl(zu(),t)])));return t},jwt:function(e){return Qs(il,e)},keyof:function(e){const t=e._zod.def.shape;return Jl(Object.keys(t))},ksuid:function(e){return Js(Ku,e)},lazy:vc,length:qa,literal:Hl,locales:Is,looseObject:Cl,lowercase:Wa,lt:Ta,lte:Oa,map:function(e,t,n){return new ql({type:"map",keyType:e,valueType:t,...pn(n)})},maxLength:La,maxSize:za,mime:Ga,minLength:Za,minSize:Da,multipleOf:ja,nan:function(e){return Ea(cc,e)},nanoid:function(e){return Ls(Wu,e)},nativeEnum:function(e,t){return new Wl({type:"enum",entries:e,...pn(t)})},negative:Pa,never:xl,nonnegative:Ua,nonoptional:sc,nonpositive:Ra,normalize:Xa,null:vl,nullable:ec,nullish:function(e){return Xl(ec(e))},number:al,object:Ol,optional:Xl,overwrite:Ya,parse:Nu,parseAsync:Cu,partialRecord:function(e,t,n){const r=dn(e);return r._zod.values=void 0,new Ll({type:"record",keyType:r,valueType:t,...pn(n)})},pipe:pc,positive:Aa,prefault:ic,preprocess:function(e,t){return pc(Gl(e),t)},prettifyError:Dn,promise:function(e){return new yc({type:"promise",innerType:e})},property:Ka,readonly:hc,record:Zl,refine:wc,regex:Fa,regexes:Or,registry:Ts,safeParse:Au,safeParseAsync:Pu,set:function(e,t){return new Fl({type:"set",valueType:e,...pn(t)})},setErrorMap:function(e){qt({customError:e})},size:Ma,startsWith:Ha,strictObject:Nl,string:zu,stringFormat:function(e,t,n={}){return cu(ol,e,t,n)},stringbool:(...e)=>lu({Pipe:dc,Boolean:cl,String:ju,Transform:Kl},...e),success:function(e){return new ac({type:"success",innerType:e})},superRefine:kc,symbol:function(e){return ya(hl,e)},templateLiteral:function(e,t){return new gc({type:"template_literal",parts:e,...pn(t)})},toJSONSchema:hu,toLowerCase:eu,toUpperCase:tu,transform:Gl,treeifyError:jn,trim:Qa,tuple:Ml,uint32:function(e){return da(ul,e)},uint64:function(e){return va(ml,e)},ulid:function(e){return Fs(Hu,e)},undefined:function(e){return _a(gl,e)},union:Pl,unknown:wl,uppercase:Ja,url:function(e){return Ds(qu,e)},uuid:function(e){return Rs(Zu,e)},uuidv4:function(e){return Us(Zu,e)},uuidv6:function(e){return js(Zu,e)},uuidv7:function(e){return zs(Zu,e)},void:function(e){return Ia(Il,e)},xid:function(e){return Ws(Vu,e)}},Symbol.toStringTag,{value:"Module"})),Tc=Symbol("Let zodToJsonSchema decide on which parser to use"),Oc={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},Nc=e=>{const t=(e=>"string"==typeof e?{...Oc,name:e}:{...Oc,...e})(e),n=void 0!==t.name?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map((([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}])))}};function Cc(e,t,n,r){(null==r?void 0:r.errorMessages)&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function Ac(e,t,n,r,i){e[t]=n,Cc(e,t,r,i)}const Pc=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join("/")};function Rc(e){if("openAi"!==e.target)return{};const t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:"relative"===e.$refStrategy?Pc(t,e.currentPath):t.join("/")}}function Uc(e,t){return ud(e.type._def,t)}function jc(e,t,n){const r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map(((n,r)=>jc(e,t,n)))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return zc(e,t)}}const zc=(e,t)=>{const n={type:"integer",format:"unix-time"};if("openApi3"===t.target)return n;for(const r of e.checks)switch(r.kind){case"min":Ac(n,"minimum",r.value,r.message,t);break;case"max":Ac(n,"maximum",r.value,r.message,t)}return n};let Dc;const Mc=/^[cC][^\s-]{8,}$/,Lc=/^[0-9a-z]+$/,Zc=/^[0-9A-HJKMNP-TV-Z]{26}$/,qc=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,Fc=()=>(void 0===Dc&&(Dc=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Dc),Wc=/^(?:(?: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])$/,Jc=/^(([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])$/,Bc=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Hc=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Vc=/^[a-zA-Z0-9_-]{21}$/,Kc=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;function Gc(e,t){const n={type:"string"};if(e.checks)for(const r of e.checks)switch(r.kind){case"min":Ac(n,"minLength","number"==typeof n.minLength?Math.max(n.minLength,r.value):r.value,r.message,t);break;case"max":Ac(n,"maxLength","number"==typeof n.maxLength?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case"email":switch(t.emailStrategy){case"format:email":Qc(n,"email",r.message,t);break;case"format:idn-email":Qc(n,"idn-email",r.message,t);break;case"pattern:zod":ed(n,qc,r.message,t)}break;case"url":Qc(n,"uri",r.message,t);break;case"uuid":Qc(n,"uuid",r.message,t);break;case"regex":ed(n,r.regex,r.message,t);break;case"cuid":ed(n,Mc,r.message,t);break;case"cuid2":ed(n,Lc,r.message,t);break;case"startsWith":ed(n,RegExp(`^${Yc(r.value,t)}`),r.message,t);break;case"endsWith":ed(n,RegExp(`${Yc(r.value,t)}$`),r.message,t);break;case"datetime":Qc(n,"date-time",r.message,t);break;case"date":Qc(n,"date",r.message,t);break;case"time":Qc(n,"time",r.message,t);break;case"duration":Qc(n,"duration",r.message,t);break;case"length":Ac(n,"minLength","number"==typeof n.minLength?Math.max(n.minLength,r.value):r.value,r.message,t),Ac(n,"maxLength","number"==typeof n.maxLength?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case"includes":ed(n,RegExp(Yc(r.value,t)),r.message,t);break;case"ip":"v6"!==r.version&&Qc(n,"ipv4",r.message,t),"v4"!==r.version&&Qc(n,"ipv6",r.message,t);break;case"base64url":ed(n,Hc,r.message,t);break;case"jwt":ed(n,Kc,r.message,t);break;case"cidr":"v6"!==r.version&&ed(n,Wc,r.message,t),"v4"!==r.version&&ed(n,Jc,r.message,t);break;case"emoji":ed(n,Fc(),r.message,t);break;case"ulid":ed(n,Zc,r.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":Qc(n,"binary",r.message,t);break;case"contentEncoding:base64":Ac(n,"contentEncoding","base64",r.message,t);break;case"pattern:zod":ed(n,Bc,r.message,t)}break;case"nanoid":ed(n,Vc,r.message,t)}return n}function Yc(e,t){return"escape"===t.patternStrategy?function(e){let t="";for(let n=0;n<e.length;n++)Xc.has(e[n])||(t+="\\"),t+=e[n];return t}(e):e}const Xc=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Qc(e,t,n,r){var i;e.format||(null==(i=e.anyOf)?void 0:i.some((e=>e.format)))?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):Ac(e,"format",t,n,r)}function ed(e,t,n,r){var i;e.pattern||(null==(i=e.allOf)?void 0:i.some((e=>e.pattern)))?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.allOf.push({pattern:td(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):Ac(e,"pattern",td(t,r),n,r)}function td(e,t){var n;if(!t.applyRegexFlags||!e.flags)return e.source;const r=e.flags.includes("i"),i=e.flags.includes("m"),o=e.flags.includes("s"),s=r?e.source.toLowerCase():e.source;let a="",u=!1,l=!1,c=!1;for(let d=0;d<s.length;d++)if(u)a+=s[d],u=!1;else{if(r)if(l){if(s[d].match(/[a-z]/)){c?(a+=s[d],a+=`${s[d-2]}-${s[d]}`.toUpperCase(),c=!1):"-"===s[d+1]&&(null==(n=s[d+2])?void 0:n.match(/[a-z]/))?(a+=s[d],c=!0):a+=`${s[d]}${s[d].toUpperCase()}`;continue}}else if(s[d].match(/[a-z]/)){a+=`[${s[d]}${s[d].toUpperCase()}]`;continue}if(i){if("^"===s[d]){a+="(^|(?<=[\r\n]))";continue}if("$"===s[d]){a+="($|(?=[\r\n]))";continue}}o&&"."===s[d]?a+=l?`${s[d]}\r\n`:`[${s[d]}\r\n]`:(a+=s[d],"\\"===s[d]?u=!0:l&&"]"===s[d]?l=!1:l||"["!==s[d]||(l=!0))}try{new RegExp(a)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return a}function nd(e,t){var n,r,i,o,s,a;if("openAi"===t.target&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),"openApi3"===t.target&&(null==(n=e.keyType)?void 0:n._def.typeName)===Ic.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce(((n,r)=>({...n,[r]:ud(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",r]})??Rc(t)})),{}),additionalProperties:t.rejectedAdditionalProperties};const u={type:"object",additionalProperties:ud(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if("openApi3"===t.target)return u;if((null==(r=e.keyType)?void 0:r._def.typeName)===Ic.ZodString&&(null==(i=e.keyType._def.checks)?void 0:i.length)){const{type:n,...r}=Gc(e.keyType._def,t);return{...u,propertyNames:r}}if((null==(o=e.keyType)?void 0:o._def.typeName)===Ic.ZodEnum)return{...u,propertyNames:{enum:e.keyType._def.values}};if((null==(s=e.keyType)?void 0:s._def.typeName)===Ic.ZodBranded&&e.keyType._def.type._def.typeName===Ic.ZodString&&(null==(a=e.keyType._def.type._def.checks)?void 0:a.length)){const{type:n,...r}=Uc(e.keyType._def,t);return{...u,propertyNames:r}}return u}const rd={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};const id=(e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map(((e,n)=>ud(e._def,{...t,currentPath:[...t.currentPath,"anyOf",`${n}`]}))).filter((e=>!!e&&(!t.strictUnions||"object"==typeof e&&Object.keys(e).length>0)));return n.length?{anyOf:n}:void 0};function od(e,t){const n="openAi"===t.target,r={type:"object",properties:{}},i=[],o=e.shape();for(const a in o){let e=o[a];if(void 0===e||void 0===e._def)continue;let s=sd(e);s&&n&&("ZodOptional"===e._def.typeName&&(e=e._def.innerType),e.isNullable()||(e=e.nullable()),s=!1);const u=ud(e._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});void 0!==u&&(r.properties[a]=u,s||i.push(a))}i.length&&(r.required=i);const s=function(e,t){if("ZodNever"!==e.catchall._def.typeName)return ud(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return"strict"===t.removeAdditionalStrategy?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}(e,t);return void 0!==s&&(r.additionalProperties=s),r}function sd(e){try{return e.isOptional()}catch{return!0}}const ad=(e,t,n)=>{switch(t){case Ic.ZodString:return Gc(e,n);case Ic.ZodNumber:return function(e,t){const n={type:"number"};if(!e.checks)return n;for(const r of e.checks)switch(r.kind){case"int":n.type="integer",Cc(n,"type",r.message,t);break;case"min":"jsonSchema7"===t.target?r.inclusive?Ac(n,"minimum",r.value,r.message,t):Ac(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),Ac(n,"minimum",r.value,r.message,t));break;case"max":"jsonSchema7"===t.target?r.inclusive?Ac(n,"maximum",r.value,r.message,t):Ac(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),Ac(n,"maximum",r.value,r.message,t));break;case"multipleOf":Ac(n,"multipleOf",r.value,r.message,t)}return n}(e,n);case Ic.ZodObject:return od(e,n);case Ic.ZodBigInt:return function(e,t){const n={type:"integer",format:"int64"};if(!e.checks)return n;for(const r of e.checks)switch(r.kind){case"min":"jsonSchema7"===t.target?r.inclusive?Ac(n,"minimum",r.value,r.message,t):Ac(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),Ac(n,"minimum",r.value,r.message,t));break;case"max":"jsonSchema7"===t.target?r.inclusive?Ac(n,"maximum",r.value,r.message,t):Ac(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),Ac(n,"maximum",r.value,r.message,t));break;case"multipleOf":Ac(n,"multipleOf",r.value,r.message,t)}return n}(e,n);case Ic.ZodBoolean:return{type:"boolean"};case Ic.ZodDate:return jc(e,n);case Ic.ZodUndefined:return function(e){return{not:Rc(e)}}(n);case Ic.ZodNull:return function(e){return"openApi3"===e.target?{enum:["null"],nullable:!0}:{type:"null"}}(n);case Ic.ZodArray:return function(e,t){var n,r,i;const o={type:"array"};return(null==(n=e.type)?void 0:n._def)&&(null==(i=null==(r=e.type)?void 0:r._def)?void 0:i.typeName)!==Ic.ZodAny&&(o.items=ud(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&Ac(o,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&Ac(o,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(Ac(o,"minItems",e.exactLength.value,e.exactLength.message,t),Ac(o,"maxItems",e.exactLength.value,e.exactLength.message,t)),o}(e,n);case Ic.ZodUnion:case Ic.ZodDiscriminatedUnion:return function(e,t){if("openApi3"===t.target)return id(e,t);const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every((e=>e._def.typeName in rd&&(!e._def.checks||!e._def.checks.length)))){const e=n.reduce(((e,t)=>{const n=rd[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e}),[]);return{type:e.length>1?e:e[0]}}if(n.every((e=>"ZodLiteral"===e._def.typeName&&!e.description))){const e=n.reduce(((e,t)=>{const n=typeof t._def.value;switch(n){case"string":case"number":case"boolean":return[...e,n];case"bigint":return[...e,"integer"];case"object":if(null===t._def.value)return[...e,"null"];default:return e}}),[]);if(e.length===n.length){const t=e.filter(((e,t,n)=>n.indexOf(e)===t));return{type:t.length>1?t:t[0],enum:n.reduce(((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value]),[])}}}else if(n.every((e=>"ZodEnum"===e._def.typeName)))return{type:"string",enum:n.reduce(((e,t)=>[...e,...t._def.values.filter((t=>!e.includes(t)))]),[])};return id(e,t)}(e,n);case Ic.ZodIntersection:return function(e,t){const n=[ud(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),ud(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter((e=>!!e));let r="jsonSchema2019-09"===t.target?{unevaluatedProperties:!1}:void 0;const i=[];return n.forEach((e=>{if("type"in(t=e)&&"string"===t.type||!("allOf"in t)){let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){const{additionalProperties:n,...r}=e;t=r}else r=void 0;i.push(t)}else i.push(...e.allOf),void 0===e.unevaluatedProperties&&(r=void 0);var t})),i.length?{allOf:i,...r}:void 0}(e,n);case Ic.ZodTuple:return function(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map(((e,n)=>ud(e._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]}))).reduce(((e,t)=>void 0===t?e:[...e,t]),[]),additionalItems:ud(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map(((e,n)=>ud(e._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]}))).reduce(((e,t)=>void 0===t?e:[...e,t]),[])}}(e,n);case Ic.ZodRecord:return nd(e,n);case Ic.ZodLiteral:return function(e,t){const n=typeof e.value;return"bigint"!==n&&"number"!==n&&"boolean"!==n&&"string"!==n?{type:Array.isArray(e.value)?"array":"object"}:"openApi3"===t.target?{type:"bigint"===n?"integer":n,enum:[e.value]}:{type:"bigint"===n?"integer":n,const:e.value}}(e,n);case Ic.ZodEnum:return function(e){return{type:"string",enum:Array.from(e.values)}}(e);case Ic.ZodNativeEnum:return function(e){const t=e.values,n=Object.keys(e.values).filter((e=>"number"!=typeof t[t[e]])).map((e=>t[e])),r=Array.from(new Set(n.map((e=>typeof e))));return{type:1===r.length?"string"===r[0]?"string":"number":["string","number"],enum:n}}(e);case Ic.ZodNullable:return function(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return"openApi3"===t.target?{type:rd[e.innerType._def.typeName],nullable:!0}:{type:[rd[e.innerType._def.typeName],"null"]};if("openApi3"===t.target){const n=ud(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const n=ud(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}(e,n);case Ic.ZodOptional:return((e,t)=>{var n;if(t.currentPath.toString()===(null==(n=t.propertyPath)?void 0:n.toString()))return ud(e.innerType._def,t);const r=ud(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Rc(t)},r]}:Rc(t)})(e,n);case Ic.ZodMap:return function(e,t){return"record"===t.mapStrategy?nd(e,t):{type:"array",maxItems:125,items:{type:"array",items:[ud(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Rc(t),ud(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Rc(t)],minItems:2,maxItems:2}}}(e,n);case Ic.ZodSet:return function(e,t){const n={type:"array",uniqueItems:!0,items:ud(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&Ac(n,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&Ac(n,"maxItems",e.maxSize.value,e.maxSize.message,t),n}(e,n);case Ic.ZodLazy:return()=>e.getter()._def;case Ic.ZodPromise:return function(e,t){return ud(e.type._def,t)}(e,n);case Ic.ZodNaN:case Ic.ZodNever:return function(e){return"openAi"===e.target?void 0:{not:Rc({...e,currentPath:[...e.currentPath,"not"]})}}(n);case Ic.ZodEffects:return function(e,t){return"input"===t.effectStrategy?ud(e.schema._def,t):Rc(t)}(e,n);case Ic.ZodAny:return Rc(n);case Ic.ZodUnknown:return function(e){return Rc(e)}(n);case Ic.ZodDefault:return function(e,t){return{...ud(e.innerType._def,t),default:e.defaultValue()}}(e,n);case Ic.ZodBranded:return Uc(e,n);case Ic.ZodReadonly:case Ic.ZodCatch:return((e,t)=>ud(e.innerType._def,t))(e,n);case Ic.ZodPipeline:return((e,t)=>{if("input"===t.pipeStrategy)return ud(e.in._def,t);if("output"===t.pipeStrategy)return ud(e.out._def,t);const n=ud(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]});return{allOf:[n,ud(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]})].filter((e=>void 0!==e))}})(e,n);case Ic.ZodFunction:case Ic.ZodVoid:case Ic.ZodSymbol:default:return}};function ud(e,t,n=!1){var r;const i=t.seen.get(e);if(t.override){const o=null==(r=t.override)?void 0:r.call(t,e,t,i,n);if(o!==Tc)return o}if(i&&!n){const e=ld(i,t);if(void 0!==e)return e}const o={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,o);const s=ad(e,e.typeName,t),a="function"==typeof s?ud(s(),t):s;if(a&&cd(e,t,a),t.postProcess){const n=t.postProcess(a,e,t);return o.jsonSchema=a,n}return o.jsonSchema=a,a}const ld=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Pc(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every(((e,n)=>t.currentPath[n]===e))?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Rc(t)):"seen"===t.$refStrategy?Rc(t):void 0}},cd=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),dd=(e,t)=>{const n=Nc(t);let r="object"==typeof t&&t.definitions?Object.entries(t.definitions).reduce(((e,[t,r])=>({...e,[t]:ud(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??Rc(n)})),{}):void 0;const i="string"==typeof t?t:"title"===(null==t?void 0:t.nameStrategy)||null==t?void 0:t.name,o=ud(e._def,void 0===i?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??Rc(n),s="object"==typeof t&&void 0!==t.name&&"title"===t.nameStrategy?t.name:void 0;void 0!==s&&(o.title=s),n.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:"relative"===n.$refStrategy?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));const a=void 0===i?r?{...o,[n.definitionPath]:r}:o:{$ref:[..."relative"===n.$refStrategy?[]:n.basePath,n.definitionPath,i].join("/"),[n.definitionPath]:{...r,[i]:o}};return"jsonSchema7"===n.target?a.$schema="http://json-schema.org/draft-07/schema#":"jsonSchema2019-09"!==n.target&&"openAi"!==n.target||(a.$schema="https://json-schema.org/draft/2019-09/schema#"),"openAi"===n.target&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};function pd(...e){return e.reduce(((e,t)=>({...e,...null!=t?t:{}})),{})}function md(e){return Object.fromEntries([...e.headers])}var hd=({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:r="-"}={})=>{const i=()=>{const e=n.length,r=new Array(t);for(let i=0;i<t;i++)r[i]=n[Math.random()*e|0];return r.join("")};if(null==e)return i;if(n.includes(r))throw new Be({argument:"separator",message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`},gd=hd();function fd(e){return(e instanceof Error||e instanceof DOMException)&&("AbortError"===e.name||"ResponseAborted"===e.name||"TimeoutError"===e.name)}var vd=["fetch failed","failed to fetch"];function yd({apiKey:e,environmentVariableName:t,apiKeyParameterName:n="apiKey",description:r}){if("string"==typeof e)return e;if(null!=e)throw new pt({message:`${r} API key must be a string.`});if("undefined"==typeof process)throw new pt({message:`${r} API key is missing. Pass it using the '${n}' parameter. Environment variables is not supported in this environment.`});if(null==(e=process.env[t]))throw new pt({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if("string"!=typeof e)throw new pt({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}var _d=/"__proto__"\s*:/,bd=/"constructor"\s*:/;function wd(e){const t=JSON.parse(e);return null===t||"object"!=typeof t||!1===_d.test(e)&&!1===bd.test(e)?t:function(e){let t=[e];for(;t.length;){const e=t;t=[];for(const n of e){if(Object.prototype.hasOwnProperty.call(n,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(n,"constructor")&&Object.prototype.hasOwnProperty.call(n.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const e in n){const r=n[e];r&&"object"==typeof r&&t.push(r)}}}return e}(t)}function kd(e){const{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return wd(e)}finally{Error.stackTraceLimit=t}}var xd=Symbol.for("vercel.ai.validator");function Id(e){return function(e){return"object"==typeof e&&null!==e&&xd in e&&!0===e[xd]&&"validate"in e}(e)?e:(t=e,n=async e=>{const n=await t["~standard"].validate(e);return null==n.issues?{success:!0,value:n.value}:{success:!1,error:new Tt({value:e,cause:n.issues})}},{[xd]:!0,validate:n});var t,n}async function Sd({value:e,schema:t}){const n=Id(t);try{if(null==n.validate)return{success:!0,value:e,rawValue:e};const t=await n.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:Tt.wrap({value:e,cause:t.error}),rawValue:e}}catch(r){return{success:!1,error:Tt.wrap({value:e,cause:r}),rawValue:e}}}async function $d({text:e,schema:t}){try{const n=kd(e);return null==t?n:async function({value:e,schema:t}){const n=await Sd({value:e,schema:t});if(!n.success)throw Tt.wrap({value:e,cause:n.error});return n.value}({value:n,schema:t})}catch(n){if(at.isInstance(n)||Tt.isInstance(n))throw n;throw new at({text:e,cause:n})}}async function Ed({text:e,schema:t}){try{const n=kd(e);return null==t?{success:!0,value:n,rawValue:n}:await Sd({value:n,schema:t})}catch(n){return{success:!1,error:at.isInstance(n)?n:new at({text:e,cause:n}),rawValue:void 0}}}function Td(e){try{return kd(e),!0}catch(t){return!1}}function Od({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new jt).pipeThrough(new TransformStream({async transform({data:e},n){"[DONE]"!==e&&n.enqueue(await Ed({text:e,schema:t}))}}))}async function Nd({provider:e,providerOptions:t,schema:n}){if(null==(null==t?void 0:t[e]))return;const r=await Sd({value:t[e],schema:n});if(!r.success)throw new Be({argument:"providerOptions",message:`invalid ${e} provider options`,cause:r.error});return r.value}var Cd=()=>globalThis.fetch,Ad=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:o,fetch:s})=>Pd({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:o,fetch:s}),Pd=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:i,abortSignal:o,fetch:s=Cd()})=>{try{const l=await s(e,{method:"POST",headers:(a=t,Object.fromEntries(Object.entries(a).filter((([e,t])=>null!=t)))),body:n.content,signal:o}),c=md(l);if(!l.ok){let t;try{t=await i({response:l,url:e,requestBodyValues:n.values})}catch(u){if(fd(u)||Ue.isInstance(u))throw u;throw new Ue({message:"Failed to process error response",cause:u,statusCode:l.status,url:e,responseHeaders:c,requestBodyValues:n.values})}throw t.value}try{return await r({response:l,url:e,requestBodyValues:n.values})}catch(u){if(u instanceof Error&&(fd(u)||Ue.isInstance(u)))throw u;throw new Ue({message:"Failed to process successful response",cause:u,statusCode:l.status,url:e,responseHeaders:c,requestBodyValues:n.values})}}catch(u){throw function({error:e,url:t,requestBodyValues:n}){if(fd(e))return e;if(e instanceof TypeError&&vd.includes(e.message.toLowerCase())){const r=e.cause;if(null!=r)return new Ue({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}({error:u,url:e,requestBodyValues:n.values})}var a};function Rd({id:e,name:t,inputSchema:n}){return({execute:r,outputSchema:i,toModelOutput:o,onInputStart:s,onInputDelta:a,onInputAvailable:u,...l})=>({type:"provider-defined",id:e,name:t,args:l,inputSchema:n,outputSchema:i,execute:r,toModelOutput:o,onInputStart:s,onInputDelta:a,onInputAvailable:u})}function Ud({id:e,name:t,inputSchema:n,outputSchema:r}){return({execute:i,toModelOutput:o,onInputStart:s,onInputDelta:a,onInputAvailable:u,...l})=>({type:"provider-defined",id:e,name:t,args:l,inputSchema:n,outputSchema:r,execute:i,toModelOutput:o,onInputStart:s,onInputDelta:a,onInputAvailable:u})}async function jd(e){return"function"==typeof e&&(e=e()),Promise.resolve(e)}var zd=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:i,requestBodyValues:o})=>{const s=await r.text(),a=md(r);if(""===s.trim())return{responseHeaders:a,value:new Ue({message:r.statusText,url:i,requestBodyValues:o,statusCode:r.status,responseHeaders:a,responseBody:s,isRetryable:null==n?void 0:n(r)})};try{const u=await $d({text:s,schema:e});return{responseHeaders:a,value:new Ue({message:t(u),url:i,requestBodyValues:o,statusCode:r.status,responseHeaders:a,responseBody:s,data:u,isRetryable:null==n?void 0:n(r,u)})}}catch(u){return{responseHeaders:a,value:new Ue({message:r.statusText,url:i,requestBodyValues:o,statusCode:r.status,responseHeaders:a,responseBody:s,isRetryable:null==n?void 0:n(r)})}}},Dd=e=>async({response:t})=>{const n=md(t);if(null==t.body)throw new Le({});return{responseHeaders:n,value:Od({stream:t.body,schema:e})}},Md=e=>async({response:t,url:n,requestBodyValues:r})=>{const i=await t.text(),o=await Ed({text:i,schema:e}),s=md(t);if(!o.success)throw new Ue({message:"Invalid JSON response",cause:o.error,statusCode:t.status,responseHeaders:s,responseBody:i,url:n,requestBodyValues:r});return{responseHeaders:s,value:o.value,rawValue:o.rawValue}};function Ld(e,t){return function(e){return"_zod"in e}(e)?function(e){return qd(hu(e,{target:"draft-7",io:"output",reused:"inline"}),{validate:async t=>{const n=await Pu(e,t);return n.success?{success:!0,value:n.data}:{success:!1,error:n.error}}})}(e):function(e){return qd(dd(e,{$refStrategy:"none",target:"jsonSchema7"}),{validate:async t=>{const n=await e.safeParseAsync(t);return n.success?{success:!0,value:n.data}:{success:!1,error:n.error}}})}(e)}var Zd=Symbol.for("vercel.ai.schema");function qd(e,{validate:t}={}){return{[Zd]:!0,_type:void 0,[xd]:!0,jsonSchema:e,validate:t}}function Fd(e){return null==e?qd({properties:{},additionalProperties:!1}):"object"==typeof(t=e)&&null!==t&&Zd in t&&!0===t[Zd]&&"jsonSchema"in t&&"validate"in t?e:Ld(e);var t}var{btoa:Wd,atob:Jd}=globalThis;function Bd(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=Jd(t);return Uint8Array.from(n,(e=>e.codePointAt(0)))}function Hd(e){return e instanceof Uint8Array?function(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return Wd(t)}(e):e}function Vd(e){return null==e?void 0:e.replace(/\/$/,"")}var Kd=Ol({error:Ol({message:zu(),type:zu().nullish(),param:_l().nullish(),code:Pl([zu(),al()]).nullish()})}),Gd=zd({errorSchema:Kd,errorToMessage:e=>e.error.message});function Yd({id:e,model:t,created:n}){return{id:null!=e?e:void 0,modelId:null!=t?t:void 0,timestamp:null!=n?new Date(1e3*n):void 0}}function Xd(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var Qd=Ol({logitBias:Zl(Sc(),al()).optional(),logprobs:Pl([dl(),al()]).optional(),parallelToolCalls:dl().optional(),user:zu().optional(),reasoningEffort:Jl(["minimal","low","medium","high"]).optional(),maxCompletionTokens:al().optional(),store:dl().optional(),metadata:Zl(zu().max(64),zu().max(512)).optional(),prediction:Zl(zu(),_l()).optional(),structuredOutputs:dl().optional(),serviceTier:Jl(["auto","flex","priority"]).optional(),strictJsonSchema:dl().optional(),textVerbosity:Jl(["low","medium","high"]).optional(),promptCacheKey:zu().optional(),safetyIdentifier:zu().optional()}),ep=Ol({key:zu(),type:Jl(["eq","ne","gt","gte","lt","lte"]),value:Pl([zu(),al(),dl()])}),tp=Ol({type:Jl(["and","or"]),filters:El(Pl([ep,vc((()=>tp))]))}),np=Pl([ep,tp]),rp=Ol({vectorStoreIds:El(zu()).optional(),maxNumResults:al().optional(),ranking:Ol({ranker:Jl(["auto","default-2024-08-21"]).optional()}).optional(),filters:np.optional()}),ip=Rd({id:"openai.file_search",name:"file_search",inputSchema:Ol({query:zu()})}),op=Ol({searchContextSize:Jl(["low","medium","high"]).optional(),userLocation:Ol({type:Hl("approximate"),country:zu().optional(),city:zu().optional(),region:zu().optional(),timezone:zu().optional()}).optional()}),sp=Rd({id:"openai.web_search_preview",name:"web_search_preview",inputSchema:Ol({action:Ul("type",[Ol({type:Hl("search"),query:zu()}),Ol({type:Hl("open_page"),url:zu()}),Ol({type:Hl("find"),url:zu(),pattern:zu()})]).nullish()})});var ap=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:o,presencePenalty:s,stopSequences:a,responseFormat:u,seed:l,tools:c,toolChoice:d,providerOptions:p}){var m,h,g,f;const v=[],y=null!=(m=await Nd({provider:"openai",providerOptions:p,schema:Qd}))?m:{},_=null==(h=y.structuredOutputs)||h;null!=i&&v.push({type:"unsupported-setting",setting:"topK"}),"json"!==(null==u?void 0:u.type)||null==u.schema||_||v.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{messages:b,warnings:w}=function({prompt:e,systemMessageMode:t="system"}){const n=[],r=[];for(const{role:i,content:o}of e)switch(i){case"system":switch(t){case"system":n.push({role:"system",content:o});break;case"developer":n.push({role:"developer",content:o});break;case"remove":r.push({type:"other",message:"system messages are removed for this model"});break;default:throw new Error(`Unsupported system message mode: ${t}`)}break;case"user":if(1===o.length&&"text"===o[0].type){n.push({role:"user",content:o[0].text});break}n.push({role:"user",content:o.map(((e,t)=>{var n,r,i;switch(e.type){case"text":return{type:"text",text:e.text};case"file":if(e.mediaType.startsWith("image/")){const t="image/*"===e.mediaType?"image/jpeg":e.mediaType;return{type:"image_url",image_url:{url:e.data instanceof URL?e.data.toString():`data:${t};base64,${Hd(e.data)}`,detail:null==(r=null==(n=e.providerOptions)?void 0:n.openai)?void 0:r.imageDetail}}}if(!e.mediaType.startsWith("audio/")){if("application/pdf"===e.mediaType){if(e.data instanceof URL)throw new At({functionality:"PDF file parts with URLs"});return{type:"file",file:"string"==typeof e.data&&e.data.startsWith("file-")?{file_id:e.data}:{filename:null!=(i=e.filename)?i:`part-${t}.pdf`,file_data:`data:application/pdf;base64,${Hd(e.data)}`}}}throw new At({functionality:`file part media type ${e.mediaType}`})}if(e.data instanceof URL)throw new At({functionality:"audio file parts with URLs"});switch(e.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:Hd(e.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:Hd(e.data),format:"mp3"}};default:throw new At({functionality:`audio content parts with media type ${e.mediaType}`})}}}))});break;case"assistant":{let e="";const t=[];for(const n of o)switch(n.type){case"text":e+=n.text;break;case"tool-call":t.push({id:n.toolCallId,type:"function",function:{name:n.toolName,arguments:JSON.stringify(n.input)}})}n.push({role:"assistant",content:e,tool_calls:t.length>0?t:void 0});break}case"tool":for(const e of o){const t=e.output;let r;switch(t.type){case"text":case"error-text":r=t.value;break;case"content":case"json":case"error-json":r=JSON.stringify(t.value)}n.push({role:"tool",tool_call_id:e.toolCallId,content:r})}break;default:throw new Error(`Unsupported role: ${i}`)}return{messages:n,warnings:r}}({prompt:e,systemMessageMode:pp(this.modelId)});v.push(...w);const k=null!=(g=y.strictJsonSchema)&&g,x={model:this.modelId,logit_bias:y.logitBias,logprobs:!0===y.logprobs||"number"==typeof y.logprobs||void 0,top_logprobs:"number"==typeof y.logprobs?y.logprobs:"boolean"==typeof y.logprobs&&y.logprobs?0:void 0,user:y.user,parallel_tool_calls:y.parallelToolCalls,max_tokens:t,temperature:n,top_p:r,frequency_penalty:o,presence_penalty:s,response_format:"json"===(null==u?void 0:u.type)?_&&null!=u.schema?{type:"json_schema",json_schema:{schema:u.schema,strict:k,name:null!=(f=u.name)?f:"response",description:u.description}}:{type:"json_object"}:void 0,stop:a,seed:l,verbosity:y.textVerbosity,max_completion_tokens:y.maxCompletionTokens,store:y.store,metadata:y.metadata,prediction:y.prediction,reasoning_effort:y.reasoningEffort,service_tier:y.serviceTier,prompt_cache_key:y.promptCacheKey,safety_identifier:y.safetyIdentifier,messages:b};var I;dp(this.modelId)?(null!=x.temperature&&(x.temperature=void 0,v.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),null!=x.top_p&&(x.top_p=void 0,v.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"})),null!=x.frequency_penalty&&(x.frequency_penalty=void 0,v.push({type:"unsupported-setting",setting:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),null!=x.presence_penalty&&(x.presence_penalty=void 0,v.push({type:"unsupported-setting",setting:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),null!=x.logit_bias&&(x.logit_bias=void 0,v.push({type:"other",message:"logitBias is not supported for reasoning models"})),null!=x.logprobs&&(x.logprobs=void 0,v.push({type:"other",message:"logprobs is not supported for reasoning models"})),null!=x.top_logprobs&&(x.top_logprobs=void 0,v.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),null!=x.max_tokens&&(null==x.max_completion_tokens&&(x.max_completion_tokens=x.max_tokens),x.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&null!=x.temperature&&(x.temperature=void 0,v.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),"flex"!==y.serviceTier||((I=this.modelId).startsWith("o3")||I.startsWith("o4-mini")||I.startsWith("gpt-5")&&!I.startsWith("gpt-5-chat"))||(v.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),x.service_tier=void 0),"priority"!==y.serviceTier||function(e){return e.startsWith("gpt-4")||e.startsWith("gpt-5-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-nano")&&!e.startsWith("gpt-5-chat")||e.startsWith("o3")||e.startsWith("o4-mini")}(this.modelId)||(v.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),x.service_tier=void 0);const{tools:S,toolChoice:$,toolWarnings:E}=function({tools:e,toolChoice:t,structuredOutputs:n,strictJsonSchema:r}){const i=[];if(null==(e=(null==e?void 0:e.length)?e:void 0))return{tools:void 0,toolChoice:void 0,toolWarnings:i};const o=[];for(const a of e)switch(a.type){case"function":o.push({type:"function",function:{name:a.name,description:a.description,parameters:a.inputSchema,strict:n?r:void 0}});break;case"provider-defined":switch(a.id){case"openai.file_search":{const e=rp.parse(a.args);o.push({type:"file_search",vector_store_ids:e.vectorStoreIds,max_num_results:e.maxNumResults,ranking_options:e.ranking?{ranker:e.ranking.ranker}:void 0,filters:e.filters});break}case"openai.web_search_preview":{const e=op.parse(a.args);o.push({type:"web_search_preview",search_context_size:e.searchContextSize,user_location:e.userLocation});break}default:i.push({type:"unsupported-tool",tool:a})}break;default:i.push({type:"unsupported-tool",tool:a})}if(null==t)return{tools:o,toolChoice:void 0,toolWarnings:i};const s=t.type;switch(s){case"auto":case"none":case"required":return{tools:o,toolChoice:s,toolWarnings:i};case"tool":return{tools:o,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:i};default:throw new At({functionality:`tool choice type: ${s}`})}}({tools:c,toolChoice:d,structuredOutputs:_,strictJsonSchema:k});return{args:{...x,tools:S,tool_choice:$},warnings:[...v,...E]}}async doGenerate(e){var t,n,r,i,o,s,a,u,l,c,d,p,m,h;const{args:g,warnings:f}=await this.getArgs(e),{responseHeaders:v,value:y,rawValue:_}=await Ad({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:pd(this.config.headers(),e.headers),body:g,failedResponseHandler:Gd,successfulResponseHandler:Md(lp),abortSignal:e.abortSignal,fetch:this.config.fetch}),b=y.choices[0],w=[],k=b.message.content;null!=k&&k.length>0&&w.push({type:"text",text:k});for(const $ of null!=(t=b.message.tool_calls)?t:[])w.push({type:"tool-call",toolCallId:null!=(n=$.id)?n:gd(),toolName:$.function.name,input:$.function.arguments});for(const $ of null!=(r=b.message.annotations)?r:[])w.push({type:"source",sourceType:"url",id:gd(),url:$.url,title:$.title});const x=null==(i=y.usage)?void 0:i.completion_tokens_details,I=null==(o=y.usage)?void 0:o.prompt_tokens_details,S={openai:{}};return null!=(null==x?void 0:x.accepted_prediction_tokens)&&(S.openai.acceptedPredictionTokens=null==x?void 0:x.accepted_prediction_tokens),null!=(null==x?void 0:x.rejected_prediction_tokens)&&(S.openai.rejectedPredictionTokens=null==x?void 0:x.rejected_prediction_tokens),null!=(null==(s=b.logprobs)?void 0:s.content)&&(S.openai.logprobs=b.logprobs.content),{content:w,finishReason:Xd(b.finish_reason),usage:{inputTokens:null!=(u=null==(a=y.usage)?void 0:a.prompt_tokens)?u:void 0,outputTokens:null!=(c=null==(l=y.usage)?void 0:l.completion_tokens)?c:void 0,totalTokens:null!=(p=null==(d=y.usage)?void 0:d.total_tokens)?p:void 0,reasoningTokens:null!=(m=null==x?void 0:x.reasoning_tokens)?m:void 0,cachedInputTokens:null!=(h=null==I?void 0:I.cached_tokens)?h:void 0},request:{body:g},response:{...Yd(y),headers:v,body:_},warnings:f,providerMetadata:S}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:i,value:o}=await Ad({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:pd(this.config.headers(),e.headers),body:r,failedResponseHandler:Gd,successfulResponseHandler:Dd(cp),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=[];let a="unknown";const u={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let l=!0,c=!1;const d={openai:{}};return{stream:o.pipeThrough(new TransformStream({start(e){e.enqueue({type:"stream-start",warnings:n})},transform(t,n){var r,i,o,p,m,h,g,f,v,y,_,b,w,k,x,I,S,$,E,T,O,N,C,A;if(e.includeRawChunks&&n.enqueue({type:"raw",rawValue:t.rawValue}),!t.success)return a="error",void n.enqueue({type:"error",error:t.error});const P=t.value;if("error"in P)return a="error",void n.enqueue({type:"error",error:P.error});l&&(l=!1,n.enqueue({type:"response-metadata",...Yd(P)})),null!=P.usage&&(u.inputTokens=null!=(r=P.usage.prompt_tokens)?r:void 0,u.outputTokens=null!=(i=P.usage.completion_tokens)?i:void 0,u.totalTokens=null!=(o=P.usage.total_tokens)?o:void 0,u.reasoningTokens=null!=(m=null==(p=P.usage.completion_tokens_details)?void 0:p.reasoning_tokens)?m:void 0,u.cachedInputTokens=null!=(g=null==(h=P.usage.prompt_tokens_details)?void 0:h.cached_tokens)?g:void 0,null!=(null==(f=P.usage.completion_tokens_details)?void 0:f.accepted_prediction_tokens)&&(d.openai.acceptedPredictionTokens=null==(v=P.usage.completion_tokens_details)?void 0:v.accepted_prediction_tokens),null!=(null==(y=P.usage.completion_tokens_details)?void 0:y.rejected_prediction_tokens)&&(d.openai.rejectedPredictionTokens=null==(_=P.usage.completion_tokens_details)?void 0:_.rejected_prediction_tokens));const R=P.choices[0];if(null!=(null==R?void 0:R.finish_reason)&&(a=Xd(R.finish_reason)),null!=(null==(b=null==R?void 0:R.logprobs)?void 0:b.content)&&(d.openai.logprobs=R.logprobs.content),null==(null==R?void 0:R.delta))return;const U=R.delta;if(null!=U.content&&(c||(n.enqueue({type:"text-start",id:"0"}),c=!0),n.enqueue({type:"text-delta",id:"0",delta:U.content})),null!=U.tool_calls)for(const e of U.tool_calls){const t=e.index;if(null==s[t]){if("function"!==e.type)throw new nt({data:e,message:"Expected 'function' type."});if(null==e.id)throw new nt({data:e,message:"Expected 'id' to be a string."});if(null==(null==(w=e.function)?void 0:w.name))throw new nt({data:e,message:"Expected 'function.name' to be a string."});n.enqueue({type:"tool-input-start",id:e.id,toolName:e.function.name}),s[t]={id:e.id,type:"function",function:{name:e.function.name,arguments:null!=(k=e.function.arguments)?k:""},hasFinished:!1};const r=s[t];null!=(null==(x=r.function)?void 0:x.name)&&null!=(null==(I=r.function)?void 0:I.arguments)&&(r.function.arguments.length>0&&n.enqueue({type:"tool-input-delta",id:r.id,delta:r.function.arguments}),Td(r.function.arguments)&&(n.enqueue({type:"tool-input-end",id:r.id}),n.enqueue({type:"tool-call",toolCallId:null!=(S=r.id)?S:gd(),toolName:r.function.name,input:r.function.arguments}),r.hasFinished=!0));continue}const r=s[t];r.hasFinished||(null!=(null==($=e.function)?void 0:$.arguments)&&(r.function.arguments+=null!=(T=null==(E=e.function)?void 0:E.arguments)?T:""),n.enqueue({type:"tool-input-delta",id:r.id,delta:null!=(O=e.function.arguments)?O:""}),null!=(null==(N=r.function)?void 0:N.name)&&null!=(null==(C=r.function)?void 0:C.arguments)&&Td(r.function.arguments)&&(n.enqueue({type:"tool-input-end",id:r.id}),n.enqueue({type:"tool-call",toolCallId:null!=(A=r.id)?A:gd(),toolName:r.function.name,input:r.function.arguments}),r.hasFinished=!0))}if(null!=U.annotations)for(const e of U.annotations)n.enqueue({type:"source",sourceType:"url",id:gd(),url:e.url,title:e.title})},flush(e){c&&e.enqueue({type:"text-end",id:"0"}),e.enqueue({type:"finish",finishReason:a,usage:u,...null!=d?{providerMetadata:d}:{}})}})),request:{body:r},response:{headers:i}}}},up=Ol({prompt_tokens:al().nullish(),completion_tokens:al().nullish(),total_tokens:al().nullish(),prompt_tokens_details:Ol({cached_tokens:al().nullish()}).nullish(),completion_tokens_details:Ol({reasoning_tokens:al().nullish(),accepted_prediction_tokens:al().nullish(),rejected_prediction_tokens:al().nullish()}).nullish()}).nullish(),lp=Ol({id:zu().nullish(),created:al().nullish(),model:zu().nullish(),choices:El(Ol({message:Ol({role:Hl("assistant").nullish(),content:zu().nullish(),tool_calls:El(Ol({id:zu().nullish(),type:Hl("function"),function:Ol({name:zu(),arguments:zu()})})).nullish(),annotations:El(Ol({type:Hl("url_citation"),start_index:al(),end_index:al(),url:zu(),title:zu()})).nullish()}),index:al(),logprobs:Ol({content:El(Ol({token:zu(),logprob:al(),top_logprobs:El(Ol({token:zu(),logprob:al()}))})).nullish()}).nullish(),finish_reason:zu().nullish()})),usage:up}),cp=Pl([Ol({id:zu().nullish(),created:al().nullish(),model:zu().nullish(),choices:El(Ol({delta:Ol({role:Jl(["assistant"]).nullish(),content:zu().nullish(),tool_calls:El(Ol({index:al(),id:zu().nullish(),type:Hl("function").nullish(),function:Ol({name:zu().nullish(),arguments:zu().nullish()})})).nullish(),annotations:El(Ol({type:Hl("url_citation"),start_index:al(),end_index:al(),url:zu(),title:zu()})).nullish()}).nullish(),logprobs:Ol({content:El(Ol({token:zu(),logprob:al(),top_logprobs:El(Ol({token:zu(),logprob:al()}))})).nullish()}).nullish(),finish_reason:zu().nullish(),index:al()})),usage:up}),Kd]);function dp(e){return(e.startsWith("o")||e.startsWith("gpt-5"))&&!e.startsWith("gpt-5-chat")}function pp(e){var t,n;return dp(e)?null!=(n=null==(t=mp[e])?void 0:t.systemMessageMode)?n:"developer":"system"}var mp={"o1-mini":{systemMessageMode:"remove"},"o1-mini-2024-09-12":{systemMessageMode:"remove"},"o1-preview":{systemMessageMode:"remove"},"o1-preview-2024-09-12":{systemMessageMode:"remove"},o3:{systemMessageMode:"developer"},"o3-2025-04-16":{systemMessageMode:"developer"},"o3-mini":{systemMessageMode:"developer"},"o3-mini-2025-01-31":{systemMessageMode:"developer"},"o4-mini":{systemMessageMode:"developer"},"o4-mini-2025-04-16":{systemMessageMode:"developer"}};function hp({id:e,model:t,created:n}){return{id:null!=e?e:void 0,modelId:null!=t?t:void 0,timestamp:null!=n?new Date(1e3*n):void 0}}function gp(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var fp=Ol({echo:dl().optional(),logitBias:Zl(zu(),al()).optional(),suffix:zu().optional(),user:zu().optional(),logprobs:Pl([dl(),al()]).optional()}),vp=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={},this.modelId=e,this.config=t}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:o,presencePenalty:s,stopSequences:a,responseFormat:u,tools:l,toolChoice:c,seed:d,providerOptions:p}){const m=[],h={...await Nd({provider:"openai",providerOptions:p,schema:fp}),...await Nd({provider:this.providerOptionsName,providerOptions:p,schema:fp})};null!=i&&m.push({type:"unsupported-setting",setting:"topK"}),(null==l?void 0:l.length)&&m.push({type:"unsupported-setting",setting:"tools"}),null!=c&&m.push({type:"unsupported-setting",setting:"toolChoice"}),null!=u&&"text"!==u.type&&m.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});const{prompt:g,stopSequences:f}=function({prompt:e,user:t="user",assistant:n="assistant"}){let r="";"system"===e[0].role&&(r+=`${e[0].content}\n\n`,e=e.slice(1));for(const{role:i,content:o}of e)switch(i){case"system":throw new Ye({message:"Unexpected system message in prompt: ${content}",prompt:e});case"user":r+=`${t}:\n${o.map((e=>{if("text"===e.type)return e.text})).filter(Boolean).join("")}\n\n`;break;case"assistant":r+=`${n}:\n${o.map((e=>{switch(e.type){case"text":return e.text;case"tool-call":throw new At({functionality:"tool-call messages"})}})).join("")}\n\n`;break;case"tool":throw new At({functionality:"tool messages"});default:throw new Error(`Unsupported role: ${i}`)}return r+=`${n}:\n`,{prompt:r,stopSequences:[`\n${t}:`]}}({prompt:e}),v=[...null!=f?f:[],...null!=a?a:[]];return{args:{model:this.modelId,echo:h.echo,logit_bias:h.logitBias,logprobs:!0===(null==h?void 0:h.logprobs)?0:!1===(null==h?void 0:h.logprobs)||null==h?void 0:h.logprobs,suffix:h.suffix,user:h.user,max_tokens:t,temperature:n,top_p:r,frequency_penalty:o,presence_penalty:s,seed:d,prompt:g,stop:v.length>0?v:void 0},warnings:m}}async doGenerate(e){var t,n,r;const{args:i,warnings:o}=await this.getArgs(e),{responseHeaders:s,value:a,rawValue:u}=await Ad({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:pd(this.config.headers(),e.headers),body:i,failedResponseHandler:Gd,successfulResponseHandler:Md(_p),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=a.choices[0],c={openai:{}};return null!=l.logprobs&&(c.openai.logprobs=l.logprobs),{content:[{type:"text",text:l.text}],usage:{inputTokens:null==(t=a.usage)?void 0:t.prompt_tokens,outputTokens:null==(n=a.usage)?void 0:n.completion_tokens,totalTokens:null==(r=a.usage)?void 0:r.total_tokens},finishReason:gp(l.finish_reason),request:{body:i},response:{...hp(a),headers:s,body:u},providerMetadata:c,warnings:o}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:i,value:o}=await Ad({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:pd(this.config.headers(),e.headers),body:r,failedResponseHandler:Gd,successfulResponseHandler:Dd(bp),abortSignal:e.abortSignal,fetch:this.config.fetch});let s="unknown";const a={openai:{}},u={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let l=!0;return{stream:o.pipeThrough(new TransformStream({start(e){e.enqueue({type:"stream-start",warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:"raw",rawValue:t.rawValue}),!t.success)return s="error",void n.enqueue({type:"error",error:t.error});const r=t.value;if("error"in r)return s="error",void n.enqueue({type:"error",error:r.error});l&&(l=!1,n.enqueue({type:"response-metadata",...hp(r)}),n.enqueue({type:"text-start",id:"0"})),null!=r.usage&&(u.inputTokens=r.usage.prompt_tokens,u.outputTokens=r.usage.completion_tokens,u.totalTokens=r.usage.total_tokens);const i=r.choices[0];null!=(null==i?void 0:i.finish_reason)&&(s=gp(i.finish_reason)),null!=(null==i?void 0:i.logprobs)&&(a.openai.logprobs=i.logprobs),null!=(null==i?void 0:i.text)&&i.text.length>0&&n.enqueue({type:"text-delta",id:"0",delta:i.text})},flush(e){l||e.enqueue({type:"text-end",id:"0"}),e.enqueue({type:"finish",finishReason:s,providerMetadata:a,usage:u})}})),request:{body:r},response:{headers:i}}}},yp=Ol({prompt_tokens:al(),completion_tokens:al(),total_tokens:al()}),_p=Ol({id:zu().nullish(),created:al().nullish(),model:zu().nullish(),choices:El(Ol({text:zu(),finish_reason:zu(),logprobs:Ol({tokens:El(zu()),token_logprobs:El(al()),top_logprobs:El(Zl(zu(),al())).nullish()}).nullish()})),usage:yp.nullish()}),bp=Pl([Ol({id:zu().nullish(),created:al().nullish(),model:zu().nullish(),choices:El(Ol({text:zu(),finish_reason:zu().nullish(),index:al(),logprobs:Ol({tokens:El(zu()),token_logprobs:El(al()),top_logprobs:El(Zl(zu(),al())).nullish()}).nullish()})),usage:yp.nullish()}),Kd]),wp=Ol({dimensions:al().optional(),user:zu().optional()}),kp=class{constructor(e,t){this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){var i;if(e.length>this.maxEmbeddingsPerCall)throw new kt({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const o=null!=(i=await Nd({provider:"openai",providerOptions:r,schema:wp}))?i:{},{responseHeaders:s,value:a,rawValue:u}=await Ad({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:pd(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:"float",dimensions:o.dimensions,user:o.user},failedResponseHandler:Gd,successfulResponseHandler:Md(xp),abortSignal:n,fetch:this.config.fetch});return{embeddings:a.data.map((e=>e.embedding)),usage:a.usage?{tokens:a.usage.prompt_tokens}:void 0,response:{headers:s,body:u}}}},xp=Ol({data:El(Ol({embedding:El(al())})),usage:Ol({prompt_tokens:al()}).nullish()}),Ip={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10},Sp=new Set(["gpt-image-1"]),$p=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get maxImagesPerCall(){var e;return null!=(e=Ip[this.modelId])?e:1}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:r,seed:i,providerOptions:o,headers:s,abortSignal:a}){var u,l,c,d;const p=[];null!=r&&p.push({type:"unsupported-setting",setting:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),null!=i&&p.push({type:"unsupported-setting",setting:"seed"});const m=null!=(c=null==(l=null==(u=this.config._internal)?void 0:u.currentDate)?void 0:l.call(u))?c:new Date,{value:h,responseHeaders:g}=await Ad({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:pd(this.config.headers(),s),body:{model:this.modelId,prompt:e,n:t,size:n,...null!=(d=o.openai)?d:{},...Sp.has(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:Gd,successfulResponseHandler:Md(Ep),abortSignal:a,fetch:this.config.fetch});return{images:h.data.map((e=>e.b64_json)),warnings:p,response:{timestamp:m,modelId:this.modelId,headers:g},providerMetadata:{openai:{images:h.data.map((e=>e.revised_prompt?{revisedPrompt:e.revised_prompt}:null))}}}}},Ep=Ol({data:El(Ol({b64_json:zu(),revised_prompt:zu().optional()}))}),Tp=Ol({container:Pl([zu(),Ol({fileIds:El(zu()).optional()})]).optional()}),Op={codeInterpreter:Rd({id:"openai.code_interpreter",name:"code_interpreter",inputSchema:Ol({})}),fileSearch:ip,webSearchPreview:sp};function Np(e,t){return!!t&&t.some((t=>e.startsWith(t)))}var Cp=Ol({itemId:zu().nullish(),reasoningEncryptedContent:zu().nullish()});function Ap({finishReason:e,hasToolCalls:t}){switch(e){case void 0:case null:return t?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return t?"tool-calls":"unknown"}}var Pp=Ol({type:Hl("web_search_call"),id:zu(),status:zu(),action:Ul("type",[Ol({type:Hl("search"),query:zu()}),Ol({type:Hl("open_page"),url:zu()}),Ol({type:Hl("find"),url:zu(),pattern:zu()})]).nullish()}),Rp=El(Ol({token:zu(),logprob:al(),top_logprobs:El(Ol({token:zu(),logprob:al()}))})),Up=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({maxOutputTokens:e,temperature:t,stopSequences:n,topP:r,topK:i,presencePenalty:o,frequencyPenalty:s,seed:a,prompt:u,providerOptions:l,tools:c,toolChoice:d,responseFormat:p}){var m,h;const g=[],f=function(e){const t=e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat"),n=e.startsWith("gpt-4")||e.startsWith("gpt-5-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-nano")&&!e.startsWith("gpt-5-chat")||e.startsWith("o3")||e.startsWith("o4-mini"),r={requiredAutoTruncation:!1,systemMessageMode:"system",supportsFlexProcessing:t,supportsPriorityProcessing:n};if(e.startsWith("gpt-5-chat"))return{...r,isReasoningModel:!1};if(e.startsWith("o")||e.startsWith("gpt-5")||e.startsWith("codex-")||e.startsWith("computer-use"))return e.startsWith("o1-mini")||e.startsWith("o1-preview")?{...r,isReasoningModel:!0,systemMessageMode:"remove"}:{...r,isReasoningModel:!0,systemMessageMode:"developer"};return{...r,isReasoningModel:!1}}(this.modelId);null!=i&&g.push({type:"unsupported-setting",setting:"topK"}),null!=a&&g.push({type:"unsupported-setting",setting:"seed"}),null!=o&&g.push({type:"unsupported-setting",setting:"presencePenalty"}),null!=s&&g.push({type:"unsupported-setting",setting:"frequencyPenalty"}),null!=n&&g.push({type:"unsupported-setting",setting:"stopSequences"});const{messages:v,warnings:y}=await async function({prompt:e,systemMessageMode:t,fileIdPrefixes:n}){var r,i,o,s,a,u;const l=[],c=[];for(const{role:d,content:p}of e)switch(d){case"system":switch(t){case"system":l.push({role:"system",content:p});break;case"developer":l.push({role:"developer",content:p});break;case"remove":c.push({type:"other",message:"system messages are removed for this model"});break;default:throw new Error(`Unsupported system message mode: ${t}`)}break;case"user":l.push({role:"user",content:p.map(((e,t)=>{var r,i,o;switch(e.type){case"text":return{type:"input_text",text:e.text};case"file":if(e.mediaType.startsWith("image/")){const t="image/*"===e.mediaType?"image/jpeg":e.mediaType;return{type:"input_image",...e.data instanceof URL?{image_url:e.data.toString()}:"string"==typeof e.data&&Np(e.data,n)?{file_id:e.data}:{image_url:`data:${t};base64,${Hd(e.data)}`},detail:null==(i=null==(r=e.providerOptions)?void 0:r.openai)?void 0:i.imageDetail}}if("application/pdf"===e.mediaType)return e.data instanceof URL?{type:"input_file",file_url:e.data.toString()}:{type:"input_file",..."string"==typeof e.data&&Np(e.data,n)?{file_id:e.data}:{filename:null!=(o=e.filename)?o:`part-${t}.pdf`,file_data:`data:application/pdf;base64,${Hd(e.data)}`}};throw new At({functionality:`file part media type ${e.mediaType}`})}}))});break;case"assistant":{const e={};for(const t of p)switch(t.type){case"text":l.push({role:"assistant",content:[{type:"output_text",text:t.text}],id:null!=(o=null==(i=null==(r=t.providerOptions)?void 0:r.openai)?void 0:i.itemId)?o:void 0});break;case"tool-call":if(t.providerExecuted)break;l.push({type:"function_call",call_id:t.toolCallId,name:t.toolName,arguments:JSON.stringify(t.input),id:null!=(u=null==(a=null==(s=t.providerOptions)?void 0:s.openai)?void 0:a.itemId)?u:void 0});break;case"tool-result":c.push({type:"other",message:"tool result parts in assistant messages are not supported for OpenAI responses"});break;case"reasoning":{const n=await Nd({provider:"openai",providerOptions:t.providerOptions,schema:Cp}),r=null==n?void 0:n.itemId;if(null!=r){const i=e[r],o=[];t.text.length>0?o.push({type:"summary_text",text:t.text}):void 0!==i&&c.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(t)}.`}),void 0===i?(e[r]={type:"reasoning",id:r,encrypted_content:null==n?void 0:n.reasoningEncryptedContent,summary:o},l.push(e[r])):i.summary.push(...o)}else c.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(t)}.`});break}}break}case"tool":for(const e of p){const t=e.output;let n;switch(t.type){case"text":case"error-text":n=t.value;break;case"content":case"json":case"error-json":n=JSON.stringify(t.value)}l.push({type:"function_call_output",call_id:e.toolCallId,output:n})}break;default:throw new Error(`Unsupported role: ${d}`)}return{messages:l,warnings:c}}({prompt:u,systemMessageMode:f.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes});g.push(...y);const _=await Nd({provider:"openai",providerOptions:l,schema:qp}),b=null!=(m=null==_?void 0:_.strictJsonSchema)&&m,w="number"==typeof(null==_?void 0:_.logprobs)?null==_?void 0:_.logprobs:!0===(null==_?void 0:_.logprobs)?20:void 0,k=w?Array.isArray(null==_?void 0:_.include)?[...null==_?void 0:_.include,"message.output_text.logprobs"]:["message.output_text.logprobs"]:null==_?void 0:_.include,x={model:this.modelId,input:v,temperature:t,top_p:r,max_output_tokens:e,...("json"===(null==p?void 0:p.type)||(null==_?void 0:_.textVerbosity))&&{text:{..."json"===(null==p?void 0:p.type)&&{format:null!=p.schema?{type:"json_schema",strict:b,name:null!=(h=p.name)?h:"response",description:p.description,schema:p.schema}:{type:"json_object"}},...(null==_?void 0:_.textVerbosity)&&{verbosity:_.textVerbosity}}},metadata:null==_?void 0:_.metadata,parallel_tool_calls:null==_?void 0:_.parallelToolCalls,previous_response_id:null==_?void 0:_.previousResponseId,store:null==_?void 0:_.store,user:null==_?void 0:_.user,instructions:null==_?void 0:_.instructions,service_tier:null==_?void 0:_.serviceTier,include:k,prompt_cache_key:null==_?void 0:_.promptCacheKey,safety_identifier:null==_?void 0:_.safetyIdentifier,top_logprobs:w,...f.isReasoningModel&&(null!=(null==_?void 0:_.reasoningEffort)||null!=(null==_?void 0:_.reasoningSummary))&&{reasoning:{...null!=(null==_?void 0:_.reasoningEffort)&&{effort:_.reasoningEffort},...null!=(null==_?void 0:_.reasoningSummary)&&{summary:_.reasoningSummary}}},...f.requiredAutoTruncation&&{truncation:"auto"}};f.isReasoningModel?(null!=x.temperature&&(x.temperature=void 0,g.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),null!=x.top_p&&(x.top_p=void 0,g.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"}))):(null!=(null==_?void 0:_.reasoningEffort)&&g.push({type:"unsupported-setting",setting:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),null!=(null==_?void 0:_.reasoningSummary)&&g.push({type:"unsupported-setting",setting:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),"flex"!==(null==_?void 0:_.serviceTier)||f.supportsFlexProcessing||(g.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete x.service_tier),"priority"!==(null==_?void 0:_.serviceTier)||f.supportsPriorityProcessing||(g.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete x.service_tier);const{tools:I,toolChoice:S,toolWarnings:$}=function({tools:e,toolChoice:t,strictJsonSchema:n}){const r=[];if(null==(e=(null==e?void 0:e.length)?e:void 0))return{tools:void 0,toolChoice:void 0,toolWarnings:r};const i=[];for(const s of e)switch(s.type){case"function":i.push({type:"function",name:s.name,description:s.description,parameters:s.inputSchema,strict:n});break;case"provider-defined":switch(s.id){case"openai.file_search":{const e=rp.parse(s.args);i.push({type:"file_search",vector_store_ids:e.vectorStoreIds,max_num_results:e.maxNumResults,ranking_options:e.ranking?{ranker:e.ranking.ranker}:void 0,filters:e.filters});break}case"openai.web_search_preview":{const e=op.parse(s.args);i.push({type:"web_search_preview",search_context_size:e.searchContextSize,user_location:e.userLocation});break}case"openai.code_interpreter":{const e=Tp.parse(s.args);i.push({type:"code_interpreter",container:null==e.container?{type:"auto",file_ids:void 0}:"string"==typeof e.container?e.container:{type:"auto",file_ids:e.container.fileIds}});break}default:r.push({type:"unsupported-tool",tool:s})}break;default:r.push({type:"unsupported-tool",tool:s})}if(null==t)return{tools:i,toolChoice:void 0,toolWarnings:r};const o=t.type;switch(o){case"auto":case"none":case"required":return{tools:i,toolChoice:o,toolWarnings:r};case"tool":return{tools:i,toolChoice:"code_interpreter"===t.toolName||"file_search"===t.toolName||"web_search_preview"===t.toolName?{type:t.toolName}:{type:"function",name:t.toolName},toolWarnings:r};default:throw new At({functionality:`tool choice type: ${o}`})}}({tools:c,toolChoice:d,strictJsonSchema:b});return{args:{...x,tools:I,tool_choice:S},warnings:[...g,...$]}}async doGenerate(e){var t,n,r,i,o,s,a,u,l,c,d,p,m,h;const{args:g,warnings:f}=await this.getArgs(e),v=this.config.url({path:"/responses",modelId:this.modelId}),{responseHeaders:y,value:_,rawValue:b}=await Ad({url:v,headers:pd(this.config.headers(),e.headers),body:g,failedResponseHandler:Gd,successfulResponseHandler:Md(Ol({id:zu(),created_at:al(),error:Ol({code:zu(),message:zu()}).nullish(),model:zu(),output:El(Ul("type",[Ol({type:Hl("message"),role:Hl("assistant"),id:zu(),content:El(Ol({type:Hl("output_text"),text:zu(),logprobs:Rp.nullish(),annotations:El(Ul("type",[Ol({type:Hl("url_citation"),start_index:al(),end_index:al(),url:zu(),title:zu()}),Ol({type:Hl("file_citation"),start_index:al(),end_index:al(),file_id:zu(),quote:zu()})]))}))}),Ol({type:Hl("function_call"),call_id:zu(),name:zu(),arguments:zu(),id:zu()}),Pp,Ol({type:Hl("computer_call"),id:zu(),status:zu().optional()}),Ol({type:Hl("file_search_call"),id:zu(),status:zu().optional(),queries:El(zu()).nullish(),results:El(Ol({attributes:Ol({file_id:zu(),filename:zu(),score:al(),text:zu()})})).nullish()}),Ol({type:Hl("reasoning"),id:zu(),encrypted_content:zu().nullish(),summary:El(Ol({type:Hl("summary_text"),text:zu()}))})])),incomplete_details:Ol({reason:zu()}).nullable(),usage:jp})),abortSignal:e.abortSignal,fetch:this.config.fetch});if(_.error)throw new Ue({message:_.error.message,url:v,requestBodyValues:g,statusCode:400,responseHeaders:y,responseBody:b,isRetryable:!1});const w=[],k=[];for(const I of _.output)switch(I.type){case"reasoning":0===I.summary.length&&I.summary.push({type:"summary_text",text:""});for(const e of I.summary)w.push({type:"reasoning",text:e.text,providerMetadata:{openai:{itemId:I.id,reasoningEncryptedContent:null!=(t=I.encrypted_content)?t:null}}});break;case"message":for(const t of I.content){(null==(r=null==(n=e.providerOptions)?void 0:n.openai)?void 0:r.logprobs)&&t.logprobs&&k.push(t.logprobs),w.push({type:"text",text:t.text,providerMetadata:{openai:{itemId:I.id}}});for(const e of t.annotations)"url_citation"===e.type?w.push({type:"source",sourceType:"url",id:null!=(s=null==(o=(i=this.config).generateId)?void 0:o.call(i))?s:gd(),url:e.url,title:e.title}):"file_citation"===e.type&&w.push({type:"source",sourceType:"document",id:null!=(l=null==(u=(a=this.config).generateId)?void 0:u.call(a))?l:gd(),mediaType:"text/plain",title:e.quote,filename:e.file_id})}break;case"function_call":w.push({type:"tool-call",toolCallId:I.call_id,toolName:I.name,input:I.arguments,providerMetadata:{openai:{itemId:I.id}}});break;case"web_search_call":w.push({type:"tool-call",toolCallId:I.id,toolName:"web_search_preview",input:JSON.stringify({action:I.action}),providerExecuted:!0}),w.push({type:"tool-result",toolCallId:I.id,toolName:"web_search_preview",result:{status:I.status},providerExecuted:!0});break;case"computer_call":w.push({type:"tool-call",toolCallId:I.id,toolName:"computer_use",input:"",providerExecuted:!0}),w.push({type:"tool-result",toolCallId:I.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:I.status||"completed"},providerExecuted:!0});break;case"file_search_call":w.push({type:"tool-call",toolCallId:I.id,toolName:"file_search",input:"",providerExecuted:!0}),w.push({type:"tool-result",toolCallId:I.id,toolName:"file_search",result:{type:"file_search_tool_result",status:I.status||"completed",...I.queries&&{queries:I.queries},...I.results&&{results:I.results}},providerExecuted:!0})}const x={openai:{responseId:_.id}};return k.length>0&&(x.openai.logprobs=k),{content:w,finishReason:Ap({finishReason:null==(c=_.incomplete_details)?void 0:c.reason,hasToolCalls:w.some((e=>"tool-call"===e.type))}),usage:{inputTokens:_.usage.input_tokens,outputTokens:_.usage.output_tokens,totalTokens:_.usage.input_tokens+_.usage.output_tokens,reasoningTokens:null!=(p=null==(d=_.usage.output_tokens_details)?void 0:d.reasoning_tokens)?p:void 0,cachedInputTokens:null!=(h=null==(m=_.usage.input_tokens_details)?void 0:m.cached_tokens)?h:void 0},request:{body:g},response:{id:_.id,timestamp:new Date(1e3*_.created_at),modelId:_.model,headers:y,body:b},providerMetadata:x,warnings:f}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),{responseHeaders:r,value:i}=await Ad({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:pd(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:Gd,successfulResponseHandler:Dd(Mp),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=this;let s="unknown";const a={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},u=[];let l=null;const c={};let d=!1;const p={};return{stream:i.pipeThrough(new TransformStream({start(e){e.enqueue({type:"stream-start",warnings:n})},transform(t,n){var r,i,m,h,g,f,v,y,_,b,w,k,x,I,S,$;if(e.includeRawChunks&&n.enqueue({type:"raw",rawValue:t.rawValue}),!t.success)return s="error",void n.enqueue({type:"error",error:t.error});const E=t.value;if(Zp(E))"function_call"===E.item.type?(c[E.output_index]={toolName:E.item.name,toolCallId:E.item.call_id},n.enqueue({type:"tool-input-start",id:E.item.call_id,toolName:E.item.name})):"web_search_call"===E.item.type?(c[E.output_index]={toolName:"web_search_preview",toolCallId:E.item.id},n.enqueue({type:"tool-input-start",id:E.item.id,toolName:"web_search_preview"})):"computer_call"===E.item.type?(c[E.output_index]={toolName:"computer_use",toolCallId:E.item.id},n.enqueue({type:"tool-input-start",id:E.item.id,toolName:"computer_use"})):"file_search_call"===E.item.type?(c[E.output_index]={toolName:"file_search",toolCallId:E.item.id},n.enqueue({type:"tool-input-start",id:E.item.id,toolName:"file_search"})):"message"===E.item.type?n.enqueue({type:"text-start",id:E.item.id,providerMetadata:{openai:{itemId:E.item.id}}}):function(e){return Zp(e)&&"reasoning"===e.item.type}(E)&&(p[E.item.id]={encryptedContent:E.item.encrypted_content,summaryParts:[0]},n.enqueue({type:"reasoning-start",id:`${E.item.id}:0`,providerMetadata:{openai:{itemId:E.item.id,reasoningEncryptedContent:null!=(r=E.item.encrypted_content)?r:null}}}));else if(Lp(E)){if("function_call"===E.item.type)c[E.output_index]=void 0,d=!0,n.enqueue({type:"tool-input-end",id:E.item.call_id}),n.enqueue({type:"tool-call",toolCallId:E.item.call_id,toolName:E.item.name,input:E.item.arguments,providerMetadata:{openai:{itemId:E.item.id}}});else if("web_search_call"===E.item.type)c[E.output_index]=void 0,d=!0,n.enqueue({type:"tool-input-end",id:E.item.id}),n.enqueue({type:"tool-call",toolCallId:E.item.id,toolName:"web_search_preview",input:JSON.stringify({action:E.item.action}),providerExecuted:!0}),n.enqueue({type:"tool-result",toolCallId:E.item.id,toolName:"web_search_preview",result:{status:E.item.status},providerExecuted:!0});else if("computer_call"===E.item.type)c[E.output_index]=void 0,d=!0,n.enqueue({type:"tool-input-end",id:E.item.id}),n.enqueue({type:"tool-call",toolCallId:E.item.id,toolName:"computer_use",input:"",providerExecuted:!0}),n.enqueue({type:"tool-result",toolCallId:E.item.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:E.item.status||"completed"},providerExecuted:!0});else if("file_search_call"===E.item.type)c[E.output_index]=void 0,d=!0,n.enqueue({type:"tool-input-end",id:E.item.id}),n.enqueue({type:"tool-call",toolCallId:E.item.id,toolName:"file_search",input:"",providerExecuted:!0}),n.enqueue({type:"tool-result",toolCallId:E.item.id,toolName:"file_search",result:{type:"file_search_tool_result",status:E.item.status||"completed",...E.item.queries&&{queries:E.item.queries},...E.item.results&&{results:E.item.results}},providerExecuted:!0});else if("message"===E.item.type)n.enqueue({type:"text-end",id:E.item.id});else if(function(e){return Lp(e)&&"reasoning"===e.item.type}(E)){const e=p[E.item.id];for(const t of e.summaryParts)n.enqueue({type:"reasoning-end",id:`${E.item.id}:${t}`,providerMetadata:{openai:{itemId:E.item.id,reasoningEncryptedContent:null!=(i=E.item.encrypted_content)?i:null}}});delete p[E.item.id]}}else if(function(e){return"response.function_call_arguments.delta"===e.type}(E)){const e=c[E.output_index];null!=e&&n.enqueue({type:"tool-input-delta",id:e.toolCallId,delta:E.delta})}else!function(e){return"response.created"===e.type}(E)?!function(e){return"response.output_text.delta"===e.type}(E)?!function(e){return"response.reasoning_summary_part.added"===e.type}(E)?!function(e){return"response.reasoning_summary_text.delta"===e.type}(E)?!function(e){return"response.completed"===e.type||"response.incomplete"===e.type}(E)?!function(e){return"response.output_text.annotation.added"===e.type}(E)?function(e){return"error"===e.type}(E)&&n.enqueue({type:"error",error:E}):"url_citation"===E.annotation.type?n.enqueue({type:"source",sourceType:"url",id:null!=(x=null==(k=(w=o.config).generateId)?void 0:k.call(w))?x:gd(),url:E.annotation.url,title:E.annotation.title}):"file_citation"===E.annotation.type&&n.enqueue({type:"source",sourceType:"document",id:null!=($=null==(S=(I=o.config).generateId)?void 0:S.call(I))?$:gd(),mediaType:"text/plain",title:E.annotation.quote,filename:E.annotation.file_id}):(s=Ap({finishReason:null==(f=E.response.incomplete_details)?void 0:f.reason,hasToolCalls:d}),a.inputTokens=E.response.usage.input_tokens,a.outputTokens=E.response.usage.output_tokens,a.totalTokens=E.response.usage.input_tokens+E.response.usage.output_tokens,a.reasoningTokens=null!=(y=null==(v=E.response.usage.output_tokens_details)?void 0:v.reasoning_tokens)?y:void 0,a.cachedInputTokens=null!=(b=null==(_=E.response.usage.input_tokens_details)?void 0:_.cached_tokens)?b:void 0):n.enqueue({type:"reasoning-delta",id:`${E.item_id}:${E.summary_index}`,delta:E.delta,providerMetadata:{openai:{itemId:E.item_id}}}):E.summary_index>0&&(null==(m=p[E.item_id])||m.summaryParts.push(E.summary_index),n.enqueue({type:"reasoning-start",id:`${E.item_id}:${E.summary_index}`,providerMetadata:{openai:{itemId:E.item_id,reasoningEncryptedContent:null!=(g=null==(h=p[E.item_id])?void 0:h.encryptedContent)?g:null}}})):(n.enqueue({type:"text-delta",id:E.item_id,delta:E.delta}),E.logprobs&&u.push(E.logprobs)):(l=E.response.id,n.enqueue({type:"response-metadata",id:E.response.id,timestamp:new Date(1e3*E.response.created_at),modelId:E.response.model}))},flush(e){const t={openai:{responseId:l}};u.length>0&&(t.openai.logprobs=u),e.enqueue({type:"finish",finishReason:s,usage:a,providerMetadata:t})}})),request:{body:t},response:{headers:r}}}},jp=Ol({input_tokens:al(),input_tokens_details:Ol({cached_tokens:al().nullish()}).nullish(),output_tokens:al(),output_tokens_details:Ol({reasoning_tokens:al().nullish()}).nullish()}),zp=Ol({type:Hl("response.output_text.delta"),item_id:zu(),delta:zu(),logprobs:Rp.nullish()}),Dp=Ol({type:Hl("error"),code:zu(),message:zu(),param:zu().nullish(),sequence_number:al()}),Mp=Pl([zp,Ol({type:Jl(["response.completed","response.incomplete"]),response:Ol({incomplete_details:Ol({reason:zu()}).nullish(),usage:jp})}),Ol({type:Hl("response.created"),response:Ol({id:zu(),created_at:al(),model:zu()})}),Ol({type:Hl("response.output_item.added"),output_index:al(),item:Ul("type",[Ol({type:Hl("message"),id:zu()}),Ol({type:Hl("reasoning"),id:zu(),encrypted_content:zu().nullish()}),Ol({type:Hl("function_call"),id:zu(),call_id:zu(),name:zu(),arguments:zu()}),Ol({type:Hl("web_search_call"),id:zu(),status:zu(),action:Ol({type:Hl("search"),query:zu().optional()}).nullish()}),Ol({type:Hl("computer_call"),id:zu(),status:zu()}),Ol({type:Hl("file_search_call"),id:zu(),status:zu(),queries:El(zu()).nullish(),results:El(Ol({attributes:Ol({file_id:zu(),filename:zu(),score:al(),text:zu()})})).optional()})])}),Ol({type:Hl("response.output_item.done"),output_index:al(),item:Ul("type",[Ol({type:Hl("message"),id:zu()}),Ol({type:Hl("reasoning"),id:zu(),encrypted_content:zu().nullish()}),Ol({type:Hl("function_call"),id:zu(),call_id:zu(),name:zu(),arguments:zu(),status:Hl("completed")}),Pp,Ol({type:Hl("computer_call"),id:zu(),status:Hl("completed")}),Ol({type:Hl("file_search_call"),id:zu(),status:Hl("completed"),queries:El(zu()).nullish(),results:El(Ol({attributes:Ol({file_id:zu(),filename:zu(),score:al(),text:zu()})})).nullish()})])}),Ol({type:Hl("response.function_call_arguments.delta"),item_id:zu(),output_index:al(),delta:zu()}),Ol({type:Hl("response.output_text.annotation.added"),annotation:Ul("type",[Ol({type:Hl("url_citation"),url:zu(),title:zu()}),Ol({type:Hl("file_citation"),file_id:zu(),quote:zu()})])}),Ol({type:Hl("response.reasoning_summary_part.added"),item_id:zu(),summary_index:al()}),Ol({type:Hl("response.reasoning_summary_text.delta"),item_id:zu(),summary_index:al(),delta:zu()}),Dp,Ol({type:zu()}).loose()]);function Lp(e){return"response.output_item.done"===e.type}function Zp(e){return"response.output_item.added"===e.type}var qp=Ol({metadata:_l().nullish(),parallelToolCalls:dl().nullish(),previousResponseId:zu().nullish(),store:dl().nullish(),user:zu().nullish(),reasoningEffort:zu().nullish(),strictJsonSchema:dl().nullish(),instructions:zu().nullish(),reasoningSummary:zu().nullish(),serviceTier:Jl(["auto","flex","priority"]).nullish(),include:El(Jl(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),textVerbosity:Jl(["low","medium","high"]).nullish(),promptCacheKey:zu().nullish(),safetyIdentifier:zu().nullish(),logprobs:Pl([dl(),al().min(1).max(20)]).optional()}),Fp=Ol({instructions:zu().nullish(),speed:al().min(.25).max(4).default(1).nullish()}),Wp=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({text:e,voice:t="alloy",outputFormat:n="mp3",speed:r,instructions:i,language:o,providerOptions:s}){const a=[],u=await Nd({provider:"openai",providerOptions:s,schema:Fp}),l={model:this.modelId,input:e,voice:t,response_format:"mp3",speed:r,instructions:i};if(n&&(["mp3","opus","aac","flac","wav","pcm"].includes(n)?l.response_format=n:a.push({type:"unsupported-setting",setting:"outputFormat",details:`Unsupported output format: ${n}. Using mp3 instead.`})),u){const e={};for(const t in e){const n=e[t];void 0!==n&&(l[t]=n)}}return o&&a.push({type:"unsupported-setting",setting:"language",details:`OpenAI speech models do not support language selection. Language parameter "${o}" was ignored.`}),{requestBody:l,warnings:a}}async doGenerate(e){var t,n,r;const i=null!=(r=null==(n=null==(t=this.config._internal)?void 0:t.currentDate)?void 0:n.call(t))?r:new Date,{requestBody:o,warnings:s}=await this.getArgs(e),{value:a,responseHeaders:u,rawValue:l}=await Ad({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:pd(this.config.headers(),e.headers),body:o,failedResponseHandler:Gd,successfulResponseHandler:async({response:e,url:t,requestBodyValues:n})=>{const r=md(e);if(!e.body)throw new Ue({message:"Response body is empty",url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0});try{const t=await e.arrayBuffer();return{responseHeaders:r,value:new Uint8Array(t)}}catch(i){throw new Ue({message:"Failed to read response as array buffer",url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0,cause:i})}},abortSignal:e.abortSignal,fetch:this.config.fetch});return{audio:a,warnings:s,request:{body:JSON.stringify(o)},response:{timestamp:i,modelId:this.modelId,headers:u,body:l}}}},Jp=Ol({include:El(zu()).optional(),language:zu().optional(),prompt:zu().optional(),temperature:al().min(0).max(1).default(0).optional(),timestampGranularities:El(Jl(["word","segment"])).default(["segment"]).optional()}),Bp={afrikaans:"af",arabic:"ar",armenian:"hy",azerbaijani:"az",belarusian:"be",bosnian:"bs",bulgarian:"bg",catalan:"ca",chinese:"zh",croatian:"hr",czech:"cs",danish:"da",dutch:"nl",english:"en",estonian:"et",finnish:"fi",french:"fr",galician:"gl",german:"de",greek:"el",hebrew:"he",hindi:"hi",hungarian:"hu",icelandic:"is",indonesian:"id",italian:"it",japanese:"ja",kannada:"kn",kazakh:"kk",korean:"ko",latvian:"lv",lithuanian:"lt",macedonian:"mk",malay:"ms",marathi:"mr",maori:"mi",nepali:"ne",norwegian:"no",persian:"fa",polish:"pl",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"sr",slovak:"sk",slovenian:"sl",spanish:"es",swahili:"sw",swedish:"sv",tagalog:"tl",tamil:"ta",thai:"th",turkish:"tr",ukrainian:"uk",urdu:"ur",vietnamese:"vi",welsh:"cy"},Hp=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({audio:e,mediaType:t,providerOptions:n}){const r=await Nd({provider:"openai",providerOptions:n,schema:Jp}),i=new FormData,o=e instanceof Uint8Array?new Blob([e]):new Blob([Bd(e)]);if(i.append("model",this.modelId),i.append("file",new File([o],"audio",{type:t})),r){const e={include:r.include,language:r.language,prompt:r.prompt,response_format:"verbose_json",temperature:r.temperature,timestamp_granularities:r.timestampGranularities};for(const[t,n]of Object.entries(e))null!=n&&i.append(t,String(n))}return{formData:i,warnings:[]}}async doGenerate(e){var t,n,r,i,o,s,a,u;const l=null!=(r=null==(n=null==(t=this.config._internal)?void 0:t.currentDate)?void 0:n.call(t))?r:new Date,{formData:c,warnings:d}=await this.getArgs(e),{value:p,responseHeaders:m,rawValue:h}=await(async({url:e,headers:t,formData:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:o,fetch:s})=>Pd({url:e,headers:t,body:{content:n,values:Object.fromEntries(n.entries())},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:o,fetch:s}))({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:pd(this.config.headers(),e.headers),formData:c,failedResponseHandler:Gd,successfulResponseHandler:Md(Vp),abortSignal:e.abortSignal,fetch:this.config.fetch}),g=null!=p.language&&p.language in Bp?Bp[p.language]:void 0;return{text:p.text,segments:null!=(a=null!=(s=null==(i=p.segments)?void 0:i.map((e=>({text:e.text,startSecond:e.start,endSecond:e.end}))))?s:null==(o=p.words)?void 0:o.map((e=>({text:e.word,startSecond:e.start,endSecond:e.end}))))?a:[],language:g,durationInSeconds:null!=(u=p.duration)?u:void 0,warnings:d,response:{timestamp:l,modelId:this.modelId,headers:m,body:h}}}},Vp=Ol({text:zu(),language:zu().nullish(),duration:al().nullish(),words:El(Ol({word:zu(),start:al(),end:al()})).nullish(),segments:El(Ol({id:al(),seek:al(),start:al(),end:al(),text:zu(),tokens:El(al()),temperature:al(),avg_logprob:al(),compression_ratio:al(),no_speech_prob:al()})).nullish()});function Kp(e={}){var t,n;const r=null!=(t=Vd(e.baseURL))?t:"https://api.openai.com/v1",i=null!=(n=e.name)?n:"openai",o=()=>({Authorization:`Bearer ${yd({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers}),s=t=>new kp(t,{provider:`${i}.embedding`,url:({path:e})=>`${r}${e}`,headers:o,fetch:e.fetch}),a=t=>new $p(t,{provider:`${i}.image`,url:({path:e})=>`${r}${e}`,headers:o,fetch:e.fetch}),u=t=>new Hp(t,{provider:`${i}.transcription`,url:({path:e})=>`${r}${e}`,headers:o,fetch:e.fetch}),l=t=>new Wp(t,{provider:`${i}.speech`,url:({path:e})=>`${r}${e}`,headers:o,fetch:e.fetch}),c=e=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return d(e)},d=t=>new Up(t,{provider:`${i}.responses`,url:({path:e})=>`${r}${e}`,headers:o,fetch:e.fetch,fileIdPrefixes:["file-"]}),p=function(e){return c(e)};return p.languageModel=c,p.chat=t=>new ap(t,{provider:`${i}.chat`,url:({path:e})=>`${r}${e}`,headers:o,fetch:e.fetch}),p.completion=t=>new vp(t,{provider:`${i}.completion`,url:({path:e})=>`${r}${e}`,headers:o,fetch:e.fetch}),p.responses=d,p.embedding=s,p.textEmbedding=s,p.textEmbeddingModel=s,p.image=a,p.imageModel=a,p.transcription=u,p.transcriptionModel=u,p.speech=l,p.speechModel=l,p.tools=Op,p}var Gp=Kp(),Yp=zd({errorSchema:Ol({type:Hl("error"),error:Ol({type:zu(),message:zu()})}),errorToMessage:e=>e.error.message}),Xp=Ol({citations:Ol({enabled:dl()}).optional(),title:zu().optional(),context:zu().optional()}),Qp=Ol({sendReasoning:dl().optional(),thinking:Ol({type:Pl([Hl("enabled"),Hl("disabled")]),budgetTokens:al().optional()}).optional(),disableParallelToolUse:dl().optional()});function em(e){var t;const n=null==e?void 0:e.anthropic;return null!=(t=null==n?void 0:n.cacheControl)?t:null==n?void 0:n.cache_control}var tm=Ol({maxUses:al().optional(),allowedDomains:El(zu()).optional(),blockedDomains:El(zu()).optional(),userLocation:Ol({type:Hl("approximate"),city:zu().optional(),region:zu().optional(),country:zu().optional(),timezone:zu().optional()}).optional()}),nm=El(Ol({url:zu(),title:zu(),pageAge:zu().nullable(),encryptedContent:zu(),type:zu()})),rm=Ud({id:"anthropic.web_search_20250305",name:"web_search",inputSchema:Ol({query:zu()}),outputSchema:nm});function im(e){return"object"==typeof e&&null!==e&&"type"in e&&"web_search_20250305"===e.type}var om=Ol({type:Hl("code_execution_result"),stdout:zu(),stderr:zu(),return_code:al()}),sm=Ud({id:"anthropic.code_execution_20250522",name:"code_execution",inputSchema:Ol({code:zu()}),outputSchema:om});function am(e){if("string"==typeof e)return Buffer.from(e,"base64").toString("utf-8");if(e instanceof Uint8Array)return(new TextDecoder).decode(e);if(e instanceof URL)throw new At({functionality:"URL-based text documents are not supported for citations"});throw new At({functionality:"unsupported data type for text documents: "+typeof e})}async function um({prompt:e,sendReasoning:t,warnings:n}){var r,i,o,s,a;const u=new Set,l=function(e){const t=[];let n;for(const r of e){const{role:e}=r;switch(e){case"system":"system"!==(null==n?void 0:n.type)&&(n={type:"system",messages:[]},t.push(n)),n.messages.push(r);break;case"assistant":"assistant"!==(null==n?void 0:n.type)&&(n={type:"assistant",messages:[]},t.push(n)),n.messages.push(r);break;case"user":case"tool":"user"!==(null==n?void 0:n.type)&&(n={type:"user",messages:[]},t.push(n)),n.messages.push(r);break;default:throw new Error(`Unsupported role: ${e}`)}}return t}(e);let c;const d=[];async function p(e){var t,n;const r=await Nd({provider:"anthropic",providerOptions:e,schema:Xp});return null!=(n=null==(t=null==r?void 0:r.citations)?void 0:t.enabled)&&n}async function m(e){const t=await Nd({provider:"anthropic",providerOptions:e,schema:Xp});return{title:null==t?void 0:t.title,context:null==t?void 0:t.context}}for(let h=0;h<l.length;h++){const e=l[h],g=h===l.length-1,f=e.type;switch(f){case"system":if(null!=c)throw new At({functionality:"Multiple system messages that are separated by user/assistant messages"});c=e.messages.map((({content:e,providerOptions:t})=>({type:"text",text:e,cache_control:em(t)})));break;case"user":{const t=[];for(const n of e.messages){const{role:e,content:a}=n;switch(e){case"user":for(let e=0;e<a.length;e++){const s=a[e],l=e===a.length-1,c=null!=(r=em(s.providerOptions))?r:l?em(n.providerOptions):void 0;switch(s.type){case"text":t.push({type:"text",text:s.text,cache_control:c});break;case"file":if(s.mediaType.startsWith("image/"))t.push({type:"image",source:s.data instanceof URL?{type:"url",url:s.data.toString()}:{type:"base64",media_type:"image/*"===s.mediaType?"image/jpeg":s.mediaType,data:Hd(s.data)},cache_control:c});else if("application/pdf"===s.mediaType){u.add("pdfs-2024-09-25");const e=await p(s.providerOptions),n=await m(s.providerOptions);t.push({type:"document",source:s.data instanceof URL?{type:"url",url:s.data.toString()}:{type:"base64",media_type:"application/pdf",data:Hd(s.data)},title:null!=(i=n.title)?i:s.filename,...n.context&&{context:n.context},...e&&{citations:{enabled:!0}},cache_control:c})}else{if("text/plain"!==s.mediaType)throw new At({functionality:`media type: ${s.mediaType}`});{const e=await p(s.providerOptions),n=await m(s.providerOptions);t.push({type:"document",source:s.data instanceof URL?{type:"url",url:s.data.toString()}:{type:"text",media_type:"text/plain",data:am(s.data)},title:null!=(o=n.title)?o:s.filename,...n.context&&{context:n.context},...e&&{citations:{enabled:!0}},cache_control:c})}}}}break;case"tool":for(let e=0;e<a.length;e++){const r=a[e],i=e===a.length-1,o=null!=(s=em(r.providerOptions))?s:i?em(n.providerOptions):void 0,u=r.output;let l;switch(u.type){case"content":l=u.value.map((e=>{switch(e.type){case"text":return{type:"text",text:e.text,cache_control:void 0};case"media":if(e.mediaType.startsWith("image/"))return{type:"image",source:{type:"base64",media_type:e.mediaType,data:e.data},cache_control:void 0};throw new At({functionality:`media type: ${e.mediaType}`})}}));break;case"text":case"error-text":l=u.value;break;default:l=JSON.stringify(u.value)}t.push({type:"tool_result",tool_use_id:r.toolCallId,content:l,is_error:"error-text"===u.type||"error-json"===u.type||void 0,cache_control:o})}break;default:throw new Error(`Unsupported role: ${e}`)}}d.push({role:"user",content:t});break}case"assistant":{const r=[];for(let i=0;i<e.messages.length;i++){const o=e.messages[i],s=i===e.messages.length-1,{content:u}=o;for(let e=0;e<u.length;e++){const i=u[e],l=e===u.length-1,c=null!=(a=em(i.providerOptions))?a:l?em(o.providerOptions):void 0;switch(i.type){case"text":r.push({type:"text",text:g&&s&&l?i.text.trim():i.text,cache_control:c});break;case"reasoning":if(t){const e=await Nd({provider:"anthropic",providerOptions:i.providerOptions,schema:fm});null!=e?null!=e.signature?r.push({type:"thinking",thinking:i.text,signature:e.signature,cache_control:c}):null!=e.redactedData?r.push({type:"redacted_thinking",data:e.redactedData,cache_control:c}):n.push({type:"other",message:"unsupported reasoning metadata"}):n.push({type:"other",message:"unsupported reasoning metadata"})}else n.push({type:"other",message:"sending reasoning content is disabled for this model"});break;case"tool-call":if(i.providerExecuted){if("web_search"===i.toolName){r.push({type:"server_tool_use",id:i.toolCallId,name:"web_search",input:i.input,cache_control:c});break}if("code_execution"===i.toolName){r.push({type:"server_tool_use",id:i.toolCallId,name:"code_execution",input:i.input,cache_control:c});break}n.push({type:"other",message:`provider executed tool call for tool ${i.toolName} is not supported`});break}r.push({type:"tool_use",id:i.toolCallId,name:i.toolName,input:i.input,cache_control:c});break;case"tool-result":if("web_search"===i.toolName){const e=i.output;if("json"!==e.type){n.push({type:"other",message:`provider executed tool result output type ${e.type} for tool ${i.toolName} is not supported`});break}const t=nm.parse(e.value);r.push({type:"web_search_tool_result",tool_use_id:i.toolCallId,content:t.map((e=>({url:e.url,title:e.title,page_age:e.pageAge,encrypted_content:e.encryptedContent,type:e.type}))),cache_control:c});break}if("code_execution"===i.toolName){const e=i.output;if("json"!==e.type){n.push({type:"other",message:`provider executed tool result output type ${e.type} for tool ${i.toolName} is not supported`});break}const t=om.parse(e.value);r.push({type:"code_execution_tool_result",tool_use_id:i.toolCallId,content:{type:t.type,stdout:t.stdout,stderr:t.stderr,return_code:t.return_code},cache_control:c});break}n.push({type:"other",message:`provider executed tool result for tool ${i.toolName} is not supported`})}}}d.push({role:"assistant",content:r});break}default:throw new Error(`content type: ${f}`)}}return{prompt:{system:c,messages:d},betas:u}}function lm({finishReason:e,isJsonResponseFromTool:t}){switch(e){case"end_turn":case"stop_sequence":return"stop";case"tool_use":return t?"stop":"tool-calls";case"max_tokens":return"length";default:return"unknown"}}var cm={webSearchResult:Ol({type:Hl("web_search_result_location"),cited_text:zu(),url:zu(),title:zu(),encrypted_index:zu()}),pageLocation:Ol({type:Hl("page_location"),cited_text:zu(),document_index:al(),document_title:zu().nullable(),start_page_number:al(),end_page_number:al()}),charLocation:Ol({type:Hl("char_location"),cited_text:zu(),document_index:al(),document_title:zu().nullable(),start_char_index:al(),end_char_index:al()})},dm=Ul("type",[cm.webSearchResult,cm.pageLocation,cm.charLocation]);function pm(e,t,n,r){if("page_location"===e.type||"char_location"===e.type){const i=function(e,t,n){var r;const i=t[e.document_index];if(!i)return null;const o="page_location"===e.type?{citedText:e.cited_text,startPageNumber:e.start_page_number,endPageNumber:e.end_page_number}:{citedText:e.cited_text,startCharIndex:e.start_char_index,endCharIndex:e.end_char_index};return{type:"source",sourceType:"document",id:n(),mediaType:i.mediaType,title:null!=(r=e.document_title)?r:i.title,filename:i.filename,providerMetadata:{anthropic:o}}}(e,t,n);i&&r(i)}}Ul("type",[cm.pageLocation,cm.charLocation]);var mm=class{constructor(e,t){var n;this.specificationVersion="v2",this.modelId=e,this.config=t,this.generateId=null!=(n=t.generateId)?n:gd}supportsUrl(e){return"https:"===e.protocol}get provider(){return this.config.provider}get supportedUrls(){var e,t,n;return null!=(n=null==(t=(e=this.config).supportedUrls)?void 0:t.call(e))?n:{}}async getArgs({prompt:e,maxOutputTokens:t=4096,temperature:n,topP:r,topK:i,frequencyPenalty:o,presencePenalty:s,stopSequences:a,responseFormat:u,seed:l,tools:c,toolChoice:d,providerOptions:p}){var m,h,g;const f=[];null!=o&&f.push({type:"unsupported-setting",setting:"frequencyPenalty"}),null!=s&&f.push({type:"unsupported-setting",setting:"presencePenalty"}),null!=l&&f.push({type:"unsupported-setting",setting:"seed"}),"json"===(null==u?void 0:u.type)&&(null==u.schema?f.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format requires a schema. The response format is ignored."}):null!=c&&f.push({type:"unsupported-setting",setting:"tools",details:"JSON response format does not support tools. The provided tools are ignored."}));const v="json"===(null==u?void 0:u.type)&&null!=u.schema?{type:"function",name:"json",description:"Respond with a JSON object.",inputSchema:u.schema}:void 0,y=await Nd({provider:"anthropic",providerOptions:p,schema:Qp}),{prompt:_,betas:b}=await um({prompt:e,sendReasoning:null==(m=null==y?void 0:y.sendReasoning)||m,warnings:f}),w="enabled"===(null==(h=null==y?void 0:y.thinking)?void 0:h.type),k=null==(g=null==y?void 0:y.thinking)?void 0:g.budgetTokens,x={model:this.modelId,max_tokens:t,temperature:n,top_k:i,top_p:r,stop_sequences:a,...w&&{thinking:{type:"enabled",budget_tokens:k}},system:_.system,messages:_.messages};if(w){if(null==k)throw new At({functionality:"thinking requires a budget"});null!=x.temperature&&(x.temperature=void 0,f.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported when thinking is enabled"})),null!=i&&(x.top_k=void 0,f.push({type:"unsupported-setting",setting:"topK",details:"topK is not supported when thinking is enabled"})),null!=r&&(x.top_p=void 0,f.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported when thinking is enabled"})),x.max_tokens=t+k}const{tools:I,toolChoice:S,toolWarnings:$,betas:E}=function({tools:e,toolChoice:t,disableParallelToolUse:n}){e=(null==e?void 0:e.length)?e:void 0;const r=[],i=new Set;if(null==e)return{tools:void 0,toolChoice:void 0,toolWarnings:r,betas:i};const o=[];for(const a of e)if(im(a))o.push(a);else switch(a.type){case"function":const e=em(a.providerOptions);o.push({name:a.name,description:a.description,input_schema:a.inputSchema,cache_control:e});break;case"provider-defined":switch(a.id){case"anthropic.computer_20250124":i.add("computer-use-2025-01-24"),o.push({name:"computer",type:"computer_20250124",display_width_px:a.args.displayWidthPx,display_height_px:a.args.displayHeightPx,display_number:a.args.displayNumber});break;case"anthropic.computer_20241022":i.add("computer-use-2024-10-22"),o.push({name:"computer",type:"computer_20241022",display_width_px:a.args.displayWidthPx,display_height_px:a.args.displayHeightPx,display_number:a.args.displayNumber});break;case"anthropic.text_editor_20250124":i.add("computer-use-2025-01-24"),o.push({name:"str_replace_editor",type:"text_editor_20250124"});break;case"anthropic.text_editor_20241022":i.add("computer-use-2024-10-22"),o.push({name:"str_replace_editor",type:"text_editor_20241022"});break;case"anthropic.text_editor_20250429":i.add("computer-use-2025-01-24"),o.push({name:"str_replace_based_edit_tool",type:"text_editor_20250429"});break;case"anthropic.bash_20250124":i.add("computer-use-2025-01-24"),o.push({name:"bash",type:"bash_20250124"});break;case"anthropic.bash_20241022":i.add("computer-use-2024-10-22"),o.push({name:"bash",type:"bash_20241022"});break;case"anthropic.web_search_20250305":{const e=tm.parse(a.args);o.push({type:"web_search_20250305",name:"web_search",max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,user_location:e.userLocation});break}case"anthropic.code_execution_20250522":i.add("code-execution-2025-05-22"),o.push({type:"code_execution_20250522",name:"code_execution"});break;default:r.push({type:"unsupported-tool",tool:a})}break;default:r.push({type:"unsupported-tool",tool:a})}if(null==t)return{tools:o,toolChoice:n?{type:"auto",disable_parallel_tool_use:n}:void 0,toolWarnings:r,betas:i};const s=t.type;switch(s){case"auto":return{tools:o,toolChoice:{type:"auto",disable_parallel_tool_use:n},toolWarnings:r,betas:i};case"required":return{tools:o,toolChoice:{type:"any",disable_parallel_tool_use:n},toolWarnings:r,betas:i};case"none":return{tools:void 0,toolChoice:void 0,toolWarnings:r,betas:i};case"tool":return{tools:o,toolChoice:{type:"tool",name:t.toolName,disable_parallel_tool_use:n},toolWarnings:r,betas:i};default:throw new At({functionality:`tool choice type: ${s}`})}}(null!=v?{tools:[v],toolChoice:{type:"tool",toolName:v.name},disableParallelToolUse:null==y?void 0:y.disableParallelToolUse}:{tools:null!=c?c:[],toolChoice:d,disableParallelToolUse:null==y?void 0:y.disableParallelToolUse});return{args:{...x,tools:I,tool_choice:S},warnings:[...f,...$],betas:new Set([...b,...E]),usesJsonResponseTool:null!=v}}async getHeaders({betas:e,headers:t}){return pd(await jd(this.config.headers),e.size>0?{"anthropic-beta":Array.from(e).join(",")}:{},t)}buildRequestUrl(e){var t,n,r;return null!=(r=null==(n=(t=this.config).buildRequestUrl)?void 0:n.call(t,this.config.baseURL,e))?r:`${this.config.baseURL}/messages`}transformRequestBody(e){var t,n,r;return null!=(r=null==(n=(t=this.config).transformRequestBody)?void 0:n.call(t,e))?r:e}extractCitationDocuments(e){return e.filter((e=>"user"===e.role)).flatMap((e=>e.content)).filter((e=>{var t,n;if("file"!==e.type)return!1;if("application/pdf"!==e.mediaType&&"text/plain"!==e.mediaType)return!1;const r=null==(t=e.providerOptions)?void 0:t.anthropic,i=null==r?void 0:r.citations;return null!=(n=null==i?void 0:i.enabled)&&n})).map((e=>{var t;const n=e;return{title:null!=(t=n.filename)?t:"Untitled Document",filename:n.filename,mediaType:n.mediaType}}))}async doGenerate(e){var t,n,r,i,o;const{args:s,warnings:a,betas:u,usesJsonResponseTool:l}=await this.getArgs(e),c=this.extractCitationDocuments(e.prompt),{responseHeaders:d,value:p,rawValue:m}=await Ad({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:u,headers:e.headers}),body:this.transformRequestBody(s),failedResponseHandler:Yp,successfulResponseHandler:Md(hm),abortSignal:e.abortSignal,fetch:this.config.fetch}),h=[];for(const g of p.content)switch(g.type){case"text":if(!l&&(h.push({type:"text",text:g.text}),g.citations))for(const e of g.citations)pm(e,c,this.generateId,(e=>h.push(e)));break;case"thinking":h.push({type:"reasoning",text:g.thinking,providerMetadata:{anthropic:{signature:g.signature}}});break;case"redacted_thinking":h.push({type:"reasoning",text:"",providerMetadata:{anthropic:{redactedData:g.data}}});break;case"tool_use":h.push(l?{type:"text",text:JSON.stringify(g.input)}:{type:"tool-call",toolCallId:g.id,toolName:g.name,input:JSON.stringify(g.input)});break;case"server_tool_use":"web_search"!==g.name&&"code_execution"!==g.name||h.push({type:"tool-call",toolCallId:g.id,toolName:g.name,input:JSON.stringify(g.input),providerExecuted:!0});break;case"web_search_tool_result":if(Array.isArray(g.content)){h.push({type:"tool-result",toolCallId:g.tool_use_id,toolName:"web_search",result:g.content.map((e=>{var t;return{url:e.url,title:e.title,pageAge:null!=(t=e.page_age)?t:null,encryptedContent:e.encrypted_content,type:e.type}})),providerExecuted:!0});for(const e of g.content)h.push({type:"source",sourceType:"url",id:this.generateId(),url:e.url,title:e.title,providerMetadata:{anthropic:{pageAge:null!=(t=e.page_age)?t:null}}})}else h.push({type:"tool-result",toolCallId:g.tool_use_id,toolName:"web_search",isError:!0,result:{type:"web_search_tool_result_error",errorCode:g.content.error_code},providerExecuted:!0});break;case"code_execution_tool_result":"code_execution_result"===g.content.type?h.push({type:"tool-result",toolCallId:g.tool_use_id,toolName:"code_execution",result:{type:g.content.type,stdout:g.content.stdout,stderr:g.content.stderr,return_code:g.content.return_code},providerExecuted:!0}):"code_execution_tool_result_error"===g.content.type&&h.push({type:"tool-result",toolCallId:g.tool_use_id,toolName:"code_execution",isError:!0,result:{type:"code_execution_tool_result_error",errorCode:g.content.error_code},providerExecuted:!0})}return{content:h,finishReason:lm({finishReason:p.stop_reason,isJsonResponseFromTool:l}),usage:{inputTokens:p.usage.input_tokens,outputTokens:p.usage.output_tokens,totalTokens:p.usage.input_tokens+p.usage.output_tokens,cachedInputTokens:null!=(n=p.usage.cache_read_input_tokens)?n:void 0},request:{body:s},response:{id:null!=(r=p.id)?r:void 0,modelId:null!=(i=p.model)?i:void 0,headers:d,body:m},warnings:a,providerMetadata:{anthropic:{usage:p.usage,cacheCreationInputTokens:null!=(o=p.usage.cache_creation_input_tokens)?o:null}}}}async doStream(e){const{args:t,warnings:n,betas:r,usesJsonResponseTool:i}=await this.getArgs(e),o=this.extractCitationDocuments(e.prompt),s={...t,stream:!0},{responseHeaders:a,value:u}=await Ad({url:this.buildRequestUrl(!0),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(s),failedResponseHandler:Yp,successfulResponseHandler:Dd(gm),abortSignal:e.abortSignal,fetch:this.config.fetch});let l="unknown";const c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},d={};let p,m;const h=this.generateId;return{stream:u.pipeThrough(new TransformStream({start(e){e.enqueue({type:"stream-start",warnings:n})},transform(t,n){var r,s,a,u,g,f,v;if(e.includeRawChunks&&n.enqueue({type:"raw",rawValue:t.rawValue}),!t.success)return void n.enqueue({type:"error",error:t.error});const y=t.value;switch(y.type){case"ping":return;case"content_block_start":{const e=y.content_block.type;switch(m=e,e){case"text":return d[y.index]={type:"text"},void n.enqueue({type:"text-start",id:String(y.index)});case"thinking":return d[y.index]={type:"reasoning"},void n.enqueue({type:"reasoning-start",id:String(y.index)});case"redacted_thinking":return d[y.index]={type:"reasoning"},void n.enqueue({type:"reasoning-start",id:String(y.index),providerMetadata:{anthropic:{redactedData:y.content_block.data}}});case"tool_use":return d[y.index]=i?{type:"text"}:{type:"tool-call",toolCallId:y.content_block.id,toolName:y.content_block.name,input:""},void n.enqueue(i?{type:"text-start",id:String(y.index)}:{type:"tool-input-start",id:y.content_block.id,toolName:y.content_block.name});case"server_tool_use":return void("web_search"!==y.content_block.name&&"code_execution"!==y.content_block.name||(d[y.index]={type:"tool-call",toolCallId:y.content_block.id,toolName:y.content_block.name,input:"",providerExecuted:!0},n.enqueue({type:"tool-input-start",id:y.content_block.id,toolName:y.content_block.name,providerExecuted:!0})));case"web_search_tool_result":{const e=y.content_block;if(Array.isArray(e.content)){n.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:"web_search",result:e.content.map((e=>{var t;return{url:e.url,title:e.title,pageAge:null!=(t=e.page_age)?t:null,encryptedContent:e.encrypted_content,type:e.type}})),providerExecuted:!0});for(const t of e.content)n.enqueue({type:"source",sourceType:"url",id:h(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:null!=(r=t.page_age)?r:null}}})}else n.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:"web_search",isError:!0,result:{type:"web_search_tool_result_error",errorCode:e.content.error_code},providerExecuted:!0});return}case"code_execution_tool_result":{const e=y.content_block;return void("code_execution_result"===e.content.type?n.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:"code_execution",result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code},providerExecuted:!0}):"code_execution_tool_result_error"===e.content.type&&n.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:"code_execution",isError:!0,result:{type:"code_execution_tool_result_error",errorCode:e.content.error_code},providerExecuted:!0}))}default:throw new Error(`Unsupported content block type: ${e}`)}}case"content_block_stop":if(null!=d[y.index]){const e=d[y.index];switch(e.type){case"text":n.enqueue({type:"text-end",id:String(y.index)});break;case"reasoning":n.enqueue({type:"reasoning-end",id:String(y.index)});break;case"tool-call":i||(n.enqueue({type:"tool-input-end",id:e.toolCallId}),n.enqueue(e))}delete d[y.index]}return void(m=void 0);case"content_block_delta":{const e=y.delta.type;switch(e){case"text_delta":if(i)return;return void n.enqueue({type:"text-delta",id:String(y.index),delta:y.delta.text});case"thinking_delta":return void n.enqueue({type:"reasoning-delta",id:String(y.index),delta:y.delta.thinking});case"signature_delta":return void("thinking"===m&&n.enqueue({type:"reasoning-delta",id:String(y.index),delta:"",providerMetadata:{anthropic:{signature:y.delta.signature}}}));case"input_json_delta":{const e=d[y.index],t=y.delta.partial_json;if(i){if("text"!==(null==e?void 0:e.type))return;n.enqueue({type:"text-delta",id:String(y.index),delta:t})}else{if("tool-call"!==(null==e?void 0:e.type))return;n.enqueue({type:"tool-input-delta",id:e.toolCallId,delta:t}),e.input+=t}return}case"citations_delta":return void pm(y.delta.citation,o,h,(e=>n.enqueue(e)));default:throw new Error(`Unsupported delta type: ${e}`)}}case"message_start":return c.inputTokens=y.message.usage.input_tokens,c.cachedInputTokens=null!=(s=y.message.usage.cache_read_input_tokens)?s:void 0,p={anthropic:{usage:y.message.usage,cacheCreationInputTokens:null!=(a=y.message.usage.cache_creation_input_tokens)?a:null}},void n.enqueue({type:"response-metadata",id:null!=(u=y.message.id)?u:void 0,modelId:null!=(g=y.message.model)?g:void 0});case"message_delta":return c.outputTokens=y.usage.output_tokens,c.totalTokens=(null!=(f=c.inputTokens)?f:0)+(null!=(v=y.usage.output_tokens)?v:0),void(l=lm({finishReason:y.delta.stop_reason,isJsonResponseFromTool:i}));case"message_stop":return void n.enqueue({type:"finish",finishReason:l,usage:c,providerMetadata:p});case"error":return void n.enqueue({type:"error",error:y.error});default:throw new Error(`Unsupported chunk type: ${y}`)}}})),request:{body:s},response:{headers:a}}}},hm=Ol({type:Hl("message"),id:zu().nullish(),model:zu().nullish(),content:El(Ul("type",[Ol({type:Hl("text"),text:zu(),citations:El(dm).optional()}),Ol({type:Hl("thinking"),thinking:zu(),signature:zu()}),Ol({type:Hl("redacted_thinking"),data:zu()}),Ol({type:Hl("tool_use"),id:zu(),name:zu(),input:wl()}),Ol({type:Hl("server_tool_use"),id:zu(),name:zu(),input:Zl(zu(),wl()).nullish()}),Ol({type:Hl("web_search_tool_result"),tool_use_id:zu(),content:Pl([El(Ol({type:Hl("web_search_result"),url:zu(),title:zu(),encrypted_content:zu(),page_age:zu().nullish()})),Ol({type:Hl("web_search_tool_result_error"),error_code:zu()})])}),Ol({type:Hl("code_execution_tool_result"),tool_use_id:zu(),content:Pl([Ol({type:Hl("code_execution_result"),stdout:zu(),stderr:zu(),return_code:al()}),Ol({type:Hl("code_execution_tool_result_error"),error_code:zu()})])})])),stop_reason:zu().nullish(),usage:Cl({input_tokens:al(),output_tokens:al(),cache_creation_input_tokens:al().nullish(),cache_read_input_tokens:al().nullish()})}),gm=Ul("type",[Ol({type:Hl("message_start"),message:Ol({id:zu().nullish(),model:zu().nullish(),usage:Cl({input_tokens:al(),output_tokens:al(),cache_creation_input_tokens:al().nullish(),cache_read_input_tokens:al().nullish()})})}),Ol({type:Hl("content_block_start"),index:al(),content_block:Ul("type",[Ol({type:Hl("text"),text:zu()}),Ol({type:Hl("thinking"),thinking:zu()}),Ol({type:Hl("tool_use"),id:zu(),name:zu()}),Ol({type:Hl("redacted_thinking"),data:zu()}),Ol({type:Hl("server_tool_use"),id:zu(),name:zu(),input:Zl(zu(),wl()).nullish()}),Ol({type:Hl("web_search_tool_result"),tool_use_id:zu(),content:Pl([El(Ol({type:Hl("web_search_result"),url:zu(),title:zu(),encrypted_content:zu(),page_age:zu().nullish()})),Ol({type:Hl("web_search_tool_result_error"),error_code:zu()})])}),Ol({type:Hl("code_execution_tool_result"),tool_use_id:zu(),content:Pl([Ol({type:Hl("code_execution_result"),stdout:zu(),stderr:zu(),return_code:al()}),Ol({type:Hl("code_execution_tool_result_error"),error_code:zu()})])})])}),Ol({type:Hl("content_block_delta"),index:al(),delta:Ul("type",[Ol({type:Hl("input_json_delta"),partial_json:zu()}),Ol({type:Hl("text_delta"),text:zu()}),Ol({type:Hl("thinking_delta"),thinking:zu()}),Ol({type:Hl("signature_delta"),signature:zu()}),Ol({type:Hl("citations_delta"),citation:dm})])}),Ol({type:Hl("content_block_stop"),index:al()}),Ol({type:Hl("error"),error:Ol({type:zu(),message:zu()})}),Ol({type:Hl("message_delta"),delta:Ol({stop_reason:zu().nullish()}),usage:Ol({output_tokens:al()})}),Ol({type:Hl("message_stop")}),Ol({type:Hl("ping")})]),fm=Ol({signature:zu().optional(),redactedData:zu().optional()}),vm=Rd({id:"anthropic.bash_20241022",name:"bash",inputSchema:Ec.object({command:Ec.string(),restart:Ec.boolean().optional()})}),ym=Rd({id:"anthropic.bash_20250124",name:"bash",inputSchema:Ec.object({command:Ec.string(),restart:Ec.boolean().optional()})}),_m=Rd({id:"anthropic.computer_20241022",name:"computer",inputSchema:Ol({action:Jl(["key","type","mouse_move","left_click","left_click_drag","right_click","middle_click","double_click","screenshot","cursor_position"]),coordinate:El(al().int()).optional(),text:zu().optional()})}),bm=Rd({id:"anthropic.computer_20250124",name:"computer",inputSchema:Ol({action:Jl(["key","hold_key","type","cursor_position","mouse_move","left_mouse_down","left_mouse_up","left_click","left_click_drag","right_click","middle_click","double_click","triple_click","scroll","wait","screenshot"]),coordinate:Ml([al().int(),al().int()]).optional(),duration:al().optional(),scroll_amount:al().optional(),scroll_direction:Jl(["up","down","left","right"]).optional(),start_coordinate:Ml([al().int(),al().int()]).optional(),text:zu().optional()})}),wm={bash_20241022:vm,bash_20250124:ym,textEditor_20241022:Rd({id:"anthropic.text_editor_20241022",name:"str_replace_editor",inputSchema:Ol({command:Jl(["view","create","str_replace","insert","undo_edit"]),path:zu(),file_text:zu().optional(),insert_line:al().int().optional(),new_str:zu().optional(),old_str:zu().optional(),view_range:El(al().int()).optional()})}),textEditor_20250124:Rd({id:"anthropic.text_editor_20250124",name:"str_replace_editor",inputSchema:Ol({command:Jl(["view","create","str_replace","insert","undo_edit"]),path:zu(),file_text:zu().optional(),insert_line:al().int().optional(),new_str:zu().optional(),old_str:zu().optional(),view_range:El(al().int()).optional()})}),textEditor_20250429:Rd({id:"anthropic.text_editor_20250429",name:"str_replace_based_edit_tool",inputSchema:Ol({command:Jl(["view","create","str_replace","insert"]),path:zu(),file_text:zu().optional(),insert_line:al().int().optional(),new_str:zu().optional(),old_str:zu().optional(),view_range:El(al().int()).optional()})}),computer_20241022:_m,computer_20250124:bm,webSearch_20250305:(e={})=>rm(e),codeExecution_20250522:(e={})=>sm(e)};function km(e={}){var t;const n=null!=(t=Vd(e.baseURL))?t:"https://api.anthropic.com/v1",r=()=>({"anthropic-version":"2023-06-01","x-api-key":yd({apiKey:e.apiKey,environmentVariableName:"ANTHROPIC_API_KEY",description:"Anthropic"}),...e.headers}),i=t=>{var i;return new mm(t,{provider:"anthropic.messages",baseURL:n,headers:r,fetch:e.fetch,generateId:null!=(i=e.generateId)?i:gd,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/]})})},o=function(e){if(new.target)throw new Error("The Anthropic model function cannot be called with the new keyword.");return i(e)};return o.languageModel=i,o.chat=i,o.messages=i,o.textEmbeddingModel=e=>{throw new vt({modelId:e,modelType:"textEmbeddingModel"})},o.imageModel=e=>{throw new vt({modelId:e,modelType:"imageModel"})},o.tools=wm,o}var xm=km(),Im=zd({errorSchema:Ol({error:Ol({code:al().nullable(),message:zu(),status:zu()})}),errorToMessage:e=>e.error.message}),Sm=Ol({outputDimensionality:al().optional(),taskType:Jl(["SEMANTIC_SIMILARITY","CLASSIFICATION","CLUSTERING","RETRIEVAL_DOCUMENT","RETRIEVAL_QUERY","QUESTION_ANSWERING","FACT_VERIFICATION","CODE_RETRIEVAL_QUERY"]).optional()}),$m=class{constructor(e,t){this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){const i=await Nd({provider:"google",providerOptions:r,schema:Sm});if(e.length>this.maxEmbeddingsPerCall)throw new kt({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const o=pd(await jd(this.config.headers),t);if(1===e.length){const{responseHeaders:t,value:r,rawValue:s}=await Ad({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:o,body:{model:`models/${this.modelId}`,content:{parts:[{text:e[0]}]},outputDimensionality:null==i?void 0:i.outputDimensionality,taskType:null==i?void 0:i.taskType},failedResponseHandler:Im,successfulResponseHandler:Md(Tm),abortSignal:n,fetch:this.config.fetch});return{embeddings:[r.embedding.values],usage:void 0,response:{headers:t,body:s}}}const{responseHeaders:s,value:a,rawValue:u}=await Ad({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:o,body:{requests:e.map((e=>({model:`models/${this.modelId}`,content:{role:"user",parts:[{text:e}]},outputDimensionality:null==i?void 0:i.outputDimensionality,taskType:null==i?void 0:i.taskType})))},failedResponseHandler:Im,successfulResponseHandler:Md(Em),abortSignal:n,fetch:this.config.fetch});return{embeddings:a.embeddings.map((e=>e.values)),usage:void 0,response:{headers:s,body:u}}}},Em=Ol({embeddings:El(Ol({values:El(al())}))}),Tm=Ol({embedding:Ol({values:El(al())})});function Om(e){if(null==e||function(e){return null!=e&&"object"==typeof e&&"object"===e.type&&(null==e.properties||0===Object.keys(e.properties).length)&&!e.additionalProperties}(e))return;if("boolean"==typeof e)return{type:"boolean",properties:{}};const{type:t,description:n,required:r,properties:i,items:o,allOf:s,anyOf:a,oneOf:u,format:l,const:c,minLength:d,enum:p}=e,m={};if(n&&(m.description=n),r&&(m.required=r),l&&(m.format=l),void 0!==c&&(m.enum=[c]),t&&(Array.isArray(t)?t.includes("null")?(m.type=t.filter((e=>"null"!==e))[0],m.nullable=!0):m.type=t:m.type="null"===t?"null":t),void 0!==p&&(m.enum=p),null!=i&&(m.properties=Object.entries(i).reduce(((e,[t,n])=>(e[t]=Om(n),e)),{})),o&&(m.items=Array.isArray(o)?o.map(Om):Om(o)),s&&(m.allOf=s.map(Om)),a)if(a.some((e=>"object"==typeof e&&"null"===(null==e?void 0:e.type)))){const e=a.filter((e=>!("object"==typeof e&&"null"===(null==e?void 0:e.type))));if(1===e.length){const t=Om(e[0]);"object"==typeof t&&(m.nullable=!0,Object.assign(m,t))}else m.anyOf=e.map(Om),m.nullable=!0}else m.anyOf=a.map(Om);return u&&(m.oneOf=u.map(Om)),void 0!==d&&(m.minLength=d),m}function Nm(e){return e.includes("/")?e:`models/${e}`}var Cm=Ol({responseModalities:El(Jl(["TEXT","IMAGE"])).optional(),thinkingConfig:Ol({thinkingBudget:al().optional(),includeThoughts:dl().optional()}).optional(),cachedContent:zu().optional(),structuredOutputs:dl().optional(),safetySettings:El(Ol({category:Jl(["HARM_CATEGORY_UNSPECIFIED","HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_SEXUALLY_EXPLICIT","HARM_CATEGORY_CIVIC_INTEGRITY"]),threshold:Jl(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"])})).optional(),threshold:Jl(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"]).optional(),audioTimestamp:dl().optional(),labels:Zl(zu(),zu()).optional()});function Am({finishReason:e,hasToolCalls:t}){switch(e){case"STOP":return t?"tool-calls":"stop";case"MAX_TOKENS":return"length";case"IMAGE_SAFETY":case"RECITATION":case"SAFETY":case"BLOCKLIST":case"PROHIBITED_CONTENT":case"SPII":return"content-filter";case"FINISH_REASON_UNSPECIFIED":case"OTHER":return"other";case"MALFORMED_FUNCTION_CALL":return"error";default:return"unknown"}}var Pm=Ol({web:Ol({uri:zu(),title:zu()}).nullish(),retrievedContext:Ol({uri:zu(),title:zu()}).nullish()}),Rm=Ol({webSearchQueries:El(zu()).nullish(),retrievalQueries:El(zu()).nullish(),searchEntryPoint:Ol({renderedContent:zu()}).nullish(),groundingChunks:El(Pm).nullish(),groundingSupports:El(Ol({segment:Ol({startIndex:al().nullish(),endIndex:al().nullish(),text:zu().nullish()}),segment_text:zu().nullish(),groundingChunkIndices:El(al()).nullish(),supportChunkIndices:El(al()).nullish(),confidenceScores:El(al()).nullish(),confidenceScore:El(al()).nullish()})).nullish(),retrievalMetadata:Pl([Ol({webDynamicRetrievalScore:al()}),Ol({})]).nullish()}),Um=Rd({id:"google.google_search",name:"google_search",inputSchema:Ol({mode:Jl(["MODE_DYNAMIC","MODE_UNSPECIFIED"]).default("MODE_UNSPECIFIED"),dynamicThreshold:al().default(1)})}),jm=Ol({retrievedUrl:zu(),urlRetrievalStatus:zu()}),zm=Ol({urlMetadata:El(jm)}),Dm=Rd({id:"google.url_context",name:"url_context",inputSchema:Ol({})}),Mm=class{constructor(e,t){var n;this.specificationVersion="v2",this.modelId=e,this.config=t,this.generateId=null!=(n=t.generateId)?n:gd}get provider(){return this.config.provider}get supportedUrls(){var e,t,n;return null!=(n=null==(t=(e=this.config).supportedUrls)?void 0:t.call(e))?n:{}}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:o,presencePenalty:s,stopSequences:a,responseFormat:u,seed:l,tools:c,toolChoice:d,providerOptions:p}){var m,h;const g=[],f=await Nd({provider:"google",providerOptions:p,schema:Cm});!0!==(null==(m=null==f?void 0:f.thinkingConfig)?void 0:m.includeThoughts)||this.config.provider.startsWith("google.vertex.")||g.push({type:"other",message:`The 'includeThoughts' option is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${this.config.provider}).`});const v=this.modelId.toLowerCase().startsWith("gemma-"),{contents:y,systemInstruction:_}=function(e,t){var n;const r=[],i=[];let o=!0;const s=null!=(n=null==t?void 0:t.isGemmaModel)&&n;for(const{role:a,content:u}of e)switch(a){case"system":if(!o)throw new At({functionality:"system messages are only supported at the beginning of the conversation"});r.push({text:u});break;case"user":{o=!1;const e=[];for(const t of u)switch(t.type){case"text":e.push({text:t.text});break;case"file":{const n="image/*"===t.mediaType?"image/jpeg":t.mediaType;e.push(t.data instanceof URL?{fileData:{mimeType:n,fileUri:t.data.toString()}}:{inlineData:{mimeType:n,data:Hd(t.data)}});break}}i.push({role:"user",parts:e});break}case"assistant":o=!1,i.push({role:"model",parts:u.map((e=>{var t,n,r,i,o,s;switch(e.type){case"text":return 0===e.text.length?void 0:{text:e.text,thoughtSignature:null==(n=null==(t=e.providerOptions)?void 0:t.google)?void 0:n.thoughtSignature};case"reasoning":return 0===e.text.length?void 0:{text:e.text,thought:!0,thoughtSignature:null==(i=null==(r=e.providerOptions)?void 0:r.google)?void 0:i.thoughtSignature};case"file":if("image/png"!==e.mediaType)throw new At({functionality:"Only PNG images are supported in assistant messages"});if(e.data instanceof URL)throw new At({functionality:"File data URLs in assistant messages are not supported"});return{inlineData:{mimeType:e.mediaType,data:Hd(e.data)}};case"tool-call":return{functionCall:{name:e.toolName,args:e.input},thoughtSignature:null==(s=null==(o=e.providerOptions)?void 0:o.google)?void 0:s.thoughtSignature}}})).filter((e=>void 0!==e))});break;case"tool":o=!1,i.push({role:"user",parts:u.map((e=>({functionResponse:{name:e.toolName,response:{name:e.toolName,content:e.output.value}}})))})}if(s&&r.length>0&&i.length>0&&"user"===i[0].role){const e=r.map((e=>e.text)).join("\n\n");i[0].parts.unshift({text:e+"\n\n"})}return{systemInstruction:r.length>0&&!s?{parts:r}:void 0,contents:i}}(e,{isGemmaModel:v}),{tools:b,toolConfig:w,toolWarnings:k}=function({tools:e,toolChoice:t,modelId:n}){var r;e=(null==e?void 0:e.length)?e:void 0;const i=[],o=n.includes("gemini-2"),s=n.includes("gemini-1.5-flash")&&!n.includes("-8b");if(null==e)return{tools:void 0,toolConfig:void 0,toolWarnings:i};const a=e.some((e=>"function"===e.type)),u=e.some((e=>"provider-defined"===e.type));if(a&&u&&i.push({type:"unsupported-tool",tool:e.find((e=>"function"===e.type)),details:"Cannot mix function tools with provider-defined tools in the same request. Please use either function tools or provider-defined tools, but not both."}),u){const t={};return e.filter((e=>"provider-defined"===e.type)).forEach((e=>{switch(e.id){case"google.google_search":o?t.googleSearch={}:t.googleSearchRetrieval=s?{dynamicRetrievalConfig:{mode:e.args.mode,dynamicThreshold:e.args.dynamicThreshold}}:{};break;case"google.url_context":o?t.urlContext={}:i.push({type:"unsupported-tool",tool:e,details:"The URL context tool is not supported with other Gemini models than Gemini 2."});break;case"google.code_execution":o?t.codeExecution={}:i.push({type:"unsupported-tool",tool:e,details:"The code execution tools is not supported with other Gemini models than Gemini 2."});break;default:i.push({type:"unsupported-tool",tool:e})}})),{tools:Object.keys(t).length>0?t:void 0,toolConfig:void 0,toolWarnings:i}}const l=[];for(const d of e)"function"===d.type?l.push({name:d.name,description:null!=(r=d.description)?r:"",parameters:Om(d.inputSchema)}):i.push({type:"unsupported-tool",tool:d});if(null==t)return{tools:{functionDeclarations:l},toolConfig:void 0,toolWarnings:i};const c=t.type;switch(c){case"auto":return{tools:{functionDeclarations:l},toolConfig:{functionCallingConfig:{mode:"AUTO"}},toolWarnings:i};case"none":return{tools:{functionDeclarations:l},toolConfig:{functionCallingConfig:{mode:"NONE"}},toolWarnings:i};case"required":return{tools:{functionDeclarations:l},toolConfig:{functionCallingConfig:{mode:"ANY"}},toolWarnings:i};case"tool":return{tools:{functionDeclarations:l},toolConfig:{functionCallingConfig:{mode:"ANY",allowedFunctionNames:[t.toolName]}},toolWarnings:i};default:throw new At({functionality:`tool choice type: ${c}`})}}({tools:c,toolChoice:d,modelId:this.modelId});return{args:{generationConfig:{maxOutputTokens:t,temperature:n,topK:i,topP:r,frequencyPenalty:o,presencePenalty:s,stopSequences:a,seed:l,responseMimeType:"json"===(null==u?void 0:u.type)?"application/json":void 0,responseSchema:"json"!==(null==u?void 0:u.type)||null==u.schema||null!=(h=null==f?void 0:f.structuredOutputs)&&!h?void 0:Om(u.schema),...(null==f?void 0:f.audioTimestamp)&&{audioTimestamp:f.audioTimestamp},responseModalities:null==f?void 0:f.responseModalities,thinkingConfig:null==f?void 0:f.thinkingConfig},contents:y,systemInstruction:v?void 0:_,safetySettings:null==f?void 0:f.safetySettings,tools:b,toolConfig:w,cachedContent:null==f?void 0:f.cachedContent,labels:null==f?void 0:f.labels},warnings:[...g,...k]}}async doGenerate(e){var t,n,r,i,o,s,a,u,l,c,d,p;const{args:m,warnings:h}=await this.getArgs(e),g=JSON.stringify(m),f=pd(await jd(this.config.headers),e.headers),{responseHeaders:v,value:y,rawValue:_}=await Ad({url:`${this.config.baseURL}/${Nm(this.modelId)}:generateContent`,headers:f,body:m,failedResponseHandler:Im,successfulResponseHandler:Md(Wm),abortSignal:e.abortSignal,fetch:this.config.fetch}),b=y.candidates[0],w=[],k=null!=(n=null==(t=b.content)?void 0:t.parts)?n:[],x=y.usageMetadata;let I;for(const $ of k)if("executableCode"in $&&(null==(r=$.executableCode)?void 0:r.code)){const e=this.config.generateId();I=e,w.push({type:"tool-call",toolCallId:e,toolName:"code_execution",input:JSON.stringify($.executableCode),providerExecuted:!0})}else"codeExecutionResult"in $&&$.codeExecutionResult?(w.push({type:"tool-result",toolCallId:I,toolName:"code_execution",result:{outcome:$.codeExecutionResult.outcome,output:$.codeExecutionResult.output},providerExecuted:!0}),I=void 0):"text"in $&&null!=$.text&&$.text.length>0?w.push({type:!0===$.thought?"reasoning":"text",text:$.text,providerMetadata:$.thoughtSignature?{google:{thoughtSignature:$.thoughtSignature}}:void 0}):"functionCall"in $?w.push({type:"tool-call",toolCallId:this.config.generateId(),toolName:$.functionCall.name,input:JSON.stringify($.functionCall.args),providerMetadata:$.thoughtSignature?{google:{thoughtSignature:$.thoughtSignature}}:void 0}):"inlineData"in $&&w.push({type:"file",data:$.inlineData.data,mediaType:$.inlineData.mimeType});const S=null!=(i=Lm({groundingMetadata:b.groundingMetadata,generateId:this.config.generateId}))?i:[];for(const $ of S)w.push($);return{content:w,finishReason:Am({finishReason:b.finishReason,hasToolCalls:w.some((e=>"tool-call"===e.type))}),usage:{inputTokens:null!=(o=null==x?void 0:x.promptTokenCount)?o:void 0,outputTokens:null!=(s=null==x?void 0:x.candidatesTokenCount)?s:void 0,totalTokens:null!=(a=null==x?void 0:x.totalTokenCount)?a:void 0,reasoningTokens:null!=(u=null==x?void 0:x.thoughtsTokenCount)?u:void 0,cachedInputTokens:null!=(l=null==x?void 0:x.cachedContentTokenCount)?l:void 0},warnings:h,providerMetadata:{google:{groundingMetadata:null!=(c=b.groundingMetadata)?c:null,urlContextMetadata:null!=(d=b.urlContextMetadata)?d:null,safetyRatings:null!=(p=b.safetyRatings)?p:null,usageMetadata:null!=x?x:null}},request:{body:g},response:{headers:v,body:_}}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),r=JSON.stringify(t),i=pd(await jd(this.config.headers),e.headers),{responseHeaders:o,value:s}=await Ad({url:`${this.config.baseURL}/${Nm(this.modelId)}:streamGenerateContent?alt=sse`,headers:i,body:t,failedResponseHandler:Im,successfulResponseHandler:Dd(Jm),abortSignal:e.abortSignal,fetch:this.config.fetch});let a="unknown";const u={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let l;const c=this.config.generateId;let d=!1,p=null,m=null,h=0;const g=new Set;let f;return{stream:s.pipeThrough(new TransformStream({start(e){e.enqueue({type:"stream-start",warnings:n})},transform(t,n){var r,i,o,s,v,y,_,b,w,k,x;if(e.includeRawChunks&&n.enqueue({type:"raw",rawValue:t.rawValue}),!t.success)return void n.enqueue({type:"error",error:t.error});const I=t.value,S=I.usageMetadata;null!=S&&(u.inputTokens=null!=(r=S.promptTokenCount)?r:void 0,u.outputTokens=null!=(i=S.candidatesTokenCount)?i:void 0,u.totalTokens=null!=(o=S.totalTokenCount)?o:void 0,u.reasoningTokens=null!=(s=S.thoughtsTokenCount)?s:void 0,u.cachedInputTokens=null!=(v=S.cachedContentTokenCount)?v:void 0);const $=null==(y=I.candidates)?void 0:y[0];if(null==$)return;const E=$.content,T=Lm({groundingMetadata:$.groundingMetadata,generateId:c});if(null!=T)for(const e of T)"url"!==e.sourceType||g.has(e.url)||(g.add(e.url),n.enqueue(e));if(null!=E){const e=null!=(_=E.parts)?_:[];for(const i of e)if("executableCode"in i&&(null==(b=i.executableCode)?void 0:b.code)){const e=c();f=e,n.enqueue({type:"tool-call",toolCallId:e,toolName:"code_execution",input:JSON.stringify(i.executableCode),providerExecuted:!0}),d=!0}else if("codeExecutionResult"in i&&i.codeExecutionResult){const e=f;e&&(n.enqueue({type:"tool-result",toolCallId:e,toolName:"code_execution",result:{outcome:i.codeExecutionResult.outcome,output:i.codeExecutionResult.output},providerExecuted:!0}),f=void 0)}else"text"in i&&null!=i.text&&i.text.length>0&&(!0===i.thought?(null!==p&&(n.enqueue({type:"text-end",id:p}),p=null),null===m&&(m=String(h++),n.enqueue({type:"reasoning-start",id:m,providerMetadata:i.thoughtSignature?{google:{thoughtSignature:i.thoughtSignature}}:void 0})),n.enqueue({type:"reasoning-delta",id:m,delta:i.text,providerMetadata:i.thoughtSignature?{google:{thoughtSignature:i.thoughtSignature}}:void 0})):(null!==m&&(n.enqueue({type:"reasoning-end",id:m}),m=null),null===p&&(p=String(h++),n.enqueue({type:"text-start",id:p,providerMetadata:i.thoughtSignature?{google:{thoughtSignature:i.thoughtSignature}}:void 0})),n.enqueue({type:"text-delta",id:p,delta:i.text,providerMetadata:i.thoughtSignature?{google:{thoughtSignature:i.thoughtSignature}}:void 0})));const t=function(e){return null==e?void 0:e.filter((e=>"inlineData"in e))}(E.parts);if(null!=t)for(const i of t)n.enqueue({type:"file",mediaType:i.inlineData.mimeType,data:i.inlineData.data});const r=function({parts:e,generateId:t}){const n=null==e?void 0:e.filter((e=>"functionCall"in e));return null==n||0===n.length?void 0:n.map((e=>({type:"tool-call",toolCallId:t(),toolName:e.functionCall.name,args:JSON.stringify(e.functionCall.args),providerMetadata:e.thoughtSignature?{google:{thoughtSignature:e.thoughtSignature}}:void 0})))}({parts:E.parts,generateId:c});if(null!=r)for(const i of r)n.enqueue({type:"tool-input-start",id:i.toolCallId,toolName:i.toolName,providerMetadata:i.providerMetadata}),n.enqueue({type:"tool-input-delta",id:i.toolCallId,delta:i.args,providerMetadata:i.providerMetadata}),n.enqueue({type:"tool-input-end",id:i.toolCallId,providerMetadata:i.providerMetadata}),n.enqueue({type:"tool-call",toolCallId:i.toolCallId,toolName:i.toolName,input:i.args,providerMetadata:i.providerMetadata}),d=!0}null!=$.finishReason&&(a=Am({finishReason:$.finishReason,hasToolCalls:d}),l={google:{groundingMetadata:null!=(w=$.groundingMetadata)?w:null,urlContextMetadata:null!=(k=$.urlContextMetadata)?k:null,safetyRatings:null!=(x=$.safetyRatings)?x:null}},null!=S&&(l.google.usageMetadata=S))},flush(e){null!==p&&e.enqueue({type:"text-end",id:p}),null!==m&&e.enqueue({type:"reasoning-end",id:m}),e.enqueue({type:"finish",finishReason:a,usage:u,providerMetadata:l})}})),response:{headers:o},request:{body:r}}}};function Lm({groundingMetadata:e,generateId:t}){var n;return null==(n=null==e?void 0:e.groundingChunks)?void 0:n.filter((e=>null!=e.web)).map((e=>({type:"source",sourceType:"url",id:t(),url:e.web.uri,title:e.web.title})))}var Zm=Ol({parts:El(Pl([Ol({functionCall:Ol({name:zu(),args:wl()}),thoughtSignature:zu().nullish()}),Ol({inlineData:Ol({mimeType:zu(),data:zu()})}),Ol({executableCode:Ol({language:zu(),code:zu()}).nullish(),codeExecutionResult:Ol({outcome:zu(),output:zu()}).nullish(),text:zu().nullish(),thought:dl().nullish(),thoughtSignature:zu().nullish()})])).nullish()}),qm=Ol({category:zu().nullish(),probability:zu().nullish(),probabilityScore:al().nullish(),severity:zu().nullish(),severityScore:al().nullish(),blocked:dl().nullish()}),Fm=Ol({cachedContentTokenCount:al().nullish(),thoughtsTokenCount:al().nullish(),promptTokenCount:al().nullish(),candidatesTokenCount:al().nullish(),totalTokenCount:al().nullish()}),Wm=Ol({candidates:El(Ol({content:Zm.nullish().or(Ol({}).strict()),finishReason:zu().nullish(),safetyRatings:El(qm).nullish(),groundingMetadata:Rm.nullish(),urlContextMetadata:zm.nullish()})),usageMetadata:Fm.nullish()}),Jm=Ol({candidates:El(Ol({content:Zm.nullish(),finishReason:zu().nullish(),safetyRatings:El(qm).nullish(),groundingMetadata:Rm.nullish(),urlContextMetadata:zm.nullish()})).nullish(),usageMetadata:Fm.nullish()}),Bm={googleSearch:Um,urlContext:Dm,codeExecution:Ud({id:"google.code_execution",name:"code_execution",inputSchema:Ol({language:zu().describe("The programming language of the code."),code:zu().describe("The code to be executed.")}),outputSchema:Ol({outcome:zu().describe('The outcome of the execution (e.g., "OUTCOME_OK").'),output:zu().describe("The output from the code execution.")})})},Hm=class{constructor(e,t,n){this.modelId=e,this.settings=t,this.config=n,this.specificationVersion="v2"}get maxImagesPerCall(){var e;return null!=(e=this.settings.maxImagesPerCall)?e:4}get provider(){return this.config.provider}async doGenerate(e){var t,n,r;const{prompt:i,n:o=1,size:s="1024x1024",aspectRatio:a="1:1",seed:u,providerOptions:l,headers:c,abortSignal:d}=e,p=[];null!=s&&p.push({type:"unsupported-setting",setting:"size",details:"This model does not support the `size` option. Use `aspectRatio` instead."}),null!=u&&p.push({type:"unsupported-setting",setting:"seed",details:"This model does not support the `seed` option through this provider."});const m=await Nd({provider:"google",providerOptions:l,schema:Km}),h=null!=(r=null==(n=null==(t=this.config._internal)?void 0:t.currentDate)?void 0:n.call(t))?r:new Date,g={sampleCount:o};null!=a&&(g.aspectRatio=a),m&&Object.assign(g,m);const f={instances:[{prompt:i}],parameters:g},{responseHeaders:v,value:y}=await Ad({url:`${this.config.baseURL}/models/${this.modelId}:predict`,headers:pd(await jd(this.config.headers),c),body:f,failedResponseHandler:Im,successfulResponseHandler:Md(Vm),abortSignal:d,fetch:this.config.fetch});return{images:y.predictions.map((e=>e.bytesBase64Encoded)),warnings:null!=p?p:[],providerMetadata:{google:{images:y.predictions.map((e=>({})))}},response:{timestamp:h,modelId:this.modelId,headers:v}}}},Vm=Ol({predictions:El(Ol({bytesBase64Encoded:zu()})).default([])}),Km=Ol({personGeneration:Jl(["dont_allow","allow_adult","allow_all"]).nullish(),aspectRatio:Jl(["1:1","3:4","4:3","9:16","16:9"]).nullish()});function Gm(e={}){var t;const n=null!=(t=Vd(e.baseURL))?t:"https://generativelanguage.googleapis.com/v1beta",r=()=>({"x-goog-api-key":yd({apiKey:e.apiKey,environmentVariableName:"GOOGLE_GENERATIVE_AI_API_KEY",description:"Google Generative AI"}),...e.headers}),i=t=>{var i;return new Mm(t,{provider:"google.generative-ai",baseURL:n,headers:r,generateId:null!=(i=e.generateId)?i:gd,supportedUrls:()=>({"*":[new RegExp(`^${n}/files/.*$`),new RegExp("^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$"),new RegExp("^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$")]}),fetch:e.fetch})},o=t=>new $m(t,{provider:"google.generative-ai",baseURL:n,headers:r,fetch:e.fetch}),s=(t,i={})=>new Hm(t,i,{provider:"google.generative-ai",baseURL:n,headers:r,fetch:e.fetch}),a=function(e){if(new.target)throw new Error("The Google Generative AI model function cannot be called with the new keyword.");return i(e)};return a.languageModel=i,a.chat=i,a.generativeAI=i,a.embedding=o,a.textEmbedding=o,a.textEmbeddingModel=o,a.image=s,a.imageModel=s,a.tools=Bm,a}var Ym=Gm(),Xm=class{constructor(e){this.apiKey=e}async getAccessToken(){return this.apiKey}async refreshToken(){return Promise.resolve()}},Qm=class{constructor(e){n(this,"getTokenFn"),n(this,"refreshTokenFn"),n(this,"onRefreshErrorFn"),this.getTokenFn=e.getTokenFn,this.refreshTokenFn=e.refreshTokenFn,this.onRefreshErrorFn=e.onRefreshErrorFn}async getAccessToken(){return this.getTokenFn()}async refreshToken(){return this.refreshTokenFn()}onRefreshError(e){this.onRefreshErrorFn&&this.onRefreshErrorFn(e)}},eh={baseUrl:"undefined"!=typeof process&&(null==(e=process.env)?void 0:e.ECHO_BASE_URL)||"https://echo.merit.systems"};var th="https://echo.router.merit.systems",nh=class{constructor(e,t){n(this,"isRefreshing",!1),n(this,"refreshPromise",null),this.baseUrl=e,this.tokenProvider=t}async request(e,t={}){var n;const r=await this.tokenProvider.getAccessToken(),i=await fetch(`${this.baseUrl}${e}`,{...t,headers:{"Content-Type":"application/json",...t.headers,...r&&{Authorization:`Bearer ${r}`}}});if(401===i.status&&!(null==(n=t.headers)?void 0:n["X-Retry"])){await this.handleTokenRefresh();const n=await this.tokenProvider.getAccessToken();return fetch(`${this.baseUrl}${e}`,{...t,headers:{"Content-Type":"application/json",...t.headers,...n&&{Authorization:`Bearer ${n}`},"X-Retry":"true"}})}return i}async handleTokenRefresh(){if(this.isRefreshing&&this.refreshPromise)return this.refreshPromise;this.isRefreshing=!0,this.refreshPromise=this.performRefresh();try{await this.refreshPromise}finally{this.isRefreshing=!1,this.refreshPromise=null}}async performRefresh(){try{await this.tokenProvider.refreshToken()}catch(e){throw this.tokenProvider.onRefreshError&&this.tokenProvider.onRefreshError(e),e}}async get(e,t){return this.request(e,{...t,method:"GET"})}async post(e,t,n){return this.request(e,{...n,method:"POST",body:t?JSON.stringify(t):null})}async put(e,t,n){return this.request(e,{...n,method:"PUT",body:t?JSON.stringify(t):null})}async delete(e,t){return this.request(e,{...t,method:"DELETE"})}},rh=class extends Error{constructor(e,t,r){super(t),n(this,"code"),n(this,"statusCode"),n(this,"endpoint"),this.name="EchoError",this.code=e,void 0!==(null==r?void 0:r.statusCode)&&(this.statusCode=r.statusCode),void 0!==(null==r?void 0:r.endpoint)&&(this.endpoint=r.endpoint)}};function ih(e,t,n){if("TypeError"===e.name)return new rh("NETWORK_ERROR","Network error"+(t?` while ${t}`:""),n?{endpoint:n}:void 0);const r=e.message.match(/^HTTP (\d+): (.*)$/);if(r&&r[1]&&r[2]){const e=parseInt(r[1]),i=r[2];return new rh(`HTTP_${e}`,`${i}${t?` while ${t}`:""}`,n?{statusCode:e,endpoint:n}:{statusCode:e})}return new rh("UNKNOWN_ERROR",`${e.message}${t?` while ${t}`:""}`,n?{endpoint:n}:void 0)}var oh=class{constructor(e){this.http=e}async handleRequest(e,t,n){try{const t=await e();if(!t.ok){const e=await t.text();throw new Error(`HTTP ${t.status}: ${e}`)}return await t.json()}catch(r){if(r instanceof Error)throw ih(r,t,n);throw new rh("UNKNOWN_ERROR","Unknown error occurred",n?{endpoint:n}:void 0)}}},sh=class extends oh{constructor(e,t){super(e),this.baseUrl=t}async listEchoApps(){return(await this.handleRequest((()=>this.http.get("/api/v1/apps")),"listing Echo apps","/api/v1/apps")).apps}async getEchoApp(e){return this.handleRequest((()=>this.http.get(`/api/v1/apps/${e}`)),"fetching Echo app",`/api/v1/apps/${e}`)}getAppUrl(e){return`${this.baseUrl}/apps/${e}`}},ah=class extends oh{constructor(e){super(e)}async getBalance(){return this.handleRequest((()=>this.http.get("/api/v1/balance")),"fetching balance","/api/v1/balance")}async getFreeBalance(e){const t={echoAppId:e};return this.handleRequest((()=>this.http.post("/api/v1/balance/free",t)),"fetching free tier balance","/api/v1/balance/free")}},uh=class extends oh{constructor(e){super(e)}async getSupportedModels(){return this.handleRequest((()=>this.http.get("/api/v1/supported-models")),"fetching supported models","/api/v1/supported-models")}async listSupportedModels(){try{return(await this.getSupportedModels()).models}catch(e){throw e}}async getSupportedModelsByProvider(){try{return(await this.getSupportedModels()).models_by_provider}catch(e){throw e}}},lh=class extends oh{constructor(e){super(e)}async createPaymentLink(e){return this.handleRequest((()=>this.http.post("/api/v1/stripe/payment-link",e)),"creating payment link","/api/v1/stripe/payment-link")}async getPaymentUrl(e,t,n){const r={amount:e,description:t||"Echo Credits"};n&&(r.successUrl=n);try{return(await this.createPaymentLink(r)).paymentLink.url}catch(i){throw i}}},ch=class extends oh{constructor(e){super(e)}async getUserInfo(){return this.handleRequest((()=>this.http.get("/api/v1/user")),"fetching user info","/api/v1/user")}async registerReferralCode(e,t){const n={echoAppId:e,code:t};return this.handleRequest((()=>this.http.post("/api/v1/user/referral",n)),"registering referral code","/api/v1/user/referral")}},dh=class{constructor(e){var t;if(n(this,"http"),n(this,"config"),n(this,"tokenProvider"),n(this,"balance"),n(this,"payments"),n(this,"apps"),n(this,"users"),n(this,"models"),this.config=(t=e,{...eh,...t}),null==e?void 0:e.tokenProvider)this.tokenProvider=e.tokenProvider;else{const e=this.config.apiKey||process.env.ECHO_API_KEY;if(!e)throw new Error("No API key or token provider provided");this.tokenProvider=new Xm(e)}this.http=new nh(this.config.baseUrl,this.tokenProvider),this.balance=new ah(this.http),this.payments=new lh(this.http),this.apps=new sh(this.http,this.config.baseUrl),this.users=new ch(this.http),this.models=new uh(this.http)}};function ph({appId:e,baseRouterUrl:t=th},n){const r=async()=>{const r=await n(e);return Kp({baseURL:t,apiKey:r??""})};return Object.assign((async e=>(await r())(e)),{languageModel:async e=>(await r()).languageModel(e),chat:async e=>(await r()).chat(e),responses:async e=>(await r()).responses(e),completion:async e=>(await r()).completion(e),embedding:async e=>(await r()).embedding(e),textEmbedding:async e=>(await r()).textEmbedding(e),textEmbeddingModel:async e=>(await r()).textEmbeddingModel(e),image:async e=>(await r()).image(e),imageModel:async e=>(await r()).imageModel(e),transcription:async e=>(await r()).transcription(e),speech:async e=>(await r()).speech(e),tools:Gp.tools})}function mh({appId:e,baseRouterUrl:t=th},n){const r=async()=>{const r=await n(e);return km({baseURL:t,apiKey:r??""})};return Object.assign((async e=>(await r())(e)),{languageModel:async e=>(await r()).languageModel(e),chat:async e=>(await r()).chat(e),messages:async e=>(await r()).messages(e),textEmbeddingModel:async e=>(await r()).textEmbeddingModel(e),imageModel:async e=>(await r()).imageModel(e),tools:xm.tools})}function hh({appId:e,baseRouterUrl:t=th},n){const r=async()=>{const r=await n(e);return Gm({baseURL:t,apiKey:r??""})};return Object.assign((async e=>(await r())(e)),{languageModel:async e=>(await r()).languageModel(e),chat:async e=>(await r()).chat(e),image:async(e,t)=>(await r()).image(e,t),imageModel:async e=>(await r()).imageModel(e),textEmbedding:async e=>(await r()).textEmbedding(e),textEmbeddingModel:async e=>(await r()).textEmbeddingModel(e),generativeAI:async e=>(await r()).generativeAI(e),embedding:async e=>(await r()).embedding(e),tools:Ym.tools})}function gh({apiUrl:e}){var t,n;const r=$e(),[o,s]=i.useState(null);return i.useEffect((()=>{if(!r.user)return void s(null);const t=new Qm({getTokenFn:()=>{var e;return Promise.resolve((null==(e=r.user)?void 0:e.access_token)||null)},refreshTokenFn:async()=>{const e=await r.signinSilent();if(!e)throw new Error("Silent renew did not yield a new access token");return e.access_token},onRefreshErrorFn:async e=>{console.error("Token refresh failed:",e),await r.removeUser(),await r.clearStaleState()}}),n=new dh({baseUrl:e,tokenProvider:t});return s(n),()=>{s(null)}}),[e,r.user,null==(n=null==(t=r.user)?void 0:t.profile)?void 0:n.sub,r.signinSilent,r.signoutSilent]),o}const fh=i.createContext(null),vh=i.createContext(null);function yh({config:e,children:t}){var n,o,s;const a=$e(),u=a.user,l=u?function(e){return{id:e.profile.sub||"",email:e.profile.email||"",name:e.profile.name||e.profile.preferred_username||"",picture:e.profile.picture||""}}(u):null,c=e.apiUrl||"https://echo.merit.systems",d=(null==(n=a.user)?void 0:n.access_token)||null,p=gh({apiUrl:c}),{balance:m,freeTierBalance:h,refreshBalance:g,error:f,isLoading:v}=function(e,t){const[n,r]=i.useState(null),[o,s]=i.useState(null),[a,u]=i.useState(null),[l,c]=i.useState(!1),d=i.useCallback((async()=>{if(!e)throw new Error("Not authenticated");c(!0);try{const[n,i]=await Promise.all([e.balance.getBalance(),e.balance.getFreeBalance(t)]);r(n),s(i),u(null)}catch(n){const e=ih(n instanceof Error?n:new Error(String(n)),"refreshing balance");throw u(e.message),e}finally{c(!1)}}),[e,t]);return i.useEffect((()=>{e&&t?d().catch((e=>{console.error("Error loading initial balance:",e)})):(r(null),s(null),u(null))}),[e,t,d]),{balance:n,freeTierBalance:o,error:a,isLoading:l,refreshBalance:d}}(p,e.appId),{createPaymentLink:y,error:_,isLoading:b}=function(e){const[t,n]=i.useState(null),[r,o]=i.useState(!1);return{createPaymentLink:i.useCallback((async(t,r,i)=>{if(!e)throw new Error("Not authenticated");o(!0);try{const o=await e.payments.createPaymentLink({amount:t,description:r||"Echo Credits",successUrl:i||window.location.origin});return n(null),o.paymentLink.url}catch(s){const e=ih(s instanceof Error?s:new Error(String(s)),"creating payment link");throw n(e.message),e}finally{o(!1)}}),[e]),error:t,isLoading:r}}(p),w=i.useCallback((async()=>{try{await a.removeUser()}catch(e){console.error("Error during auth cleanup:",e)}}),[a.removeUser]),k=i.useCallback((async()=>{var e;return(null==(e=a.user)?void 0:e.access_token)||null}),[null==(o=a.user)?void 0:o.access_token]),x=(null==(s=a.error)?void 0:s.message)||f||_||null,I=a.isLoading&&!a.isAuthenticated,S=a.isLoading&&a.isAuthenticated,$=I||v||b,E=i.useMemo((()=>({user:l||null,rawUser:u,balance:m,freeTierBalance:h,isAuthenticated:a.isAuthenticated,isLoading:$,error:x,token:d,echoClient:p,signIn:a.signinRedirect,signOut:w,refreshBalance:g,createPaymentLink:y,getToken:k,clearAuth:w,config:e})),[l,u,m,h,a.isAuthenticated,$,x,d,p,a.signinRedirect,w,g,y,k,e]),T=i.useMemo((()=>({isRefreshing:S})),[S]);return r.jsx(fh.Provider,{value:E,children:r.jsx(vh.Provider,{value:T,children:t})})}function _h(){const e=i.useContext(fh);if(!e)throw new Error("useEcho must be used within an EchoProvider");return e}
|
|
2
|
-
/*! @license DOMPurify 3.2.6 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.2.6/LICENSE */const{entries:bh,setPrototypeOf:wh,isFrozen:kh,getPrototypeOf:xh,getOwnPropertyDescriptor:Ih}=Object;let{freeze:Sh,seal:$h,create:Eh}=Object,{apply:Th,construct:Oh}="undefined"!=typeof Reflect&&Reflect;Sh||(Sh=function(e){return e}),$h||($h=function(e){return e}),Th||(Th=function(e,t,n){return e.apply(t,n)}),Oh||(Oh=function(e,t){return new e(...t)});const Nh=Jh(Array.prototype.forEach),Ch=Jh(Array.prototype.lastIndexOf),Ah=Jh(Array.prototype.pop),Ph=Jh(Array.prototype.push),Rh=Jh(Array.prototype.splice),Uh=Jh(String.prototype.toLowerCase),jh=Jh(String.prototype.toString),zh=Jh(String.prototype.match),Dh=Jh(String.prototype.replace),Mh=Jh(String.prototype.indexOf),Lh=Jh(String.prototype.trim),Zh=Jh(Object.prototype.hasOwnProperty),qh=Jh(RegExp.prototype.test),Fh=(Wh=TypeError,function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return Oh(Wh,t)});var Wh;function Jh(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return Th(e,t,r)}}function Bh(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Uh;wh&&wh(e,null);let r=t.length;for(;r--;){let i=t[r];if("string"==typeof i){const e=n(i);e!==i&&(kh(t)||(t[r]=e),i=e)}e[i]=!0}return e}function Hh(e){for(let t=0;t<e.length;t++){Zh(e,t)||(e[t]=null)}return e}function Vh(e){const t=Eh(null);for(const[n,r]of bh(e)){Zh(e,n)&&(Array.isArray(r)?t[n]=Hh(r):r&&"object"==typeof r&&r.constructor===Object?t[n]=Vh(r):t[n]=r)}return t}function Kh(e,t){for(;null!==e;){const n=Ih(e,t);if(n){if(n.get)return Jh(n.get);if("function"==typeof n.value)return Jh(n.value)}e=xh(e)}return function(){return null}}const Gh=Sh(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","section","select","shadow","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),Yh=Sh(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","filter","font","g","glyph","glyphref","hkern","image","line","lineargradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),Xh=Sh(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),Qh=Sh(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),eg=Sh(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),tg=Sh(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),ng=Sh(["#text"]),rg=Sh(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","face","for","headers","height","hidden","high","href","hreflang","id","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),ig=Sh(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),og=Sh(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),sg=Sh(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),ag=$h(/\{\{[\w\W]*|[\w\W]*\}\}/gm),ug=$h(/<%[\w\W]*|[\w\W]*%>/gm),lg=$h(/\$\{[\w\W]*/gm),cg=$h(/^data-[\-\w.\u00B7-\uFFFF]+$/),dg=$h(/^aria-[\-\w]+$/),pg=$h(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),mg=$h(/^(?:\w+script|data):/i),hg=$h(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),gg=$h(/^html$/i),fg=$h(/^[a-z][.\w]*(-[.\w]+)+$/i);var vg=Object.freeze({__proto__:null,ARIA_ATTR:dg,ATTR_WHITESPACE:hg,CUSTOM_ELEMENT:fg,DATA_ATTR:cg,DOCTYPE_NAME:gg,ERB_EXPR:ug,IS_ALLOWED_URI:pg,IS_SCRIPT_OR_DATA:mg,MUSTACHE_EXPR:ag,TMPLIT_EXPR:lg});const yg=1,_g=3,bg=7,wg=8,kg=9;var xg=function e(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"undefined"==typeof window?null:window;const n=t=>e(t);if(n.version="3.2.6",n.removed=[],!t||!t.document||t.document.nodeType!==kg||!t.Element)return n.isSupported=!1,n;let{document:r}=t;const i=r,o=i.currentScript,{DocumentFragment:s,HTMLTemplateElement:a,Node:u,Element:l,NodeFilter:c,NamedNodeMap:d=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:p,DOMParser:m,trustedTypes:h}=t,g=l.prototype,f=Kh(g,"cloneNode"),v=Kh(g,"remove"),y=Kh(g,"nextSibling"),_=Kh(g,"childNodes"),b=Kh(g,"parentNode");if("function"==typeof a){const e=r.createElement("template");e.content&&e.content.ownerDocument&&(r=e.content.ownerDocument)}let w,k="";const{implementation:x,createNodeIterator:I,createDocumentFragment:S,getElementsByTagName:$}=r,{importNode:E}=i;let T={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]};n.isSupported="function"==typeof bh&&"function"==typeof b&&x&&void 0!==x.createHTMLDocument;const{MUSTACHE_EXPR:O,ERB_EXPR:N,TMPLIT_EXPR:C,DATA_ATTR:A,ARIA_ATTR:P,IS_SCRIPT_OR_DATA:R,ATTR_WHITESPACE:U,CUSTOM_ELEMENT:j}=vg;let{IS_ALLOWED_URI:z}=vg,D=null;const M=Bh({},[...Gh,...Yh,...Xh,...eg,...ng]);let L=null;const Z=Bh({},[...rg,...ig,...og,...sg]);let q=Object.seal(Eh(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),F=null,W=null,J=!0,B=!0,H=!1,V=!0,K=!1,G=!0,Y=!1,X=!1,Q=!1,ee=!1,te=!1,ne=!1,re=!0,ie=!1,oe=!0,se=!1,ae={},ue=null;const le=Bh({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let ce=null;const de=Bh({},["audio","video","img","source","image","track"]);let pe=null;const me=Bh({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),he="http://www.w3.org/1998/Math/MathML",ge="http://www.w3.org/2000/svg",fe="http://www.w3.org/1999/xhtml";let ve=fe,ye=!1,_e=null;const be=Bh({},[he,ge,fe],jh);let we=Bh({},["mi","mo","mn","ms","mtext"]),ke=Bh({},["annotation-xml"]);const xe=Bh({},["title","style","font","a","script"]);let Ie=null;const Se=["application/xhtml+xml","text/html"];let $e=null,Ee=null;const Te=r.createElement("form"),Oe=function(e){return e instanceof RegExp||e instanceof Function},Ne=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!Ee||Ee!==e){if(e&&"object"==typeof e||(e={}),e=Vh(e),Ie=-1===Se.indexOf(e.PARSER_MEDIA_TYPE)?"text/html":e.PARSER_MEDIA_TYPE,$e="application/xhtml+xml"===Ie?jh:Uh,D=Zh(e,"ALLOWED_TAGS")?Bh({},e.ALLOWED_TAGS,$e):M,L=Zh(e,"ALLOWED_ATTR")?Bh({},e.ALLOWED_ATTR,$e):Z,_e=Zh(e,"ALLOWED_NAMESPACES")?Bh({},e.ALLOWED_NAMESPACES,jh):be,pe=Zh(e,"ADD_URI_SAFE_ATTR")?Bh(Vh(me),e.ADD_URI_SAFE_ATTR,$e):me,ce=Zh(e,"ADD_DATA_URI_TAGS")?Bh(Vh(de),e.ADD_DATA_URI_TAGS,$e):de,ue=Zh(e,"FORBID_CONTENTS")?Bh({},e.FORBID_CONTENTS,$e):le,F=Zh(e,"FORBID_TAGS")?Bh({},e.FORBID_TAGS,$e):Vh({}),W=Zh(e,"FORBID_ATTR")?Bh({},e.FORBID_ATTR,$e):Vh({}),ae=!!Zh(e,"USE_PROFILES")&&e.USE_PROFILES,J=!1!==e.ALLOW_ARIA_ATTR,B=!1!==e.ALLOW_DATA_ATTR,H=e.ALLOW_UNKNOWN_PROTOCOLS||!1,V=!1!==e.ALLOW_SELF_CLOSE_IN_ATTR,K=e.SAFE_FOR_TEMPLATES||!1,G=!1!==e.SAFE_FOR_XML,Y=e.WHOLE_DOCUMENT||!1,ee=e.RETURN_DOM||!1,te=e.RETURN_DOM_FRAGMENT||!1,ne=e.RETURN_TRUSTED_TYPE||!1,Q=e.FORCE_BODY||!1,re=!1!==e.SANITIZE_DOM,ie=e.SANITIZE_NAMED_PROPS||!1,oe=!1!==e.KEEP_CONTENT,se=e.IN_PLACE||!1,z=e.ALLOWED_URI_REGEXP||pg,ve=e.NAMESPACE||fe,we=e.MATHML_TEXT_INTEGRATION_POINTS||we,ke=e.HTML_INTEGRATION_POINTS||ke,q=e.CUSTOM_ELEMENT_HANDLING||{},e.CUSTOM_ELEMENT_HANDLING&&Oe(e.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(q.tagNameCheck=e.CUSTOM_ELEMENT_HANDLING.tagNameCheck),e.CUSTOM_ELEMENT_HANDLING&&Oe(e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(q.attributeNameCheck=e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),e.CUSTOM_ELEMENT_HANDLING&&"boolean"==typeof e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements&&(q.allowCustomizedBuiltInElements=e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),K&&(B=!1),te&&(ee=!0),ae&&(D=Bh({},ng),L=[],!0===ae.html&&(Bh(D,Gh),Bh(L,rg)),!0===ae.svg&&(Bh(D,Yh),Bh(L,ig),Bh(L,sg)),!0===ae.svgFilters&&(Bh(D,Xh),Bh(L,ig),Bh(L,sg)),!0===ae.mathMl&&(Bh(D,eg),Bh(L,og),Bh(L,sg))),e.ADD_TAGS&&(D===M&&(D=Vh(D)),Bh(D,e.ADD_TAGS,$e)),e.ADD_ATTR&&(L===Z&&(L=Vh(L)),Bh(L,e.ADD_ATTR,$e)),e.ADD_URI_SAFE_ATTR&&Bh(pe,e.ADD_URI_SAFE_ATTR,$e),e.FORBID_CONTENTS&&(ue===le&&(ue=Vh(ue)),Bh(ue,e.FORBID_CONTENTS,$e)),oe&&(D["#text"]=!0),Y&&Bh(D,["html","head","body"]),D.table&&(Bh(D,["tbody"]),delete F.tbody),e.TRUSTED_TYPES_POLICY){if("function"!=typeof e.TRUSTED_TYPES_POLICY.createHTML)throw Fh('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw Fh('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');w=e.TRUSTED_TYPES_POLICY,k=w.createHTML("")}else void 0===w&&(w=function(e,t){if("object"!=typeof e||"function"!=typeof e.createPolicy)return null;let n=null;const r="data-tt-policy-suffix";t&&t.hasAttribute(r)&&(n=t.getAttribute(r));const i="dompurify"+(n?"#"+n:"");try{return e.createPolicy(i,{createHTML:e=>e,createScriptURL:e=>e})}catch(o){return console.warn("TrustedTypes policy "+i+" could not be created."),null}}(h,o)),null!==w&&"string"==typeof k&&(k=w.createHTML(""));Sh&&Sh(e),Ee=e}},Ce=Bh({},[...Yh,...Xh,...Qh]),Ae=Bh({},[...eg,...tg]),Pe=function(e){Ph(n.removed,{element:e});try{b(e).removeChild(e)}catch(t){v(e)}},Re=function(e,t){try{Ph(n.removed,{attribute:t.getAttributeNode(e),from:t})}catch(r){Ph(n.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e)if(ee||te)try{Pe(t)}catch(r){}else try{t.setAttribute(e,"")}catch(r){}},Ue=function(e){let t=null,n=null;if(Q)e="<remove></remove>"+e;else{const t=zh(e,/^[\r\n\t ]+/);n=t&&t[0]}"application/xhtml+xml"===Ie&&ve===fe&&(e='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+e+"</body></html>");const i=w?w.createHTML(e):e;if(ve===fe)try{t=(new m).parseFromString(i,Ie)}catch(s){}if(!t||!t.documentElement){t=x.createDocument(ve,"template",null);try{t.documentElement.innerHTML=ye?k:i}catch(s){}}const o=t.body||t.documentElement;return e&&n&&o.insertBefore(r.createTextNode(n),o.childNodes[0]||null),ve===fe?$.call(t,Y?"html":"body")[0]:Y?t.documentElement:o},je=function(e){return I.call(e.ownerDocument||e,e,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},ze=function(e){return e instanceof p&&("string"!=typeof e.nodeName||"string"!=typeof e.textContent||"function"!=typeof e.removeChild||!(e.attributes instanceof d)||"function"!=typeof e.removeAttribute||"function"!=typeof e.setAttribute||"string"!=typeof e.namespaceURI||"function"!=typeof e.insertBefore||"function"!=typeof e.hasChildNodes)},De=function(e){return"function"==typeof u&&e instanceof u};function Me(e,t,r){Nh(e,(e=>{e.call(n,t,r,Ee)}))}const Le=function(e){let t=null;if(Me(T.beforeSanitizeElements,e,null),ze(e))return Pe(e),!0;const r=$e(e.nodeName);if(Me(T.uponSanitizeElement,e,{tagName:r,allowedTags:D}),G&&e.hasChildNodes()&&!De(e.firstElementChild)&&qh(/<[/\w!]/g,e.innerHTML)&&qh(/<[/\w!]/g,e.textContent))return Pe(e),!0;if(e.nodeType===bg)return Pe(e),!0;if(G&&e.nodeType===wg&&qh(/<[/\w]/g,e.data))return Pe(e),!0;if(!D[r]||F[r]){if(!F[r]&&qe(r)){if(q.tagNameCheck instanceof RegExp&&qh(q.tagNameCheck,r))return!1;if(q.tagNameCheck instanceof Function&&q.tagNameCheck(r))return!1}if(oe&&!ue[r]){const t=b(e)||e.parentNode,n=_(e)||e.childNodes;if(n&&t){for(let r=n.length-1;r>=0;--r){const i=f(n[r],!0);i.__removalCount=(e.__removalCount||0)+1,t.insertBefore(i,y(e))}}}return Pe(e),!0}return e instanceof l&&!function(e){let t=b(e);t&&t.tagName||(t={namespaceURI:ve,tagName:"template"});const n=Uh(e.tagName),r=Uh(t.tagName);return!!_e[e.namespaceURI]&&(e.namespaceURI===ge?t.namespaceURI===fe?"svg"===n:t.namespaceURI===he?"svg"===n&&("annotation-xml"===r||we[r]):Boolean(Ce[n]):e.namespaceURI===he?t.namespaceURI===fe?"math"===n:t.namespaceURI===ge?"math"===n&&ke[r]:Boolean(Ae[n]):e.namespaceURI===fe?!(t.namespaceURI===ge&&!ke[r])&&!(t.namespaceURI===he&&!we[r])&&!Ae[n]&&(xe[n]||!Ce[n]):!("application/xhtml+xml"!==Ie||!_e[e.namespaceURI]))}(e)?(Pe(e),!0):"noscript"!==r&&"noembed"!==r&&"noframes"!==r||!qh(/<\/no(script|embed|frames)/i,e.innerHTML)?(K&&e.nodeType===_g&&(t=e.textContent,Nh([O,N,C],(e=>{t=Dh(t,e," ")})),e.textContent!==t&&(Ph(n.removed,{element:e.cloneNode()}),e.textContent=t)),Me(T.afterSanitizeElements,e,null),!1):(Pe(e),!0)},Ze=function(e,t,n){if(re&&("id"===t||"name"===t)&&(n in r||n in Te))return!1;if(B&&!W[t]&&qh(A,t));else if(J&&qh(P,t));else if(!L[t]||W[t]){if(!(qe(e)&&(q.tagNameCheck instanceof RegExp&&qh(q.tagNameCheck,e)||q.tagNameCheck instanceof Function&&q.tagNameCheck(e))&&(q.attributeNameCheck instanceof RegExp&&qh(q.attributeNameCheck,t)||q.attributeNameCheck instanceof Function&&q.attributeNameCheck(t))||"is"===t&&q.allowCustomizedBuiltInElements&&(q.tagNameCheck instanceof RegExp&&qh(q.tagNameCheck,n)||q.tagNameCheck instanceof Function&&q.tagNameCheck(n))))return!1}else if(pe[t]);else if(qh(z,Dh(n,U,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==Mh(n,"data:")||!ce[e]){if(H&&!qh(R,Dh(n,U,"")));else if(n)return!1}else;return!0},qe=function(e){return"annotation-xml"!==e&&zh(e,j)},Fe=function(e){Me(T.beforeSanitizeAttributes,e,null);const{attributes:t}=e;if(!t||ze(e))return;const r={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:L,forceKeepAttr:void 0};let i=t.length;for(;i--;){const s=t[i],{name:a,namespaceURI:u,value:l}=s,c=$e(a),d=l;let p="value"===a?d:Lh(d);if(r.attrName=c,r.attrValue=p,r.keepAttr=!0,r.forceKeepAttr=void 0,Me(T.uponSanitizeAttribute,e,r),p=r.attrValue,!ie||"id"!==c&&"name"!==c||(Re(a,e),p="user-content-"+p),G&&qh(/((--!?|])>)|<\/(style|title)/i,p)){Re(a,e);continue}if(r.forceKeepAttr)continue;if(!r.keepAttr){Re(a,e);continue}if(!V&&qh(/\/>/i,p)){Re(a,e);continue}K&&Nh([O,N,C],(e=>{p=Dh(p,e," ")}));const m=$e(e.nodeName);if(Ze(m,c,p)){if(w&&"object"==typeof h&&"function"==typeof h.getAttributeType)if(u);else switch(h.getAttributeType(m,c)){case"TrustedHTML":p=w.createHTML(p);break;case"TrustedScriptURL":p=w.createScriptURL(p)}if(p!==d)try{u?e.setAttributeNS(u,a,p):e.setAttribute(a,p),ze(e)?Pe(e):Ah(n.removed)}catch(o){Re(a,e)}}else Re(a,e)}Me(T.afterSanitizeAttributes,e,null)},We=function e(t){let n=null;const r=je(t);for(Me(T.beforeSanitizeShadowDOM,t,null);n=r.nextNode();)Me(T.uponSanitizeShadowNode,n,null),Le(n),Fe(n),n.content instanceof s&&e(n.content);Me(T.afterSanitizeShadowDOM,t,null)};return n.sanitize=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=null,o=null,a=null,l=null;if(ye=!e,ye&&(e="\x3c!--\x3e"),"string"!=typeof e&&!De(e)){if("function"!=typeof e.toString)throw Fh("toString is not a function");if("string"!=typeof(e=e.toString()))throw Fh("dirty is not a string, aborting")}if(!n.isSupported)return e;if(X||Ne(t),n.removed=[],"string"==typeof e&&(se=!1),se){if(e.nodeName){const t=$e(e.nodeName);if(!D[t]||F[t])throw Fh("root node is forbidden and cannot be sanitized in-place")}}else if(e instanceof u)r=Ue("\x3c!----\x3e"),o=r.ownerDocument.importNode(e,!0),o.nodeType===yg&&"BODY"===o.nodeName||"HTML"===o.nodeName?r=o:r.appendChild(o);else{if(!ee&&!K&&!Y&&-1===e.indexOf("<"))return w&&ne?w.createHTML(e):e;if(r=Ue(e),!r)return ee?null:ne?k:""}r&&Q&&Pe(r.firstChild);const c=je(se?e:r);for(;a=c.nextNode();)Le(a),Fe(a),a.content instanceof s&&We(a.content);if(se)return e;if(ee){if(te)for(l=S.call(r.ownerDocument);r.firstChild;)l.appendChild(r.firstChild);else l=r;return(L.shadowroot||L.shadowrootmode)&&(l=E.call(i,l,!0)),l}let d=Y?r.outerHTML:r.innerHTML;return Y&&D["!doctype"]&&r.ownerDocument&&r.ownerDocument.doctype&&r.ownerDocument.doctype.name&&qh(gg,r.ownerDocument.doctype.name)&&(d="<!DOCTYPE "+r.ownerDocument.doctype.name+">\n"+d),K&&Nh([O,N,C],(e=>{d=Dh(d,e," ")})),w&&ne?w.createHTML(d):d},n.setConfig=function(){Ne(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),X=!0},n.clearConfig=function(){Ee=null,X=!1},n.isValidAttribute=function(e,t,n){Ee||Ne({});const r=$e(e),i=$e(t);return Ze(r,i,n)},n.addHook=function(e,t){"function"==typeof t&&Ph(T[e],t)},n.removeHook=function(e,t){if(void 0!==t){const n=Ch(T[e],t);return-1===n?void 0:Rh(T[e],n,1)[0]}return Ah(T[e])},n.removeHooks=function(e){T[e]=[]},n.removeAllHooks=function(){T={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},n}();const Ig=(()=>{if("undefined"!=typeof window)return xg;try{const{JSDOM:e}=require("jsdom"),{window:t}=new e("");return xg(t)}catch{return{sanitize:e=>String(e||"").replace(/<[^>]*>/g,"")}}})();function Sg(e){if(!e)return"";const t=String(e);try{let e=Ig.sanitize(t,{ALLOWED_TAGS:[],ALLOWED_ATTR:[],KEEP_CONTENT:!0,RETURN_DOM:!1,RETURN_DOM_FRAGMENT:!1,FORCE_BODY:!0});if(!e.trim()&&t){t.replace(/<[^>]*>/g,"").trim()&&(e=t.replace(/<[^>]*>/g,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"").trim())}return e.trim().slice(0,1e3)}catch{return t.replace(/<[^>]*>/g,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"").trim().slice(0,1e3)}}async function $g(e,t={}){const{onComplete:n,onCancel:r,onError:i}=t,o=function(e){if(!e)return"";const t=Sg(e);try{const e=new URL(t);return"http:"===e.protocol||"https:"===e.protocol?t:""}catch{return""}}(e);if(!o){const e=new Error("Invalid payment URL provided");throw null==i||i(e),e}try{const e=window.open(o,"echo-payment","width=600,height=700,scrollbars=yes,resizable=yes");if(e&&!e.closed)return new Promise((t=>{const i=()=>{try{if(e.closed)return null==n||n(),void t();setTimeout(i,1e3)}catch{null==n||n(),t()}};i(),setTimeout((()=>{e.close(),null==r||r(),t()}),6e5)}));return confirm("Payment will open in a new tab. Click OK to continue, or Cancel to abort.")?(sessionStorage.setItem("echo_payment_flow","true"),window.location.href=o,new Promise((e=>{const t=()=>{"completed"===sessionStorage.getItem("echo_payment_flow")&&(sessionStorage.removeItem("echo_payment_flow"),null==n||n(),window.removeEventListener("focus",t),e())};window.addEventListener("focus",t),setTimeout((()=>{window.removeEventListener("focus",t),sessionStorage.removeItem("echo_payment_flow"),null==r||r(),e()}),18e5)}))):(null==r||r(),Promise.resolve())}catch(s){const e=s instanceof Error?s:new Error("Payment flow failed");throw null==i||i(e),e}}const Eg=({className:e="",width:t=16,height:n=16,variant:i="light"})=>{const o="dark"===i?"#DFE2D9":"#232323";return r.jsxs("svg",{id:"Layer_1","data-name":"Layer 1",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 226.03 261",className:e,width:t,height:n,"aria-label":"Echo Logo",children:[r.jsx("defs",{children:r.jsx("style",{children:`\n .cls-1 {\n fill: none;\n }\n .cls-3 {\n fill: #7f0404;\n }\n .cls-4 {\n fill: ${o};\n }\n .cls-5 {\n fill: #a50404;\n }\n .cls-6 {\n fill: #cd0202;\n opacity: .9;\n }\n `})}),r.jsx("polygon",{className:"cls-6",points:"59.23 99.45 59.23 161.55 113.02 192.61 113.02 130.5 59.23 99.45"}),r.jsx("polygon",{className:"cls-5",points:"113.02 68.39 113.02 68.39 59.23 99.45 113.02 130.5 166.8 99.45 113.02 68.39"}),r.jsx("polygon",{className:"cls-3",points:"166.8 99.45 113.02 130.5 113.02 192.61 113.02 192.61 166.8 161.55 166.8 99.45"}),r.jsxs("g",{children:[r.jsx("path",{className:"cls-4",d:"m113.02,196.41l-57.08-32.95v-65.91l57.08-32.95,57.08,32.95v65.91l-57.08,32.95Zm-52.53-35.58l52.53,30.33,52.53-30.33v-60.66l-52.53-30.33-52.53,30.33v60.66Z"}),r.jsx("path",{className:"cls-4",d:"m113.02,261L0,195.75V65.25L113.02,0l113.02,65.25v130.5l-113.02,65.25ZM6.82,191.81l106.2,61.31,106.2-61.31v-122.62L113.02,7.88,6.82,69.19v122.62Z"}),r.jsx("rect",{className:"cls-4",x:"111.88",y:"3.94",width:"2.27",height:"63.28"}),r.jsx("rect",{className:"cls-4",x:"-.83",y:"176.82",width:"63.28",height:"2.27",transform:"translate(-84.84 39.24) rotate(-29.99)"}),r.jsx("rect",{className:"cls-4",x:"194.08",y:"146.32",width:"2.27",height:"63.28",transform:"translate(-56.51 258.05) rotate(-60)"}),r.jsx("rect",{className:"cls-4",x:"111.88",y:"130.5",width:"2.27",height:"126.56"}),r.jsx("rect",{className:"cls-4",x:"104.54",y:"97.72",width:"126.56",height:"2.27",transform:"translate(-26.95 97.14) rotate(-29.99)"}),r.jsx("rect",{className:"cls-4",x:"57.08",y:"35.58",width:"2.27",height:"126.56",transform:"translate(-56.51 99.84) rotate(-60)"})]})]})};const Tg=({onAddCredits:e,onCancel:t,isProcessing:n})=>{const[o,s]=i.useState(""),a=i.useRef(null);i.useEffect((()=>{a.current&&a.current.focus()}),[]);const u=""!==o&&Number(o)>0;return r.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:"8px"},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[r.jsx("span",{style:{fontSize:"14px",color:"#6b7280",fontFamily:"HelveticaNowDisplay, sans-serif"},children:"$"}),r.jsx("input",{ref:a,type:"number",placeholder:"0.00",value:o,onChange:e=>s(e.target.value),style:{width:"96px",textAlign:"right",padding:"8px 12px",border:"1px solid #e5e7eb",borderRadius:"6px",fontSize:"14px",fontFamily:"HelveticaNowDisplay, sans-serif",outline:"none",backgroundColor:"#ffffff"},min:"1",step:"0.01"})]}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[r.jsx("button",{onClick:t,style:{padding:"8px 12px",backgroundColor:"transparent",color:"#6b7280",border:"none",borderRadius:"6px",fontSize:"14px",cursor:"pointer",fontFamily:"HelveticaNowDisplay, sans-serif",textDecoration:"none"},onMouseEnter:e=>{e.currentTarget.style.color="#111827"},onMouseLeave:e=>{e.currentTarget.style.color="#6b7280"},children:"Cancel"}),r.jsx("button",{onClick:()=>{const t=Number(o);t>0&&e(t)},disabled:n||!u,style:{padding:"8px 16px",backgroundColor:n||!u?"#9ca3af":"#dc2626",color:"white",border:"none",borderRadius:"6px",fontSize:"14px",fontWeight:"500",cursor:n||!u?"not-allowed":"pointer",fontFamily:"HelveticaNowDisplay, sans-serif"},onMouseEnter:e=>{!n&&u&&(e.currentTarget.style.backgroundColor="#b91c1c")},onMouseLeave:e=>{!n&&u&&(e.currentTarget.style.backgroundColor="#dc2626")},children:n?"Processing...":"Add Credits"})]})]})};const Og=i.createContext(null);var Ng=({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:r="-"}={})=>{const i=()=>{const e=n.length,r=new Array(t);for(let i=0;i<t;i++)r[i]=n[Math.random()*e|0];return r.join("")};if(null==e)return i;if(n.includes(r))throw new Be({argument:"separator",message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`},Cg=Ng(),Ag=/"__proto__"\s*:/,Pg=/"constructor"\s*:/;function Rg(e){const t=JSON.parse(e);return null===t||"object"!=typeof t||!1===Ag.test(e)&&!1===Pg.test(e)?t:function(e){let t=[e];for(;t.length;){const e=t;t=[];for(const n of e){if(Object.prototype.hasOwnProperty.call(n,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(n,"constructor")&&Object.prototype.hasOwnProperty.call(n.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const e in n){const r=n[e];r&&"object"==typeof r&&t.push(r)}}}return e}(t)}var Ug=Symbol.for("vercel.ai.validator");function jg(e){return function(e){return"object"==typeof e&&null!==e&&Ug in e&&!0===e[Ug]&&"validate"in e}(e)?e:(t=e,n=async e=>{const n=await t["~standard"].validate(e);return null==n.issues?{success:!0,value:n.value}:{success:!1,error:new Tt({value:e,cause:n.issues})}},{[Ug]:!0,validate:n});var t,n}async function zg({value:e,schema:t}){const n=await Dg({value:e,schema:t});if(!n.success)throw Tt.wrap({value:e,cause:n.error});return n.value}async function Dg({value:e,schema:t}){const n=jg(t);try{if(null==n.validate)return{success:!0,value:e,rawValue:e};const t=await n.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:Tt.wrap({value:e,cause:t.error}),rawValue:e}}catch(r){return{success:!1,error:Tt.wrap({value:e,cause:r}),rawValue:e}}}async function Mg({text:e,schema:t}){try{const n=function(e){const{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return Rg(e)}finally{Error.stackTraceLimit=t}}(e);return null==t?{success:!0,value:n,rawValue:n}:await Dg({value:n,schema:t})}catch(n){return{success:!1,error:at.isInstance(n)?n:new at({text:e,cause:n}),rawValue:void 0}}}async function Lg(e){return"function"==typeof e&&(e=e()),Promise.resolve(e)}function Zg(e,t){return function(e){return"_zod"in e}(e)?function(e){return Fg(hu(e,{target:"draft-7",io:"output",reused:"inline"}),{validate:async t=>{const n=await Pu(e,t);return n.success?{success:!0,value:n.data}:{success:!1,error:n.error}}})}(e):function(e){return Fg(dd(e,{$refStrategy:"none",target:"jsonSchema7"}),{validate:async t=>{const n=await e.safeParseAsync(t);return n.success?{success:!0,value:n.data}:{success:!1,error:n.error}}})}(e)}var qg=Symbol.for("vercel.ai.schema");function Fg(e,{validate:t}={}){return{[qg]:!0,_type:void 0,[Ug]:!0,jsonSchema:e,validate:t}}function Wg(e){return null==e?Fg({properties:{},additionalProperties:!1}):"object"==typeof(t=e)&&null!==t&&qg in t&&!0===t[qg]&&"jsonSchema"in t&&"validate"in t?e:Zg(e);var t}var Jg,Bg=Object.defineProperty,Hg="AI_NoObjectGeneratedError",Vg=`vercel.ai.error.${Hg}`,Kg=Symbol.for(Vg),Gg=class extends Ce{constructor({message:e="No object generated.",cause:t,text:n,response:r,usage:i,finishReason:o}){super({name:Hg,message:e,cause:t}),this[Jg]=!0,this.text=n,this.response=r,this.usage=i,this.finishReason=o}static isInstance(e){return Ce.hasMarker(e,Vg)}};Jg=Kg;var Yg=Pl([zu(),xc(Uint8Array),xc(ArrayBuffer),bc((e=>{var t,n;return null!=(n=null==(t=globalThis.Buffer)?void 0:t.isBuffer(e))&&n}),{message:"Must be a Buffer"})]),Xg=vc((()=>Pl([vl(),zu(),al(),dl(),Zl(zu(),Xg),El(Xg)]))),Qg=Zl(zu(),Zl(zu(),Xg)),ef=Ol({type:Hl("text"),text:zu(),providerOptions:Qg.optional()}),tf=Ol({type:Hl("image"),image:Pl([Yg,xc(URL)]),mediaType:zu().optional(),providerOptions:Qg.optional()}),nf=Ol({type:Hl("file"),data:Pl([Yg,xc(URL)]),filename:zu().optional(),mediaType:zu(),providerOptions:Qg.optional()}),rf=Ol({type:Hl("reasoning"),text:zu(),providerOptions:Qg.optional()}),of=Ol({type:Hl("tool-call"),toolCallId:zu(),toolName:zu(),input:wl(),providerOptions:Qg.optional(),providerExecuted:dl().optional()}),sf=Ul("type",[Ol({type:Hl("text"),value:zu()}),Ol({type:Hl("json"),value:Xg}),Ol({type:Hl("error-text"),value:zu()}),Ol({type:Hl("error-json"),value:Xg}),Ol({type:Hl("content"),value:El(Pl([Ol({type:Hl("text"),text:zu()}),Ol({type:Hl("media"),data:zu(),mediaType:zu()})]))})]),af=Ol({type:Hl("tool-result"),toolCallId:zu(),toolName:zu(),output:sf,providerOptions:Qg.optional()}),uf=Ol({role:Hl("system"),content:zu(),providerOptions:Qg.optional()}),lf=Ol({role:Hl("user"),content:Pl([zu(),El(Pl([ef,tf,nf]))]),providerOptions:Qg.optional()}),cf=Ol({role:Hl("assistant"),content:Pl([zu(),El(Pl([ef,nf,rf,of,af]))]),providerOptions:Qg.optional()});Pl([uf,lf,cf,Ol({role:Hl("tool"),content:El(af),providerOptions:Qg.optional()})]),Ng({prefix:"aitxt",size:24}),TransformStream;var df=Pl([Nl({type:Hl("text-start"),id:zu(),providerMetadata:Qg.optional()}),Nl({type:Hl("text-delta"),id:zu(),delta:zu(),providerMetadata:Qg.optional()}),Nl({type:Hl("text-end"),id:zu(),providerMetadata:Qg.optional()}),Nl({type:Hl("error"),errorText:zu()}),Nl({type:Hl("tool-input-start"),toolCallId:zu(),toolName:zu(),providerExecuted:dl().optional(),dynamic:dl().optional()}),Nl({type:Hl("tool-input-delta"),toolCallId:zu(),inputTextDelta:zu()}),Nl({type:Hl("tool-input-available"),toolCallId:zu(),toolName:zu(),input:wl(),providerExecuted:dl().optional(),providerMetadata:Qg.optional(),dynamic:dl().optional()}),Nl({type:Hl("tool-input-error"),toolCallId:zu(),toolName:zu(),input:wl(),providerExecuted:dl().optional(),providerMetadata:Qg.optional(),dynamic:dl().optional(),errorText:zu()}),Nl({type:Hl("tool-output-available"),toolCallId:zu(),output:wl(),providerExecuted:dl().optional(),dynamic:dl().optional(),preliminary:dl().optional()}),Nl({type:Hl("tool-output-error"),toolCallId:zu(),errorText:zu(),providerExecuted:dl().optional(),dynamic:dl().optional()}),Nl({type:Hl("reasoning"),text:zu(),providerMetadata:Qg.optional()}),Nl({type:Hl("reasoning-start"),id:zu(),providerMetadata:Qg.optional()}),Nl({type:Hl("reasoning-delta"),id:zu(),delta:zu(),providerMetadata:Qg.optional()}),Nl({type:Hl("reasoning-end"),id:zu(),providerMetadata:Qg.optional()}),Nl({type:Hl("reasoning-part-finish")}),Nl({type:Hl("source-url"),sourceId:zu(),url:zu(),title:zu().optional(),providerMetadata:Qg.optional()}),Nl({type:Hl("source-document"),sourceId:zu(),mediaType:zu(),title:zu(),filename:zu().optional(),providerMetadata:Qg.optional()}),Nl({type:Hl("file"),url:zu(),mediaType:zu(),providerMetadata:Qg.optional()}),Nl({type:zu().startsWith("data-"),id:zu().optional(),data:wl(),transient:dl().optional()}),Nl({type:Hl("start-step")}),Nl({type:Hl("finish-step")}),Nl({type:Hl("start"),messageId:zu().optional(),messageMetadata:wl().optional()}),Nl({type:Hl("finish"),messageMetadata:wl().optional()}),Nl({type:Hl("abort")}),Nl({type:Hl("message-metadata"),messageMetadata:wl()})]);function pf(e,t){if(void 0===e&&void 0===t)return;if(void 0===e)return t;if(void 0===t)return e;const n={...e};for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const i=t[r];if(void 0===i)continue;const o=r in e?e[r]:void 0,s=!(null===i||"object"!=typeof i||Array.isArray(i)||i instanceof Date||i instanceof RegExp),a=!(null==o||"object"!=typeof o||Array.isArray(o)||o instanceof Date||o instanceof RegExp);n[r]=s&&a?pf(o,i):i}return n}function mf(e){const t=["ROOT"];let n=-1,r=null;function i(e,i,o){switch(e){case'"':n=i,t.pop(),t.push(o),t.push("INSIDE_STRING");break;case"f":case"t":case"n":n=i,r=i,t.pop(),t.push(o),t.push("INSIDE_LITERAL");break;case"-":t.pop(),t.push(o),t.push("INSIDE_NUMBER");break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":n=i,t.pop(),t.push(o),t.push("INSIDE_NUMBER");break;case"{":n=i,t.pop(),t.push(o),t.push("INSIDE_OBJECT_START");break;case"[":n=i,t.pop(),t.push(o),t.push("INSIDE_ARRAY_START")}}function o(e,r){switch(e){case",":t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break;case"}":n=r,t.pop()}}function s(e,r){switch(e){case",":t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break;case"]":n=r,t.pop()}}for(let u=0;u<e.length;u++){const a=e[u];switch(t[t.length-1]){case"ROOT":i(a,u,"FINISH");break;case"INSIDE_OBJECT_START":switch(a){case'"':t.pop(),t.push("INSIDE_OBJECT_KEY");break;case"}":n=u,t.pop()}break;case"INSIDE_OBJECT_AFTER_COMMA":if('"'===a)t.pop(),t.push("INSIDE_OBJECT_KEY");break;case"INSIDE_OBJECT_KEY":if('"'===a)t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break;case"INSIDE_OBJECT_AFTER_KEY":if(":"===a)t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break;case"INSIDE_OBJECT_BEFORE_VALUE":i(a,u,"INSIDE_OBJECT_AFTER_VALUE");break;case"INSIDE_OBJECT_AFTER_VALUE":o(a,u);break;case"INSIDE_STRING":switch(a){case'"':t.pop(),n=u;break;case"\\":t.push("INSIDE_STRING_ESCAPE");break;default:n=u}break;case"INSIDE_ARRAY_START":if("]"===a)n=u,t.pop();else n=u,i(a,u,"INSIDE_ARRAY_AFTER_VALUE");break;case"INSIDE_ARRAY_AFTER_VALUE":switch(a){case",":t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break;case"]":n=u,t.pop();break;default:n=u}break;case"INSIDE_ARRAY_AFTER_COMMA":i(a,u,"INSIDE_ARRAY_AFTER_VALUE");break;case"INSIDE_STRING_ESCAPE":t.pop(),n=u;break;case"INSIDE_NUMBER":switch(a){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":n=u;break;case"e":case"E":case"-":case".":break;case",":t.pop(),"INSIDE_ARRAY_AFTER_VALUE"===t[t.length-1]&&s(a,u),"INSIDE_OBJECT_AFTER_VALUE"===t[t.length-1]&&o(a,u);break;case"}":t.pop(),"INSIDE_OBJECT_AFTER_VALUE"===t[t.length-1]&&o(a,u);break;case"]":t.pop(),"INSIDE_ARRAY_AFTER_VALUE"===t[t.length-1]&&s(a,u);break;default:t.pop()}break;case"INSIDE_LITERAL":{const i=e.substring(r,u+1);"false".startsWith(i)||"true".startsWith(i)||"null".startsWith(i)?n=u:(t.pop(),"INSIDE_OBJECT_AFTER_VALUE"===t[t.length-1]?o(a,u):"INSIDE_ARRAY_AFTER_VALUE"===t[t.length-1]&&s(a,u));break}}}let a=e.slice(0,n+1);for(let u=t.length-1;u>=0;u--){switch(t[u]){case"INSIDE_STRING":a+='"';break;case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":a+="}";break;case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":a+="]";break;case"INSIDE_LITERAL":{const t=e.substring(r,e.length);"true".startsWith(t)?a+="true".slice(t.length):"false".startsWith(t)?a+="false".slice(t.length):"null".startsWith(t)&&(a+="null".slice(t.length))}}}return a}async function hf(e){if(void 0===e)return{value:void 0,state:"undefined-input"};let t=await Mg({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await Mg({text:mf(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function gf(e){return e.type.startsWith("tool-")}function ff(e){return e.type.split("-").slice(1).join("-")}function vf({lastMessage:e,messageId:t}){return{message:"assistant"===(null==e?void 0:e.role)?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function yf({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:i,onToolCall:o,onData:s}){return e.pipeThrough(new TransformStream({async transform(e,a){await r((async({state:r,write:u})=>{var l,c,d,p;function m(e){const t=r.message.parts.filter(gf).find((t=>t.toolCallId===e));if(null==t)throw new Error("tool-output-error must be preceded by a tool-input-available");return t}function h(e){const t=r.message.parts.filter((e=>"dynamic-tool"===e.type)).find((t=>t.toolCallId===e));if(null==t)throw new Error("tool-output-error must be preceded by a tool-input-available");return t}function g(e){var t;const n=r.message.parts.find((t=>gf(t)&&t.toolCallId===e.toolCallId)),i=e,o=n;null!=n?(n.state=e.state,o.input=i.input,o.output=i.output,o.errorText=i.errorText,o.rawInput=i.rawInput,o.preliminary=i.preliminary,o.providerExecuted=null!=(t=i.providerExecuted)?t:n.providerExecuted,null!=i.providerMetadata&&"input-available"===n.state&&(n.callProviderMetadata=i.providerMetadata)):r.message.parts.push({type:`tool-${e.toolName}`,toolCallId:e.toolCallId,state:e.state,input:i.input,output:i.output,rawInput:i.rawInput,errorText:i.errorText,providerExecuted:i.providerExecuted,preliminary:i.preliminary,...null!=i.providerMetadata?{callProviderMetadata:i.providerMetadata}:{}})}function f(e){var t;const n=r.message.parts.find((t=>"dynamic-tool"===t.type&&t.toolCallId===e.toolCallId)),i=e,o=n;null!=n?(n.state=e.state,o.toolName=e.toolName,o.input=i.input,o.output=i.output,o.errorText=i.errorText,o.rawInput=null!=(t=i.rawInput)?t:o.rawInput,o.preliminary=i.preliminary,null!=i.providerMetadata&&"input-available"===n.state&&(n.callProviderMetadata=i.providerMetadata)):r.message.parts.push({type:"dynamic-tool",toolName:e.toolName,toolCallId:e.toolCallId,state:e.state,input:i.input,output:i.output,errorText:i.errorText,preliminary:i.preliminary,...null!=i.providerMetadata?{callProviderMetadata:i.providerMetadata}:{}})}async function v(e){if(null!=e){const n=null!=r.message.metadata?pf(r.message.metadata,e):e;null!=t&&await zg({value:n,schema:t}),r.message.metadata=n}}switch(e.type){case"text-start":{const t={type:"text",text:"",providerMetadata:e.providerMetadata,state:"streaming"};r.activeTextParts[e.id]=t,r.message.parts.push(t),u();break}case"text-delta":{const t=r.activeTextParts[e.id];t.text+=e.delta,t.providerMetadata=null!=(l=e.providerMetadata)?l:t.providerMetadata,u();break}case"text-end":{const t=r.activeTextParts[e.id];t.state="done",t.providerMetadata=null!=(c=e.providerMetadata)?c:t.providerMetadata,delete r.activeTextParts[e.id],u();break}case"reasoning-start":{const t={type:"reasoning",text:"",providerMetadata:e.providerMetadata,state:"streaming"};r.activeReasoningParts[e.id]=t,r.message.parts.push(t),u();break}case"reasoning-delta":{const t=r.activeReasoningParts[e.id];t.text+=e.delta,t.providerMetadata=null!=(d=e.providerMetadata)?d:t.providerMetadata,u();break}case"reasoning-end":{const t=r.activeReasoningParts[e.id];t.providerMetadata=null!=(p=e.providerMetadata)?p:t.providerMetadata,t.state="done",delete r.activeReasoningParts[e.id],u();break}case"file":r.message.parts.push({type:"file",mediaType:e.mediaType,url:e.url}),u();break;case"source-url":r.message.parts.push({type:"source-url",sourceId:e.sourceId,url:e.url,title:e.title,providerMetadata:e.providerMetadata}),u();break;case"source-document":r.message.parts.push({type:"source-document",sourceId:e.sourceId,mediaType:e.mediaType,title:e.title,filename:e.filename,providerMetadata:e.providerMetadata}),u();break;case"tool-input-start":{const t=r.message.parts.filter(gf);r.partialToolCalls[e.toolCallId]={text:"",toolName:e.toolName,index:t.length,dynamic:e.dynamic},e.dynamic?f({toolCallId:e.toolCallId,toolName:e.toolName,state:"input-streaming",input:void 0}):g({toolCallId:e.toolCallId,toolName:e.toolName,state:"input-streaming",input:void 0,providerExecuted:e.providerExecuted}),u();break}case"tool-input-delta":{const t=r.partialToolCalls[e.toolCallId];t.text+=e.inputTextDelta;const{value:n}=await hf(t.text);t.dynamic?f({toolCallId:e.toolCallId,toolName:t.toolName,state:"input-streaming",input:n}):g({toolCallId:e.toolCallId,toolName:t.toolName,state:"input-streaming",input:n}),u();break}case"tool-input-available":e.dynamic?f({toolCallId:e.toolCallId,toolName:e.toolName,state:"input-available",input:e.input,providerMetadata:e.providerMetadata}):g({toolCallId:e.toolCallId,toolName:e.toolName,state:"input-available",input:e.input,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}),u(),o&&!e.providerExecuted&&await o({toolCall:e});break;case"tool-input-error":e.dynamic?f({toolCallId:e.toolCallId,toolName:e.toolName,state:"output-error",input:e.input,errorText:e.errorText,providerMetadata:e.providerMetadata}):g({toolCallId:e.toolCallId,toolName:e.toolName,state:"output-error",input:void 0,rawInput:e.input,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}),u();break;case"tool-output-available":if(e.dynamic){const t=h(e.toolCallId);f({toolCallId:e.toolCallId,toolName:t.toolName,state:"output-available",input:t.input,output:e.output,preliminary:e.preliminary})}else{const t=m(e.toolCallId);g({toolCallId:e.toolCallId,toolName:ff(t),state:"output-available",input:t.input,output:e.output,providerExecuted:e.providerExecuted,preliminary:e.preliminary})}u();break;case"tool-output-error":if(e.dynamic){const t=h(e.toolCallId);f({toolCallId:e.toolCallId,toolName:t.toolName,state:"output-error",input:t.input,errorText:e.errorText})}else{const t=m(e.toolCallId);g({toolCallId:e.toolCallId,toolName:ff(t),state:"output-error",input:t.input,rawInput:t.rawInput,errorText:e.errorText})}u();break;case"start-step":r.message.parts.push({type:"step-start"});break;case"finish-step":r.activeTextParts={},r.activeReasoningParts={};break;case"start":null!=e.messageId&&(r.message.id=e.messageId),await v(e.messageMetadata),null==e.messageId&&null==e.messageMetadata||u();break;case"finish":case"message-metadata":await v(e.messageMetadata),null!=e.messageMetadata&&u();break;case"error":null==i||i(new Error(e.errorText));break;default:if(function(e){return e.type.startsWith("data-")}(e)){null!=(null==n?void 0:n[e.type])&&await zg({value:e.data,schema:n[e.type]});const t=e;if(t.transient){null==s||s(t);break}const i=null!=t.id?r.message.parts.find((e=>t.type===e.type&&t.id===e.id)):void 0;null!=i?i.data=t.data:r.message.parts.push(t),null==s||s(t),u()}}a.enqueue(e)}))}}))}Ng({prefix:"aitxt",size:24}),Ng({prefix:"aiobj",size:24});var _f=class{constructor(){this.queue=[],this.isProcessing=!1}async processQueue(){if(!this.isProcessing){for(this.isProcessing=!0;this.queue.length>0;)await this.queue[0](),this.queue.shift();this.isProcessing=!1}}async run(e){return new Promise(((t,n)=>{this.queue.push((async()=>{try{await e(),t()}catch(r){n(r)}})),this.processQueue()}))}};Ng({prefix:"aiobj",size:24});((e,t)=>{for(var n in t)Bg(e,n,{get:t[n],enumerable:!0})})({},{object:()=>wf,text:()=>bf});var bf=()=>({type:"text",responseFormat:{type:"text"},parsePartial:async({text:e})=>({partial:e}),parseOutput:async({text:e})=>e}),wf=({schema:e})=>{const t=Wg(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:e}){const t=await hf(e);switch(t.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:t.value};default:{const e=t.state;throw new Error(`Unsupported parse state: ${e}`)}}},async parseOutput({text:e},n){const r=await Mg({text:e});if(!r.success)throw new Gg({message:"No object generated: could not parse the response.",cause:r.error,text:e,response:n.response,usage:n.usage,finishReason:n.finishReason});const i=await Dg({value:r.value,schema:t});if(!i.success)throw new Gg({message:"No object generated: response did not match schema.",cause:i.error,text:e,response:n.response,usage:n.usage,finishReason:n.finishReason});return i.value}}},kf=Cl({name:zu(),version:zu()}),xf=Cl({_meta:Xl(Ol({}).loose())}),If=xf,Sf=Ol({method:zu(),params:Xl(xf)}),$f=Cl({experimental:Xl(Ol({}).loose()),logging:Xl(Ol({}).loose()),prompts:Xl(Cl({listChanged:Xl(dl())})),resources:Xl(Cl({subscribe:Xl(dl()),listChanged:Xl(dl())})),tools:Xl(Cl({listChanged:Xl(dl())}))});If.extend({protocolVersion:zu(),capabilities:$f,serverInfo:kf,instructions:Xl(zu())});var Ef=If.extend({nextCursor:Xl(zu())}),Tf=Ol({name:zu(),description:Xl(zu()),inputSchema:Ol({type:Hl("object"),properties:Xl(Ol({}).loose())}).loose()}).loose();Ef.extend({tools:El(Tf)});var Of=Ol({type:Hl("text"),text:zu()}).loose(),Nf=Ol({type:Hl("image"),data:tl(),mimeType:zu()}).loose(),Cf=Ol({uri:zu(),mimeType:Xl(zu())}).loose(),Af=Cf.extend({text:zu()}),Pf=Cf.extend({blob:tl()}),Rf=Ol({type:Hl("resource"),resource:Pl([Af,Pf])}).loose();If.extend({content:El(Pl([Of,Nf,Rf])),isError:dl().default(!1).optional()}).or(If.extend({toolResult:wl()}));var Uf="2.0",jf=Ol({jsonrpc:Hl(Uf),id:Pl([zu(),al().int()])}).merge(Sf).strict(),zf=Ol({jsonrpc:Hl(Uf),id:Pl([zu(),al().int()]),result:If}).strict(),Df=Ol({jsonrpc:Hl(Uf),id:Pl([zu(),al().int()]),error:Ol({code:al().int(),message:zu(),data:Xl(wl())})}).strict();Pl([jf,Ol({jsonrpc:Hl(Uf)}).merge(Ol({method:zu(),params:Xl(xf)})).strict(),zf,Df]);var Mf,Lf,Zf=class{constructor({api:e="/api/chat",credentials:t,headers:n,body:r,fetch:i,prepareSendMessagesRequest:o,prepareReconnectToStreamRequest:s}){this.api=e,this.credentials=t,this.headers=n,this.body=r,this.fetch=i,this.prepareSendMessagesRequest=o,this.prepareReconnectToStreamRequest=s}async sendMessages({abortSignal:e,...t}){var n,r,i,o,s;const a=await Lg(this.body),u=await Lg(this.headers),l=await Lg(this.credentials),c=await(null==(n=this.prepareSendMessagesRequest)?void 0:n.call(this,{api:this.api,id:t.chatId,messages:t.messages,body:{...a,...t.body},headers:{...u,...t.headers},credentials:l,requestMetadata:t.metadata,trigger:t.trigger,messageId:t.messageId})),d=null!=(r=null==c?void 0:c.api)?r:this.api,p=void 0!==(null==c?void 0:c.headers)?c.headers:{...u,...t.headers},m=void 0!==(null==c?void 0:c.body)?c.body:{...a,...t.body,id:t.chatId,messages:t.messages,trigger:t.trigger,messageId:t.messageId},h=null!=(i=null==c?void 0:c.credentials)?i:l,g=null!=(o=this.fetch)?o:globalThis.fetch,f=await g(d,{method:"POST",headers:{"Content-Type":"application/json",...p},body:JSON.stringify(m),credentials:h,signal:e});if(!f.ok)throw new Error(null!=(s=await f.text())?s:"Failed to fetch the chat response.");if(!f.body)throw new Error("The response body is empty.");return this.processResponseStream(f.body)}async reconnectToStream(e){var t,n,r,i,o;const s=await Lg(this.body),a=await Lg(this.headers),u=await Lg(this.credentials),l=await(null==(t=this.prepareReconnectToStreamRequest)?void 0:t.call(this,{api:this.api,id:e.chatId,body:{...s,...e.body},headers:{...a,...e.headers},credentials:u,requestMetadata:e.metadata})),c=null!=(n=null==l?void 0:l.api)?n:`${this.api}/${e.chatId}/stream`,d=void 0!==(null==l?void 0:l.headers)?l.headers:{...a,...e.headers},p=null!=(r=null==l?void 0:l.credentials)?r:u,m=null!=(i=this.fetch)?i:globalThis.fetch,h=await m(c,{method:"GET",headers:d,credentials:p});if(204===h.status)return null;if(!h.ok)throw new Error(null!=(o=await h.text())?o:"Failed to fetch the chat response.");if(!h.body)throw new Error("The response body is empty.");return this.processResponseStream(h.body)}},qf=class extends Zf{constructor(e={}){super(e)}processResponseStream(e){return function({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new jt).pipeThrough(new TransformStream({async transform({data:e},n){"[DONE]"!==e&&n.enqueue(await Mg({text:e,schema:t}))}}))}({stream:e,schema:df}).pipeThrough(new TransformStream({async transform(e,t){if(!e.success)throw e.error;t.enqueue(e.value)}}))}},Ff=class{constructor({generateId:e=Cg,id:t=e(),transport:n=new qf,messageMetadataSchema:r,dataPartSchemas:i,state:o,onError:s,onToolCall:a,onFinish:u,onData:l,sendAutomaticallyWhen:c}){this.activeResponse=void 0,this.jobExecutor=new _f,this.sendMessage=async(e,t)=>{var n,r,i,o;if(null==e)return void(await this.makeRequest({trigger:"submit-message",messageId:null==(n=this.lastMessage)?void 0:n.id,...t}));let s;if("text"in e||"files"in e){const t=Array.isArray(e.files)?e.files:await async function(e){if(null==e)return[];if(!(globalThis.FileList&&e instanceof globalThis.FileList))throw new Error("FileList is not supported in the current environment");return Promise.all(Array.from(e).map((async e=>{const{name:t,type:n}=e;return{type:"file",mediaType:n,filename:t,url:await new Promise(((t,n)=>{const r=new FileReader;r.onload=e=>{var n;t(null==(n=e.target)?void 0:n.result)},r.onerror=e=>n(e),r.readAsDataURL(e)}))}})))}(e.files);s={parts:[...t,..."text"in e&&null!=e.text?[{type:"text",text:e.text}]:[]]}}else s=e;if(null!=e.messageId){const t=this.state.messages.findIndex((t=>t.id===e.messageId));if(-1===t)throw new Error(`message with id ${e.messageId} not found`);if("user"!==this.state.messages[t].role)throw new Error(`message with id ${e.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,t+1),this.state.replaceMessage(t,{...s,id:e.messageId,role:null!=(r=s.role)?r:"user",metadata:e.metadata})}else this.state.pushMessage({...s,id:null!=(i=s.id)?i:this.generateId(),role:null!=(o=s.role)?o:"user",metadata:e.metadata});await this.makeRequest({trigger:"submit-message",messageId:e.messageId,...t})},this.regenerate=async({messageId:e,...t}={})=>{const n=null==e?this.state.messages.length-1:this.state.messages.findIndex((t=>t.id===e));if(-1===n)throw new Error(`message ${e} not found`);this.state.messages=this.state.messages.slice(0,"assistant"===this.messages[n].role?n:n+1),await this.makeRequest({trigger:"regenerate-message",messageId:e,...t})},this.resumeStream=async(e={})=>{await this.makeRequest({trigger:"resume-stream",...e})},this.clearError=()=>{"error"===this.status&&(this.state.error=void 0,this.setStatus({status:"ready"}))},this.addToolResult=async({tool:e,toolCallId:t,output:n})=>this.jobExecutor.run((async()=>{var e,r;const i=this.state.messages,o=i[i.length-1];this.state.replaceMessage(i.length-1,{...o,parts:o.parts.map((e=>gf(e)&&e.toolCallId===t?{...e,state:"output-available",output:n}:e))}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map((e=>gf(e)&&e.toolCallId===t?{...e,state:"output-available",output:n,errorText:void 0}:e))),"streaming"!==this.status&&"submitted"!==this.status&&(null==(e=this.sendAutomaticallyWhen)?void 0:e.call(this,{messages:this.state.messages}))&&this.makeRequest({trigger:"submit-message",messageId:null==(r=this.lastMessage)?void 0:r.id})})),this.stop=async()=>{var e;"streaming"!==this.status&&"submitted"!==this.status||(null==(e=this.activeResponse)?void 0:e.abortController)&&this.activeResponse.abortController.abort()},this.id=t,this.transport=n,this.generateId=e,this.messageMetadataSchema=r,this.dataPartSchemas=i,this.state=o,this.onError=s,this.onToolCall=a,this.onFinish=u,this.onData=l,this.sendAutomaticallyWhen=c}get status(){return this.state.status}setStatus({status:e,error:t}){this.status!==e&&(this.state.status=e,this.state.error=t)}get error(){return this.state.error}get messages(){return this.state.messages}get lastMessage(){return this.state.messages[this.state.messages.length-1]}set messages(e){this.state.messages=e}async makeRequest({trigger:e,metadata:t,headers:n,body:r,messageId:i}){var o,s,a;this.setStatus({status:"submitted",error:void 0});const u=this.lastMessage;try{const s={state:vf({lastMessage:this.state.snapshot(u),messageId:this.generateId()}),abortController:new AbortController};let a;if(this.activeResponse=s,"resume-stream"===e){const e=await this.transport.reconnectToStream({chatId:this.id,metadata:t,headers:n,body:r});if(null==e)return void this.setStatus({status:"ready"});a=e}else a=await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:s.abortController.signal,metadata:t,headers:n,body:r,trigger:e,messageId:i});const l=e=>this.jobExecutor.run((()=>e({state:s.state,write:()=>{var e;this.setStatus({status:"streaming"});s.state.message.id===(null==(e=this.lastMessage)?void 0:e.id)?this.state.replaceMessage(this.state.messages.length-1,s.state.message):this.state.pushMessage(s.state.message)}})));await async function({stream:e,onError:t}){const n=e.getReader();try{for(;;){const{done:e}=await n.read();if(e)break}}catch(r){null==t||t(r)}finally{n.releaseLock()}}({stream:yf({stream:a,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:l,onError:e=>{throw e}}),onError:e=>{throw e}}),null==(o=this.onFinish)||o.call(this,{message:s.state.message}),this.setStatus({status:"ready"})}catch(l){if("AbortError"===l.name)return this.setStatus({status:"ready"}),null;this.onError&&l instanceof Error&&this.onError(l),this.setStatus({status:"error",error:l})}finally{this.activeResponse=void 0}(null==(s=this.sendAutomaticallyWhen)?void 0:s.call(this,{messages:this.state.messages}))&&await this.makeRequest({trigger:"submit-message",messageId:null==(a=this.lastMessage)?void 0:a.id,metadata:t,headers:n,body:r})}},Wf=Ol({type:Hl("text"),text:zu(),state:Jl(["streaming","done"]).optional(),providerMetadata:Qg.optional()}),Jf=Ol({type:Hl("reasoning"),text:zu(),state:Jl(["streaming","done"]).optional(),providerMetadata:Qg.optional()}),Bf=Ol({type:Hl("source-url"),sourceId:zu(),url:zu(),title:zu().optional(),providerMetadata:Qg.optional()}),Hf=Ol({type:Hl("source-document"),sourceId:zu(),mediaType:zu(),title:zu(),filename:zu().optional(),providerMetadata:Qg.optional()}),Vf=Ol({type:Hl("file"),mediaType:zu(),filename:zu().optional(),url:zu(),providerMetadata:Qg.optional()}),Kf=Ol({type:Hl("step-start")}),Gf=Ol({type:zu().startsWith("data-"),id:zu().optional(),data:wl()}),Yf=[Ol({type:Hl("dynamic-tool"),toolName:zu(),toolCallId:zu(),state:Hl("input-streaming"),input:wl().optional(),output:xl().optional(),errorText:xl().optional()}),Ol({type:Hl("dynamic-tool"),toolName:zu(),toolCallId:zu(),state:Hl("input-available"),input:wl(),output:xl().optional(),errorText:xl().optional(),callProviderMetadata:Qg.optional()}),Ol({type:Hl("dynamic-tool"),toolName:zu(),toolCallId:zu(),state:Hl("output-available"),input:wl(),output:wl(),errorText:xl().optional(),callProviderMetadata:Qg.optional(),preliminary:dl().optional()}),Ol({type:Hl("dynamic-tool"),toolName:zu(),toolCallId:zu(),state:Hl("output-error"),input:wl(),output:xl().optional(),errorText:zu(),callProviderMetadata:Qg.optional()})],Xf=[Ol({type:zu().startsWith("tool-"),toolCallId:zu(),state:Hl("input-streaming"),input:wl().optional(),output:xl().optional(),errorText:xl().optional()}),Ol({type:zu().startsWith("tool-"),toolCallId:zu(),state:Hl("input-available"),input:wl(),output:xl().optional(),errorText:xl().optional(),callProviderMetadata:Qg.optional()}),Ol({type:zu().startsWith("tool-"),toolCallId:zu(),state:Hl("output-available"),input:wl(),output:wl(),errorText:xl().optional(),callProviderMetadata:Qg.optional(),preliminary:dl().optional()}),Ol({type:zu().startsWith("tool-"),toolCallId:zu(),state:Hl("output-error"),input:wl(),output:xl().optional(),errorText:zu(),callProviderMetadata:Qg.optional()})];function Qf(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function ev(){if(Lf)return Mf;return Lf=1,Mf=function(e,t){if("function"!=typeof e)throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof e}\`.`);let n,r=0;return function(...i){clearTimeout(n);const o=Date.now(),s=t-(o-r);s<=0?(r=o,e.apply(this,i)):n=setTimeout((()=>{r=Date.now(),e.apply(this,i)}),s)}}}Ol({id:zu(),role:Jl(["system","user","assistant"]),metadata:wl().optional(),parts:El(Pl([Wf,Jf,Bf,Hf,Vf,Kf,Gf,...Yf,...Xf]))});const tv=Qf(ev());var nv,rv,iv,ov,sv,av,uv,lv,cv,dv=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},pv=(e,t,n)=>(dv(e,t,"read from private field"),n?n.call(e):t.get(e)),mv=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},hv=(e,t,n,r)=>(dv(e,t,"write to private field"),t.set(e,n),n);var gv,fv=class{constructor(e=[]){mv(this,nv,void 0),mv(this,rv,"ready"),mv(this,iv,void 0),mv(this,ov,new Set),mv(this,sv,new Set),mv(this,av,new Set),this.pushMessage=e=>{hv(this,nv,pv(this,nv).concat(e)),pv(this,uv).call(this)},this.popMessage=()=>{hv(this,nv,pv(this,nv).slice(0,-1)),pv(this,uv).call(this)},this.replaceMessage=(e,t)=>{hv(this,nv,[...pv(this,nv).slice(0,e),this.snapshot(t),...pv(this,nv).slice(e+1)]),pv(this,uv).call(this)},this.snapshot=e=>structuredClone(e),this["~registerMessagesCallback"]=(e,t)=>{const n=t?(r=e,null!=(i=t)?tv(r,i):r):e;var r,i;return pv(this,ov).add(n),()=>{pv(this,ov).delete(n)}},this["~registerStatusCallback"]=e=>(pv(this,sv).add(e),()=>{pv(this,sv).delete(e)}),this["~registerErrorCallback"]=e=>(pv(this,av).add(e),()=>{pv(this,av).delete(e)}),mv(this,uv,(()=>{pv(this,ov).forEach((e=>e()))})),mv(this,lv,(()=>{pv(this,sv).forEach((e=>e()))})),mv(this,cv,(()=>{pv(this,av).forEach((e=>e()))})),hv(this,nv,e)}get status(){return pv(this,rv)}set status(e){hv(this,rv,e),pv(this,lv).call(this)}get error(){return pv(this,iv)}set error(e){hv(this,iv,e),pv(this,cv).call(this)}get messages(){return pv(this,nv)}set messages(e){hv(this,nv,[...e]),pv(this,uv).call(this)}};nv=new WeakMap,rv=new WeakMap,iv=new WeakMap,ov=new WeakMap,sv=new WeakMap,av=new WeakMap,uv=new WeakMap,lv=new WeakMap,cv=new WeakMap;var vv=class extends Ff{constructor({messages:e,...t}){const n=new fv(e);super({...t,state:n}),mv(this,gv,void 0),this["~registerMessagesCallback"]=(e,t)=>pv(this,gv)["~registerMessagesCallback"](e,t),this["~registerStatusCallback"]=e=>pv(this,gv)["~registerStatusCallback"](e),this["~registerErrorCallback"]=e=>pv(this,gv)["~registerErrorCallback"](e),hv(this,gv,n)}};gv=new WeakMap;var yv,_v=Object.defineProperty,bv="AI_NoObjectGeneratedError",wv=`vercel.ai.error.${bv}`,kv=Symbol.for(wv),xv=class extends Ce{constructor({message:e="No object generated.",cause:t,text:n,response:r,usage:i,finishReason:o}){super({name:bv,message:e,cause:t}),this[yv]=!0,this.text=n,this.response=r,this.usage=i,this.finishReason=o}static isInstance(e){return Ce.hasMarker(e,wv)}};yv=kv;var Iv,Sv="AI_MessageConversionError",$v=`vercel.ai.error.${Sv}`,Ev=Symbol.for($v),Tv=class extends Ce{constructor({originalMessage:e,message:t}){super({name:Sv,message:t}),this[Iv]=!0,this.originalMessage=e}static isInstance(e){return Ce.hasMarker(e,$v)}};Iv=Ev;var Ov=Pl([zu(),xc(Uint8Array),xc(ArrayBuffer),bc((e=>{var t,n;return null!=(n=null==(t=globalThis.Buffer)?void 0:t.isBuffer(e))&&n}),{message:"Must be a Buffer"})]),Nv=vc((()=>Pl([vl(),zu(),al(),dl(),Zl(zu(),Nv),El(Nv)]))),Cv=Zl(zu(),Zl(zu(),Nv)),Av=Ol({type:Hl("text"),text:zu(),providerOptions:Cv.optional()}),Pv=Ol({type:Hl("image"),image:Pl([Ov,xc(URL)]),mediaType:zu().optional(),providerOptions:Cv.optional()}),Rv=Ol({type:Hl("file"),data:Pl([Ov,xc(URL)]),filename:zu().optional(),mediaType:zu(),providerOptions:Cv.optional()}),Uv=Ol({type:Hl("reasoning"),text:zu(),providerOptions:Cv.optional()}),jv=Ol({type:Hl("tool-call"),toolCallId:zu(),toolName:zu(),input:wl(),providerOptions:Cv.optional(),providerExecuted:dl().optional()}),zv=Ul("type",[Ol({type:Hl("text"),value:zu()}),Ol({type:Hl("json"),value:Nv}),Ol({type:Hl("error-text"),value:zu()}),Ol({type:Hl("error-json"),value:Nv}),Ol({type:Hl("content"),value:El(Pl([Ol({type:Hl("text"),text:zu()}),Ol({type:Hl("media"),data:zu(),mediaType:zu()})]))})]),Dv=Ol({type:Hl("tool-result"),toolCallId:zu(),toolName:zu(),output:zv,providerOptions:Cv.optional()}),Mv=Ol({role:Hl("system"),content:zu(),providerOptions:Cv.optional()}),Lv=Ol({role:Hl("user"),content:Pl([zu(),El(Pl([Av,Pv,Rv]))]),providerOptions:Cv.optional()}),Zv=Ol({role:Hl("assistant"),content:Pl([zu(),El(Pl([Av,Rv,Uv,jv,Dv]))]),providerOptions:Cv.optional()});function qv({output:e,tool:t,errorMode:n}){return"text"===n?{type:"error-text",value:Ze(e)}:"json"===n?{type:"error-json",value:Fv(e)}:(null==t?void 0:t.toModelOutput)?t.toModelOutput(e):"string"==typeof e?{type:"text",value:e}:{type:"json",value:Fv(e)}}function Fv(e){return void 0===e?null:e}function Wv(e){const t=["ROOT"];let n=-1,r=null;function i(e,i,o){switch(e){case'"':n=i,t.pop(),t.push(o),t.push("INSIDE_STRING");break;case"f":case"t":case"n":n=i,r=i,t.pop(),t.push(o),t.push("INSIDE_LITERAL");break;case"-":t.pop(),t.push(o),t.push("INSIDE_NUMBER");break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":n=i,t.pop(),t.push(o),t.push("INSIDE_NUMBER");break;case"{":n=i,t.pop(),t.push(o),t.push("INSIDE_OBJECT_START");break;case"[":n=i,t.pop(),t.push(o),t.push("INSIDE_ARRAY_START")}}function o(e,r){switch(e){case",":t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break;case"}":n=r,t.pop()}}function s(e,r){switch(e){case",":t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break;case"]":n=r,t.pop()}}for(let u=0;u<e.length;u++){const a=e[u];switch(t[t.length-1]){case"ROOT":i(a,u,"FINISH");break;case"INSIDE_OBJECT_START":switch(a){case'"':t.pop(),t.push("INSIDE_OBJECT_KEY");break;case"}":n=u,t.pop()}break;case"INSIDE_OBJECT_AFTER_COMMA":if('"'===a)t.pop(),t.push("INSIDE_OBJECT_KEY");break;case"INSIDE_OBJECT_KEY":if('"'===a)t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break;case"INSIDE_OBJECT_AFTER_KEY":if(":"===a)t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break;case"INSIDE_OBJECT_BEFORE_VALUE":i(a,u,"INSIDE_OBJECT_AFTER_VALUE");break;case"INSIDE_OBJECT_AFTER_VALUE":o(a,u);break;case"INSIDE_STRING":switch(a){case'"':t.pop(),n=u;break;case"\\":t.push("INSIDE_STRING_ESCAPE");break;default:n=u}break;case"INSIDE_ARRAY_START":if("]"===a)n=u,t.pop();else n=u,i(a,u,"INSIDE_ARRAY_AFTER_VALUE");break;case"INSIDE_ARRAY_AFTER_VALUE":switch(a){case",":t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break;case"]":n=u,t.pop();break;default:n=u}break;case"INSIDE_ARRAY_AFTER_COMMA":i(a,u,"INSIDE_ARRAY_AFTER_VALUE");break;case"INSIDE_STRING_ESCAPE":t.pop(),n=u;break;case"INSIDE_NUMBER":switch(a){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":n=u;break;case"e":case"E":case"-":case".":break;case",":t.pop(),"INSIDE_ARRAY_AFTER_VALUE"===t[t.length-1]&&s(a,u),"INSIDE_OBJECT_AFTER_VALUE"===t[t.length-1]&&o(a,u);break;case"}":t.pop(),"INSIDE_OBJECT_AFTER_VALUE"===t[t.length-1]&&o(a,u);break;case"]":t.pop(),"INSIDE_ARRAY_AFTER_VALUE"===t[t.length-1]&&s(a,u);break;default:t.pop()}break;case"INSIDE_LITERAL":{const i=e.substring(r,u+1);"false".startsWith(i)||"true".startsWith(i)||"null".startsWith(i)?n=u:(t.pop(),"INSIDE_OBJECT_AFTER_VALUE"===t[t.length-1]?o(a,u):"INSIDE_ARRAY_AFTER_VALUE"===t[t.length-1]&&s(a,u));break}}}let a=e.slice(0,n+1);for(let u=t.length-1;u>=0;u--){switch(t[u]){case"INSIDE_STRING":a+='"';break;case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":a+="}";break;case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":a+="]";break;case"INSIDE_LITERAL":{const t=e.substring(r,e.length);"true".startsWith(t)?a+="true".slice(t.length):"false".startsWith(t)?a+="false".slice(t.length):"null".startsWith(t)&&(a+="null".slice(t.length))}}}return a}function Jv(e){return e.type.startsWith("tool-")}function Bv(e){return e.type.split("-").slice(1).join("-")}Pl([Mv,Lv,Zv,Ol({role:Hl("tool"),content:El(Dv),providerOptions:Cv.optional()})]),hd({prefix:"aitxt",size:24}),TransformStream,Pl([Nl({type:Hl("text-start"),id:zu(),providerMetadata:Cv.optional()}),Nl({type:Hl("text-delta"),id:zu(),delta:zu(),providerMetadata:Cv.optional()}),Nl({type:Hl("text-end"),id:zu(),providerMetadata:Cv.optional()}),Nl({type:Hl("error"),errorText:zu()}),Nl({type:Hl("tool-input-start"),toolCallId:zu(),toolName:zu(),providerExecuted:dl().optional(),dynamic:dl().optional()}),Nl({type:Hl("tool-input-delta"),toolCallId:zu(),inputTextDelta:zu()}),Nl({type:Hl("tool-input-available"),toolCallId:zu(),toolName:zu(),input:wl(),providerExecuted:dl().optional(),providerMetadata:Cv.optional(),dynamic:dl().optional()}),Nl({type:Hl("tool-input-error"),toolCallId:zu(),toolName:zu(),input:wl(),providerExecuted:dl().optional(),providerMetadata:Cv.optional(),dynamic:dl().optional(),errorText:zu()}),Nl({type:Hl("tool-output-available"),toolCallId:zu(),output:wl(),providerExecuted:dl().optional(),dynamic:dl().optional(),preliminary:dl().optional()}),Nl({type:Hl("tool-output-error"),toolCallId:zu(),errorText:zu(),providerExecuted:dl().optional(),dynamic:dl().optional()}),Nl({type:Hl("reasoning"),text:zu(),providerMetadata:Cv.optional()}),Nl({type:Hl("reasoning-start"),id:zu(),providerMetadata:Cv.optional()}),Nl({type:Hl("reasoning-delta"),id:zu(),delta:zu(),providerMetadata:Cv.optional()}),Nl({type:Hl("reasoning-end"),id:zu(),providerMetadata:Cv.optional()}),Nl({type:Hl("reasoning-part-finish")}),Nl({type:Hl("source-url"),sourceId:zu(),url:zu(),title:zu().optional(),providerMetadata:Cv.optional()}),Nl({type:Hl("source-document"),sourceId:zu(),mediaType:zu(),title:zu(),filename:zu().optional(),providerMetadata:Cv.optional()}),Nl({type:Hl("file"),url:zu(),mediaType:zu(),providerMetadata:Cv.optional()}),Nl({type:zu().startsWith("data-"),id:zu().optional(),data:wl(),transient:dl().optional()}),Nl({type:Hl("start-step")}),Nl({type:Hl("finish-step")}),Nl({type:Hl("start"),messageId:zu().optional(),messageMetadata:wl().optional()}),Nl({type:Hl("finish"),messageMetadata:wl().optional()}),Nl({type:Hl("abort")}),Nl({type:Hl("message-metadata"),messageMetadata:wl()})]),hd({prefix:"aitxt",size:24}),hd({prefix:"aiobj",size:24}),hd({prefix:"aiobj",size:24});((e,t)=>{for(var n in t)_v(e,n,{get:t[n],enumerable:!0})})({},{object:()=>Vv,text:()=>Hv});var Hv=()=>({type:"text",responseFormat:{type:"text"},parsePartial:async({text:e})=>({partial:e}),parseOutput:async({text:e})=>e}),Vv=({schema:e})=>{const t=Fd(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:e}){const t=await async function(e){if(void 0===e)return{value:void 0,state:"undefined-input"};let t=await Ed({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await Ed({text:Wv(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}(e);switch(t.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:t.value};default:{const e=t.state;throw new Error(`Unsupported parse state: ${e}`)}}},async parseOutput({text:e},n){const r=await Ed({text:e});if(!r.success)throw new xv({message:"No object generated: could not parse the response.",cause:r.error,text:e,response:n.response,usage:n.usage,finishReason:n.finishReason});const i=await Sd({value:r.value,schema:t});if(!i.success)throw new xv({message:"No object generated: response did not match schema.",cause:i.error,text:e,response:n.response,usage:n.usage,finishReason:n.finishReason});return i.value}}},Kv=Cl({name:zu(),version:zu()}),Gv=Cl({_meta:Xl(Ol({}).loose())}),Yv=Gv,Xv=Ol({method:zu(),params:Xl(Gv)}),Qv=Cl({experimental:Xl(Ol({}).loose()),logging:Xl(Ol({}).loose()),prompts:Xl(Cl({listChanged:Xl(dl())})),resources:Xl(Cl({subscribe:Xl(dl()),listChanged:Xl(dl())})),tools:Xl(Cl({listChanged:Xl(dl())}))});Yv.extend({protocolVersion:zu(),capabilities:Qv,serverInfo:Kv,instructions:Xl(zu())});var ey=Yv.extend({nextCursor:Xl(zu())}),ty=Ol({name:zu(),description:Xl(zu()),inputSchema:Ol({type:Hl("object"),properties:Xl(Ol({}).loose())}).loose()}).loose();ey.extend({tools:El(ty)});var ny=Ol({type:Hl("text"),text:zu()}).loose(),ry=Ol({type:Hl("image"),data:tl(),mimeType:zu()}).loose(),iy=Ol({uri:zu(),mimeType:Xl(zu())}).loose(),oy=iy.extend({text:zu()}),sy=iy.extend({blob:tl()}),ay=Ol({type:Hl("resource"),resource:Pl([oy,sy])}).loose();Yv.extend({content:El(Pl([ny,ry,ay])),isError:dl().default(!1).optional()}).or(Yv.extend({toolResult:wl()}));var uy="2.0",ly=Ol({jsonrpc:Hl(uy),id:Pl([zu(),al().int()])}).merge(Xv).strict(),cy=Ol({jsonrpc:Hl(uy),id:Pl([zu(),al().int()]),result:Yv}).strict(),dy=Ol({jsonrpc:Hl(uy),id:Pl([zu(),al().int()]),error:Ol({code:al().int(),message:zu(),data:Xl(wl())})}).strict();Pl([ly,Ol({jsonrpc:Hl(uy)}).merge(Ol({method:zu(),params:Xl(Gv)})).strict(),cy,dy]);var py=Ol({type:Hl("text"),text:zu(),state:Jl(["streaming","done"]).optional(),providerMetadata:Cv.optional()}),my=Ol({type:Hl("reasoning"),text:zu(),state:Jl(["streaming","done"]).optional(),providerMetadata:Cv.optional()}),hy=Ol({type:Hl("source-url"),sourceId:zu(),url:zu(),title:zu().optional(),providerMetadata:Cv.optional()}),gy=Ol({type:Hl("source-document"),sourceId:zu(),mediaType:zu(),title:zu(),filename:zu().optional(),providerMetadata:Cv.optional()}),fy=Ol({type:Hl("file"),mediaType:zu(),filename:zu().optional(),url:zu(),providerMetadata:Cv.optional()}),vy=Ol({type:Hl("step-start")}),yy=Ol({type:zu().startsWith("data-"),id:zu().optional(),data:wl()}),_y=[Ol({type:Hl("dynamic-tool"),toolName:zu(),toolCallId:zu(),state:Hl("input-streaming"),input:wl().optional(),output:xl().optional(),errorText:xl().optional()}),Ol({type:Hl("dynamic-tool"),toolName:zu(),toolCallId:zu(),state:Hl("input-available"),input:wl(),output:xl().optional(),errorText:xl().optional(),callProviderMetadata:Cv.optional()}),Ol({type:Hl("dynamic-tool"),toolName:zu(),toolCallId:zu(),state:Hl("output-available"),input:wl(),output:wl(),errorText:xl().optional(),callProviderMetadata:Cv.optional(),preliminary:dl().optional()}),Ol({type:Hl("dynamic-tool"),toolName:zu(),toolCallId:zu(),state:Hl("output-error"),input:wl(),output:xl().optional(),errorText:zu(),callProviderMetadata:Cv.optional()})],by=[Ol({type:zu().startsWith("tool-"),toolCallId:zu(),state:Hl("input-streaming"),input:wl().optional(),output:xl().optional(),errorText:xl().optional()}),Ol({type:zu().startsWith("tool-"),toolCallId:zu(),state:Hl("input-available"),input:wl(),output:xl().optional(),errorText:xl().optional(),callProviderMetadata:Cv.optional()}),Ol({type:zu().startsWith("tool-"),toolCallId:zu(),state:Hl("output-available"),input:wl(),output:wl(),errorText:xl().optional(),callProviderMetadata:Cv.optional(),preliminary:dl().optional()}),Ol({type:zu().startsWith("tool-"),toolCallId:zu(),state:Hl("output-error"),input:wl(),output:xl().optional(),errorText:zu(),callProviderMetadata:Cv.optional()})];function wy(){const e=function(){const e=i.useContext(Og);if(!e)throw new Error("useChat must be used within an EchoChatProvider");return e}();return{async sendMessages(t){const{messages:n,abortSignal:r,...i}=t,o=function(e,t){const n=[];(null==t?void 0:t.ignoreIncompleteToolCalls)&&(e=e.map((e=>({...e,parts:e.parts.filter((e=>!Jv(e)||"input-streaming"!==e.state&&"input-available"!==e.state))}))));for(const r of e)switch(r.role){case"system":{const e=r.parts.filter((e=>"text"===e.type)),t=e.reduce(((e,t)=>null!=t.providerMetadata?{...e,...t.providerMetadata}:e),{});n.push({role:"system",content:e.map((e=>e.text)).join(""),...Object.keys(t).length>0?{providerOptions:t}:{}});break}case"user":n.push({role:"user",content:r.parts.filter((e=>"text"===e.type||"file"===e.type)).map((e=>{switch(e.type){case"text":return{type:"text",text:e.text,...null!=e.providerMetadata?{providerOptions:e.providerMetadata}:{}};case"file":return{type:"file",mediaType:e.mediaType,filename:e.filename,data:e.url,...null!=e.providerMetadata?{providerOptions:e.providerMetadata}:{}};default:return e}}))});break;case"assistant":if(null!=r.parts){let e=function(){var e,o;if(0===i.length)return;const s=[];for(const n of i)if("text"===n.type)s.push({type:"text",text:n.text,...null!=n.providerMetadata?{providerOptions:n.providerMetadata}:{}});else if("file"===n.type)s.push({type:"file",mediaType:n.mediaType,filename:n.filename,data:n.url});else if("reasoning"===n.type)s.push({type:"reasoning",text:n.text,providerOptions:n.providerMetadata});else if("dynamic-tool"===n.type){const e=n.toolName;if("input-streaming"===n.state)throw new Tv({originalMessage:r,message:`incomplete tool input is not supported: ${n.toolCallId}`});s.push({type:"tool-call",toolCallId:n.toolCallId,toolName:e,input:n.input,...null!=n.callProviderMetadata?{providerOptions:n.callProviderMetadata}:{}})}else{if(!Jv(n))throw new Error(`Unsupported part: ${n}`);{const i=Bv(n);if("input-streaming"===n.state)throw new Tv({originalMessage:r,message:`incomplete tool input is not supported: ${n.toolCallId}`});s.push({type:"tool-call",toolCallId:n.toolCallId,toolName:i,input:"output-error"===n.state?null!=(e=n.input)?e:n.rawInput:n.input,providerExecuted:n.providerExecuted,...null!=n.callProviderMetadata?{providerOptions:n.callProviderMetadata}:{}}),!0!==n.providerExecuted||"output-available"!==n.state&&"output-error"!==n.state||s.push({type:"tool-result",toolCallId:n.toolCallId,toolName:i,output:qv({output:"output-error"===n.state?n.errorText:n.output,tool:null==(o=null==t?void 0:t.tools)?void 0:o[i],errorMode:"output-error"===n.state?"json":"none"})})}}n.push({role:"assistant",content:s});const a=i.filter((e=>Jv(e)&&!0!==e.providerExecuted||"dynamic-tool"===e.type));a.length>0&&n.push({role:"tool",content:a.map((e=>{var n;switch(e.state){case"output-error":case"output-available":{const r="dynamic-tool"===e.type?e.toolName:Bv(e);return{type:"tool-result",toolCallId:e.toolCallId,toolName:r,output:qv({output:"output-error"===e.state?e.errorText:e.output,tool:null==(n=null==t?void 0:t.tools)?void 0:n[r],errorMode:"output-error"===e.state?"text":"none"})}}default:throw new Tv({originalMessage:r,message:`Unsupported tool part state: ${e.state}`})}}))}),i=[]},i=[];for(const t of r.parts)"text"===t.type||"reasoning"===t.type||"file"===t.type||"dynamic-tool"===t.type||Jv(t)?i.push(t):"step-start"===t.type&&e();e();break}break;default:{const e=r.role;throw new Tv({originalMessage:r,message:`Unsupported role: ${e}`})}}return n}(n.map((({role:e,parts:t,metadata:n})=>({role:e,parts:t,metadata:n}))));return await e({uiMessages:n,modelMessages:o,abortSignal:r,...i})},reconnectToStream:async()=>null}}Ol({id:zu(),role:Jl(["system","user","assistant"]),metadata:wl().optional(),parts:El(Pl([py,my,hy,gy,fy,vy,yy,..._y,...by]))}),exports.EchoChatProvider=function({chatFn:e,children:t}){return r.jsx(Og.Provider,{value:e,children:t})},exports.EchoProvider=function({config:e,children:t}){const[n,o]=i.useState(!1);if(i.useEffect((()=>{o(!0)}),[]),!n)return null;const s=e.apiUrl||"https://echo.merit.systems",a={userManager:"undefined"!=typeof window&&window.__echoUserManager||new ce({authority:s,client_id:e.appId,redirect_uri:e.redirectUri||window.location.origin,scope:e.scope||"llm:invoke offline_access",silentRequestTimeoutInSeconds:10,automaticSilentRenew:!0,silent_redirect_uri:e.redirectUri||window.location.origin,includeIdTokenInSilentRenew:!1,validateSubOnSilentRenew:!0,loadUserInfo:!0,metadata:{authorization_endpoint:`${s}/api/oauth/authorize`,token_endpoint:`${s}/api/oauth/token`,userinfo_endpoint:`${s}/api/oauth/userinfo`,issuer:s,jwks_uri:`${s}/.well-known/jwks.json`,end_session_endpoint:`${s}/api/oauth/logout`},userStore:new N({store:window.localStorage})}),onSigninCallback:()=>{window.location.search.includes("code=")&&window.history.replaceState({},document.title,window.location.pathname)}};return r.jsx(Se,{...a,children:r.jsx(yh,{config:e,children:t})})},exports.EchoSignIn=function({onSuccess:e,onError:t,className:n="",children:o}){const{signIn:s,isLoading:a,user:u,error:l}=_h(),[c,d]=i.useState(!1);i.useEffect((()=>{u&&e&&e(u)}),[u,e]),i.useEffect((()=>{l&&t&&t(new Error(l))}),[l,t]);const p=async()=>{try{await s()}catch(e){t&&t(e instanceof Error?e:new Error("Sign in failed"))}};return u?r.jsx("div",{className:`echo-signin-success ${n}`,children:r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"12px 16px",backgroundColor:"#f8fafc",border:"1px solid #e2e8f0",borderRadius:"8px",color:"#334155",fontSize:"14px",fontFamily:"HelveticaNowDisplay, sans-serif",fontWeight:"800",width:"fit-content"},children:[r.jsx(Eg,{width:16,height:16,variant:"light"}),r.jsxs("span",{children:["Signed in as ",Sg((null==u?void 0:u.name)||(null==u?void 0:u.email))]})]})}):r.jsx("div",{className:`echo-signin ${n}`,children:o?r.jsx("div",{onClick:p,style:{cursor:"pointer"},children:o}):r.jsxs("button",{onClick:p,disabled:a,className:"echo-signin-button",style:{display:"flex",alignItems:"center",gap:"8px",padding:"12px 20px",backgroundColor:a?"#f3f4f6":c?"#f1f5f9":"#ffffff",color:a?"#9ca3af":"#09090b",border:"1px solid #e2e8f0",borderRadius:"8px",cursor:a?"not-allowed":"pointer",fontSize:"14px",fontWeight:"800",fontFamily:"HelveticaNowDisplay, sans-serif",transition:"all 0.2s ease",boxShadow:"0 1px 2px 0 rgba(0, 0, 0, 0.05)",backdropFilter:"blur(8px)"},onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),children:[r.jsx(Eg,{width:16,height:16,variant:"light"}),r.jsx("span",{children:a?"Signing in...":"Sign in"})]})})},exports.EchoTokenPurchase=function({onPurchaseComplete:e,onError:t,className:n="",children:o}){const{createPaymentLink:s,user:a,balance:u,freeTierBalance:l,refreshBalance:c}=_h(),[d,p]=i.useState(!1),[m,h]=i.useState(null),[g,f]=i.useState(!1),[v,y]=i.useState(!1),_=e=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(e),b=()=>{var e,t;return(((null==(e=null==l?void 0:l.userSpendInfo)?void 0:e.amountLeft)||0)<0?0:(null==(t=null==l?void 0:l.userSpendInfo)?void 0:t.amountLeft)||0)+((null==u?void 0:u.balance)||0)},w=async n=>{if(!a){const e=new Error("Please sign in to purchase tokens");return h(e.message),void(t&&t(e))}try{p(!0),h(null);const r=await s(n);await $g(r,{onComplete:async()=>{try{await c(),f(!1),y(!1),e&&u&&e(u)}catch(n){const e=n instanceof Error?n:new Error("Failed to refresh balance");h(e.message),t&&t(e)}finally{p(!1)}},onCancel:()=>{p(!1)},onError:e=>{h(e.message),t&&t(e),p(!1)}})}catch(r){const e=r instanceof Error?r:new Error("Failed to create payment link");h(e.message),t&&t(e),p(!1)}},k=()=>{f(!1),y(!1),h(null)};if(!a)return r.jsx("div",{className:`echo-token-purchase ${n}`,children:r.jsx("div",{className:"echo-token-purchase-unauthorized",style:{padding:"12px",backgroundColor:"#fef3c7",color:"#92400e",borderRadius:"8px",fontSize:"14px"},children:"Please sign in to purchase tokens"})});const x=()=>{const[e,t]=i.useState(!1);return r.jsxs("button",{onClick:()=>f(!0),className:`echo-token-purchase-compact ${n}`,style:{display:"flex",alignItems:"center",gap:"8px",padding:"10px 12px",borderRadius:"8px",backgroundColor:e?"#f1f5f9":"#ffffff",border:"1px solid #e5e7eb",color:"#09090b",fontSize:"14px",fontWeight:"800",cursor:"pointer",backdropFilter:"blur(8px)",transition:"all 0.2s ease",boxShadow:"0 1px 2px 0 rgba(0, 0, 0, 0.05)",height:"40px",fontFamily:"HelveticaNowDisplay, sans-serif"},onMouseEnter:()=>t(!0),onMouseLeave:()=>t(!1),children:[r.jsx(Eg,{width:16,height:16,variant:"light"}),r.jsx("span",{children:_(b())}),r.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:e?"#dc2626":"#6b7280",transition:"color 0.2s ease"},children:[r.jsx("path",{d:"M7 7h10v10"}),r.jsx("path",{d:"M7 17 17 7"})]})]})},I=()=>r.jsx("div",{style:{position:"fixed",top:0,left:0,right:0,bottom:0,backgroundColor:"rgba(0, 0, 0, 0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,padding:"16px"},onClick:e=>{e.target===e.currentTarget&&k()},children:r.jsxs("div",{style:{backgroundColor:"#ffffff",borderRadius:"12px",border:"1px solid #e5e7eb",padding:"0",width:"100%",maxWidth:"450px",maxHeight:"90vh",overflow:"hidden",boxShadow:"0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)",fontFamily:"HelveticaNowDisplay, sans-serif",display:"flex",flexDirection:"column",minHeight:"320px"},children:[r.jsx("div",{style:{padding:"16px 16px 0 16px",marginBottom:"12px"},children:r.jsx("h2",{style:{fontSize:"18px",fontWeight:"500",color:"#111827",margin:0,fontFamily:"HelveticaNowDisplay, sans-serif"},children:"Credits"})}),r.jsxs("div",{style:{padding:"0 16px",marginBottom:"16px"},children:[r.jsx("p",{style:{fontSize:"14px",color:"#6b7280",margin:"0 0 4px 0",fontFamily:"HelveticaNowDisplay, sans-serif"},children:"Total Available"}),r.jsx("p",{style:{fontSize:"28px",fontWeight:"700",color:"#111827",margin:"0 0 12px 0",fontFamily:"HelveticaNowDisplay, sans-serif"},children:_(b())}),r.jsxs("div",{style:{marginBottom:"8px"},children:[l&&b()>0&&r.jsxs("div",{style:{marginBottom:"8px"},children:[r.jsxs("div",{style:{fontSize:"12px",color:"#6b7280",fontFamily:"HelveticaNowDisplay, sans-serif",display:"flex",alignItems:"center",gap:"6px",marginBottom:"4px"},children:[r.jsx("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:"#3b82f6"}}),r.jsxs("span",{children:[_(l.userSpendInfo.amountLeft<0?0:l.userSpendInfo.amountLeft)," ","Free Tier",l.userSpendInfo&&l.userSpendInfo.spendLimit&&r.jsxs("span",{style:{color:"#9ca3af",marginLeft:"8px"},children:["(",_(l.userSpendInfo.amountSpent>l.userSpendInfo.spendLimit?l.userSpendInfo.spendLimit:l.userSpendInfo.amountSpent)," ","of"," ",_(l.userSpendInfo.spendLimit)," ","spent)"]})]})]}),l.userSpendInfo&&l.userSpendInfo.spendLimit&&r.jsx("div",{style:{width:"100%",height:"4px",backgroundColor:"#e5e7eb",borderRadius:"2px",overflow:"hidden",marginBottom:"4px",border:"1px solid #d1d5db"},children:r.jsx("div",{style:{width:`${Math.max(0,Math.min(100,Math.max(0,l.userSpendInfo.amountLeft)/(l.userSpendInfo.spendLimit||1)*100))}%`,height:"100%",backgroundColor:"#3b82f6"}})})]}),u&&u.balance>0&&r.jsxs("div",{style:{fontSize:"12px",color:"#6b7280",fontFamily:"HelveticaNowDisplay, sans-serif"},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",marginBottom:"4px"},children:[r.jsx("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:"#dc2626"}}),r.jsxs("span",{children:[_(u.balance)," Paid Credits",u.totalSpent&&r.jsxs("span",{style:{color:"#9ca3af",marginLeft:"8px"},children:["(",_(u.totalSpent)," /"," ",_(u.totalPaid)," spent)"]})]})]}),u.totalPaid>0&&r.jsx("div",{style:{width:"100%",height:"4px",backgroundColor:"#e5e7eb",borderRadius:"2px",overflow:"hidden",border:"1px solid #d1d5db"},children:r.jsx("div",{style:{width:`${Math.max(0,Math.min(100,u.balance/u.totalPaid*100))}%`,height:"100%",backgroundColor:"#dc2626"}})})]})]})]}),r.jsxs("div",{style:{padding:"0 16px 16px 16px",borderTop:"1px solid #f3f4f6",paddingTop:"16px"},children:[r.jsx("p",{style:{fontSize:"14px",color:"#6b7280",margin:"0 0 12px 0",fontFamily:"HelveticaNowDisplay, sans-serif"},children:"Add Credits"}),v?r.jsx(Tg,{onAddCredits:w,onCancel:()=>y(!1),isProcessing:d}):r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[r.jsx("button",{onClick:()=>w(10),disabled:d,style:{width:"100%",padding:"12px 16px",backgroundColor:d?"#9ca3af":"#dc2626",color:"white",border:"none",borderRadius:"6px",fontSize:"14px",fontWeight:"600",cursor:d?"not-allowed":"pointer",transition:"background-color 0.2s ease",fontFamily:"HelveticaNowDisplay, sans-serif"},onMouseEnter:e=>{d||(e.currentTarget.style.backgroundColor="#b91c1c")},onMouseLeave:e=>{d||(e.currentTarget.style.backgroundColor="#dc2626")},children:d?"Processing...":"Add $10 Credits"}),r.jsx("button",{onClick:()=>y(!0),style:{width:"100%",padding:"8px 16px",fontSize:"14px",color:"#6b7280",backgroundColor:"transparent",border:"1px solid #e5e7eb",borderRadius:"6px",cursor:"pointer",fontFamily:"HelveticaNowDisplay, sans-serif"},onMouseEnter:e=>{e.currentTarget.style.color="#111827",e.currentTarget.style.borderColor="#d1d5db"},onMouseLeave:e=>{e.currentTarget.style.color="#6b7280",e.currentTarget.style.borderColor="#e5e7eb"},children:"Choose different amount"})]})]}),m&&r.jsx("div",{style:{margin:"0 16px 12px 16px",padding:"8px 12px",backgroundColor:"#fee2e2",color:"#dc2626",borderRadius:"6px",fontSize:"14px",fontFamily:"HelveticaNowDisplay, sans-serif"},children:m}),r.jsx("div",{style:{padding:"12px 16px",display:"flex",justifyContent:"flex-end",borderTop:"1px solid #f3f4f6"},children:r.jsx("button",{onClick:k,style:{padding:"8px 16px",backgroundColor:"#f3f4f6",color:"#374151",border:"none",borderRadius:"6px",fontSize:"14px",cursor:"pointer",fontFamily:"HelveticaNowDisplay, sans-serif"},onMouseEnter:e=>{e.currentTarget.style.backgroundColor="#e5e7eb"},onMouseLeave:e=>{e.currentTarget.style.backgroundColor="#f3f4f6"},children:"Close"})})]})});return r.jsxs(r.Fragment,{children:[o?r.jsx("div",{onClick:()=>f(!0),style:{cursor:"pointer"},children:o}):r.jsx(x,{}),g&&r.jsx(I,{})]})},exports.Logo=Eg,exports.useChat=function(){return function({experimental_throttle:e,resume:t=!1,...n}={}){const r=i.useRef("chat"in n?n.chat:new vv(n));("chat"in n&&n.chat!==r.current||"id"in n&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new vv(n));const o="id"in n?n.id:null,s=i.useCallback((t=>r.current["~registerMessagesCallback"](t,e)),[e,o]),a=i.useSyncExternalStore(s,(()=>r.current.messages),(()=>r.current.messages)),u=i.useSyncExternalStore(r.current["~registerStatusCallback"],(()=>r.current.status),(()=>r.current.status)),l=i.useSyncExternalStore(r.current["~registerErrorCallback"],(()=>r.current.error),(()=>r.current.error)),c=i.useCallback((e=>{"function"==typeof e&&(e=e(r.current.messages)),r.current.messages=e}),[r]);return i.useEffect((()=>{t&&r.current.resumeStream()}),[t,r]),{id:r.current.id,messages:a,setMessages:c,sendMessage:r.current.sendMessage,regenerate:r.current.regenerate,clearError:r.current.clearError,stop:r.current.stop,error:l,resumeStream:r.current.resumeStream,status:u,addToolResult:r.current.addToolResult}}({transport:wy()})},exports.useEcho=_h,exports.useEchoClient=gh,exports.useEchoModelProviders=()=>{const{token:e,config:t}=_h();return i.useMemo((()=>{const n={appId:t.appId,baseRouterUrl:t.baseRouterUrl},r=async()=>e;return{openai:ph(n,r),anthropic:mh(n,r),google:hh(n,r)}}),[e,t.appId,t.baseRouterUrl])},exports.useEchoOpenAI=function(e={}){const{baseURL:t="https://echo.router.merit.systems",enabled:n=!0}=e,{token:r,user:o}=_h(),[s,a]=i.useState(void 0),[u,l]=i.useState(null),[c,d]=i.useState(!1),p=i.useRef(null);return i.useEffect((()=>{if(p.current&&p.current.abort(),!n||!r)return a(void 0),l(null),void d(!1);return(async()=>{const e=new AbortController;p.current=e,d(!0),l(null);try{if(e.signal.aborted)return;const{default:n}=await import("openai");if(e.signal.aborted)return;const i=new n({apiKey:r,baseURL:t,dangerouslyAllowBrowser:!0});e.signal.aborted||a(i)}catch(n){if(!e.signal.aborted){const e=n instanceof Error?n.message:"Failed to load OpenAI";e.includes("Cannot resolve module")||e.includes("Module not found")||e.includes("openai")?l("OpenAI package not found. Please install it with: pnpm add openai"):l(`Failed to initialize OpenAI client: ${e}`),console.error("Error loading OpenAI:",n),a(void 0)}}finally{e.signal.aborted||d(!1)}})(),()=>{p.current&&p.current.abort()}}),[r,o,t,n]),{openai:s,isReady:void 0!==s&&!c,error:u,isLoading:c}};
|
|
1
|
+
"use strict";Object.create;var e,t=Object.defineProperty,n=(Object.getOwnPropertyDescriptor,Object.getOwnPropertyNames,Object.getPrototypeOf,Object.prototype.hasOwnProperty,(e,n,r)=>((e,n,r)=>n in e?t(e,n,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[n]=r)(e,"symbol"!=typeof n?n+"":n,r));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("react/jsx-runtime"),o=require("react");class i extends Error{}function s(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return function(e){return decodeURIComponent(atob(e).replace(/(.)/g,((e,t)=>{let n=t.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n="0"+n),"%"+n})))}(t)}catch(n){return atob(t)}}i.prototype.name="InvalidTokenError";var a,u,l,c={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},d=(e=>(e[e.NONE=0]="NONE",e[e.ERROR=1]="ERROR",e[e.WARN=2]="WARN",e[e.INFO=3]="INFO",e[e.DEBUG=4]="DEBUG",e))(d||{});(l=d||(d={})).reset=function(){a=3,u=c},l.setLevel=function(e){if(!(0<=e&&e<=4))throw new Error("Invalid log level");a=e},l.setLogger=function(e){u=e};var p=class e{constructor(e){this._name=e}debug(...t){a>=4&&u.debug(e._format(this._name,this._method),...t)}info(...t){a>=3&&u.info(e._format(this._name,this._method),...t)}warn(...t){a>=2&&u.warn(e._format(this._name,this._method),...t)}error(...t){a>=1&&u.error(e._format(this._name,this._method),...t)}throw(e){throw this.error(e),e}create(e){const t=Object.create(this);return t._method=e,t.debug("begin"),t}static createStatic(t,n){const r=new e(`${t}.${n}`);return r.debug("begin"),r}static _format(e,t){const n=`[${e}]`;return t?`${n} ${t}:`:n}static debug(t,...n){a>=4&&u.debug(e._format(t),...n)}static info(t,...n){a>=3&&u.info(e._format(t),...n)}static warn(t,...n){a>=2&&u.warn(e._format(t),...n)}static error(t,...n){a>=1&&u.error(e._format(t),...n)}};d.reset();var m=class{static decode(e){try{return function(e,t){if("string"!=typeof e)throw new i("Invalid token specified: must be a string");t||(t={});const n=!0===t.header?0:1,r=e.split(".")[n];if("string"!=typeof r)throw new i(`Invalid token specified: missing part #${n+1}`);let o;try{o=s(r)}catch(a){throw new i(`Invalid token specified: invalid base64 for part #${n+1} (${a.message})`)}try{return JSON.parse(o)}catch(a){throw new i(`Invalid token specified: invalid json for part #${n+1} (${a.message})`)}}(e)}catch(t){throw p.error("JwtUtils.decode",t),t}}static async generateSignedJwt(e,t,n){const r=`${g.encodeBase64Url((new TextEncoder).encode(JSON.stringify(e)))}.${g.encodeBase64Url((new TextEncoder).encode(JSON.stringify(t)))}`,o=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,(new TextEncoder).encode(r));return`${r}.${g.encodeBase64Url(new Uint8Array(o))}`}},_=e=>btoa([...new Uint8Array(e)].map((e=>String.fromCharCode(e))).join("")),h=class e{static _randomWord(){const e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}static generateUUIDv4(){return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(t=>(+t^e._randomWord()&15>>+t/4).toString(16))).replace(/-/g,"")}static generateCodeVerifier(){return e.generateUUIDv4()+e.generateUUIDv4()+e.generateUUIDv4()}static async generateCodeChallenge(e){if(!crypto.subtle)throw new Error("Crypto.subtle is available only in secure contexts (HTTPS).");try{const t=(new TextEncoder).encode(e),n=await crypto.subtle.digest("SHA-256",t);return _(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(t){throw p.error("CryptoUtils.generateCodeChallenge",t),t}}static generateBasicAuth(e,t){const n=(new TextEncoder).encode([e,t].join(":"));return _(n)}static async hash(e,t){const n=(new TextEncoder).encode(t),r=await crypto.subtle.digest(e,n);return new Uint8Array(r)}static async customCalculateJwkThumbprint(t){let n;switch(t.kty){case"RSA":n={e:t.e,kty:t.kty,n:t.n};break;case"EC":n={crv:t.crv,kty:t.kty,x:t.x,y:t.y};break;case"OKP":n={crv:t.crv,kty:t.kty,x:t.x};break;case"oct":n={crv:t.k,kty:t.kty};break;default:throw new Error("Unknown jwk type")}const r=await e.hash("SHA-256",JSON.stringify(n));return e.encodeBase64Url(r)}static async generateDPoPProof({url:t,accessToken:n,httpMethod:r,keyPair:o,nonce:i}){let s,a;const u={jti:window.crypto.randomUUID(),htm:null!=r?r:"GET",htu:t,iat:Math.floor(Date.now()/1e3)};n&&(s=await e.hash("SHA-256",n),a=e.encodeBase64Url(s),u.ath=a),i&&(u.nonce=i);try{const e=await crypto.subtle.exportKey("jwk",o.publicKey),t={alg:"ES256",typ:"dpop+jwt",jwk:{crv:e.crv,kty:e.kty,x:e.x,y:e.y}};return await m.generateSignedJwt(t,u,o.privateKey)}catch(l){throw l instanceof TypeError?new Error(`Error exporting dpop public key: ${l.message}`):l}}static async generateDPoPJkt(t){try{const n=await crypto.subtle.exportKey("jwk",t.publicKey);return await e.customCalculateJwkThumbprint(n)}catch(n){throw n instanceof TypeError?new Error(`Could not retrieve dpop keys from storage: ${n.message}`):n}}static async generateDPoPKeys(){return await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign","verify"])}};h.encodeBase64Url=e=>_(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");var g=h,f=class{constructor(e){this._name=e,this._callbacks=[],this._logger=new p(`Event('${this._name}')`)}addHandler(e){return this._callbacks.push(e),()=>this.removeHandler(e)}removeHandler(e){const t=this._callbacks.lastIndexOf(e);t>=0&&this._callbacks.splice(t,1)}async raise(...e){this._logger.debug("raise:",...e);for(const t of this._callbacks)await t(...e)}},v=class{static center({...e}){var t;return null==e.width&&(e.width=null!=(t=[800,720,600,480].find((e=>e<=window.outerWidth/1.618)))?t:360),null!=e.left||(e.left=Math.max(0,Math.round(window.screenX+(window.outerWidth-e.width)/2))),null!=e.height&&(null!=e.top||(e.top=Math.max(0,Math.round(window.screenY+(window.outerHeight-e.height)/2)))),e}static serialize(e){return Object.entries(e).filter((([,e])=>null!=e)).map((([e,t])=>`${e}=${"boolean"!=typeof t?t:t?"yes":"no"}`)).join(",")}},y=class e extends f{constructor(){super(...arguments),this._logger=new p(`Timer('${this._name}')`),this._timerHandle=null,this._expiration=0,this._callback=()=>{const t=this._expiration-e.getEpochTime();this._logger.debug("timer completes in",t),this._expiration<=e.getEpochTime()&&(this.cancel(),super.raise())}}static getEpochTime(){return Math.floor(Date.now()/1e3)}init(t){const n=this._logger.create("init");t=Math.max(Math.floor(t),1);const r=e.getEpochTime()+t;if(this.expiration===r&&this._timerHandle)return void n.debug("skipping since already initialized for expiration at",this.expiration);this.cancel(),n.debug("using duration",t),this._expiration=r;const o=Math.min(t,5);this._timerHandle=setInterval(this._callback,1e3*o)}get expiration(){return this._expiration}cancel(){this._logger.create("cancel"),this._timerHandle&&(clearInterval(this._timerHandle),this._timerHandle=null)}},b=class{static readParams(e,t="query"){if(!e)throw new TypeError("Invalid URL");const n=new URL(e,"http://127.0.0.1")["fragment"===t?"hash":"search"];return new URLSearchParams(n.slice(1))}},k=";",w=class extends Error{constructor(e,t){var n,r,o;if(super(e.error_description||e.error||""),this.form=t,this.name="ErrorResponse",!e.error)throw p.error("ErrorResponse","No error passed"),new Error("No error passed");this.error=e.error,this.error_description=null!=(n=e.error_description)?n:null,this.error_uri=null!=(r=e.error_uri)?r:null,this.state=e.userState,this.session_state=null!=(o=e.session_state)?o:null,this.url_state=e.url_state}},x=class extends Error{constructor(e){super(e),this.name="ErrorTimeout"}},I=class{constructor(e){this._logger=new p("AccessTokenEvents"),this._expiringTimer=new y("Access token expiring"),this._expiredTimer=new y("Access token expired"),this._expiringNotificationTimeInSeconds=e.expiringNotificationTimeInSeconds}async load(e){const t=this._logger.create("load");if(e.access_token&&void 0!==e.expires_in){const n=e.expires_in;if(t.debug("access token present, remaining duration:",n),n>0){let e=n-this._expiringNotificationTimeInSeconds;e<=0&&(e=1),t.debug("registering expiring timer, raising in",e,"seconds"),this._expiringTimer.init(e)}else t.debug("canceling existing expiring timer because we're past expiration."),this._expiringTimer.cancel();const r=n+1;t.debug("registering expired timer, raising in",r,"seconds"),this._expiredTimer.init(r)}else this._expiringTimer.cancel(),this._expiredTimer.cancel()}async unload(){this._logger.debug("unload: canceling existing access token timers"),this._expiringTimer.cancel(),this._expiredTimer.cancel()}addAccessTokenExpiring(e){return this._expiringTimer.addHandler(e)}removeAccessTokenExpiring(e){this._expiringTimer.removeHandler(e)}addAccessTokenExpired(e){return this._expiredTimer.addHandler(e)}removeAccessTokenExpired(e){this._expiredTimer.removeHandler(e)}},S=class{constructor(e,t,n,r,o){this._callback=e,this._client_id=t,this._intervalInSeconds=r,this._stopOnError=o,this._logger=new p("CheckSessionIFrame"),this._timer=null,this._session_state=null,this._message=e=>{e.origin===this._frame_origin&&e.source===this._frame.contentWindow&&("error"===e.data?(this._logger.error("error message from check session op iframe"),this._stopOnError&&this.stop()):"changed"===e.data?(this._logger.debug("changed message from check session op iframe"),this.stop(),this._callback()):this._logger.debug(e.data+" message from check session op iframe"))};const i=new URL(n);this._frame_origin=i.origin,this._frame=window.document.createElement("iframe"),this._frame.style.visibility="hidden",this._frame.style.position="fixed",this._frame.style.left="-1000px",this._frame.style.top="0",this._frame.width="0",this._frame.height="0",this._frame.src=i.href}load(){return new Promise((e=>{this._frame.onload=()=>{e()},window.document.body.appendChild(this._frame),window.addEventListener("message",this._message,!1)}))}start(e){if(this._session_state===e)return;this._logger.create("start"),this.stop(),this._session_state=e;const t=()=>{this._frame.contentWindow&&this._session_state&&this._frame.contentWindow.postMessage(this._client_id+" "+this._session_state,this._frame_origin)};t(),this._timer=setInterval(t,1e3*this._intervalInSeconds)}stop(){this._logger.create("stop"),this._session_state=null,this._timer&&(clearInterval(this._timer),this._timer=null)}},$=class{constructor(){this._logger=new p("InMemoryWebStorage"),this._data={}}clear(){this._logger.create("clear"),this._data={}}getItem(e){return this._logger.create(`getItem('${e}')`),this._data[e]}setItem(e,t){this._logger.create(`setItem('${e}')`),this._data[e]=t}removeItem(e){this._logger.create(`removeItem('${e}')`),delete this._data[e]}get length(){return Object.getOwnPropertyNames(this._data).length}key(e){return Object.getOwnPropertyNames(this._data)[e]}},O=class extends Error{constructor(e,t){super(t),this.name="ErrorDPoPNonce",this.nonce=e}},E=class{constructor(e=[],t=null,n={}){this._jwtHandler=t,this._extraHeaders=n,this._logger=new p("JsonService"),this._contentTypes=[],this._contentTypes.push(...e,"application/json"),t&&this._contentTypes.push("application/jwt")}async fetchWithTimeout(e,t={}){const{timeoutInSeconds:n,...r}=t;if(!n)return await fetch(e,r);const o=new AbortController,i=setTimeout((()=>o.abort()),1e3*n);try{return await fetch(e,{...t,signal:o.signal})}catch(s){if(s instanceof DOMException&&"AbortError"===s.name)throw new x("Network timed out");throw s}finally{clearTimeout(i)}}async getJson(e,{token:t,credentials:n,timeoutInSeconds:r}={}){const o=this._logger.create("getJson"),i={Accept:this._contentTypes.join(", ")};let s;t&&(o.debug("token passed, setting Authorization header"),i.Authorization="Bearer "+t),this._appendExtraHeaders(i);try{o.debug("url:",e),s=await this.fetchWithTimeout(e,{method:"GET",headers:i,timeoutInSeconds:r,credentials:n})}catch(l){throw o.error("Network Error"),l}o.debug("HTTP response received, status",s.status);const a=s.headers.get("Content-Type");if(a&&!this._contentTypes.find((e=>a.startsWith(e)))&&o.throw(new Error(`Invalid response Content-Type: ${null!=a?a:"undefined"}, from URL: ${e}`)),s.ok&&this._jwtHandler&&(null==a?void 0:a.startsWith("application/jwt")))return await this._jwtHandler(await s.text());let u;try{u=await s.json()}catch(l){if(o.error("Error parsing JSON response",l),s.ok)throw l;throw new Error(`${s.statusText} (${s.status})`)}if(!s.ok){if(o.error("Error from server:",u),u.error)throw new w(u);throw new Error(`${s.statusText} (${s.status}): ${JSON.stringify(u)}`)}return u}async postForm(e,{body:t,basicAuth:n,timeoutInSeconds:r,initCredentials:o,extraHeaders:i}){const s=this._logger.create("postForm"),a={Accept:this._contentTypes.join(", "),"Content-Type":"application/x-www-form-urlencoded",...i};let u;void 0!==n&&(a.Authorization="Basic "+n),this._appendExtraHeaders(a);try{s.debug("url:",e),u=await this.fetchWithTimeout(e,{method:"POST",headers:a,body:t,timeoutInSeconds:r,credentials:o})}catch(p){throw s.error("Network error"),p}s.debug("HTTP response received, status",u.status);const l=u.headers.get("Content-Type");if(l&&!this._contentTypes.find((e=>l.startsWith(e))))throw new Error(`Invalid response Content-Type: ${null!=l?l:"undefined"}, from URL: ${e}`);const c=await u.text();let d={};if(c)try{d=JSON.parse(c)}catch(p){if(s.error("Error parsing JSON response",p),u.ok)throw p;throw new Error(`${u.statusText} (${u.status})`)}if(!u.ok){if(s.error("Error from server:",d),u.headers.has("dpop-nonce")){const e=u.headers.get("dpop-nonce");throw new O(e,`${JSON.stringify(d)}`)}if(d.error)throw new w(d,t);throw new Error(`${u.statusText} (${u.status}): ${JSON.stringify(d)}`)}return d}_appendExtraHeaders(e){const t=this._logger.create("appendExtraHeaders"),n=Object.keys(this._extraHeaders),r=["accept","content-type"],o=["authorization"];0!==n.length&&n.forEach((n=>{if(r.includes(n.toLocaleLowerCase()))return void t.warn("Protected header could not be set",n,r);if(o.includes(n.toLocaleLowerCase())&&Object.keys(e).includes(n))return void t.warn("Header could not be overridden",n,o);const i="function"==typeof this._extraHeaders[n]?this._extraHeaders[n]():this._extraHeaders[n];i&&""!==i&&(e[n]=i)}))}},T=class{constructor(e){this._settings=e,this._logger=new p("MetadataService"),this._signingKeys=null,this._metadata=null,this._metadataUrl=this._settings.metadataUrl,this._jsonService=new E(["application/jwk-set+json"],null,this._settings.extraHeaders),this._settings.signingKeys&&(this._logger.debug("using signingKeys from settings"),this._signingKeys=this._settings.signingKeys),this._settings.metadata&&(this._logger.debug("using metadata from settings"),this._metadata=this._settings.metadata),this._settings.fetchRequestCredentials&&(this._logger.debug("using fetchRequestCredentials from settings"),this._fetchRequestCredentials=this._settings.fetchRequestCredentials)}resetSigningKeys(){this._signingKeys=null}async getMetadata(){const e=this._logger.create("getMetadata");if(this._metadata)return e.debug("using cached values"),this._metadata;if(!this._metadataUrl)throw e.throw(new Error("No authority or metadataUrl configured on settings")),null;e.debug("getting metadata from",this._metadataUrl);const t=await this._jsonService.getJson(this._metadataUrl,{credentials:this._fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return e.debug("merging remote JSON with seed metadata"),this._metadata=Object.assign({},t,this._settings.metadataSeed),this._metadata}getIssuer(){return this._getMetadataProperty("issuer")}getAuthorizationEndpoint(){return this._getMetadataProperty("authorization_endpoint")}getUserInfoEndpoint(){return this._getMetadataProperty("userinfo_endpoint")}getTokenEndpoint(e=!0){return this._getMetadataProperty("token_endpoint",e)}getCheckSessionIframe(){return this._getMetadataProperty("check_session_iframe",!0)}getEndSessionEndpoint(){return this._getMetadataProperty("end_session_endpoint",!0)}getRevocationEndpoint(e=!0){return this._getMetadataProperty("revocation_endpoint",e)}getKeysEndpoint(e=!0){return this._getMetadataProperty("jwks_uri",e)}async _getMetadataProperty(e,t=!1){const n=this._logger.create(`_getMetadataProperty('${e}')`),r=await this.getMetadata();if(n.debug("resolved"),void 0===r[e]){if(!0===t)return void n.warn("Metadata does not contain optional property");n.throw(new Error("Metadata does not contain property "+e))}return r[e]}async getSigningKeys(){const e=this._logger.create("getSigningKeys");if(this._signingKeys)return e.debug("returning signingKeys from cache"),this._signingKeys;const t=await this.getKeysEndpoint(!1);e.debug("got jwks_uri",t);const n=await this._jsonService.getJson(t,{timeoutInSeconds:this._settings.requestTimeoutInSeconds});if(e.debug("got key set",n),!Array.isArray(n.keys))throw e.throw(new Error("Missing keys on keyset")),null;return this._signingKeys=n.keys,this._signingKeys}},R=class{constructor({prefix:e="oidc.",store:t=localStorage}={}){this._logger=new p("WebStorageStateStore"),this._store=t,this._prefix=e}async set(e,t){this._logger.create(`set('${e}')`),e=this._prefix+e,await this._store.setItem(e,t)}async get(e){this._logger.create(`get('${e}')`),e=this._prefix+e;return await this._store.getItem(e)}async remove(e){this._logger.create(`remove('${e}')`),e=this._prefix+e;const t=await this._store.getItem(e);return await this._store.removeItem(e),t}async getAllKeys(){this._logger.create("getAllKeys");const e=await this._store.length,t=[];for(let n=0;n<e;n++){const e=await this._store.key(n);e&&0===e.indexOf(this._prefix)&&t.push(e.substr(this._prefix.length))}return t}},N=class{constructor({authority:e,metadataUrl:t,metadata:n,signingKeys:r,metadataSeed:o,client_id:i,client_secret:s,response_type:a="code",scope:u="openid",redirect_uri:l,post_logout_redirect_uri:c,client_authentication:d="client_secret_post",prompt:p,display:m,max_age:_,ui_locales:h,acr_values:g,resource:f,response_mode:v,filterProtocolClaims:y=!0,loadUserInfo:b=!1,requestTimeoutInSeconds:k,staleStateAgeInSeconds:w=900,mergeClaimsStrategy:x={array:"replace"},disablePKCE:I=!1,stateStore:S,revokeTokenAdditionalContentTypes:O,fetchRequestCredentials:E,refreshTokenAllowedScope:T,extraQueryParams:N={},extraTokenParams:A={},extraHeaders:C={},dpop:P,omitScopeWhenRequesting:U=!1}){var j;if(this.authority=e,t?this.metadataUrl=t:(this.metadataUrl=e,e&&(this.metadataUrl.endsWith("/")||(this.metadataUrl+="/"),this.metadataUrl+=".well-known/openid-configuration")),this.metadata=n,this.metadataSeed=o,this.signingKeys=r,this.client_id=i,this.client_secret=s,this.response_type=a,this.scope=u,this.redirect_uri=l,this.post_logout_redirect_uri=c,this.client_authentication=d,this.prompt=p,this.display=m,this.max_age=_,this.ui_locales=h,this.acr_values=g,this.resource=f,this.response_mode=v,this.filterProtocolClaims=null==y||y,this.loadUserInfo=!!b,this.staleStateAgeInSeconds=w,this.mergeClaimsStrategy=x,this.omitScopeWhenRequesting=U,this.disablePKCE=!!I,this.revokeTokenAdditionalContentTypes=O,this.fetchRequestCredentials=E||"same-origin",this.requestTimeoutInSeconds=k,S)this.stateStore=S;else{const e="undefined"!=typeof window?window.localStorage:new $;this.stateStore=new R({store:e})}if(this.refreshTokenAllowedScope=T,this.extraQueryParams=N,this.extraTokenParams=A,this.extraHeaders=C,this.dpop=P,this.dpop&&!(null==(j=this.dpop)?void 0:j.store))throw new Error("A DPoPStore is required when dpop is enabled")}},A=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new p("UserInfoService"),this._getClaimsFromJwt=async e=>{const t=this._logger.create("_getClaimsFromJwt");try{const n=m.decode(e);return t.debug("JWT decoding successful"),n}catch(n){throw t.error("Error parsing JWT response"),n}},this._jsonService=new E(void 0,this._getClaimsFromJwt,this._settings.extraHeaders)}async getClaims(e){const t=this._logger.create("getClaims");e||this._logger.throw(new Error("No token passed"));const n=await this._metadataService.getUserInfoEndpoint();t.debug("got userinfo url",n);const r=await this._jsonService.getJson(n,{token:e,credentials:this._settings.fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return t.debug("got claims",r),r}},C=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new p("TokenClient"),this._jsonService=new E(this._settings.revokeTokenAdditionalContentTypes,null,this._settings.extraHeaders)}async exchangeCode({grant_type:e="authorization_code",redirect_uri:t=this._settings.redirect_uri,client_id:n=this._settings.client_id,client_secret:r=this._settings.client_secret,extraHeaders:o,...i}){const s=this._logger.create("exchangeCode");n||s.throw(new Error("A client_id is required")),t||s.throw(new Error("A redirect_uri is required")),i.code||s.throw(new Error("A code is required"));const a=new URLSearchParams({grant_type:e,redirect_uri:t});for(const[d,p]of Object.entries(i))null!=p&&a.set(d,p);let u;switch(this._settings.client_authentication){case"client_secret_basic":if(null==r)throw s.throw(new Error("A client_secret is required")),null;u=g.generateBasicAuth(n,r);break;case"client_secret_post":a.append("client_id",n),r&&a.append("client_secret",r)}const l=await this._metadataService.getTokenEndpoint(!1);s.debug("got token endpoint");const c=await this._jsonService.postForm(l,{body:a,basicAuth:u,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:o});return s.debug("got response"),c}async exchangeCredentials({grant_type:e="password",client_id:t=this._settings.client_id,client_secret:n=this._settings.client_secret,scope:r=this._settings.scope,...o}){const i=this._logger.create("exchangeCredentials");t||i.throw(new Error("A client_id is required"));const s=new URLSearchParams({grant_type:e});this._settings.omitScopeWhenRequesting||s.set("scope",r);for(const[c,d]of Object.entries(o))null!=d&&s.set(c,d);let a;switch(this._settings.client_authentication){case"client_secret_basic":if(null==n)throw i.throw(new Error("A client_secret is required")),null;a=g.generateBasicAuth(t,n);break;case"client_secret_post":s.append("client_id",t),n&&s.append("client_secret",n)}const u=await this._metadataService.getTokenEndpoint(!1);i.debug("got token endpoint");const l=await this._jsonService.postForm(u,{body:s,basicAuth:a,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials});return i.debug("got response"),l}async exchangeRefreshToken({grant_type:e="refresh_token",client_id:t=this._settings.client_id,client_secret:n=this._settings.client_secret,timeoutInSeconds:r,extraHeaders:o,...i}){const s=this._logger.create("exchangeRefreshToken");t||s.throw(new Error("A client_id is required")),i.refresh_token||s.throw(new Error("A refresh_token is required"));const a=new URLSearchParams({grant_type:e});for(const[d,p]of Object.entries(i))Array.isArray(p)?p.forEach((e=>a.append(d,e))):null!=p&&a.set(d,p);let u;switch(this._settings.client_authentication){case"client_secret_basic":if(null==n)throw s.throw(new Error("A client_secret is required")),null;u=g.generateBasicAuth(t,n);break;case"client_secret_post":a.append("client_id",t),n&&a.append("client_secret",n)}const l=await this._metadataService.getTokenEndpoint(!1);s.debug("got token endpoint");const c=await this._jsonService.postForm(l,{body:a,basicAuth:u,timeoutInSeconds:r,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:o});return s.debug("got response"),c}async revoke(e){var t;const n=this._logger.create("revoke");e.token||n.throw(new Error("A token is required"));const r=await this._metadataService.getRevocationEndpoint(!1);n.debug(`got revocation endpoint, revoking ${null!=(t=e.token_type_hint)?t:"default token type"}`);const o=new URLSearchParams;for(const[i,s]of Object.entries(e))null!=s&&o.set(i,s);o.set("client_id",this._settings.client_id),this._settings.client_secret&&o.set("client_secret",this._settings.client_secret),await this._jsonService.postForm(r,{body:o,timeoutInSeconds:this._settings.requestTimeoutInSeconds}),n.debug("got response")}},P=class{constructor(e,t,n){this._settings=e,this._metadataService=t,this._claimsService=n,this._logger=new p("ResponseValidator"),this._userInfoService=new A(this._settings,this._metadataService),this._tokenClient=new C(this._settings,this._metadataService)}async validateSigninResponse(e,t,n){const r=this._logger.create("validateSigninResponse");this._processSigninState(e,t),r.debug("state processed"),await this._processCode(e,t,n),r.debug("code processed"),e.isOpenId&&this._validateIdTokenAttributes(e),r.debug("tokens validated"),await this._processClaims(e,null==t?void 0:t.skipUserInfo,e.isOpenId),r.debug("claims processed")}async validateCredentialsResponse(e,t){const n=this._logger.create("validateCredentialsResponse"),r=e.isOpenId&&!!e.id_token;r&&this._validateIdTokenAttributes(e),n.debug("tokens validated"),await this._processClaims(e,t,r),n.debug("claims processed")}async validateRefreshResponse(e,t){const n=this._logger.create("validateRefreshResponse");e.userState=t.data,null!=e.session_state||(e.session_state=t.session_state),null!=e.scope||(e.scope=t.scope),e.isOpenId&&e.id_token&&(this._validateIdTokenAttributes(e,t.id_token),n.debug("ID Token validated")),e.id_token||(e.id_token=t.id_token,e.profile=t.profile);const r=e.isOpenId&&!!e.id_token;await this._processClaims(e,!1,r),n.debug("claims processed")}validateSignoutResponse(e,t){const n=this._logger.create("validateSignoutResponse");if(t.id!==e.state&&n.throw(new Error("State does not match")),n.debug("state validated"),e.userState=t.data,e.error)throw n.warn("Response was error",e.error),new w(e)}_processSigninState(e,t){const n=this._logger.create("_processSigninState");if(t.id!==e.state&&n.throw(new Error("State does not match")),t.client_id||n.throw(new Error("No client_id on state")),t.authority||n.throw(new Error("No authority on state")),this._settings.authority!==t.authority&&n.throw(new Error("authority mismatch on settings vs. signin state")),this._settings.client_id&&this._settings.client_id!==t.client_id&&n.throw(new Error("client_id mismatch on settings vs. signin state")),n.debug("state validated"),e.userState=t.data,e.url_state=t.url_state,null!=e.scope||(e.scope=t.scope),e.error)throw n.warn("Response was error",e.error),new w(e);t.code_verifier&&!e.code&&n.throw(new Error("Expected code in response"))}async _processClaims(e,t=!1,n=!0){const r=this._logger.create("_processClaims");if(e.profile=this._claimsService.filterProtocolClaims(e.profile),t||!this._settings.loadUserInfo||!e.access_token)return void r.debug("not loading user info");r.debug("loading user info");const o=await this._userInfoService.getClaims(e.access_token);r.debug("user info claims received from user info endpoint"),n&&o.sub!==e.profile.sub&&r.throw(new Error("subject from UserInfo response does not match subject in ID Token")),e.profile=this._claimsService.mergeClaims(e.profile,this._claimsService.filterProtocolClaims(o)),r.debug("user info claims received, updated profile:",e.profile)}async _processCode(e,t,n){const r=this._logger.create("_processCode");if(e.code){r.debug("Validating code");const o=await this._tokenClient.exchangeCode({client_id:t.client_id,client_secret:t.client_secret,code:e.code,redirect_uri:t.redirect_uri,code_verifier:t.code_verifier,extraHeaders:n,...t.extraTokenParams});Object.assign(e,o)}else r.debug("No code to process")}_validateIdTokenAttributes(e,t){var n;const r=this._logger.create("_validateIdTokenAttributes");r.debug("decoding ID Token JWT");const o=m.decode(null!=(n=e.id_token)?n:"");if(o.sub||r.throw(new Error("ID Token is missing a subject claim")),t){const e=m.decode(t);o.sub!==e.sub&&r.throw(new Error("sub in id_token does not match current sub")),o.auth_time&&o.auth_time!==e.auth_time&&r.throw(new Error("auth_time in id_token does not match original auth_time")),o.azp&&o.azp!==e.azp&&r.throw(new Error("azp in id_token does not match original azp")),!o.azp&&e.azp&&r.throw(new Error("azp not in id_token, but present in original id_token"))}e.profile=o}},U=class e{constructor(e){this.id=e.id||g.generateUUIDv4(),this.data=e.data,e.created&&e.created>0?this.created=e.created:this.created=y.getEpochTime(),this.request_type=e.request_type,this.url_state=e.url_state}toStorageString(){return new p("State").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state})}static fromStorageString(t){return p.createStatic("State","fromStorageString"),Promise.resolve(new e(JSON.parse(t)))}static async clearStaleState(t,n){const r=p.createStatic("State","clearStaleState"),o=y.getEpochTime()-n,i=await t.getAllKeys();r.debug("got keys",i);for(let a=0;a<i.length;a++){const n=i[a],u=await t.get(n);let l=!1;if(u)try{const t=await e.fromStorageString(u);r.debug("got item from key:",n,t.created),t.created<=o&&(l=!0)}catch(s){r.error("Error parsing state for key:",n,s),l=!0}else r.debug("no item in storage for key:",n),l=!0;l&&(r.debug("removed item for key:",n),t.remove(n))}}},j=class e extends U{constructor(e){super(e),this.code_verifier=e.code_verifier,this.code_challenge=e.code_challenge,this.authority=e.authority,this.client_id=e.client_id,this.redirect_uri=e.redirect_uri,this.scope=e.scope,this.client_secret=e.client_secret,this.extraTokenParams=e.extraTokenParams,this.response_mode=e.response_mode,this.skipUserInfo=e.skipUserInfo}static async create(t){const n=!0===t.code_verifier?g.generateCodeVerifier():t.code_verifier||void 0,r=n?await g.generateCodeChallenge(n):void 0;return new e({...t,code_verifier:n,code_challenge:r})}toStorageString(){return new p("SigninState").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state,code_verifier:this.code_verifier,authority:this.authority,client_id:this.client_id,redirect_uri:this.redirect_uri,scope:this.scope,client_secret:this.client_secret,extraTokenParams:this.extraTokenParams,response_mode:this.response_mode,skipUserInfo:this.skipUserInfo})}static fromStorageString(t){p.createStatic("SigninState","fromStorageString");const n=JSON.parse(t);return e.create(n)}},z=class e{constructor(e){this.url=e.url,this.state=e.state}static async create({url:t,authority:n,client_id:r,redirect_uri:o,response_type:i,scope:s,state_data:a,response_mode:u,request_type:l,client_secret:c,nonce:d,url_state:p,resource:m,skipUserInfo:_,extraQueryParams:h,extraTokenParams:g,disablePKCE:f,dpopJkt:v,omitScopeWhenRequesting:y,...b}){if(!t)throw this._logger.error("create: No url passed"),new Error("url");if(!r)throw this._logger.error("create: No client_id passed"),new Error("client_id");if(!o)throw this._logger.error("create: No redirect_uri passed"),new Error("redirect_uri");if(!i)throw this._logger.error("create: No response_type passed"),new Error("response_type");if(!s)throw this._logger.error("create: No scope passed"),new Error("scope");if(!n)throw this._logger.error("create: No authority passed"),new Error("authority");const w=await j.create({data:a,request_type:l,url_state:p,code_verifier:!f,client_id:r,authority:n,redirect_uri:o,response_mode:u,client_secret:c,scope:s,extraTokenParams:g,skipUserInfo:_}),x=new URL(t);x.searchParams.append("client_id",r),x.searchParams.append("redirect_uri",o),x.searchParams.append("response_type",i),y||x.searchParams.append("scope",s),d&&x.searchParams.append("nonce",d),v&&x.searchParams.append("dpop_jkt",v);let I=w.id;if(p&&(I=`${I}${k}${p}`),x.searchParams.append("state",I),w.code_challenge&&(x.searchParams.append("code_challenge",w.code_challenge),x.searchParams.append("code_challenge_method","S256")),m){(Array.isArray(m)?m:[m]).forEach((e=>x.searchParams.append("resource",e)))}for(const[e,k]of Object.entries({response_mode:u,...b,...h}))null!=k&&x.searchParams.append(e,k.toString());return new e({url:x.href,state:w})}};z._logger=new p("SigninRequest");var D=z,M=class{constructor(e){if(this.access_token="",this.token_type="",this.profile={},this.state=e.get("state"),this.session_state=e.get("session_state"),this.state){const e=decodeURIComponent(this.state).split(k);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(k))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri"),this.code=e.get("code")}get expires_in(){if(void 0!==this.expires_at)return this.expires_at-y.getEpochTime()}set expires_in(e){"string"==typeof e&&(e=Number(e)),void 0!==e&&e>=0&&(this.expires_at=Math.floor(e)+y.getEpochTime())}get isOpenId(){var e;return(null==(e=this.scope)?void 0:e.split(" ").includes("openid"))||!!this.id_token}},L=class{constructor({url:e,state_data:t,id_token_hint:n,post_logout_redirect_uri:r,extraQueryParams:o,request_type:i,client_id:s,url_state:a}){if(this._logger=new p("SignoutRequest"),!e)throw this._logger.error("ctor: No url passed"),new Error("url");const u=new URL(e);if(n&&u.searchParams.append("id_token_hint",n),s&&u.searchParams.append("client_id",s),r&&(u.searchParams.append("post_logout_redirect_uri",r),t||a)){this.state=new U({data:t,request_type:i,url_state:a});let e=this.state.id;a&&(e=`${e}${k}${a}`),u.searchParams.append("state",e)}for(const[l,c]of Object.entries({...o}))null!=c&&u.searchParams.append(l,c.toString());this.url=u.href}},q=class{constructor(e){if(this.state=e.get("state"),this.state){const e=decodeURIComponent(this.state).split(k);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(k))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri")}},Z=["nbf","jti","auth_time","nonce","acr","amr","azp","at_hash"],F=["sub","iss","aud","exp","iat"],W=class{constructor(e){this._settings=e,this._logger=new p("ClaimsService")}filterProtocolClaims(e){const t={...e};if(this._settings.filterProtocolClaims){let e;e=Array.isArray(this._settings.filterProtocolClaims)?this._settings.filterProtocolClaims:Z;for(const n of e)F.includes(n)||delete t[n]}return t}mergeClaims(e,t){const n={...e};for(const[r,o]of Object.entries(t))if(n[r]!==o)if(Array.isArray(n[r])||Array.isArray(o))if("replace"==this._settings.mergeClaimsStrategy.array)n[r]=o;else{const e=Array.isArray(n[r])?n[r]:[n[r]];for(const t of Array.isArray(o)?o:[o])e.includes(t)||e.push(t);n[r]=e}else"object"==typeof n[r]&&"object"==typeof o?n[r]=this.mergeClaims(n[r],o):n[r]=o;return n}},J=class{constructor(e,t){this.keys=e,this.nonce=t}},B=class{constructor(e,t){this._logger=new p("OidcClient"),this.settings=e instanceof N?e:new N(e),this.metadataService=null!=t?t:new T(this.settings),this._claimsService=new W(this.settings),this._validator=new P(this.settings,this.metadataService,this._claimsService),this._tokenClient=new C(this.settings,this.metadataService)}async createSigninRequest({state:e,request:t,request_uri:n,request_type:r,id_token_hint:o,login_hint:i,skipUserInfo:s,nonce:a,url_state:u,response_type:l=this.settings.response_type,scope:c=this.settings.scope,redirect_uri:d=this.settings.redirect_uri,prompt:p=this.settings.prompt,display:m=this.settings.display,max_age:_=this.settings.max_age,ui_locales:h=this.settings.ui_locales,acr_values:g=this.settings.acr_values,resource:f=this.settings.resource,response_mode:v=this.settings.response_mode,extraQueryParams:y=this.settings.extraQueryParams,extraTokenParams:b=this.settings.extraTokenParams,dpopJkt:k,omitScopeWhenRequesting:w=this.settings.omitScopeWhenRequesting}){const x=this._logger.create("createSigninRequest");if("code"!==l)throw new Error("Only the Authorization Code flow (with PKCE) is supported");const I=await this.metadataService.getAuthorizationEndpoint();x.debug("Received authorization endpoint",I);const S=await D.create({url:I,authority:this.settings.authority,client_id:this.settings.client_id,redirect_uri:d,response_type:l,scope:c,state_data:e,url_state:u,prompt:p,display:m,max_age:_,ui_locales:h,id_token_hint:o,login_hint:i,acr_values:g,dpopJkt:k,resource:f,request:t,request_uri:n,extraQueryParams:y,extraTokenParams:b,request_type:r,response_mode:v,client_secret:this.settings.client_secret,skipUserInfo:s,nonce:a,disablePKCE:this.settings.disablePKCE,omitScopeWhenRequesting:w});await this.clearStaleState();const $=S.state;return await this.settings.stateStore.set($.id,$.toStorageString()),S}async readSigninResponseState(e,t=!1){const n=this._logger.create("readSigninResponseState"),r=new M(b.readParams(e,this.settings.response_mode));if(!r.state)throw n.throw(new Error("No state in response")),null;const o=await this.settings.stateStore[t?"remove":"get"](r.state);if(!o)throw n.throw(new Error("No matching state found in storage")),null;return{state:await j.fromStorageString(o),response:r}}async processSigninResponse(e,t,n=!0){const r=this._logger.create("processSigninResponse"),{state:o,response:i}=await this.readSigninResponseState(e,n);if(r.debug("received state from storage; validating response"),this.settings.dpop&&this.settings.dpop.store){const e=await this.getDpopProof(this.settings.dpop.store);t={...t,DPoP:e}}try{await this._validator.validateSigninResponse(i,o,t)}catch(s){if(!(s instanceof O&&this.settings.dpop))throw s;{const e=await this.getDpopProof(this.settings.dpop.store,s.nonce);t.DPoP=e,await this._validator.validateSigninResponse(i,o,t)}}return i}async getDpopProof(e,t){let n,r;return(await e.getAllKeys()).includes(this.settings.client_id)?(r=await e.get(this.settings.client_id),r.nonce!==t&&t&&(r.nonce=t,await e.set(this.settings.client_id,r))):(n=await g.generateDPoPKeys(),r=new J(n,t),await e.set(this.settings.client_id,r)),await g.generateDPoPProof({url:await this.metadataService.getTokenEndpoint(!1),httpMethod:"POST",keyPair:r.keys,nonce:r.nonce})}async processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:n=!1,extraTokenParams:r={}}){const o=await this._tokenClient.exchangeCredentials({username:e,password:t,...r}),i=new M(new URLSearchParams);return Object.assign(i,o),await this._validator.validateCredentialsResponse(i,n),i}async useRefreshToken({state:e,redirect_uri:t,resource:n,timeoutInSeconds:r,extraHeaders:o,extraTokenParams:i}){var s;const a=this._logger.create("useRefreshToken");let u,l;if(void 0===this.settings.refreshTokenAllowedScope)u=e.scope;else{const t=this.settings.refreshTokenAllowedScope.split(" ");u=((null==(s=e.scope)?void 0:s.split(" "))||[]).filter((e=>t.includes(e))).join(" ")}if(this.settings.dpop&&this.settings.dpop.store){const e=await this.getDpopProof(this.settings.dpop.store);o={...o,DPoP:e}}try{l=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:u,redirect_uri:t,resource:n,timeoutInSeconds:r,extraHeaders:o,...i})}catch(d){if(!(d instanceof O&&this.settings.dpop))throw d;o.DPoP=await this.getDpopProof(this.settings.dpop.store,d.nonce),l=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:u,redirect_uri:t,resource:n,timeoutInSeconds:r,extraHeaders:o,...i})}const c=new M(new URLSearchParams);return Object.assign(c,l),a.debug("validating response",c),await this._validator.validateRefreshResponse(c,{...e,scope:u}),c}async createSignoutRequest({state:e,id_token_hint:t,client_id:n,request_type:r,url_state:o,post_logout_redirect_uri:i=this.settings.post_logout_redirect_uri,extraQueryParams:s=this.settings.extraQueryParams}={}){const a=this._logger.create("createSignoutRequest"),u=await this.metadataService.getEndSessionEndpoint();if(!u)throw a.throw(new Error("No end session endpoint")),null;a.debug("Received end session endpoint",u),n||!i||t||(n=this.settings.client_id);const l=new L({url:u,id_token_hint:t,client_id:n,post_logout_redirect_uri:i,state_data:e,extraQueryParams:s,request_type:r,url_state:o});await this.clearStaleState();const c=l.state;return c&&(a.debug("Signout request has state to persist"),await this.settings.stateStore.set(c.id,c.toStorageString())),l}async readSignoutResponseState(e,t=!1){const n=this._logger.create("readSignoutResponseState"),r=new q(b.readParams(e,this.settings.response_mode));if(!r.state){if(n.debug("No state in response"),r.error)throw n.warn("Response was error:",r.error),new w(r);return{state:void 0,response:r}}const o=await this.settings.stateStore[t?"remove":"get"](r.state);if(!o)throw n.throw(new Error("No matching state found in storage")),null;return{state:await U.fromStorageString(o),response:r}}async processSignoutResponse(e){const t=this._logger.create("processSignoutResponse"),{state:n,response:r}=await this.readSignoutResponseState(e,!0);return n?(t.debug("Received state from storage; validating response"),this._validator.validateSignoutResponse(r,n)):t.debug("No state from storage; skipping response validation"),r}clearStaleState(){return this._logger.create("clearStaleState"),U.clearStaleState(this.settings.stateStore,this.settings.staleStateAgeInSeconds)}async revokeToken(e,t){return this._logger.create("revokeToken"),await this._tokenClient.revoke({token:e,token_type_hint:t})}},H=class{constructor(e){this._userManager=e,this._logger=new p("SessionMonitor"),this._start=async e=>{const t=e.session_state;if(!t)return;const n=this._logger.create("_start");if(e.profile?(this._sub=e.profile.sub,n.debug("session_state",t,", sub",this._sub)):(this._sub=void 0,n.debug("session_state",t,", anonymous user")),this._checkSessionIFrame)this._checkSessionIFrame.start(t);else try{const e=await this._userManager.metadataService.getCheckSessionIframe();if(e){n.debug("initializing check session iframe");const r=this._userManager.settings.client_id,o=this._userManager.settings.checkSessionIntervalInSeconds,i=this._userManager.settings.stopCheckSessionOnError,s=new S(this._callback,r,e,o,i);await s.load(),this._checkSessionIFrame=s,s.start(t)}else n.warn("no check session iframe found in the metadata")}catch(r){n.error("Error from getCheckSessionIframe:",r instanceof Error?r.message:r)}},this._stop=()=>{const e=this._logger.create("_stop");if(this._sub=void 0,this._checkSessionIFrame&&this._checkSessionIFrame.stop(),this._userManager.settings.monitorAnonymousSession){const t=setInterval((async()=>{clearInterval(t);try{const e=await this._userManager.querySessionStatus();if(e){const t={session_state:e.session_state,profile:e.sub?{sub:e.sub}:null};this._start(t)}}catch(n){e.error("error from querySessionStatus",n instanceof Error?n.message:n)}}),1e3)}},this._callback=async()=>{const e=this._logger.create("_callback");try{const t=await this._userManager.querySessionStatus();let n=!0;t&&this._checkSessionIFrame?t.sub===this._sub?(n=!1,this._checkSessionIFrame.start(t.session_state),e.debug("same sub still logged in at OP, session state has changed, restarting check session iframe; session_state",t.session_state),await this._userManager.events._raiseUserSessionChanged()):e.debug("different subject signed into OP",t.sub):e.debug("subject no longer signed into OP"),n?this._sub?await this._userManager.events._raiseUserSignedOut():await this._userManager.events._raiseUserSignedIn():e.debug("no change in session detected, no event to raise")}catch(t){this._sub&&(e.debug("Error calling queryCurrentSigninSession; raising signed out event",t),await this._userManager.events._raiseUserSignedOut())}},e||this._logger.throw(new Error("No user manager passed")),this._userManager.events.addUserLoaded(this._start),this._userManager.events.addUserUnloaded(this._stop),this._init().catch((e=>{this._logger.error(e)}))}async _init(){this._logger.create("_init");const e=await this._userManager.getUser();if(e)this._start(e);else if(this._userManager.settings.monitorAnonymousSession){const e=await this._userManager.querySessionStatus();if(e){const t={session_state:e.session_state,profile:e.sub?{sub:e.sub}:null};this._start(t)}}}},V=class e{constructor(e){var t;this.id_token=e.id_token,this.session_state=null!=(t=e.session_state)?t:null,this.access_token=e.access_token,this.refresh_token=e.refresh_token,this.token_type=e.token_type,this.scope=e.scope,this.profile=e.profile,this.expires_at=e.expires_at,this.state=e.userState,this.url_state=e.url_state}get expires_in(){if(void 0!==this.expires_at)return this.expires_at-y.getEpochTime()}set expires_in(e){void 0!==e&&(this.expires_at=Math.floor(e)+y.getEpochTime())}get expired(){const e=this.expires_in;if(void 0!==e)return e<=0}get scopes(){var e,t;return null!=(t=null==(e=this.scope)?void 0:e.split(" "))?t:[]}toStorageString(){return new p("User").create("toStorageString"),JSON.stringify({id_token:this.id_token,session_state:this.session_state,access_token:this.access_token,refresh_token:this.refresh_token,token_type:this.token_type,scope:this.scope,profile:this.profile,expires_at:this.expires_at})}static fromStorageString(t){return p.createStatic("User","fromStorageString"),new e(JSON.parse(t))}},G="oidc-client",K=class{constructor(){this._abort=new f("Window navigation aborted"),this._disposeHandlers=new Set,this._window=null}async navigate(e){const t=this._logger.create("navigate");if(!this._window)throw new Error("Attempted to navigate on a disposed window");t.debug("setting URL in window"),this._window.location.replace(e.url);const{url:n,keepOpen:r}=await new Promise(((n,r)=>{const o=o=>{var i;const s=o.data,a=null!=(i=e.scriptOrigin)?i:window.location.origin;if(o.origin===a&&(null==s?void 0:s.source)===G){try{const n=b.readParams(s.url,e.response_mode).get("state");if(n||t.warn("no state found in response url"),o.source!==this._window&&n!==e.state)return}catch{this._dispose(),r(new Error("Invalid response from window"))}n(s)}};window.addEventListener("message",o,!1),this._disposeHandlers.add((()=>window.removeEventListener("message",o,!1)));const i=new BroadcastChannel(`oidc-client-popup-${e.state}`);i.addEventListener("message",o,!1),this._disposeHandlers.add((()=>i.close())),this._disposeHandlers.add(this._abort.addHandler((e=>{this._dispose(),r(e)})))}));return t.debug("got response from window"),this._dispose(),r||this.close(),{url:n}}_dispose(){this._logger.create("_dispose");for(const e of this._disposeHandlers)e();this._disposeHandlers.clear()}static _notifyParent(e,t,n=!1,r=window.location.origin){const o={source:G,url:t,keepOpen:n},i=new p("_notifyParent");if(e)i.debug("With parent. Using parent.postMessage."),e.postMessage(o,r);else{i.debug("No parent. Using BroadcastChannel.");const e=new URL(t).searchParams.get("state");if(!e)throw new Error("No parent and no state in URL. Can't complete notification.");const n=new BroadcastChannel(`oidc-client-popup-${e}`);n.postMessage(o),n.close()}}},Y={location:!1,toolbar:!1,height:640,closePopupWindowAfterInSeconds:-1},X="_blank",Q=60,ee=2,te=class extends N{constructor(e){const{popup_redirect_uri:t=e.redirect_uri,popup_post_logout_redirect_uri:n=e.post_logout_redirect_uri,popupWindowFeatures:r=Y,popupWindowTarget:o=X,redirectMethod:i="assign",redirectTarget:s="self",iframeNotifyParentOrigin:a=e.iframeNotifyParentOrigin,iframeScriptOrigin:u=e.iframeScriptOrigin,requestTimeoutInSeconds:l,silent_redirect_uri:c=e.redirect_uri,silentRequestTimeoutInSeconds:d,automaticSilentRenew:p=!0,validateSubOnSilentRenew:m=!0,includeIdTokenInSilentRenew:_=!1,monitorSession:h=!1,monitorAnonymousSession:g=!1,checkSessionIntervalInSeconds:f=ee,query_status_response_type:v="code",stopCheckSessionOnError:y=!0,revokeTokenTypes:b=["access_token","refresh_token"],revokeTokensOnSignout:k=!1,includeIdTokenInSilentSignout:w=!1,accessTokenExpiringNotificationTimeInSeconds:x=Q,userStore:I}=e;if(super(e),this.popup_redirect_uri=t,this.popup_post_logout_redirect_uri=n,this.popupWindowFeatures=r,this.popupWindowTarget=o,this.redirectMethod=i,this.redirectTarget=s,this.iframeNotifyParentOrigin=a,this.iframeScriptOrigin=u,this.silent_redirect_uri=c,this.silentRequestTimeoutInSeconds=d||l||10,this.automaticSilentRenew=p,this.validateSubOnSilentRenew=m,this.includeIdTokenInSilentRenew=_,this.monitorSession=h,this.monitorAnonymousSession=g,this.checkSessionIntervalInSeconds=f,this.stopCheckSessionOnError=y,this.query_status_response_type=v,this.revokeTokenTypes=b,this.revokeTokensOnSignout=k,this.includeIdTokenInSilentSignout=w,this.accessTokenExpiringNotificationTimeInSeconds=x,I)this.userStore=I;else{const e="undefined"!=typeof window?window.sessionStorage:new $;this.userStore=new R({store:e})}}},ne=class e extends K{constructor({silentRequestTimeoutInSeconds:t=10}){super(),this._logger=new p("IFrameWindow"),this._timeoutInSeconds=t,this._frame=e.createHiddenIframe(),this._window=this._frame.contentWindow}static createHiddenIframe(){const e=window.document.createElement("iframe");return e.style.visibility="hidden",e.style.position="fixed",e.style.left="-1000px",e.style.top="0",e.width="0",e.height="0",window.document.body.appendChild(e),e}async navigate(e){this._logger.debug("navigate: Using timeout of:",this._timeoutInSeconds);const t=setTimeout((()=>{this._abort.raise(new x("IFrame timed out without a response"))}),1e3*this._timeoutInSeconds);return this._disposeHandlers.add((()=>clearTimeout(t))),await super.navigate(e)}close(){var e;this._frame&&(this._frame.parentNode&&(this._frame.addEventListener("load",(e=>{var t;const n=e.target;null==(t=n.parentNode)||t.removeChild(n),this._abort.raise(new Error("IFrame removed from DOM"))}),!0),null==(e=this._frame.contentWindow)||e.location.replace("about:blank")),this._frame=null),this._window=null}static notifyParent(e,t){return super._notifyParent(window.parent,e,!1,t)}},re=class{constructor(e){this._settings=e,this._logger=new p("IFrameNavigator")}async prepare({silentRequestTimeoutInSeconds:e=this._settings.silentRequestTimeoutInSeconds}){return new ne({silentRequestTimeoutInSeconds:e})}async callback(e){this._logger.create("callback"),ne.notifyParent(e,this._settings.iframeNotifyParentOrigin)}},oe=class extends K{constructor({popupWindowTarget:e=X,popupWindowFeatures:t={},popupSignal:n}){super(),this._logger=new p("PopupWindow");const r=v.center({...Y,...t});this._window=window.open(void 0,e,v.serialize(r)),n&&n.addEventListener("abort",(()=>{var e;this._abort.raise(new Error(null!=(e=n.reason)?e:"Popup aborted"))})),t.closePopupWindowAfterInSeconds&&t.closePopupWindowAfterInSeconds>0&&setTimeout((()=>{this._window&&"boolean"==typeof this._window.closed&&!this._window.closed?this.close():this._abort.raise(new Error("Popup blocked by user"))}),1e3*t.closePopupWindowAfterInSeconds)}async navigate(e){var t;null==(t=this._window)||t.focus();const n=setInterval((()=>{this._window&&!this._window.closed||(this._logger.debug("Popup closed by user or isolated by redirect"),r(),this._disposeHandlers.delete(r))}),500),r=()=>clearInterval(n);return this._disposeHandlers.add(r),await super.navigate(e)}close(){this._window&&(this._window.closed||(this._window.close(),this._abort.raise(new Error("Popup closed")))),this._window=null}static notifyOpener(e,t){super._notifyParent(window.opener,e,t),t||window.opener||window.close()}},ie=class{constructor(e){this._settings=e,this._logger=new p("PopupNavigator")}async prepare({popupWindowFeatures:e=this._settings.popupWindowFeatures,popupWindowTarget:t=this._settings.popupWindowTarget,popupSignal:n}){return new oe({popupWindowFeatures:e,popupWindowTarget:t,popupSignal:n})}async callback(e,{keepOpen:t=!1}){this._logger.create("callback"),oe.notifyOpener(e,t)}},se=class{constructor(e){this._settings=e,this._logger=new p("RedirectNavigator")}async prepare({redirectMethod:e=this._settings.redirectMethod,redirectTarget:t=this._settings.redirectTarget}){var n;this._logger.create("prepare");let r=window.self;"top"===t&&(r=null!=(n=window.top)?n:window.self);const o=r.location[e].bind(r.location);let i;return{navigate:async e=>{this._logger.create("navigate");const t=new Promise(((e,t)=>{i=t}));return o(e.url),await t},close:()=>{this._logger.create("close"),null==i||i(new Error("Redirect aborted")),r.stop()}}}async callback(){}},ae=class extends I{constructor(e){super({expiringNotificationTimeInSeconds:e.accessTokenExpiringNotificationTimeInSeconds}),this._logger=new p("UserManagerEvents"),this._userLoaded=new f("User loaded"),this._userUnloaded=new f("User unloaded"),this._silentRenewError=new f("Silent renew error"),this._userSignedIn=new f("User signed in"),this._userSignedOut=new f("User signed out"),this._userSessionChanged=new f("User session changed")}async load(e,t=!0){await super.load(e),t&&await this._userLoaded.raise(e)}async unload(){await super.unload(),await this._userUnloaded.raise()}addUserLoaded(e){return this._userLoaded.addHandler(e)}removeUserLoaded(e){return this._userLoaded.removeHandler(e)}addUserUnloaded(e){return this._userUnloaded.addHandler(e)}removeUserUnloaded(e){return this._userUnloaded.removeHandler(e)}addSilentRenewError(e){return this._silentRenewError.addHandler(e)}removeSilentRenewError(e){return this._silentRenewError.removeHandler(e)}async _raiseSilentRenewError(e){await this._silentRenewError.raise(e)}addUserSignedIn(e){return this._userSignedIn.addHandler(e)}removeUserSignedIn(e){this._userSignedIn.removeHandler(e)}async _raiseUserSignedIn(){await this._userSignedIn.raise()}addUserSignedOut(e){return this._userSignedOut.addHandler(e)}removeUserSignedOut(e){this._userSignedOut.removeHandler(e)}async _raiseUserSignedOut(){await this._userSignedOut.raise()}addUserSessionChanged(e){return this._userSessionChanged.addHandler(e)}removeUserSessionChanged(e){this._userSessionChanged.removeHandler(e)}async _raiseUserSessionChanged(){await this._userSessionChanged.raise()}},ue=class{constructor(e){this._userManager=e,this._logger=new p("SilentRenewService"),this._isStarted=!1,this._retryTimer=new y("Retry Silent Renew"),this._tokenExpiring=async()=>{const e=this._logger.create("_tokenExpiring");try{await this._userManager.signinSilent(),e.debug("silent token renewal successful")}catch(t){if(t instanceof x)return e.warn("ErrorTimeout from signinSilent:",t,"retry in 5s"),void this._retryTimer.init(5);e.error("Error from signinSilent:",t),await this._userManager.events._raiseSilentRenewError(t)}}}async start(){const e=this._logger.create("start");if(!this._isStarted){this._isStarted=!0,this._userManager.events.addAccessTokenExpiring(this._tokenExpiring),this._retryTimer.addHandler(this._tokenExpiring);try{await this._userManager.getUser()}catch(t){e.error("getUser error",t)}}}stop(){this._isStarted&&(this._retryTimer.cancel(),this._retryTimer.removeHandler(this._tokenExpiring),this._userManager.events.removeAccessTokenExpiring(this._tokenExpiring),this._isStarted=!1)}},le=class{constructor(e){this.refresh_token=e.refresh_token,this.id_token=e.id_token,this.session_state=e.session_state,this.scope=e.scope,this.profile=e.profile,this.data=e.state}},ce=class{constructor(e,t,n,r){this._logger=new p("UserManager"),this.settings=new te(e),this._client=new B(e),this._redirectNavigator=null!=t?t:new se(this.settings),this._popupNavigator=null!=n?n:new ie(this.settings),this._iframeNavigator=null!=r?r:new re(this.settings),this._events=new ae(this.settings),this._silentRenewService=new ue(this),this.settings.automaticSilentRenew&&this.startSilentRenew(),this._sessionMonitor=null,this.settings.monitorSession&&(this._sessionMonitor=new H(this))}get events(){return this._events}get metadataService(){return this._client.metadataService}async getUser(e=!1){const t=this._logger.create("getUser"),n=await this._loadUser();return n?(t.info("user loaded"),await this._events.load(n,e),n):(t.info("user not found in storage"),null)}async removeUser(){const e=this._logger.create("removeUser");await this.storeUser(null),e.info("user removed from storage"),await this._events.unload()}async signinRedirect(e={}){var t;this._logger.create("signinRedirect");const{redirectMethod:n,...r}=e;let o;(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(o=await this.generateDPoPJkt(this.settings.dpop));const i=await this._redirectNavigator.prepare({redirectMethod:n});await this._signinStart({request_type:"si:r",dpopJkt:o,...r},i)}async signinRedirectCallback(e=window.location.href){const t=this._logger.create("signinRedirectCallback"),n=await this._signinEnd(e);return n.profile&&n.profile.sub?t.info("success, signed in subject",n.profile.sub):t.info("no subject"),n}async signinResourceOwnerCredentials({username:e,password:t,skipUserInfo:n=!1}){const r=this._logger.create("signinResourceOwnerCredential"),o=await this._client.processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:n,extraTokenParams:this.settings.extraTokenParams});r.debug("got signin response");const i=await this._buildUser(o);return i.profile&&i.profile.sub?r.info("success, signed in subject",i.profile.sub):r.info("no subject"),i}async signinPopup(e={}){var t;const n=this._logger.create("signinPopup");let r;(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(r=await this.generateDPoPJkt(this.settings.dpop));const{popupWindowFeatures:o,popupWindowTarget:i,popupSignal:s,...a}=e,u=this.settings.popup_redirect_uri;u||n.throw(new Error("No popup_redirect_uri configured"));const l=await this._popupNavigator.prepare({popupWindowFeatures:o,popupWindowTarget:i,popupSignal:s}),c=await this._signin({request_type:"si:p",redirect_uri:u,display:"popup",dpopJkt:r,...a},l);return c&&(c.profile&&c.profile.sub?n.info("success, signed in subject",c.profile.sub):n.info("no subject")),c}async signinPopupCallback(e=window.location.href,t=!1){const n=this._logger.create("signinPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),n.info("success")}async signinSilent(e={}){var t,n;const r=this._logger.create("signinSilent"),{silentRequestTimeoutInSeconds:o,...i}=e;let s,a=await this._loadUser();if(null==a?void 0:a.refresh_token){r.debug("using refresh token");const e=new le(a);return await this._useRefreshToken({state:e,redirect_uri:i.redirect_uri,resource:i.resource,extraTokenParams:i.extraTokenParams,timeoutInSeconds:o})}(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(s=await this.generateDPoPJkt(this.settings.dpop));const u=this.settings.silent_redirect_uri;let l;u||r.throw(new Error("No silent_redirect_uri configured")),a&&this.settings.validateSubOnSilentRenew&&(r.debug("subject prior to silent renew:",a.profile.sub),l=a.profile.sub);const c=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:o});return a=await this._signin({request_type:"si:s",redirect_uri:u,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?null==a?void 0:a.id_token:void 0,dpopJkt:s,...i},c,l),a&&((null==(n=a.profile)?void 0:n.sub)?r.info("success, signed in subject",a.profile.sub):r.info("no subject")),a}async _useRefreshToken(e){const t=await this._client.useRefreshToken({timeoutInSeconds:this.settings.silentRequestTimeoutInSeconds,...e}),n=new V({...e.state,...t});return await this.storeUser(n),await this._events.load(n),n}async signinSilentCallback(e=window.location.href){const t=this._logger.create("signinSilentCallback");await this._iframeNavigator.callback(e),t.info("success")}async signinCallback(e=window.location.href){const{state:t}=await this._client.readSigninResponseState(e);switch(t.request_type){case"si:r":return await this.signinRedirectCallback(e);case"si:p":await this.signinPopupCallback(e);break;case"si:s":await this.signinSilentCallback(e);break;default:throw new Error("invalid response_type in state")}}async signoutCallback(e=window.location.href,t=!1){const{state:n}=await this._client.readSignoutResponseState(e);if(n)switch(n.request_type){case"so:r":return await this.signoutRedirectCallback(e);case"so:p":await this.signoutPopupCallback(e,t);break;case"so:s":await this.signoutSilentCallback(e);break;default:throw new Error("invalid response_type in state")}}async querySessionStatus(e={}){const t=this._logger.create("querySessionStatus"),{silentRequestTimeoutInSeconds:n,...r}=e,o=this.settings.silent_redirect_uri;o||t.throw(new Error("No silent_redirect_uri configured"));const i=await this._loadUser(),s=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:n}),a=await this._signinStart({request_type:"si:s",redirect_uri:o,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?null==i?void 0:i.id_token:void 0,response_type:this.settings.query_status_response_type,scope:"openid",skipUserInfo:!0,...r},s);try{const e={},n=await this._client.processSigninResponse(a.url,e);return t.debug("got signin response"),n.session_state&&n.profile.sub?(t.info("success for subject",n.profile.sub),{session_state:n.session_state,sub:n.profile.sub}):(t.info("success, user not authenticated"),null)}catch(u){if(this.settings.monitorAnonymousSession&&u instanceof w)switch(u.error){case"login_required":case"consent_required":case"interaction_required":case"account_selection_required":return t.info("success for anonymous user"),{session_state:u.session_state}}throw u}}async _signin(e,t,n){const r=await this._signinStart(e,t);return await this._signinEnd(r.url,n)}async _signinStart(e,t){const n=this._logger.create("_signinStart");try{const r=await this._client.createSigninRequest(e);return n.debug("got signin request"),await t.navigate({url:r.url,state:r.state.id,response_mode:r.state.response_mode,scriptOrigin:this.settings.iframeScriptOrigin})}catch(r){throw n.debug("error after preparing navigator, closing navigator window"),t.close(),r}}async _signinEnd(e,t){const n=this._logger.create("_signinEnd"),r=await this._client.processSigninResponse(e,{});n.debug("got signin response");return await this._buildUser(r,t)}async _buildUser(e,t){const n=this._logger.create("_buildUser"),r=new V(e);if(t){if(t!==r.profile.sub)throw n.debug("current user does not match user returned from signin. sub from signin:",r.profile.sub),new w({...e,error:"login_required"});n.debug("current user matches user returned from signin")}return await this.storeUser(r),n.debug("user stored"),await this._events.load(r),r}async signoutRedirect(e={}){const t=this._logger.create("signoutRedirect"),{redirectMethod:n,...r}=e,o=await this._redirectNavigator.prepare({redirectMethod:n});await this._signoutStart({request_type:"so:r",post_logout_redirect_uri:this.settings.post_logout_redirect_uri,...r},o),t.info("success")}async signoutRedirectCallback(e=window.location.href){const t=this._logger.create("signoutRedirectCallback"),n=await this._signoutEnd(e);return t.info("success"),n}async signoutPopup(e={}){const t=this._logger.create("signoutPopup"),{popupWindowFeatures:n,popupWindowTarget:r,popupSignal:o,...i}=e,s=this.settings.popup_post_logout_redirect_uri,a=await this._popupNavigator.prepare({popupWindowFeatures:n,popupWindowTarget:r,popupSignal:o});await this._signout({request_type:"so:p",post_logout_redirect_uri:s,state:null==s?void 0:{},...i},a),t.info("success")}async signoutPopupCallback(e=window.location.href,t=!1){const n=this._logger.create("signoutPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),n.info("success")}async _signout(e,t){const n=await this._signoutStart(e,t);return await this._signoutEnd(n.url)}async _signoutStart(e={},t){var n;const r=this._logger.create("_signoutStart");try{const o=await this._loadUser();r.debug("loaded current user from storage"),this.settings.revokeTokensOnSignout&&await this._revokeInternal(o);const i=e.id_token_hint||o&&o.id_token;i&&(r.debug("setting id_token_hint in signout request"),e.id_token_hint=i),await this.removeUser(),r.debug("user removed, creating signout request");const s=await this._client.createSignoutRequest(e);return r.debug("got signout request"),await t.navigate({url:s.url,state:null==(n=s.state)?void 0:n.id,scriptOrigin:this.settings.iframeScriptOrigin})}catch(o){throw r.debug("error after preparing navigator, closing navigator window"),t.close(),o}}async _signoutEnd(e){const t=this._logger.create("_signoutEnd"),n=await this._client.processSignoutResponse(e);return t.debug("got signout response"),n}async signoutSilent(e={}){var t;const n=this._logger.create("signoutSilent"),{silentRequestTimeoutInSeconds:r,...o}=e,i=this.settings.includeIdTokenInSilentSignout?null==(t=await this._loadUser())?void 0:t.id_token:void 0,s=this.settings.popup_post_logout_redirect_uri,a=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:r});await this._signout({request_type:"so:s",post_logout_redirect_uri:s,id_token_hint:i,...o},a),n.info("success")}async signoutSilentCallback(e=window.location.href){const t=this._logger.create("signoutSilentCallback");await this._iframeNavigator.callback(e),t.info("success")}async revokeTokens(e){const t=await this._loadUser();await this._revokeInternal(t,e)}async _revokeInternal(e,t=this.settings.revokeTokenTypes){const n=this._logger.create("_revokeInternal");if(!e)return;const r=t.filter((t=>"string"==typeof e[t]));if(r.length){for(const t of r)await this._client.revokeToken(e[t],t),n.info(`${t} revoked successfully`),"access_token"!==t&&(e[t]=null);await this.storeUser(e),n.debug("user stored"),await this._events.load(e)}else n.debug("no need to revoke due to no token(s)")}startSilentRenew(){this._logger.create("startSilentRenew"),this._silentRenewService.start()}stopSilentRenew(){this._silentRenewService.stop()}get _userStoreKey(){return`user:${this.settings.authority}:${this.settings.client_id}`}async _loadUser(){const e=this._logger.create("_loadUser"),t=await this.settings.userStore.get(this._userStoreKey);return t?(e.debug("user storageString loaded"),V.fromStorageString(t)):(e.debug("no user storageString"),null)}async storeUser(e){const t=this._logger.create("storeUser");if(e){t.debug("storing user");const n=e.toStorageString();await this.settings.userStore.set(this._userStoreKey,n)}else this._logger.debug("removing user"),await this.settings.userStore.remove(this._userStoreKey),this.settings.dpop&&await this.settings.dpop.store.remove(this.settings.client_id)}async clearStaleState(){await this._client.clearStaleState()}async dpopProof(e,t,n,r){var o,i;const s=await(null==(i=null==(o=this.settings.dpop)?void 0:o.store)?void 0:i.get(this.settings.client_id));if(s)return await g.generateDPoPProof({url:e,accessToken:null==t?void 0:t.access_token,httpMethod:n,keyPair:s.keys,nonce:r})}async generateDPoPJkt(e){let t=await e.store.get(this.settings.client_id);if(!t){const n=await g.generateDPoPKeys();t=new J(n),await e.store.set(this.settings.client_id,t)}return await g.generateDPoPJkt(t.keys)}},de=o.createContext(void 0);de.displayName="AuthContext";var pe={isLoading:!0,isAuthenticated:!1},me=(e,t)=>{switch(t.type){case"INITIALISED":case"USER_LOADED":return{...e,user:t.user,isLoading:!1,isAuthenticated:!!t.user&&!t.user.expired,error:void 0};case"USER_SIGNED_OUT":case"USER_UNLOADED":return{...e,user:void 0,isAuthenticated:!1};case"NAVIGATOR_INIT":return{...e,isLoading:!0,activeNavigator:t.method};case"NAVIGATOR_CLOSE":return{...e,isLoading:!1,activeNavigator:void 0};case"ERROR":{const n=t.error;return n.toString=()=>`${n.name}: ${n.message}`,{...e,isLoading:!1,error:n}}default:{const n=new TypeError(`unknown type ${t.type}`),r={name:n.name,message:n.message,innerError:n,stack:n.stack,source:"unknown",toString:()=>`${r.name}: ${r.message}`};return{...e,isLoading:!1,error:r}}}},_e=ve("signinCallback","Sign-in failed"),he=ve("signoutCallback","Sign-out failed"),ge=ve("renewSilent","Renew silent failed");function fe(e,t){return{name:ye(e,"name",(()=>"Error")),message:ye(e,"message",(()=>t)),stack:ye(e,"stack",(()=>(new Error).stack)),innerError:e}}function ve(e,t){return n=>({...fe(n,t),source:e})}function ye(e,t,n){if(e&&"object"==typeof e){const n=e[t];if("string"==typeof n)return n}return n()}var be,ke=["clearStaleState","querySessionStatus","revokeTokens","startSilentRenew","stopSilentRenew"],we=["signinPopup","signinSilent","signinRedirect","signinResourceOwnerCredentials","signoutPopup","signoutRedirect","signoutSilent"],xe=e=>()=>{throw new Error(`UserManager#${e} was called from an unsupported context. If this is a server-rendered page, defer this call with useEffect() or pass a custom UserManager implementation.`)},Ie="undefined"==typeof window?null:ce,Se=e=>{const{children:t,onSigninCallback:n,skipSigninCallback:r,matchSignoutCallback:i,onSignoutCallback:s,onRemoveUser:a,userManager:u=null,...l}=e,[c]=o.useState((()=>null!=u?u:Ie?new Ie(l):{settings:l})),[d,p]=o.useReducer(me,pe),m=o.useMemo((()=>Object.assign({settings:c.settings,events:c.events},Object.fromEntries(ke.map((e=>{var t,n;return[e,null!=(n=null==(t=c[e])?void 0:t.bind(c))?n:xe(e)]}))),Object.fromEntries(we.map((e=>[e,c[e]?async t=>{p({type:"NAVIGATOR_INIT",method:e});try{return await c[e](t)}catch(n){return p({type:"ERROR",error:{...fe(n,`Unknown error while executing ${e}(...).`),source:e,args:t}}),null}finally{p({type:"NAVIGATOR_CLOSE"})}}:xe(e)]))))),[c]),_=o.useRef(!1);o.useEffect((()=>{c&&!_.current&&(_.current=!0,(async()=>{try{let e=null;((e=window.location)=>{let t=new URLSearchParams(e.search);return!!((t.get("code")||t.get("error"))&&t.get("state")||(t=new URLSearchParams(e.hash.replace("#","?")),(t.get("code")||t.get("error"))&&t.get("state")))})()&&!r&&(e=await c.signinCallback(),n&&await n(e)),e=e||await c.getUser(),p({type:"INITIALISED",user:e})}catch(e){p({type:"ERROR",error:_e(e)})}try{if(i&&i(c.settings)){const e=await c.signoutCallback();s&&await s(e)}}catch(e){p({type:"ERROR",error:he(e)})}})())}),[c,r,n,s,i]),o.useEffect((()=>{if(!c)return;const e=e=>{p({type:"USER_LOADED",user:e})};c.events.addUserLoaded(e);const t=()=>{p({type:"USER_UNLOADED"})};c.events.addUserUnloaded(t);const n=()=>{p({type:"USER_SIGNED_OUT"})};c.events.addUserSignedOut(n);const r=e=>{p({type:"ERROR",error:ge(e)})};return c.events.addSilentRenewError(r),()=>{c.events.removeUserLoaded(e),c.events.removeUserUnloaded(t),c.events.removeUserSignedOut(n),c.events.removeSilentRenewError(r)}}),[c]);const h=o.useCallback((async()=>{await c.removeUser(),a&&await a()}),[c,a]),g=o.useMemo((()=>({...d,...m,removeUser:h})),[d,m,h]);return o.createElement(de.Provider,{value:g},t)},$e=()=>{const e=o.useContext(de);return e||console.warn("AuthProvider context is undefined, please verify you are calling useAuth() as child of a <AuthProvider> component."),e},Oe="vercel.ai.error",Ee=Symbol.for(Oe),Te=class e extends Error{constructor({name:e,message:t,cause:n}){super(t),this[be]=!0,this.name=e,this.cause=n}static isInstance(t){return e.hasMarker(t,Oe)}static hasMarker(e,t){const n=Symbol.for(t);return null!=e&&"object"==typeof e&&n in e&&"boolean"==typeof e[n]&&!0===e[n]}};be=Ee;var Re,Ne=Te,Ae="AI_APICallError",Ce=`vercel.ai.error.${Ae}`,Pe=Symbol.for(Ce),Ue=class extends Ne{constructor({message:e,url:t,requestBodyValues:n,statusCode:r,responseHeaders:o,responseBody:i,cause:s,isRetryable:a=null!=r&&(408===r||409===r||429===r||r>=500),data:u}){super({name:Ae,message:e,cause:s}),this[Re]=!0,this.url=t,this.requestBodyValues=n,this.statusCode=r,this.responseHeaders=o,this.responseBody=i,this.isRetryable=a,this.data=u}static isInstance(e){return Ne.hasMarker(e,Ce)}};Re=Pe;var je,ze="AI_EmptyResponseBodyError",De=`vercel.ai.error.${ze}`,Me=Symbol.for(De),Le=class extends Ne{constructor({message:e="Empty response body"}={}){super({name:ze,message:e}),this[je]=!0}static isInstance(e){return Ne.hasMarker(e,De)}};function qe(e){return null==e?"unknown error":"string"==typeof e?e:e instanceof Error?e.message:JSON.stringify(e)}je=Me;var Ze,Fe="AI_InvalidArgumentError",We=`vercel.ai.error.${Fe}`,Je=Symbol.for(We),Be=class extends Ne{constructor({message:e,cause:t,argument:n}){super({name:Fe,message:e,cause:t}),this[Ze]=!0,this.argument=n}static isInstance(e){return Ne.hasMarker(e,We)}};Ze=Je;var He,Ve="AI_InvalidPromptError",Ge=`vercel.ai.error.${Ve}`,Ke=Symbol.for(Ge),Ye=class extends Ne{constructor({prompt:e,message:t,cause:n}){super({name:Ve,message:`Invalid prompt: ${t}`,cause:n}),this[He]=!0,this.prompt=e}static isInstance(e){return Ne.hasMarker(e,Ge)}};He=Ke;var Xe,Qe="AI_InvalidResponseDataError",et=`vercel.ai.error.${Qe}`,tt=Symbol.for(et),nt=class extends Ne{constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:Qe,message:t}),this[Xe]=!0,this.data=e}static isInstance(e){return Ne.hasMarker(e,et)}};Xe=tt;var rt,ot="AI_JSONParseError",it=`vercel.ai.error.${ot}`,st=Symbol.for(it),at=class extends Ne{constructor({text:e,cause:t}){super({name:ot,message:`JSON parsing failed: Text: ${e}.\nError message: ${qe(t)}`,cause:t}),this[rt]=!0,this.text=e}static isInstance(e){return Ne.hasMarker(e,it)}};rt=st;var ut,lt="AI_LoadAPIKeyError",ct=`vercel.ai.error.${lt}`,dt=Symbol.for(ct),pt=class extends Ne{constructor({message:e}){super({name:lt,message:e}),this[ut]=!0}static isInstance(e){return Ne.hasMarker(e,ct)}};ut=dt;var mt,_t="AI_NoSuchModelError",ht=`vercel.ai.error.${_t}`,gt=Symbol.for(ht),ft=class extends Ne{constructor({errorName:e=_t,modelId:t,modelType:n,message:r=`No such ${n}: ${t}`}){super({name:e,message:r}),this[mt]=!0,this.modelId=t,this.modelType=n}static isInstance(e){return Ne.hasMarker(e,ht)}};mt=gt;var vt,yt="AI_TooManyEmbeddingValuesForCallError",bt=`vercel.ai.error.${yt}`,kt=Symbol.for(bt),wt=class extends Ne{constructor(e){super({name:yt,message:`Too many values for a single embedding call. The ${e.provider} model "${e.modelId}" can only embed up to ${e.maxEmbeddingsPerCall} values per call, but ${e.values.length} values were provided.`}),this[vt]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return Ne.hasMarker(e,bt)}};vt=kt;var xt,It="AI_TypeValidationError",St=`vercel.ai.error.${It}`,$t=Symbol.for(St);xt=$t;var Ot,Et=class e extends Ne{constructor({value:e,cause:t}){super({name:It,message:`Type validation failed: Value: ${JSON.stringify(e)}.\nError message: ${qe(t)}`,cause:t}),this[xt]=!0,this.value=e}static isInstance(e){return Ne.hasMarker(e,St)}static wrap({value:t,cause:n}){return e.isInstance(n)&&n.value===t?n:new e({value:t,cause:n})}},Tt="AI_UnsupportedFunctionalityError",Rt=`vercel.ai.error.${Tt}`,Nt=Symbol.for(Rt),At=class extends Ne{constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:Tt,message:t}),this[Ot]=!0,this.functionality=e}static isInstance(e){return Ne.hasMarker(e,Rt)}};Ot=Nt;class Ct extends Error{constructor(e,t){super(e),this.name="ParseError",this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}}function Pt(e){}function Ut(e){if("function"==typeof e)throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=Pt,onError:n=Pt,onRetry:r=Pt,onComment:o}=e;let i,s="",a=!0,u="",l="";function c(e){if(""===e)return u.length>0&&t({id:i,event:l||void 0,data:u.endsWith("\n")?u.slice(0,-1):u}),i=void 0,u="",void(l="");if(e.startsWith(":"))return void(o&&o(e.slice(e.startsWith(": ")?2:1)));const n=e.indexOf(":");if(-1===n)d(e,"",e);else{const t=e.slice(0,n),r=" "===e[n+1]?2:1;d(t,e.slice(n+r),e)}}function d(e,t,o){switch(e){case"event":l=t;break;case"data":u=`${u}${t}\n`;break;case"id":i=t.includes("\0")?void 0:t;break;case"retry":/^\d+$/.test(t)?r(parseInt(t,10)):n(new Ct(`Invalid \`retry\` value: "${t}"`,{type:"invalid-retry",value:t,line:o}));break;default:n(new Ct(`Unknown field "${e.length>20?`${e.slice(0,20)}…`:e}"`,{type:"unknown-field",field:e,value:t,line:o}))}}return{feed:function(e){const t=a?e.replace(/^\xEF\xBB\xBF/,""):e,[n,r]=function(e){const t=[];let n="",r=0;for(;r<e.length;){const o=e.indexOf("\r",r),i=e.indexOf("\n",r);let s=-1;if(-1!==o&&-1!==i?s=Math.min(o,i):-1!==o?s=o===e.length-1?-1:o:-1!==i&&(s=i),-1===s){n=e.slice(r);break}{const n=e.slice(r,s);t.push(n),r=s+1,"\r"===e[r-1]&&"\n"===e[r]&&r++}}return[t,n]}(`${s}${t}`);for(const o of n)c(o);s=r,a=!1},reset:function(e={}){s&&e.consume&&c(s),a=!0,i=void 0,u="",l="",s=""}}}class jt extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let r;super({start(o){r=Ut({onEvent:e=>{o.enqueue(e)},onError(t){"terminate"===e?o.error(t):"function"==typeof e&&e(t)},onRetry:t,onComment:n})},transform(e){r.feed(e)}})}}const zt=Object.freeze({status:"aborted"});function Dt(e,t,n){function r(n,r){var o;Object.defineProperty(n,"_zod",{value:n._zod??{},enumerable:!1}),(o=n._zod).traits??(o.traits=new Set),n._zod.traits.add(e),t(n,r);for(const e in s.prototype)e in n||Object.defineProperty(n,e,{value:s.prototype[e].bind(n)});n._zod.constr=s,n._zod.def=r}const o=(null==n?void 0:n.Parent)??Object;class i extends o{}function s(e){var t;const o=(null==n?void 0:n.Parent)?new i:this;r(o,e),(t=o._zod).deferred??(t.deferred=[]);for(const n of o._zod.deferred)n();return o}return Object.defineProperty(i,"name",{value:e}),Object.defineProperty(s,"init",{value:r}),Object.defineProperty(s,Symbol.hasInstance,{value:t=>{var r,o;return!!((null==n?void 0:n.Parent)&&t instanceof n.Parent)||(null==(o=null==(r=null==t?void 0:t._zod)?void 0:r.traits)?void 0:o.has(e))}}),Object.defineProperty(s,"name",{value:e}),s}const Mt=Symbol("zod_brand");class Lt extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const qt={};function Zt(e){return e&&Object.assign(qt,e),qt}function Ft(e){const t=Object.values(e).filter((e=>"number"==typeof e));return Object.entries(e).filter((([e,n])=>-1===t.indexOf(+e))).map((([e,t])=>t))}function Wt(e,t="|"){return e.map((e=>mn(e))).join(t)}function Jt(e,t){return"bigint"==typeof t?t.toString():t}function Bt(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Ht(e){return null==e}function Vt(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function Gt(e,t){const n=(e.toString().split(".")[1]||"").length,r=t.toString();let o=(r.split(".")[1]||"").length;if(0===o&&/\d?e-\d?/.test(r)){const e=r.match(/\d?e-(\d?)/);(null==e?void 0:e[1])&&(o=Number.parseInt(e[1]))}const i=n>o?n:o;return Number.parseInt(e.toFixed(i).replace(".",""))%Number.parseInt(t.toFixed(i).replace(".",""))/10**i}const Kt=Symbol("evaluating");function Yt(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==Kt)return void 0===r&&(r=Kt,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Xt(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function Qt(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function en(...e){const t={};for(const n of e){const e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function tn(e){return JSON.stringify(e)}const nn="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function rn(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const on=Bt((()=>{var e;if("undefined"!=typeof navigator&&(null==(e=null==navigator?void 0:navigator.userAgent)?void 0:e.includes("Cloudflare")))return!1;try{return new Function(""),!0}catch(t){return!1}}));function sn(e){if(!1===rn(e))return!1;const t=e.constructor;if(void 0===t)return!0;const n=t.prototype;return!1!==rn(n)&&!1!==Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")}function an(e){return sn(e)?{...e}:e}const un=new Set(["string","number","symbol"]),ln=new Set(["string","number","bigint","boolean","symbol","undefined"]);function cn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function dn(e,t,n){const r=new e._zod.constr(t??e._zod.def);return t&&!(null==n?void 0:n.parent)||(r._zod.parent=e),r}function pn(e){const t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==(null==t?void 0:t.message)){if(void 0!==(null==t?void 0:t.error))throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,"string"==typeof t.error?{...t,error:()=>t.error}:t}function mn(e){return"bigint"==typeof e?e.toString()+"n":"string"==typeof e?`"${e}"`:`${e}`}function _n(e){return Object.keys(e).filter((t=>"optional"===e[t]._zod.optin&&"optional"===e[t]._zod.optout))}const hn={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},gn={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function fn(e,t){const n=e._zod.def;return dn(e,en(e._zod.def,{get shape(){const e={};for(const r in t){if(!(r in n.shape))throw new Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return Qt(this,"shape",e),e},checks:[]}))}function vn(e,t){const n=e._zod.def,r=en(e._zod.def,{get shape(){const r={...e._zod.def.shape};for(const e in t){if(!(e in n.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return Qt(this,"shape",r),r},checks:[]});return dn(e,r)}function yn(e,t){if(!sn(t))throw new Error("Invalid input to extend: expected a plain object");const n=en(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return Qt(this,"shape",n),n},checks:[]});return dn(e,n)}function bn(e,t){const n=en(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return Qt(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:[]});return dn(e,n)}function kn(e,t,n){const r=en(t._zod.def,{get shape(){const r=t._zod.def.shape,o={...r};if(n)for(const t in n){if(!(t in r))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(o[t]=e?new e({type:"optional",innerType:r[t]}):r[t])}else for(const t in r)o[t]=e?new e({type:"optional",innerType:r[t]}):r[t];return Qt(this,"shape",o),o},checks:[]});return dn(t,r)}function wn(e,t,n){const r=en(t._zod.def,{get shape(){const r=t._zod.def.shape,o={...r};if(n)for(const t in n){if(!(t in o))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(o[t]=new e({type:"nonoptional",innerType:r[t]}))}else for(const t in r)o[t]=new e({type:"nonoptional",innerType:r[t]});return Qt(this,"shape",o),o},checks:[]});return dn(t,r)}function xn(e,t=0){var n;for(let r=t;r<e.issues.length;r++)if(!0!==(null==(n=e.issues[r])?void 0:n.continue))return!0;return!1}function In(e,t){return t.map((t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t}))}function Sn(e){return"string"==typeof e?e:null==e?void 0:e.message}function $n(e,t,n){var r,o,i,s,a,u;const l={...e,path:e.path??[]};if(!e.message){const c=Sn(null==(i=null==(o=null==(r=e.inst)?void 0:r._zod.def)?void 0:o.error)?void 0:i.call(o,e))??Sn(null==(s=null==t?void 0:t.error)?void 0:s.call(t,e))??Sn(null==(a=n.customError)?void 0:a.call(n,e))??Sn(null==(u=n.localeError)?void 0:u.call(n,e))??"Invalid input";l.message=c}return delete l.inst,delete l.continue,(null==t?void 0:t.reportInput)||delete l.input,l}function On(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function En(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function Tn(...e){const[t,n,r]=e;return"string"==typeof t?{message:t,code:"custom",input:n,inst:r}:{...t}}const Rn=Object.freeze(Object.defineProperty({__proto__:null,BIGINT_FORMAT_RANGES:gn,Class:class{constructor(...e){}},NUMBER_FORMAT_RANGES:hn,aborted:xn,allowsEval:on,assert:function(e){},assertEqual:function(e){return e},assertIs:function(e){},assertNever:function(e){throw new Error},assertNotEqual:function(e){return e},assignProp:Qt,cached:Bt,captureStackTrace:nn,cleanEnum:function(e){return Object.entries(e).filter((([e,t])=>Number.isNaN(Number.parseInt(e,10)))).map((e=>e[1]))},cleanRegex:Vt,clone:dn,cloneDef:function(e){return en(e._zod.def)},createTransparentProxy:function(e){let t;return new Proxy({},{get:(n,r,o)=>(t??(t=e()),Reflect.get(t,r,o)),set:(n,r,o,i)=>(t??(t=e()),Reflect.set(t,r,o,i)),has:(n,r)=>(t??(t=e()),Reflect.has(t,r)),deleteProperty:(n,r)=>(t??(t=e()),Reflect.deleteProperty(t,r)),ownKeys:n=>(t??(t=e()),Reflect.ownKeys(t)),getOwnPropertyDescriptor:(n,r)=>(t??(t=e()),Reflect.getOwnPropertyDescriptor(t,r)),defineProperty:(n,r,o)=>(t??(t=e()),Reflect.defineProperty(t,r,o))})},defineLazy:Yt,esc:tn,escapeRegex:cn,extend:yn,finalizeIssue:$n,floatSafeRemainder:Gt,getElementAtPath:function(e,t){return t?t.reduce(((e,t)=>null==e?void 0:e[t]),e):e},getEnumValues:Ft,getLengthableOrigin:En,getParsedType:e=>{const t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":null===e?"null":e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?"promise":"undefined"!=typeof Map&&e instanceof Map?"map":"undefined"!=typeof Set&&e instanceof Set?"set":"undefined"!=typeof Date&&e instanceof Date?"date":"undefined"!=typeof File&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},getSizableOrigin:On,isObject:rn,isPlainObject:sn,issue:Tn,joinValues:Wt,jsonStringifyReplacer:Jt,merge:bn,mergeDefs:en,normalizeParams:pn,nullish:Ht,numKeys:function(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t},objectClone:Xt,omit:vn,optionalKeys:_n,partial:kn,pick:fn,prefixIssues:In,primitiveTypes:ln,promiseAllObject:function(e){const t=Object.keys(e),n=t.map((t=>e[t]));return Promise.all(n).then((e=>{const n={};for(let r=0;r<t.length;r++)n[t[r]]=e[r];return n}))},propertyKeyTypes:un,randomString:function(e=10){const t="abcdefghijklmnopqrstuvwxyz";let n="";for(let r=0;r<e;r++)n+=t[Math.floor(26*Math.random())];return n},required:wn,shallowClone:an,stringifyPrimitive:mn,unwrapMessage:Sn},Symbol.toStringTag,{value:"Module"})),Nn=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Jt,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},An=Dt("$ZodError",Nn),Cn=Dt("$ZodError",Nn,{Parent:Error});function Pn(e,t=e=>e.message){const n={},r=[];for(const o of e.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}function Un(e,t){const n=t||function(e){return e.message},r={_errors:[]},o=e=>{for(const t of e.issues)if("invalid_union"===t.code&&t.errors.length)t.errors.map((e=>o({issues:e})));else if("invalid_key"===t.code)o({issues:t.issues});else if("invalid_element"===t.code)o({issues:t.issues});else if(0===t.path.length)r._errors.push(n(t));else{let e=r,o=0;for(;o<t.path.length;){const r=t.path[o];o===t.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(n(t))):e[r]=e[r]||{_errors:[]},e=e[r],o++}}};return o(e),r}function jn(e,t){const n=t||function(e){return e.message},r={errors:[]},o=(e,t=[])=>{var i,s;for(const a of e.issues)if("invalid_union"===a.code&&a.errors.length)a.errors.map((e=>o({issues:e},a.path)));else if("invalid_key"===a.code)o({issues:a.issues},a.path);else if("invalid_element"===a.code)o({issues:a.issues},a.path);else{const e=[...t,...a.path];if(0===e.length){r.errors.push(n(a));continue}let o=r,u=0;for(;u<e.length;){const t=e[u],r=u===e.length-1;"string"==typeof t?(o.properties??(o.properties={}),(i=o.properties)[t]??(i[t]={errors:[]}),o=o.properties[t]):(o.items??(o.items=[]),(s=o.items)[t]??(s[t]={errors:[]}),o=o.items[t]),r&&o.errors.push(n(a)),u++}}};return o(e),r}function zn(e){const t=[],n=e.map((e=>"object"==typeof e?e.key:e));for(const r of n)"number"==typeof r?t.push(`[${r}]`):"symbol"==typeof r?t.push(`[${JSON.stringify(String(r))}]`):/[^\w$]/.test(r)?t.push(`[${JSON.stringify(r)}]`):(t.length&&t.push("."),t.push(r));return t.join("")}function Dn(e){var t;const n=[],r=[...e.issues].sort(((e,t)=>(e.path??[]).length-(t.path??[]).length));for(const o of r)n.push(`✖ ${o.message}`),(null==(t=o.path)?void 0:t.length)&&n.push(` → at ${zn(o.path)}`);return n.join("\n")}const Mn=e=>(t,n,r,o)=>{const i=r?Object.assign(r,{async:!1}):{async:!1},s=t._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw new Lt;if(s.issues.length){const t=new((null==o?void 0:o.Err)??e)(s.issues.map((e=>$n(e,i,Zt()))));throw nn(t,null==o?void 0:o.callee),t}return s.value},Ln=Mn(Cn),qn=e=>async(t,n,r,o)=>{const i=r?Object.assign(r,{async:!0}):{async:!0};let s=t._zod.run({value:n,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){const t=new((null==o?void 0:o.Err)??e)(s.issues.map((e=>$n(e,i,Zt()))));throw nn(t,null==o?void 0:o.callee),t}return s.value},Zn=qn(Cn),Fn=e=>(t,n,r)=>{const o=r?{...r,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},o);if(i instanceof Promise)throw new Lt;return i.issues.length?{success:!1,error:new(e??An)(i.issues.map((e=>$n(e,o,Zt()))))}:{success:!0,data:i.value}},Wn=Fn(Cn),Jn=e=>async(t,n,r)=>{const o=r?Object.assign(r,{async:!0}):{async:!0};let i=t._zod.run({value:n,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map((e=>$n(e,o,Zt()))))}:{success:!0,data:i.value}},Bn=Jn(Cn),Hn=/^[cC][^\s-]{8,}$/,Vn=/^[0-9a-z]+$/,Gn=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Kn=/^[0-9a-vA-V]{20}$/,Yn=/^[A-Za-z0-9]{27}$/,Xn=/^[a-zA-Z0-9_-]{21}$/,Qn=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,er=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,tr=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,nr=tr(4),rr=tr(6),or=tr(7),ir=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function sr(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}const ar=/^(?:(?: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])$/,ur=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,lr=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,cr=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,dr=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,pr=/^[A-Za-z0-9_-]*$/,mr=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,_r=/^\+(?:[0-9]){6,14}[0-9]$/,hr="(?:(?:\\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])))",gr=new RegExp(`^${hr}$`);function fr(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function vr(e){return new RegExp(`^${fr(e)}$`)}function yr(e){const t=fr({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${hr}T(?:${r})$`)}const br=e=>{const t=e?`[\\s\\S]{${(null==e?void 0:e.minimum)??0},${(null==e?void 0:e.maximum)??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},kr=/^\d+n?$/,wr=/^\d+$/,xr=/^-?\d+(?:\.\d+)?/i,Ir=/true|false/i,Sr=/null/i,$r=/undefined/i,Or=/^[^A-Z]*$/,Er=/^[^a-z]*$/,Tr=Object.freeze(Object.defineProperty({__proto__:null,base64:dr,base64url:pr,bigint:kr,boolean:Ir,browserEmail:/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,cidrv4:lr,cidrv6:cr,cuid:Hn,cuid2:Vn,date:gr,datetime:yr,domain:/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,duration:Qn,e164:_r,email:ir,emoji:sr,extendedDuration:/^[-+]?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)?)??$/,guid:er,hostname:mr,html5Email:/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,idnEmail:/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,integer:wr,ipv4:ar,ipv6:ur,ksuid:Yn,lowercase:Or,nanoid:Xn,null:Sr,number:xr,rfc5322Email:/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,string:br,time:vr,ulid:Gn,undefined:$r,unicodeEmail:/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,uppercase:Er,uuid:tr,uuid4:nr,uuid6:rr,uuid7:or,xid:Kn},Symbol.toStringTag,{value:"Module"})),Rr=Dt("$ZodCheck",((e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])})),Nr={number:"number",bigint:"bigint",object:"date"},Ar=Dt("$ZodCheckLessThan",((e,t)=>{Rr.init(e,t);const n=Nr[typeof t.value];e._zod.onattach.push((e=>{const n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)})),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}})),Cr=Dt("$ZodCheckGreaterThan",((e,t)=>{Rr.init(e,t);const n=Nr[typeof t.value];e._zod.onattach.push((e=>{const n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)})),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}})),Pr=Dt("$ZodCheckMultipleOf",((e,t)=>{Rr.init(e,t),e._zod.onattach.push((e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)})),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof n.value?n.value%t.value===BigInt(0):0===Gt(n.value,t.value))||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}})),Ur=Dt("$ZodCheckNumberFormat",((e,t)=>{var n;Rr.init(e,t),t.format=t.format||"float64";const r=null==(n=t.format)?void 0:n.includes("int"),o=r?"int":"number",[i,s]=hn[t.format];e._zod.onattach.push((e=>{const n=e._zod.bag;n.format=t.format,n.minimum=i,n.maximum=s,r&&(n.pattern=wr)})),e._zod.check=n=>{const a=n.value;if(r){if(!Number.isInteger(a))return void n.issues.push({expected:o,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});if(!Number.isSafeInteger(a))return void(a>0?n.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,continue:!t.abort}):n.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,continue:!t.abort}))}a<i&&n.issues.push({origin:"number",input:a,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),a>s&&n.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:e})}})),jr=Dt("$ZodCheckBigIntFormat",((e,t)=>{Rr.init(e,t);const[n,r]=gn[t.format];e._zod.onattach.push((e=>{const o=e._zod.bag;o.format=t.format,o.minimum=n,o.maximum=r})),e._zod.check=o=>{const i=o.value;i<n&&o.issues.push({origin:"bigint",input:i,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort}),i>r&&o.issues.push({origin:"bigint",input:i,code:"too_big",maximum:r,inst:e})}})),zr=Dt("$ZodCheckMaxSize",((e,t)=>{var n;Rr.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Ht(t)&&void 0!==t.size}),e._zod.onattach.push((e=>{const n=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(e._zod.bag.maximum=t.maximum)})),e._zod.check=n=>{const r=n.value;r.size<=t.maximum||n.issues.push({origin:On(r),code:"too_big",maximum:t.maximum,input:r,inst:e,continue:!t.abort})}})),Dr=Dt("$ZodCheckMinSize",((e,t)=>{var n;Rr.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Ht(t)&&void 0!==t.size}),e._zod.onattach.push((e=>{const n=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(e._zod.bag.minimum=t.minimum)})),e._zod.check=n=>{const r=n.value;r.size>=t.minimum||n.issues.push({origin:On(r),code:"too_small",minimum:t.minimum,input:r,inst:e,continue:!t.abort})}})),Mr=Dt("$ZodCheckSizeEquals",((e,t)=>{var n;Rr.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Ht(t)&&void 0!==t.size}),e._zod.onattach.push((e=>{const n=e._zod.bag;n.minimum=t.size,n.maximum=t.size,n.size=t.size})),e._zod.check=n=>{const r=n.value,o=r.size;if(o===t.size)return;const i=o>t.size;n.issues.push({origin:On(r),...i?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}})),Lr=Dt("$ZodCheckMaxLength",((e,t)=>{var n;Rr.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Ht(t)&&void 0!==t.length}),e._zod.onattach.push((e=>{const n=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(e._zod.bag.maximum=t.maximum)})),e._zod.check=n=>{const r=n.value;if(r.length<=t.maximum)return;const o=En(r);n.issues.push({origin:o,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}})),qr=Dt("$ZodCheckMinLength",((e,t)=>{var n;Rr.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Ht(t)&&void 0!==t.length}),e._zod.onattach.push((e=>{const n=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(e._zod.bag.minimum=t.minimum)})),e._zod.check=n=>{const r=n.value;if(r.length>=t.minimum)return;const o=En(r);n.issues.push({origin:o,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}})),Zr=Dt("$ZodCheckLengthEquals",((e,t)=>{var n;Rr.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Ht(t)&&void 0!==t.length}),e._zod.onattach.push((e=>{const n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length})),e._zod.check=n=>{const r=n.value,o=r.length;if(o===t.length)return;const i=En(r),s=o>t.length;n.issues.push({origin:i,...s?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}})),Fr=Dt("$ZodCheckStringFormat",((e,t)=>{var n,r;Rr.init(e,t),e._zod.onattach.push((e=>{const n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??(n.patterns=new Set),n.patterns.add(t.pattern))})),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})})),Wr=Dt("$ZodCheckRegex",((e,t)=>{Fr.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}})),Jr=Dt("$ZodCheckLowerCase",((e,t)=>{t.pattern??(t.pattern=Or),Fr.init(e,t)})),Br=Dt("$ZodCheckUpperCase",((e,t)=>{t.pattern??(t.pattern=Er),Fr.init(e,t)})),Hr=Dt("$ZodCheckIncludes",((e,t)=>{Rr.init(e,t);const n=cn(t.includes),r=new RegExp("number"==typeof t.position?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push((e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)})),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}})),Vr=Dt("$ZodCheckStartsWith",((e,t)=>{Rr.init(e,t);const n=new RegExp(`^${cn(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push((e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)})),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}})),Gr=Dt("$ZodCheckEndsWith",((e,t)=>{Rr.init(e,t);const n=new RegExp(`.*${cn(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push((e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)})),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}));function Kr(e,t,n){e.issues.length&&t.issues.push(...In(n,e.issues))}const Yr=Dt("$ZodCheckProperty",((e,t)=>{Rr.init(e,t),e._zod.check=e=>{const n=t.schema._zod.run({value:e.value[t.property],issues:[]},{});if(n instanceof Promise)return n.then((n=>Kr(n,e,t.property)));Kr(n,e,t.property)}})),Xr=Dt("$ZodCheckMimeType",((e,t)=>{Rr.init(e,t);const n=new Set(t.mime);e._zod.onattach.push((e=>{e._zod.bag.mime=t.mime})),e._zod.check=r=>{n.has(r.value.type)||r.issues.push({code:"invalid_value",values:t.mime,input:r.value.type,inst:e,continue:!t.abort})}})),Qr=Dt("$ZodCheckOverwrite",((e,t)=>{Rr.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}));class eo{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e)return e(this,{execution:"sync"}),void e(this,{execution:"async"});const t=e.split("\n").filter((e=>e)),n=Math.min(...t.map((e=>e.length-e.trimStart().length))),r=t.map((e=>e.slice(n))).map((e=>" ".repeat(2*this.indent)+e));for(const o of r)this.content.push(o)}compile(){return new Function(...null==this?void 0:this.args,[...((null==this?void 0:this.content)??[""]).map((e=>` ${e}`))].join("\n"))}}const to={major:4,minor:0,patch:17},no=Dt("$ZodType",((e,t)=>{var n,r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=to;const o=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&o.unshift(e);for(const i of o)for(const t of i._zod.onattach)t(e);if(0===o.length)(r=e._zod).deferred??(r.deferred=[]),null==(n=e._zod.deferred)||n.push((()=>{e._zod.run=e._zod.parse}));else{const t=(e,t,n)=>{let r,o=xn(e);for(const i of t){if(i._zod.def.when){if(!i._zod.def.when(e))continue}else if(o)continue;const t=e.issues.length,s=i._zod.check(e);if(s instanceof Promise&&!1===(null==n?void 0:n.async))throw new Lt;if(r||s instanceof Promise)r=(r??Promise.resolve()).then((async()=>{await s;e.issues.length!==t&&(o||(o=xn(e,t)))}));else{if(e.issues.length===t)continue;o||(o=xn(e,t))}}return r?r.then((()=>e)):e};e._zod.run=(n,r)=>{const i=e._zod.parse(n,r);if(i instanceof Promise){if(!1===r.async)throw new Lt;return i.then((e=>t(e,o,r)))}return t(i,o,r)}}e["~standard"]={validate:t=>{var n;try{const r=Wn(e,t);return r.success?{value:r.data}:{issues:null==(n=r.error)?void 0:n.issues}}catch(r){return Bn(e,t).then((e=>{var t;return e.success?{value:e.data}:{issues:null==(t=e.error)?void 0:t.issues}}))}},vendor:"zod",version:1}})),ro=Dt("$ZodString",((e,t)=>{var n;no.init(e,t),e._zod.pattern=[...(null==(n=null==e?void 0:e._zod.bag)?void 0:n.patterns)??[]].pop()??br(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch(o){}return"string"==typeof n.value||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}})),oo=Dt("$ZodStringFormat",((e,t)=>{Fr.init(e,t),ro.init(e,t)})),io=Dt("$ZodGUID",((e,t)=>{t.pattern??(t.pattern=er),oo.init(e,t)})),so=Dt("$ZodUUID",((e,t)=>{if(t.version){const e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=tr(e))}else t.pattern??(t.pattern=tr());oo.init(e,t)})),ao=Dt("$ZodEmail",((e,t)=>{t.pattern??(t.pattern=ir),oo.init(e,t)})),uo=Dt("$ZodURL",((e,t)=>{oo.init(e,t),e._zod.check=n=>{try{const r=n.value.trim(),o=new URL(r);return t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:mr.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),void(t.normalize?n.value=o.href:n.value=r)}catch(r){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}})),lo=Dt("$ZodEmoji",((e,t)=>{t.pattern??(t.pattern=sr()),oo.init(e,t)})),co=Dt("$ZodNanoID",((e,t)=>{t.pattern??(t.pattern=Xn),oo.init(e,t)})),po=Dt("$ZodCUID",((e,t)=>{t.pattern??(t.pattern=Hn),oo.init(e,t)})),mo=Dt("$ZodCUID2",((e,t)=>{t.pattern??(t.pattern=Vn),oo.init(e,t)})),_o=Dt("$ZodULID",((e,t)=>{t.pattern??(t.pattern=Gn),oo.init(e,t)})),ho=Dt("$ZodXID",((e,t)=>{t.pattern??(t.pattern=Kn),oo.init(e,t)})),go=Dt("$ZodKSUID",((e,t)=>{t.pattern??(t.pattern=Yn),oo.init(e,t)})),fo=Dt("$ZodISODateTime",((e,t)=>{t.pattern??(t.pattern=yr(t)),oo.init(e,t)})),vo=Dt("$ZodISODate",((e,t)=>{t.pattern??(t.pattern=gr),oo.init(e,t)})),yo=Dt("$ZodISOTime",((e,t)=>{t.pattern??(t.pattern=vr(t)),oo.init(e,t)})),bo=Dt("$ZodISODuration",((e,t)=>{t.pattern??(t.pattern=Qn),oo.init(e,t)})),ko=Dt("$ZodIPv4",((e,t)=>{t.pattern??(t.pattern=ar),oo.init(e,t),e._zod.onattach.push((e=>{e._zod.bag.format="ipv4"}))})),wo=Dt("$ZodIPv6",((e,t)=>{t.pattern??(t.pattern=ur),oo.init(e,t),e._zod.onattach.push((e=>{e._zod.bag.format="ipv6"})),e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}})),xo=Dt("$ZodCIDRv4",((e,t)=>{t.pattern??(t.pattern=lr),oo.init(e,t)})),Io=Dt("$ZodCIDRv6",((e,t)=>{t.pattern??(t.pattern=cr),oo.init(e,t),e._zod.check=n=>{const[r,o]=n.value.split("/");try{if(!o)throw new Error;const e=Number(o);if(`${e}`!==o)throw new Error;if(e<0||e>128)throw new Error;new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}}));function So(e){if(""===e)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const $o=Dt("$ZodBase64",((e,t)=>{t.pattern??(t.pattern=dr),oo.init(e,t),e._zod.onattach.push((e=>{e._zod.bag.contentEncoding="base64"})),e._zod.check=n=>{So(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}));function Oo(e){if(!pr.test(e))return!1;const t=e.replace(/[-_]/g,(e=>"-"===e?"+":"/"));return So(t.padEnd(4*Math.ceil(t.length/4),"="))}const Eo=Dt("$ZodBase64URL",((e,t)=>{t.pattern??(t.pattern=pr),oo.init(e,t),e._zod.onattach.push((e=>{e._zod.bag.contentEncoding="base64url"})),e._zod.check=n=>{Oo(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}})),To=Dt("$ZodE164",((e,t)=>{t.pattern??(t.pattern=_r),oo.init(e,t)}));function Ro(e,t=null){try{const n=e.split(".");if(3!==n.length)return!1;const[r]=n;if(!r)return!1;const o=JSON.parse(atob(r));return(!("typ"in o)||"JWT"===(null==o?void 0:o.typ))&&(!!o.alg&&(!t||"alg"in o&&o.alg===t))}catch{return!1}}const No=Dt("$ZodJWT",((e,t)=>{oo.init(e,t),e._zod.check=n=>{Ro(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}})),Ao=Dt("$ZodCustomStringFormat",((e,t)=>{oo.init(e,t),e._zod.check=n=>{t.fn(n.value)||n.issues.push({code:"invalid_format",format:t.format,input:n.value,inst:e,continue:!t.abort})}})),Co=Dt("$ZodNumber",((e,t)=>{no.init(e,t),e._zod.pattern=e._zod.bag.pattern??xr,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch(s){}const o=n.value;if("number"==typeof o&&!Number.isNaN(o)&&Number.isFinite(o))return n;const i="number"==typeof o?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...i?{received:i}:{}}),n}})),Po=Dt("$ZodNumber",((e,t)=>{Ur.init(e,t),Co.init(e,t)})),Uo=Dt("$ZodBoolean",((e,t)=>{no.init(e,t),e._zod.pattern=Ir,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(i){}const o=n.value;return"boolean"==typeof o||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),n}})),jo=Dt("$ZodBigInt",((e,t)=>{no.init(e,t),e._zod.pattern=kr,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=BigInt(n.value)}catch(o){}return"bigint"==typeof n.value||n.issues.push({expected:"bigint",code:"invalid_type",input:n.value,inst:e}),n}})),zo=Dt("$ZodBigInt",((e,t)=>{jr.init(e,t),jo.init(e,t)})),Do=Dt("$ZodSymbol",((e,t)=>{no.init(e,t),e._zod.parse=(t,n)=>{const r=t.value;return"symbol"==typeof r||t.issues.push({expected:"symbol",code:"invalid_type",input:r,inst:e}),t}})),Mo=Dt("$ZodUndefined",((e,t)=>{no.init(e,t),e._zod.pattern=$r,e._zod.values=new Set([void 0]),e._zod.optin="optional",e._zod.optout="optional",e._zod.parse=(t,n)=>{const r=t.value;return void 0===r||t.issues.push({expected:"undefined",code:"invalid_type",input:r,inst:e}),t}})),Lo=Dt("$ZodNull",((e,t)=>{no.init(e,t),e._zod.pattern=Sr,e._zod.values=new Set([null]),e._zod.parse=(t,n)=>{const r=t.value;return null===r||t.issues.push({expected:"null",code:"invalid_type",input:r,inst:e}),t}})),qo=Dt("$ZodAny",((e,t)=>{no.init(e,t),e._zod.parse=e=>e})),Zo=Dt("$ZodUnknown",((e,t)=>{no.init(e,t),e._zod.parse=e=>e})),Fo=Dt("$ZodNever",((e,t)=>{no.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)})),Wo=Dt("$ZodVoid",((e,t)=>{no.init(e,t),e._zod.parse=(t,n)=>{const r=t.value;return void 0===r||t.issues.push({expected:"void",code:"invalid_type",input:r,inst:e}),t}})),Jo=Dt("$ZodDate",((e,t)=>{no.init(e,t),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=new Date(n.value)}catch(s){}const o=n.value,i=o instanceof Date;return i&&!Number.isNaN(o.getTime())||n.issues.push({expected:"date",code:"invalid_type",input:o,...i?{received:"Invalid Date"}:{},inst:e}),n}}));function Bo(e,t,n){e.issues.length&&t.issues.push(...In(n,e.issues)),t.value[n]=e.value}const Ho=Dt("$ZodArray",((e,t)=>{no.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),n;n.value=Array(o.length);const i=[];for(let e=0;e<o.length;e++){const s=o[e],a=t.element._zod.run({value:s,issues:[]},r);a instanceof Promise?i.push(a.then((t=>Bo(t,n,e)))):Bo(a,n,e)}return i.length?Promise.all(i).then((()=>n)):n}}));function Vo(e,t,n,r){e.issues.length&&t.issues.push(...In(n,e.issues)),void 0===e.value?n in r&&(t.value[n]=void 0):t.value[n]=e.value}const Go=Dt("$ZodObject",((e,t)=>{no.init(e,t);const n=Bt((()=>{const e=Object.keys(t.shape);for(const r of e)if(!t.shape[r]._zod.traits.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const n=_n(t.shape);return{shape:t.shape,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}}));Yt(e._zod,"propValues",(()=>{const e=t.shape,n={};for(const t in e){const r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(const e of r.values)n[t].add(e)}}return n}));let r;const o=rn,i=!qt.jitless,s=i&&on.value,a=t.catchall;let u;e._zod.parse=(l,c)=>{u??(u=n.value);const d=l.value;if(!o(d))return l.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),l;const p=[];if(i&&s&&!1===(null==c?void 0:c.async)&&!0!==c.jitless)r||(r=(e=>{const t=new eo(["shape","payload","ctx"]),r=n.value,o=e=>{const t=tn(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");const i=Object.create(null);let s=0;for(const n of r.keys)i[n]="key_"+s++;t.write("const newResult = {}");for(const n of r.keys){const e=i[n],r=tn(n);t.write(`const ${e} = ${o(n)};`),t.write(`\n if (${e}.issues.length) {\n payload.issues = payload.issues.concat(${e}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${r}, ...iss.path] : [${r}]\n })));\n }\n \n if (${e}.value === undefined) {\n if (${r} in input) {\n newResult[${r}] = undefined;\n }\n } else {\n newResult[${r}] = ${e}.value;\n }\n `)}t.write("payload.value = newResult;"),t.write("return payload;");const a=t.compile();return(t,n)=>a(e,t,n)})(t.shape)),l=r(l,c);else{l.value={};const e=u.shape;for(const t of u.keys){const n=e[t]._zod.run({value:d[t],issues:[]},c);n instanceof Promise?p.push(n.then((e=>Vo(e,l,t,d)))):Vo(n,l,t,d)}}if(!a)return p.length?Promise.all(p).then((()=>l)):l;const m=[],_=u.keySet,h=a._zod,g=h.def.type;for(const e of Object.keys(d)){if(_.has(e))continue;if("never"===g){m.push(e);continue}const t=h.run({value:d[e],issues:[]},c);t instanceof Promise?p.push(t.then((t=>Vo(t,l,e,d)))):Vo(t,l,e,d)}return m.length&&l.issues.push({code:"unrecognized_keys",keys:m,input:d,inst:e}),p.length?Promise.all(p).then((()=>l)):l}}));function Ko(e,t,n,r){for(const i of e)if(0===i.issues.length)return t.value=i.value,t;const o=e.filter((e=>!xn(e)));return 1===o.length?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map((e=>e.issues.map((e=>$n(e,r,Zt())))))}),t)}const Yo=Dt("$ZodUnion",((e,t)=>{no.init(e,t),Yt(e._zod,"optin",(()=>t.options.some((e=>"optional"===e._zod.optin))?"optional":void 0)),Yt(e._zod,"optout",(()=>t.options.some((e=>"optional"===e._zod.optout))?"optional":void 0)),Yt(e._zod,"values",(()=>{if(t.options.every((e=>e._zod.values)))return new Set(t.options.flatMap((e=>Array.from(e._zod.values))))})),Yt(e._zod,"pattern",(()=>{if(t.options.every((e=>e._zod.pattern))){const e=t.options.map((e=>e._zod.pattern));return new RegExp(`^(${e.map((e=>Vt(e.source))).join("|")})$`)}}));const n=1===t.options.length,r=t.options[0]._zod.run;e._zod.parse=(o,i)=>{if(n)return r(o,i);let s=!1;const a=[];for(const e of t.options){const t=e._zod.run({value:o.value,issues:[]},i);if(t instanceof Promise)a.push(t),s=!0;else{if(0===t.issues.length)return t;a.push(t)}}return s?Promise.all(a).then((t=>Ko(t,o,e,i))):Ko(a,o,e,i)}})),Xo=Dt("$ZodDiscriminatedUnion",((e,t)=>{Yo.init(e,t);const n=e._zod.parse;Yt(e._zod,"propValues",(()=>{const e={};for(const n of t.options){const r=n._zod.propValues;if(!r||0===Object.keys(r).length)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(const[t,n]of Object.entries(r)){e[t]||(e[t]=new Set);for(const r of n)e[t].add(r)}}return e}));const r=Bt((()=>{var e;const n=t.options,r=new Map;for(const o of n){const n=null==(e=o._zod.propValues)?void 0:e[t.discriminator];if(!n||0===n.size)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(o)}"`);for(const e of n){if(r.has(e))throw new Error(`Duplicate discriminator value "${String(e)}"`);r.set(e,o)}}return r}));e._zod.parse=(o,i)=>{const s=o.value;if(!rn(s))return o.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),o;const a=r.value.get(null==s?void 0:s[t.discriminator]);return a?a._zod.run(o,i):t.unionFallback?n(o,i):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,input:s,path:[t.discriminator],inst:e}),o)}})),Qo=Dt("$ZodIntersection",((e,t)=>{no.init(e,t),e._zod.parse=(e,n)=>{const r=e.value,o=t.left._zod.run({value:r,issues:[]},n),i=t.right._zod.run({value:r,issues:[]},n);return o instanceof Promise||i instanceof Promise?Promise.all([o,i]).then((([t,n])=>ti(e,t,n))):ti(e,o,i)}}));function ei(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(sn(e)&&sn(t)){const n=Object.keys(t),r=Object.keys(e).filter((e=>-1!==n.indexOf(e))),o={...e,...t};for(const i of r){const n=ei(e[i],t[i]);if(!n.valid)return{valid:!1,mergeErrorPath:[i,...n.mergeErrorPath]};o[i]=n.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const o=ei(e[r],t[r]);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function ti(e,t,n){if(t.issues.length&&e.issues.push(...t.issues),n.issues.length&&e.issues.push(...n.issues),xn(e))return e;const r=ei(t.value,n.value);if(!r.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return e.value=r.data,e}const ni=Dt("$ZodTuple",((e,t)=>{no.init(e,t);const n=t.items,r=n.length-[...n].reverse().findIndex((e=>"optional"!==e._zod.optin));e._zod.parse=(o,i)=>{const s=o.value;if(!Array.isArray(s))return o.issues.push({input:s,inst:e,expected:"tuple",code:"invalid_type"}),o;o.value=[];const a=[];if(!t.rest){const t=s.length>n.length,i=s.length<r-1;if(t||i)return o.issues.push({...t?{code:"too_big",maximum:n.length}:{code:"too_small",minimum:n.length},input:s,inst:e,origin:"array"}),o}let u=-1;for(const e of n){if(u++,u>=s.length&&u>=r)continue;const t=e._zod.run({value:s[u],issues:[]},i);t instanceof Promise?a.push(t.then((e=>ri(e,o,u)))):ri(t,o,u)}if(t.rest){const e=s.slice(n.length);for(const n of e){u++;const e=t.rest._zod.run({value:n,issues:[]},i);e instanceof Promise?a.push(e.then((e=>ri(e,o,u)))):ri(e,o,u)}}return a.length?Promise.all(a).then((()=>o)):o}}));function ri(e,t,n){e.issues.length&&t.issues.push(...In(n,e.issues)),t.value[n]=e.value}const oi=Dt("$ZodRecord",((e,t)=>{no.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!sn(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),n;const i=[];if(t.keyType._zod.values){const s=t.keyType._zod.values;n.value={};for(const e of s)if("string"==typeof e||"number"==typeof e||"symbol"==typeof e){const s=t.valueType._zod.run({value:o[e],issues:[]},r);s instanceof Promise?i.push(s.then((t=>{t.issues.length&&n.issues.push(...In(e,t.issues)),n.value[e]=t.value}))):(s.issues.length&&n.issues.push(...In(e,s.issues)),n.value[e]=s.value)}let a;for(const e in o)s.has(e)||(a=a??[],a.push(e));a&&a.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:a})}else{n.value={};for(const s of Reflect.ownKeys(o)){if("__proto__"===s)continue;const a=t.keyType._zod.run({value:s,issues:[]},r);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:a.issues.map((e=>$n(e,r,Zt()))),input:s,path:[s],inst:e}),n.value[a.value]=a.value;continue}const u=t.valueType._zod.run({value:o[s],issues:[]},r);u instanceof Promise?i.push(u.then((e=>{e.issues.length&&n.issues.push(...In(s,e.issues)),n.value[a.value]=e.value}))):(u.issues.length&&n.issues.push(...In(s,u.issues)),n.value[a.value]=u.value)}}return i.length?Promise.all(i).then((()=>n)):n}})),ii=Dt("$ZodMap",((e,t)=>{no.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!(o instanceof Map))return n.issues.push({expected:"map",code:"invalid_type",input:o,inst:e}),n;const i=[];n.value=new Map;for(const[s,a]of o){const u=t.keyType._zod.run({value:s,issues:[]},r),l=t.valueType._zod.run({value:a,issues:[]},r);u instanceof Promise||l instanceof Promise?i.push(Promise.all([u,l]).then((([t,i])=>{si(t,i,n,s,o,e,r)}))):si(u,l,n,s,o,e,r)}return i.length?Promise.all(i).then((()=>n)):n}}));function si(e,t,n,r,o,i,s){e.issues.length&&(un.has(typeof r)?n.issues.push(...In(r,e.issues)):n.issues.push({code:"invalid_key",origin:"map",input:o,inst:i,issues:e.issues.map((e=>$n(e,s,Zt())))})),t.issues.length&&(un.has(typeof r)?n.issues.push(...In(r,t.issues)):n.issues.push({origin:"map",code:"invalid_element",input:o,inst:i,key:r,issues:t.issues.map((e=>$n(e,s,Zt())))})),n.value.set(e.value,t.value)}const ai=Dt("$ZodSet",((e,t)=>{no.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!(o instanceof Set))return n.issues.push({input:o,inst:e,expected:"set",code:"invalid_type"}),n;const i=[];n.value=new Set;for(const e of o){const o=t.valueType._zod.run({value:e,issues:[]},r);o instanceof Promise?i.push(o.then((e=>ui(e,n)))):ui(o,n)}return i.length?Promise.all(i).then((()=>n)):n}}));function ui(e,t){e.issues.length&&t.issues.push(...e.issues),t.value.add(e.value)}const li=Dt("$ZodEnum",((e,t)=>{no.init(e,t);const n=Ft(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter((e=>un.has(typeof e))).map((e=>"string"==typeof e?cn(e):e.toString())).join("|")})$`),e._zod.parse=(t,o)=>{const i=t.value;return r.has(i)||t.issues.push({code:"invalid_value",values:n,input:i,inst:e}),t}})),ci=Dt("$ZodLiteral",((e,t)=>{if(no.init(e,t),0===t.values.length)throw new Error("Cannot create literal schema with no valid values");e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map((e=>"string"==typeof e?cn(e):e?cn(e.toString()):String(e))).join("|")})$`),e._zod.parse=(n,r)=>{const o=n.value;return e._zod.values.has(o)||n.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),n}})),di=Dt("$ZodFile",((e,t)=>{no.init(e,t),e._zod.parse=(t,n)=>{const r=t.value;return r instanceof File||t.issues.push({expected:"file",code:"invalid_type",input:r,inst:e}),t}})),pi=Dt("$ZodTransform",((e,t)=>{no.init(e,t),e._zod.parse=(e,n)=>{const r=t.transform(e.value,e);if(n.async){return(r instanceof Promise?r:Promise.resolve(r)).then((t=>(e.value=t,e)))}if(r instanceof Promise)throw new Lt;return e.value=r,e}}));function mi(e,t){return e.issues.length&&void 0===t?{issues:[],value:void 0}:e}const _i=Dt("$ZodOptional",((e,t)=>{no.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Yt(e._zod,"values",(()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0)),Yt(e._zod,"pattern",(()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${Vt(e.source)})?$`):void 0})),e._zod.parse=(e,n)=>{if("optional"===t.innerType._zod.optin){const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then((t=>mi(t,e.value))):mi(r,e.value)}return void 0===e.value?e:t.innerType._zod.run(e,n)}})),hi=Dt("$ZodNullable",((e,t)=>{no.init(e,t),Yt(e._zod,"optin",(()=>t.innerType._zod.optin)),Yt(e._zod,"optout",(()=>t.innerType._zod.optout)),Yt(e._zod,"pattern",(()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${Vt(e.source)}|null)$`):void 0})),Yt(e._zod,"values",(()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0)),e._zod.parse=(e,n)=>null===e.value?e:t.innerType._zod.run(e,n)})),gi=Dt("$ZodDefault",((e,t)=>{no.init(e,t),e._zod.optin="optional",Yt(e._zod,"values",(()=>t.innerType._zod.values)),e._zod.parse=(e,n)=>{if(void 0===e.value)return e.value=t.defaultValue,e;const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then((e=>fi(e,t))):fi(r,t)}}));function fi(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}const vi=Dt("$ZodPrefault",((e,t)=>{no.init(e,t),e._zod.optin="optional",Yt(e._zod,"values",(()=>t.innerType._zod.values)),e._zod.parse=(e,n)=>(void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))})),yi=Dt("$ZodNonOptional",((e,t)=>{no.init(e,t),Yt(e._zod,"values",(()=>{const e=t.innerType._zod.values;return e?new Set([...e].filter((e=>void 0!==e))):void 0})),e._zod.parse=(n,r)=>{const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then((t=>bi(t,e))):bi(o,e)}}));function bi(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const ki=Dt("$ZodSuccess",((e,t)=>{no.init(e,t),e._zod.parse=(e,n)=>{const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then((t=>(e.value=0===t.issues.length,e))):(e.value=0===r.issues.length,e)}})),wi=Dt("$ZodCatch",((e,t)=>{no.init(e,t),Yt(e._zod,"optin",(()=>t.innerType._zod.optin)),Yt(e._zod,"optout",(()=>t.innerType._zod.optout)),Yt(e._zod,"values",(()=>t.innerType._zod.values)),e._zod.parse=(e,n)=>{const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then((r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map((e=>$n(e,n,Zt())))},input:e.value}),e.issues=[]),e))):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map((e=>$n(e,n,Zt())))},input:e.value}),e.issues=[]),e)}})),xi=Dt("$ZodNaN",((e,t)=>{no.init(e,t),e._zod.parse=(t,n)=>("number"==typeof t.value&&Number.isNaN(t.value)||t.issues.push({input:t.value,inst:e,expected:"nan",code:"invalid_type"}),t)})),Ii=Dt("$ZodPipe",((e,t)=>{no.init(e,t),Yt(e._zod,"values",(()=>t.in._zod.values)),Yt(e._zod,"optin",(()=>t.in._zod.optin)),Yt(e._zod,"optout",(()=>t.out._zod.optout)),Yt(e._zod,"propValues",(()=>t.in._zod.propValues)),e._zod.parse=(e,n)=>{const r=t.in._zod.run(e,n);return r instanceof Promise?r.then((e=>Si(e,t,n))):Si(r,t,n)}}));function Si(e,t,n){return e.issues.length?e:t.out._zod.run({value:e.value,issues:e.issues},n)}const $i=Dt("$ZodReadonly",((e,t)=>{no.init(e,t),Yt(e._zod,"propValues",(()=>t.innerType._zod.propValues)),Yt(e._zod,"values",(()=>t.innerType._zod.values)),Yt(e._zod,"optin",(()=>t.innerType._zod.optin)),Yt(e._zod,"optout",(()=>t.innerType._zod.optout)),e._zod.parse=(e,n)=>{const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(Oi):Oi(r)}}));function Oi(e){return e.value=Object.freeze(e.value),e}const Ei=Dt("$ZodTemplateLiteral",((e,t)=>{no.init(e,t);const n=[];for(const r of t.parts)if("object"==typeof r&&null!==r){if(!r._zod.pattern)throw new Error(`Invalid template literal part, no pattern found: ${[...r._zod.traits].shift()}`);const e=r._zod.pattern instanceof RegExp?r._zod.pattern.source:r._zod.pattern;if(!e)throw new Error(`Invalid template literal part: ${r._zod.traits}`);const t=e.startsWith("^")?1:0,o=e.endsWith("$")?e.length-1:e.length;n.push(e.slice(t,o))}else{if(null!==r&&!ln.has(typeof r))throw new Error(`Invalid template literal part: ${r}`);n.push(cn(`${r}`))}e._zod.pattern=new RegExp(`^${n.join("")}$`),e._zod.parse=(n,r)=>"string"!=typeof n.value?(n.issues.push({input:n.value,inst:e,expected:"template_literal",code:"invalid_type"}),n):(e._zod.pattern.lastIndex=0,e._zod.pattern.test(n.value)||n.issues.push({input:n.value,inst:e,code:"invalid_format",format:t.format??"template_literal",pattern:e._zod.pattern.source}),n)})),Ti=Dt("$ZodPromise",((e,t)=>{no.init(e,t),e._zod.parse=(e,n)=>Promise.resolve(e.value).then((e=>t.innerType._zod.run({value:e,issues:[]},n)))})),Ri=Dt("$ZodLazy",((e,t)=>{no.init(e,t),Yt(e._zod,"innerType",(()=>t.getter())),Yt(e._zod,"pattern",(()=>e._zod.innerType._zod.pattern)),Yt(e._zod,"propValues",(()=>e._zod.innerType._zod.propValues)),Yt(e._zod,"optin",(()=>e._zod.innerType._zod.optin??void 0)),Yt(e._zod,"optout",(()=>e._zod.innerType._zod.optout??void 0)),e._zod.parse=(t,n)=>e._zod.innerType._zod.run(t,n)})),Ni=Dt("$ZodCustom",((e,t)=>{Rr.init(e,t),no.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{const r=n.value,o=t.fn(r);if(o instanceof Promise)return o.then((t=>Ai(t,n,r,e)));Ai(o,n,r,e)}}));function Ai(e,t,n,r){if(!e){const e={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(Tn(e))}}const Ci=()=>{const e={string:{unit:"حرف",verb:"أن يحوي"},file:{unit:"بايت",verb:"أن يحوي"},array:{unit:"عنصر",verb:"أن يحوي"},set:{unit:"عنصر",verb:"أن يحوي"}};function t(t){return e[t]??null}const n={regex:"مدخل",email:"بريد إلكتروني",url:"رابط",emoji:"إيموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاريخ ووقت بمعيار ISO",date:"تاريخ بمعيار ISO",time:"وقت بمعيار ISO",duration:"مدة بمعيار ISO",ipv4:"عنوان IPv4",ipv6:"عنوان IPv6",cidrv4:"مدى عناوين بصيغة IPv4",cidrv6:"مدى عناوين بصيغة IPv6",base64:"نَص بترميز base64-encoded",base64url:"نَص بترميز base64url-encoded",json_string:"نَص على هيئة JSON",e164:"رقم هاتف بمعيار E.164",jwt:"JWT",template_literal:"مدخل"};return e=>{switch(e.code){case"invalid_type":return`مدخلات غير مقبولة: يفترض إدخال ${e.expected}، ولكن تم إدخال ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`مدخلات غير مقبولة: يفترض إدخال ${mn(e.values[0])}`:`اختيار غير مقبول: يتوقع انتقاء أحد هذه الخيارات: ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?` أكبر من اللازم: يفترض أن تكون ${e.origin??"القيمة"} ${n} ${e.maximum.toString()} ${r.unit??"عنصر"}`:`أكبر من اللازم: يفترض أن تكون ${e.origin??"القيمة"} ${n} ${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`أصغر من اللازم: يفترض لـ ${e.origin} أن يكون ${n} ${e.minimum.toString()} ${r.unit}`:`أصغر من اللازم: يفترض لـ ${e.origin} أن يكون ${n} ${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`نَص غير مقبول: يجب أن يبدأ بـ "${e.prefix}"`:"ends_with"===t.format?`نَص غير مقبول: يجب أن ينتهي بـ "${t.suffix}"`:"includes"===t.format?`نَص غير مقبول: يجب أن يتضمَّن "${t.includes}"`:"regex"===t.format?`نَص غير مقبول: يجب أن يطابق النمط ${t.pattern}`:`${n[t.format]??e.format} غير مقبول`}case"not_multiple_of":return`رقم غير مقبول: يجب أن يكون من مضاعفات ${e.divisor}`;case"unrecognized_keys":return`معرف${e.keys.length>1?"ات":""} غريب${e.keys.length>1?"ة":""}: ${Wt(e.keys,"، ")}`;case"invalid_key":return`معرف غير مقبول في ${e.origin}`;case"invalid_union":default:return"مدخل غير مقبول";case"invalid_element":return`مدخل غير مقبول في ${e.origin}`}}};const Pi=()=>{const e={string:{unit:"simvol",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"element",verb:"olmalıdır"},set:{unit:"element",verb:"olmalıdır"}};function t(t){return e[t]??null}const n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Yanlış dəyər: gözlənilən ${e.expected}, daxil olan ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Yanlış dəyər: gözlənilən ${mn(e.values[0])}`:`Yanlış seçim: aşağıdakılardan biri olmalıdır: ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Çox böyük: gözlənilən ${e.origin??"dəyər"} ${n}${e.maximum.toString()} ${r.unit??"element"}`:`Çox böyük: gözlənilən ${e.origin??"dəyər"} ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Çox kiçik: gözlənilən ${e.origin} ${n}${e.minimum.toString()} ${r.unit}`:`Çox kiçik: gözlənilən ${e.origin} ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Yanlış mətn: "${t.prefix}" ilə başlamalıdır`:"ends_with"===t.format?`Yanlış mətn: "${t.suffix}" ilə bitməlidir`:"includes"===t.format?`Yanlış mətn: "${t.includes}" daxil olmalıdır`:"regex"===t.format?`Yanlış mətn: ${t.pattern} şablonuna uyğun olmalıdır`:`Yanlış ${n[t.format]??e.format}`}case"not_multiple_of":return`Yanlış ədəd: ${e.divisor} ilə bölünə bilən olmalıdır`;case"unrecognized_keys":return`Tanınmayan açar${e.keys.length>1?"lar":""}: ${Wt(e.keys,", ")}`;case"invalid_key":return`${e.origin} daxilində yanlış açar`;case"invalid_union":default:return"Yanlış dəyər";case"invalid_element":return`${e.origin} daxilində yanlış dəyər`}}};function Ui(e,t,n,r){const o=Math.abs(e),i=o%10,s=o%100;return s>=11&&s<=19?r:1===i?t:i>=2&&i<=4?n:r}const ji=()=>{const e={string:{unit:{one:"сімвал",few:"сімвалы",many:"сімвалаў"},verb:"мець"},array:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},set:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},file:{unit:{one:"байт",few:"байты",many:"байтаў"},verb:"мець"}};function t(t){return e[t]??null}const n={regex:"увод",email:"email адрас",url:"URL",emoji:"эмодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата і час",date:"ISO дата",time:"ISO час",duration:"ISO працягласць",ipv4:"IPv4 адрас",ipv6:"IPv6 адрас",cidrv4:"IPv4 дыяпазон",cidrv6:"IPv6 дыяпазон",base64:"радок у фармаце base64",base64url:"радок у фармаце base64url",json_string:"JSON радок",e164:"нумар E.164",jwt:"JWT",template_literal:"увод"};return e=>{switch(e.code){case"invalid_type":return`Няправільны ўвод: чакаўся ${e.expected}, атрымана ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"лік";case"object":if(Array.isArray(e))return"масіў";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Няправільны ўвод: чакалася ${mn(e.values[0])}`:`Няправільны варыянт: чакаўся адзін з ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);if(r){const t=Ui(Number(e.maximum),r.unit.one,r.unit.few,r.unit.many);return`Занадта вялікі: чакалася, што ${e.origin??"значэнне"} павінна ${r.verb} ${n}${e.maximum.toString()} ${t}`}return`Занадта вялікі: чакалася, што ${e.origin??"значэнне"} павінна быць ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);if(r){const t=Ui(Number(e.minimum),r.unit.one,r.unit.few,r.unit.many);return`Занадта малы: чакалася, што ${e.origin} павінна ${r.verb} ${n}${e.minimum.toString()} ${t}`}return`Занадта малы: чакалася, што ${e.origin} павінна быць ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Няправільны радок: павінен пачынацца з "${t.prefix}"`:"ends_with"===t.format?`Няправільны радок: павінен заканчвацца на "${t.suffix}"`:"includes"===t.format?`Няправільны радок: павінен змяшчаць "${t.includes}"`:"regex"===t.format?`Няправільны радок: павінен адпавядаць шаблону ${t.pattern}`:`Няправільны ${n[t.format]??e.format}`}case"not_multiple_of":return`Няправільны лік: павінен быць кратным ${e.divisor}`;case"unrecognized_keys":return`Нераспазнаны ${e.keys.length>1?"ключы":"ключ"}: ${Wt(e.keys,", ")}`;case"invalid_key":return`Няправільны ключ у ${e.origin}`;case"invalid_union":default:return"Няправільны ўвод";case"invalid_element":return`Няправільнае значэнне ў ${e.origin}`}}};const zi=()=>{const e={string:{unit:"caràcters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function t(t){return e[t]??null}const n={regex:"entrada",email:"adreça electrònica",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i hora ISO",date:"data ISO",time:"hora ISO",duration:"durada ISO",ipv4:"adreça IPv4",ipv6:"adreça IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"};return e=>{switch(e.code){case"invalid_type":return`Tipus invàlid: s'esperava ${e.expected}, s'ha rebut ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Valor invàlid: s'esperava ${mn(e.values[0])}`:`Opció invàlida: s'esperava una de ${Wt(e.values," o ")}`;case"too_big":{const n=e.inclusive?"com a màxim":"menys de",r=t(e.origin);return r?`Massa gran: s'esperava que ${e.origin??"el valor"} contingués ${n} ${e.maximum.toString()} ${r.unit??"elements"}`:`Massa gran: s'esperava que ${e.origin??"el valor"} fos ${n} ${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?"com a mínim":"més de",r=t(e.origin);return r?`Massa petit: s'esperava que ${e.origin} contingués ${n} ${e.minimum.toString()} ${r.unit}`:`Massa petit: s'esperava que ${e.origin} fos ${n} ${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Format invàlid: ha de començar amb "${t.prefix}"`:"ends_with"===t.format?`Format invàlid: ha d'acabar amb "${t.suffix}"`:"includes"===t.format?`Format invàlid: ha d'incloure "${t.includes}"`:"regex"===t.format?`Format invàlid: ha de coincidir amb el patró ${t.pattern}`:`Format invàlid per a ${n[t.format]??e.format}`}case"not_multiple_of":return`Número invàlid: ha de ser múltiple de ${e.divisor}`;case"unrecognized_keys":return`Clau${e.keys.length>1?"s":""} no reconeguda${e.keys.length>1?"s":""}: ${Wt(e.keys,", ")}`;case"invalid_key":return`Clau invàlida a ${e.origin}`;case"invalid_union":default:return"Entrada invàlida";case"invalid_element":return`Element invàlid a ${e.origin}`}}};const Di=()=>{const e={string:{unit:"znaků",verb:"mít"},file:{unit:"bajtů",verb:"mít"},array:{unit:"prvků",verb:"mít"},set:{unit:"prvků",verb:"mít"}};function t(t){return e[t]??null}const n={regex:"regulární výraz",email:"e-mailová adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"datum a čas ve formátu ISO",date:"datum ve formátu ISO",time:"čas ve formátu ISO",duration:"doba trvání ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"řetězec zakódovaný ve formátu base64",base64url:"řetězec zakódovaný ve formátu base64url",json_string:"řetězec ve formátu JSON",e164:"číslo E.164",jwt:"JWT",template_literal:"vstup"};return e=>{switch(e.code){case"invalid_type":return`Neplatný vstup: očekáváno ${e.expected}, obdrženo ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"číslo";case"string":return"řetězec";case"boolean":return"boolean";case"bigint":return"bigint";case"function":return"funkce";case"symbol":return"symbol";case"undefined":return"undefined";case"object":if(Array.isArray(e))return"pole";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Neplatný vstup: očekáváno ${mn(e.values[0])}`:`Neplatná možnost: očekávána jedna z hodnot ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Hodnota je příliš velká: ${e.origin??"hodnota"} musí mít ${n}${e.maximum.toString()} ${r.unit??"prvků"}`:`Hodnota je příliš velká: ${e.origin??"hodnota"} musí být ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Hodnota je příliš malá: ${e.origin??"hodnota"} musí mít ${n}${e.minimum.toString()} ${r.unit??"prvků"}`:`Hodnota je příliš malá: ${e.origin??"hodnota"} musí být ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Neplatný řetězec: musí začínat na "${t.prefix}"`:"ends_with"===t.format?`Neplatný řetězec: musí končit na "${t.suffix}"`:"includes"===t.format?`Neplatný řetězec: musí obsahovat "${t.includes}"`:"regex"===t.format?`Neplatný řetězec: musí odpovídat vzoru ${t.pattern}`:`Neplatný formát ${n[t.format]??e.format}`}case"not_multiple_of":return`Neplatné číslo: musí být násobkem ${e.divisor}`;case"unrecognized_keys":return`Neznámé klíče: ${Wt(e.keys,", ")}`;case"invalid_key":return`Neplatný klíč v ${e.origin}`;case"invalid_union":default:return"Neplatný vstup";case"invalid_element":return`Neplatná hodnota v ${e.origin}`}}};const Mi=()=>{const e={string:{unit:"tegn",verb:"havde"},file:{unit:"bytes",verb:"havde"},array:{unit:"elementer",verb:"indeholdt"},set:{unit:"elementer",verb:"indeholdt"}},t={string:"streng",number:"tal",boolean:"boolean",array:"liste",object:"objekt",set:"sæt",file:"fil"};function n(t){return e[t]??null}function r(e){return t[e]??e}const o={regex:"input",email:"e-mailadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslæt",date:"ISO-dato",time:"ISO-klokkeslæt",duration:"ISO-varighed",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodet streng",base64url:"base64url-kodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Ugyldigt input: forventede ${r(e.expected)}, fik ${r((e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"tal";case"object":return Array.isArray(e)?"liste":null===e?"null":Object.getPrototypeOf(e)!==Object.prototype&&e.constructor?e.constructor.name:"objekt"}return t})(e.input))}`;case"invalid_value":return 1===e.values.length?`Ugyldig værdi: forventede ${mn(e.values[0])}`:`Ugyldigt valg: forventede en af følgende ${Wt(e.values,"|")}`;case"too_big":{const t=e.inclusive?"<=":"<",o=n(e.origin),i=r(e.origin);return o?`For stor: forventede ${i??"value"} ${o.verb} ${t} ${e.maximum.toString()} ${o.unit??"elementer"}`:`For stor: forventede ${i??"value"} havde ${t} ${e.maximum.toString()}`}case"too_small":{const t=e.inclusive?">=":">",o=n(e.origin),i=r(e.origin);return o?`For lille: forventede ${i} ${o.verb} ${t} ${e.minimum.toString()} ${o.unit}`:`For lille: forventede ${i} havde ${t} ${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Ugyldig streng: skal starte med "${t.prefix}"`:"ends_with"===t.format?`Ugyldig streng: skal ende med "${t.suffix}"`:"includes"===t.format?`Ugyldig streng: skal indeholde "${t.includes}"`:"regex"===t.format?`Ugyldig streng: skal matche mønsteret ${t.pattern}`:`Ugyldig ${o[t.format]??e.format}`}case"not_multiple_of":return`Ugyldigt tal: skal være deleligt med ${e.divisor}`;case"unrecognized_keys":return`${e.keys.length>1?"Ukendte nøgler":"Ukendt nøgle"}: ${Wt(e.keys,", ")}`;case"invalid_key":return`Ugyldig nøgle i ${e.origin}`;case"invalid_union":return"Ugyldigt input: matcher ingen af de tilladte typer";case"invalid_element":return`Ugyldig værdi i ${e.origin}`;default:return"Ugyldigt input"}}};const Li=()=>{const e={string:{unit:"Zeichen",verb:"zu haben"},file:{unit:"Bytes",verb:"zu haben"},array:{unit:"Elemente",verb:"zu haben"},set:{unit:"Elemente",verb:"zu haben"}};function t(t){return e[t]??null}const n={regex:"Eingabe",email:"E-Mail-Adresse",url:"URL",emoji:"Emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-Datum und -Uhrzeit",date:"ISO-Datum",time:"ISO-Uhrzeit",duration:"ISO-Dauer",ipv4:"IPv4-Adresse",ipv6:"IPv6-Adresse",cidrv4:"IPv4-Bereich",cidrv6:"IPv6-Bereich",base64:"Base64-codierter String",base64url:"Base64-URL-codierter String",json_string:"JSON-String",e164:"E.164-Nummer",jwt:"JWT",template_literal:"Eingabe"};return e=>{switch(e.code){case"invalid_type":return`Ungültige Eingabe: erwartet ${e.expected}, erhalten ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"Zahl";case"object":if(Array.isArray(e))return"Array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Ungültige Eingabe: erwartet ${mn(e.values[0])}`:`Ungültige Option: erwartet eine von ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Zu groß: erwartet, dass ${e.origin??"Wert"} ${n}${e.maximum.toString()} ${r.unit??"Elemente"} hat`:`Zu groß: erwartet, dass ${e.origin??"Wert"} ${n}${e.maximum.toString()} ist`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Zu klein: erwartet, dass ${e.origin} ${n}${e.minimum.toString()} ${r.unit} hat`:`Zu klein: erwartet, dass ${e.origin} ${n}${e.minimum.toString()} ist`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Ungültiger String: muss mit "${t.prefix}" beginnen`:"ends_with"===t.format?`Ungültiger String: muss mit "${t.suffix}" enden`:"includes"===t.format?`Ungültiger String: muss "${t.includes}" enthalten`:"regex"===t.format?`Ungültiger String: muss dem Muster ${t.pattern} entsprechen`:`Ungültig: ${n[t.format]??e.format}`}case"not_multiple_of":return`Ungültige Zahl: muss ein Vielfaches von ${e.divisor} sein`;case"unrecognized_keys":return`${e.keys.length>1?"Unbekannte Schlüssel":"Unbekannter Schlüssel"}: ${Wt(e.keys,", ")}`;case"invalid_key":return`Ungültiger Schlüssel in ${e.origin}`;case"invalid_union":default:return"Ungültige Eingabe";case"invalid_element":return`Ungültiger Wert in ${e.origin}`}}};const qi=()=>{const e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function t(t){return e[t]??null}const n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Invalid input: expected ${e.expected}, received ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Invalid input: expected ${mn(e.values[0])}`:`Invalid option: expected one of ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Too big: expected ${e.origin??"value"} to have ${n}${e.maximum.toString()} ${r.unit??"elements"}`:`Too big: expected ${e.origin??"value"} to be ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Too small: expected ${e.origin} to have ${n}${e.minimum.toString()} ${r.unit}`:`Too small: expected ${e.origin} to be ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Invalid string: must start with "${t.prefix}"`:"ends_with"===t.format?`Invalid string: must end with "${t.suffix}"`:"includes"===t.format?`Invalid string: must include "${t.includes}"`:"regex"===t.format?`Invalid string: must match pattern ${t.pattern}`:`Invalid ${n[t.format]??e.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${e.divisor}`;case"unrecognized_keys":return`Unrecognized key${e.keys.length>1?"s":""}: ${Wt(e.keys,", ")}`;case"invalid_key":return`Invalid key in ${e.origin}`;case"invalid_union":default:return"Invalid input";case"invalid_element":return`Invalid value in ${e.origin}`}}};function Zi(){return{localeError:qi()}}const Fi=()=>{const e={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function t(t){return e[t]??null}const n={regex:"enigo",email:"retadreso",url:"URL",emoji:"emoĝio",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datotempo",date:"ISO-dato",time:"ISO-tempo",duration:"ISO-daŭro",ipv4:"IPv4-adreso",ipv6:"IPv6-adreso",cidrv4:"IPv4-rango",cidrv6:"IPv6-rango",base64:"64-ume kodita karaktraro",base64url:"URL-64-ume kodita karaktraro",json_string:"JSON-karaktraro",e164:"E.164-nombro",jwt:"JWT",template_literal:"enigo"};return e=>{switch(e.code){case"invalid_type":return`Nevalida enigo: atendiĝis ${e.expected}, riceviĝis ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"nombro";case"object":if(Array.isArray(e))return"tabelo";if(null===e)return"senvalora";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Nevalida enigo: atendiĝis ${mn(e.values[0])}`:`Nevalida opcio: atendiĝis unu el ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Tro granda: atendiĝis ke ${e.origin??"valoro"} havu ${n}${e.maximum.toString()} ${r.unit??"elementojn"}`:`Tro granda: atendiĝis ke ${e.origin??"valoro"} havu ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Tro malgranda: atendiĝis ke ${e.origin} havu ${n}${e.minimum.toString()} ${r.unit}`:`Tro malgranda: atendiĝis ke ${e.origin} estu ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Nevalida karaktraro: devas komenciĝi per "${t.prefix}"`:"ends_with"===t.format?`Nevalida karaktraro: devas finiĝi per "${t.suffix}"`:"includes"===t.format?`Nevalida karaktraro: devas inkluzivi "${t.includes}"`:"regex"===t.format?`Nevalida karaktraro: devas kongrui kun la modelo ${t.pattern}`:`Nevalida ${n[t.format]??e.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${e.divisor}`;case"unrecognized_keys":return`Nekonata${e.keys.length>1?"j":""} ŝlosilo${e.keys.length>1?"j":""}: ${Wt(e.keys,", ")}`;case"invalid_key":return`Nevalida ŝlosilo en ${e.origin}`;case"invalid_union":default:return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${e.origin}`}}};const Wi=()=>{const e={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}};function t(t){return e[t]??null}const n={regex:"entrada",email:"dirección de correo electrónico",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"fecha y hora ISO",date:"fecha ISO",time:"hora ISO",duration:"duración ISO",ipv4:"dirección IPv4",ipv6:"dirección IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"};return e=>{switch(e.code){case"invalid_type":return`Entrada inválida: se esperaba ${e.expected}, recibido ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"número";case"object":if(Array.isArray(e))return"arreglo";if(null===e)return"nulo";if(Object.getPrototypeOf(e)!==Object.prototype)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Entrada inválida: se esperaba ${mn(e.values[0])}`:`Opción inválida: se esperaba una de ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Demasiado grande: se esperaba que ${e.origin??"valor"} tuviera ${n}${e.maximum.toString()} ${r.unit??"elementos"}`:`Demasiado grande: se esperaba que ${e.origin??"valor"} fuera ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Demasiado pequeño: se esperaba que ${e.origin} tuviera ${n}${e.minimum.toString()} ${r.unit}`:`Demasiado pequeño: se esperaba que ${e.origin} fuera ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Cadena inválida: debe comenzar con "${t.prefix}"`:"ends_with"===t.format?`Cadena inválida: debe terminar en "${t.suffix}"`:"includes"===t.format?`Cadena inválida: debe incluir "${t.includes}"`:"regex"===t.format?`Cadena inválida: debe coincidir con el patrón ${t.pattern}`:`Inválido ${n[t.format]??e.format}`}case"not_multiple_of":return`Número inválido: debe ser múltiplo de ${e.divisor}`;case"unrecognized_keys":return`Llave${e.keys.length>1?"s":""} desconocida${e.keys.length>1?"s":""}: ${Wt(e.keys,", ")}`;case"invalid_key":return`Llave inválida en ${e.origin}`;case"invalid_union":default:return"Entrada inválida";case"invalid_element":return`Valor inválido en ${e.origin}`}}};const Ji=()=>{const e={string:{unit:"کاراکتر",verb:"داشته باشد"},file:{unit:"بایت",verb:"داشته باشد"},array:{unit:"آیتم",verb:"داشته باشد"},set:{unit:"آیتم",verb:"داشته باشد"}};function t(t){return e[t]??null}const n={regex:"ورودی",email:"آدرس ایمیل",url:"URL",emoji:"ایموجی",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاریخ و زمان ایزو",date:"تاریخ ایزو",time:"زمان ایزو",duration:"مدت زمان ایزو",ipv4:"IPv4 آدرس",ipv6:"IPv6 آدرس",cidrv4:"IPv4 دامنه",cidrv6:"IPv6 دامنه",base64:"base64-encoded رشته",base64url:"base64url-encoded رشته",json_string:"JSON رشته",e164:"E.164 عدد",jwt:"JWT",template_literal:"ورودی"};return e=>{switch(e.code){case"invalid_type":return`ورودی نامعتبر: میبایست ${e.expected} میبود، ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"عدد";case"object":if(Array.isArray(e))return"آرایه";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)} دریافت شد`;case"invalid_value":return 1===e.values.length?`ورودی نامعتبر: میبایست ${mn(e.values[0])} میبود`:`گزینه نامعتبر: میبایست یکی از ${Wt(e.values,"|")} میبود`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`خیلی بزرگ: ${e.origin??"مقدار"} باید ${n}${e.maximum.toString()} ${r.unit??"عنصر"} باشد`:`خیلی بزرگ: ${e.origin??"مقدار"} باید ${n}${e.maximum.toString()} باشد`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`خیلی کوچک: ${e.origin} باید ${n}${e.minimum.toString()} ${r.unit} باشد`:`خیلی کوچک: ${e.origin} باید ${n}${e.minimum.toString()} باشد`}case"invalid_format":{const t=e;return"starts_with"===t.format?`رشته نامعتبر: باید با "${t.prefix}" شروع شود`:"ends_with"===t.format?`رشته نامعتبر: باید با "${t.suffix}" تمام شود`:"includes"===t.format?`رشته نامعتبر: باید شامل "${t.includes}" باشد`:"regex"===t.format?`رشته نامعتبر: باید با الگوی ${t.pattern} مطابقت داشته باشد`:`${n[t.format]??e.format} نامعتبر`}case"not_multiple_of":return`عدد نامعتبر: باید مضرب ${e.divisor} باشد`;case"unrecognized_keys":return`کلید${e.keys.length>1?"های":""} ناشناس: ${Wt(e.keys,", ")}`;case"invalid_key":return`کلید ناشناس در ${e.origin}`;case"invalid_union":default:return"ورودی نامعتبر";case"invalid_element":return`مقدار نامعتبر در ${e.origin}`}}};const Bi=()=>{const e={string:{unit:"merkkiä",subject:"merkkijonon"},file:{unit:"tavua",subject:"tiedoston"},array:{unit:"alkiota",subject:"listan"},set:{unit:"alkiota",subject:"joukon"},number:{unit:"",subject:"luvun"},bigint:{unit:"",subject:"suuren kokonaisluvun"},int:{unit:"",subject:"kokonaisluvun"},date:{unit:"",subject:"päivämäärän"}};function t(t){return e[t]??null}const n={regex:"säännöllinen lauseke",email:"sähköpostiosoite",url:"URL-osoite",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-aikaleima",date:"ISO-päivämäärä",time:"ISO-aika",duration:"ISO-kesto",ipv4:"IPv4-osoite",ipv6:"IPv6-osoite",cidrv4:"IPv4-alue",cidrv6:"IPv6-alue",base64:"base64-koodattu merkkijono",base64url:"base64url-koodattu merkkijono",json_string:"JSON-merkkijono",e164:"E.164-luku",jwt:"JWT",template_literal:"templaattimerkkijono"};return e=>{switch(e.code){case"invalid_type":return`Virheellinen tyyppi: odotettiin ${e.expected}, oli ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Virheellinen syöte: täytyy olla ${mn(e.values[0])}`:`Virheellinen valinta: täytyy olla yksi seuraavista: ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Liian suuri: ${r.subject} täytyy olla ${n}${e.maximum.toString()} ${r.unit}`.trim():`Liian suuri: arvon täytyy olla ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Liian pieni: ${r.subject} täytyy olla ${n}${e.minimum.toString()} ${r.unit}`.trim():`Liian pieni: arvon täytyy olla ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Virheellinen syöte: täytyy alkaa "${t.prefix}"`:"ends_with"===t.format?`Virheellinen syöte: täytyy loppua "${t.suffix}"`:"includes"===t.format?`Virheellinen syöte: täytyy sisältää "${t.includes}"`:"regex"===t.format?`Virheellinen syöte: täytyy vastata säännöllistä lauseketta ${t.pattern}`:`Virheellinen ${n[t.format]??e.format}`}case"not_multiple_of":return`Virheellinen luku: täytyy olla luvun ${e.divisor} monikerta`;case"unrecognized_keys":return`${e.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${Wt(e.keys,", ")}`;case"invalid_key":return"Virheellinen avain tietueessa";case"invalid_union":return"Virheellinen unioni";case"invalid_element":return"Virheellinen arvo joukossa";default:return"Virheellinen syöte"}}};const Hi=()=>{const e={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}};function t(t){return e[t]??null}const n={regex:"entrée",email:"adresse e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date et heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"};return e=>{switch(e.code){case"invalid_type":return`Entrée invalide : ${e.expected} attendu, ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"nombre";case"object":if(Array.isArray(e))return"tableau";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)} reçu`;case"invalid_value":return 1===e.values.length?`Entrée invalide : ${mn(e.values[0])} attendu`:`Option invalide : une valeur parmi ${Wt(e.values,"|")} attendue`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Trop grand : ${e.origin??"valeur"} doit ${r.verb} ${n}${e.maximum.toString()} ${r.unit??"élément(s)"}`:`Trop grand : ${e.origin??"valeur"} doit être ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Trop petit : ${e.origin} doit ${r.verb} ${n}${e.minimum.toString()} ${r.unit}`:`Trop petit : ${e.origin} doit être ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Chaîne invalide : doit commencer par "${t.prefix}"`:"ends_with"===t.format?`Chaîne invalide : doit se terminer par "${t.suffix}"`:"includes"===t.format?`Chaîne invalide : doit inclure "${t.includes}"`:"regex"===t.format?`Chaîne invalide : doit correspondre au modèle ${t.pattern}`:`${n[t.format]??e.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${e.divisor}`;case"unrecognized_keys":return`Clé${e.keys.length>1?"s":""} non reconnue${e.keys.length>1?"s":""} : ${Wt(e.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${e.origin}`;case"invalid_union":default:return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${e.origin}`}}};const Vi=()=>{const e={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}};function t(t){return e[t]??null}const n={regex:"entrée",email:"adresse courriel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date-heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"};return e=>{switch(e.code){case"invalid_type":return`Entrée invalide : attendu ${e.expected}, reçu ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Entrée invalide : attendu ${mn(e.values[0])}`:`Option invalide : attendu l'une des valeurs suivantes ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"≤":"<",r=t(e.origin);return r?`Trop grand : attendu que ${e.origin??"la valeur"} ait ${n}${e.maximum.toString()} ${r.unit}`:`Trop grand : attendu que ${e.origin??"la valeur"} soit ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?"≥":">",r=t(e.origin);return r?`Trop petit : attendu que ${e.origin} ait ${n}${e.minimum.toString()} ${r.unit}`:`Trop petit : attendu que ${e.origin} soit ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Chaîne invalide : doit commencer par "${t.prefix}"`:"ends_with"===t.format?`Chaîne invalide : doit se terminer par "${t.suffix}"`:"includes"===t.format?`Chaîne invalide : doit inclure "${t.includes}"`:"regex"===t.format?`Chaîne invalide : doit correspondre au motif ${t.pattern}`:`${n[t.format]??e.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${e.divisor}`;case"unrecognized_keys":return`Clé${e.keys.length>1?"s":""} non reconnue${e.keys.length>1?"s":""} : ${Wt(e.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${e.origin}`;case"invalid_union":default:return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${e.origin}`}}};const Gi=()=>{const e={string:{unit:"אותיות",verb:"לכלול"},file:{unit:"בייטים",verb:"לכלול"},array:{unit:"פריטים",verb:"לכלול"},set:{unit:"פריטים",verb:"לכלול"}};function t(t){return e[t]??null}const n={regex:"קלט",email:"כתובת אימייל",url:"כתובת רשת",emoji:"אימוג'י",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"תאריך וזמן ISO",date:"תאריך ISO",time:"זמן ISO",duration:"משך זמן ISO",ipv4:"כתובת IPv4",ipv6:"כתובת IPv6",cidrv4:"טווח IPv4",cidrv6:"טווח IPv6",base64:"מחרוזת בבסיס 64",base64url:"מחרוזת בבסיס 64 לכתובות רשת",json_string:"מחרוזת JSON",e164:"מספר E.164",jwt:"JWT",template_literal:"קלט"};return e=>{switch(e.code){case"invalid_type":return`קלט לא תקין: צריך ${e.expected}, התקבל ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`קלט לא תקין: צריך ${mn(e.values[0])}`:`קלט לא תקין: צריך אחת מהאפשרויות ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`גדול מדי: ${e.origin??"value"} צריך להיות ${n}${e.maximum.toString()} ${r.unit??"elements"}`:`גדול מדי: ${e.origin??"value"} צריך להיות ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`קטן מדי: ${e.origin} צריך להיות ${n}${e.minimum.toString()} ${r.unit}`:`קטן מדי: ${e.origin} צריך להיות ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`מחרוזת לא תקינה: חייבת להתחיל ב"${t.prefix}"`:"ends_with"===t.format?`מחרוזת לא תקינה: חייבת להסתיים ב "${t.suffix}"`:"includes"===t.format?`מחרוזת לא תקינה: חייבת לכלול "${t.includes}"`:"regex"===t.format?`מחרוזת לא תקינה: חייבת להתאים לתבנית ${t.pattern}`:`${n[t.format]??e.format} לא תקין`}case"not_multiple_of":return`מספר לא תקין: חייב להיות מכפלה של ${e.divisor}`;case"unrecognized_keys":return`מפתח${e.keys.length>1?"ות":""} לא מזוה${e.keys.length>1?"ים":"ה"}: ${Wt(e.keys,", ")}`;case"invalid_key":return`מפתח לא תקין ב${e.origin}`;case"invalid_union":default:return"קלט לא תקין";case"invalid_element":return`ערך לא תקין ב${e.origin}`}}};const Ki=()=>{const e={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function t(t){return e[t]??null}const n={regex:"bemenet",email:"email cím",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO időbélyeg",date:"ISO dátum",time:"ISO idő",duration:"ISO időintervallum",ipv4:"IPv4 cím",ipv6:"IPv6 cím",cidrv4:"IPv4 tartomány",cidrv6:"IPv6 tartomány",base64:"base64-kódolt string",base64url:"base64url-kódolt string",json_string:"JSON string",e164:"E.164 szám",jwt:"JWT",template_literal:"bemenet"};return e=>{switch(e.code){case"invalid_type":return`Érvénytelen bemenet: a várt érték ${e.expected}, a kapott érték ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"szám";case"object":if(Array.isArray(e))return"tömb";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Érvénytelen bemenet: a várt érték ${mn(e.values[0])}`:`Érvénytelen opció: valamelyik érték várt ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Túl nagy: ${e.origin??"érték"} mérete túl nagy ${n}${e.maximum.toString()} ${r.unit??"elem"}`:`Túl nagy: a bemeneti érték ${e.origin??"érték"} túl nagy: ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Túl kicsi: a bemeneti érték ${e.origin} mérete túl kicsi ${n}${e.minimum.toString()} ${r.unit}`:`Túl kicsi: a bemeneti érték ${e.origin} túl kicsi ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Érvénytelen string: "${t.prefix}" értékkel kell kezdődnie`:"ends_with"===t.format?`Érvénytelen string: "${t.suffix}" értékkel kell végződnie`:"includes"===t.format?`Érvénytelen string: "${t.includes}" értéket kell tartalmaznia`:"regex"===t.format?`Érvénytelen string: ${t.pattern} mintának kell megfelelnie`:`Érvénytelen ${n[t.format]??e.format}`}case"not_multiple_of":return`Érvénytelen szám: ${e.divisor} többszörösének kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${e.keys.length>1?"s":""}: ${Wt(e.keys,", ")}`;case"invalid_key":return`Érvénytelen kulcs ${e.origin}`;case"invalid_union":default:return"Érvénytelen bemenet";case"invalid_element":return`Érvénytelen érték: ${e.origin}`}}};const Yi=()=>{const e={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function t(t){return e[t]??null}const n={regex:"input",email:"alamat email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tanggal dan waktu format ISO",date:"tanggal format ISO",time:"jam format ISO",duration:"durasi format ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"rentang alamat IPv4",cidrv6:"rentang alamat IPv6",base64:"string dengan enkode base64",base64url:"string dengan enkode base64url",json_string:"string JSON",e164:"angka E.164",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Input tidak valid: diharapkan ${e.expected}, diterima ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Input tidak valid: diharapkan ${mn(e.values[0])}`:`Pilihan tidak valid: diharapkan salah satu dari ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Terlalu besar: diharapkan ${e.origin??"value"} memiliki ${n}${e.maximum.toString()} ${r.unit??"elemen"}`:`Terlalu besar: diharapkan ${e.origin??"value"} menjadi ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Terlalu kecil: diharapkan ${e.origin} memiliki ${n}${e.minimum.toString()} ${r.unit}`:`Terlalu kecil: diharapkan ${e.origin} menjadi ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`String tidak valid: harus dimulai dengan "${t.prefix}"`:"ends_with"===t.format?`String tidak valid: harus berakhir dengan "${t.suffix}"`:"includes"===t.format?`String tidak valid: harus menyertakan "${t.includes}"`:"regex"===t.format?`String tidak valid: harus sesuai pola ${t.pattern}`:`${n[t.format]??e.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${e.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${e.keys.length>1?"s":""}: ${Wt(e.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${e.origin}`;case"invalid_union":default:return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${e.origin}`}}};const Xi=()=>{const e={string:{unit:"stafi",verb:"að hafa"},file:{unit:"bæti",verb:"að hafa"},array:{unit:"hluti",verb:"að hafa"},set:{unit:"hluti",verb:"að hafa"}};function t(t){return e[t]??null}const n={regex:"gildi",email:"netfang",url:"vefslóð",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dagsetning og tími",date:"ISO dagsetning",time:"ISO tími",duration:"ISO tímalengd",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded strengur",base64url:"base64url-encoded strengur",json_string:"JSON strengur",e164:"E.164 tölugildi",jwt:"JWT",template_literal:"gildi"};return e=>{switch(e.code){case"invalid_type":return`Rangt gildi: Þú slóst inn ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"númer";case"object":if(Array.isArray(e))return"fylki";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)} þar sem á að vera ${e.expected}`;case"invalid_value":return 1===e.values.length?`Rangt gildi: gert ráð fyrir ${mn(e.values[0])}`:`Ógilt val: má vera eitt af eftirfarandi ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Of stórt: gert er ráð fyrir að ${e.origin??"gildi"} hafi ${n}${e.maximum.toString()} ${r.unit??"hluti"}`:`Of stórt: gert er ráð fyrir að ${e.origin??"gildi"} sé ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Of lítið: gert er ráð fyrir að ${e.origin} hafi ${n}${e.minimum.toString()} ${r.unit}`:`Of lítið: gert er ráð fyrir að ${e.origin} sé ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Ógildur strengur: verður að byrja á "${t.prefix}"`:"ends_with"===t.format?`Ógildur strengur: verður að enda á "${t.suffix}"`:"includes"===t.format?`Ógildur strengur: verður að innihalda "${t.includes}"`:"regex"===t.format?`Ógildur strengur: verður að fylgja mynstri ${t.pattern}`:`Rangt ${n[t.format]??e.format}`}case"not_multiple_of":return`Röng tala: verður að vera margfeldi af ${e.divisor}`;case"unrecognized_keys":return`Óþekkt ${e.keys.length>1?"ir lyklar":"ur lykill"}: ${Wt(e.keys,", ")}`;case"invalid_key":return`Rangur lykill í ${e.origin}`;case"invalid_union":default:return"Rangt gildi";case"invalid_element":return`Rangt gildi í ${e.origin}`}}};const Qi=()=>{const e={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function t(t){return e[t]??null}const n={regex:"input",email:"indirizzo email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e ora ISO",date:"data ISO",time:"ora ISO",duration:"durata ISO",ipv4:"indirizzo IPv4",ipv6:"indirizzo IPv6",cidrv4:"intervallo IPv4",cidrv6:"intervallo IPv6",base64:"stringa codificata in base64",base64url:"URL codificata in base64",json_string:"stringa JSON",e164:"numero E.164",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Input non valido: atteso ${e.expected}, ricevuto ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"numero";case"object":if(Array.isArray(e))return"vettore";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Input non valido: atteso ${mn(e.values[0])}`:`Opzione non valida: atteso uno tra ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Troppo grande: ${e.origin??"valore"} deve avere ${n}${e.maximum.toString()} ${r.unit??"elementi"}`:`Troppo grande: ${e.origin??"valore"} deve essere ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Troppo piccolo: ${e.origin} deve avere ${n}${e.minimum.toString()} ${r.unit}`:`Troppo piccolo: ${e.origin} deve essere ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Stringa non valida: deve iniziare con "${t.prefix}"`:"ends_with"===t.format?`Stringa non valida: deve terminare con "${t.suffix}"`:"includes"===t.format?`Stringa non valida: deve includere "${t.includes}"`:"regex"===t.format?`Stringa non valida: deve corrispondere al pattern ${t.pattern}`:`Invalid ${n[t.format]??e.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${e.divisor}`;case"unrecognized_keys":return`Chiav${e.keys.length>1?"i":"e"} non riconosciut${e.keys.length>1?"e":"a"}: ${Wt(e.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${e.origin}`;case"invalid_union":default:return"Input non valido";case"invalid_element":return`Valore non valido in ${e.origin}`}}};const es=()=>{const e={string:{unit:"文字",verb:"である"},file:{unit:"バイト",verb:"である"},array:{unit:"要素",verb:"である"},set:{unit:"要素",verb:"である"}};function t(t){return e[t]??null}const n={regex:"入力値",email:"メールアドレス",url:"URL",emoji:"絵文字",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日時",date:"ISO日付",time:"ISO時刻",duration:"ISO期間",ipv4:"IPv4アドレス",ipv6:"IPv6アドレス",cidrv4:"IPv4範囲",cidrv6:"IPv6範囲",base64:"base64エンコード文字列",base64url:"base64urlエンコード文字列",json_string:"JSON文字列",e164:"E.164番号",jwt:"JWT",template_literal:"入力値"};return e=>{switch(e.code){case"invalid_type":return`無効な入力: ${e.expected}が期待されましたが、${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"数値";case"object":if(Array.isArray(e))return"配列";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}が入力されました`;case"invalid_value":return 1===e.values.length?`無効な入力: ${mn(e.values[0])}が期待されました`:`無効な選択: ${Wt(e.values,"、")}のいずれかである必要があります`;case"too_big":{const n=e.inclusive?"以下である":"より小さい",r=t(e.origin);return r?`大きすぎる値: ${e.origin??"値"}は${e.maximum.toString()}${r.unit??"要素"}${n}必要があります`:`大きすぎる値: ${e.origin??"値"}は${e.maximum.toString()}${n}必要があります`}case"too_small":{const n=e.inclusive?"以上である":"より大きい",r=t(e.origin);return r?`小さすぎる値: ${e.origin}は${e.minimum.toString()}${r.unit}${n}必要があります`:`小さすぎる値: ${e.origin}は${e.minimum.toString()}${n}必要があります`}case"invalid_format":{const t=e;return"starts_with"===t.format?`無効な文字列: "${t.prefix}"で始まる必要があります`:"ends_with"===t.format?`無効な文字列: "${t.suffix}"で終わる必要があります`:"includes"===t.format?`無効な文字列: "${t.includes}"を含む必要があります`:"regex"===t.format?`無効な文字列: パターン${t.pattern}に一致する必要があります`:`無効な${n[t.format]??e.format}`}case"not_multiple_of":return`無効な数値: ${e.divisor}の倍数である必要があります`;case"unrecognized_keys":return`認識されていないキー${e.keys.length>1?"群":""}: ${Wt(e.keys,"、")}`;case"invalid_key":return`${e.origin}内の無効なキー`;case"invalid_union":default:return"無効な入力";case"invalid_element":return`${e.origin}内の無効な値`}}};const ts=()=>{const e={string:{unit:"តួអក្សរ",verb:"គួរមាន"},file:{unit:"បៃ",verb:"គួរមាន"},array:{unit:"ធាតុ",verb:"គួរមាន"},set:{unit:"ធាតុ",verb:"គួរមាន"}};function t(t){return e[t]??null}const n={regex:"ទិន្នន័យបញ្ចូល",email:"អាសយដ្ឋានអ៊ីមែល",url:"URL",emoji:"សញ្ញាអារម្មណ៍",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"កាលបរិច្ឆេទ និងម៉ោង ISO",date:"កាលបរិច្ឆេទ ISO",time:"ម៉ោង ISO",duration:"រយៈពេល ISO",ipv4:"អាសយដ្ឋាន IPv4",ipv6:"អាសយដ្ឋាន IPv6",cidrv4:"ដែនអាសយដ្ឋាន IPv4",cidrv6:"ដែនអាសយដ្ឋាន IPv6",base64:"ខ្សែអក្សរអ៊ិកូដ base64",base64url:"ខ្សែអក្សរអ៊ិកូដ base64url",json_string:"ខ្សែអក្សរ JSON",e164:"លេខ E.164",jwt:"JWT",template_literal:"ទិន្នន័យបញ្ចូល"};return e=>{switch(e.code){case"invalid_type":return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${e.expected} ប៉ុន្តែទទួលបាន ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"មិនមែនជាលេខ (NaN)":"លេខ";case"object":if(Array.isArray(e))return"អារេ (Array)";if(null===e)return"គ្មានតម្លៃ (null)";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${mn(e.values[0])}`:`ជម្រើសមិនត្រឹមត្រូវ៖ ត្រូវជាមួយក្នុងចំណោម ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`ធំពេក៖ ត្រូវការ ${e.origin??"តម្លៃ"} ${n} ${e.maximum.toString()} ${r.unit??"ធាតុ"}`:`ធំពេក៖ ត្រូវការ ${e.origin??"តម្លៃ"} ${n} ${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`តូចពេក៖ ត្រូវការ ${e.origin} ${n} ${e.minimum.toString()} ${r.unit}`:`តូចពេក៖ ត្រូវការ ${e.origin} ${n} ${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវចាប់ផ្តើមដោយ "${t.prefix}"`:"ends_with"===t.format?`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវបញ្ចប់ដោយ "${t.suffix}"`:"includes"===t.format?`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវមាន "${t.includes}"`:"regex"===t.format?`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវតែផ្គូផ្គងនឹងទម្រង់ដែលបានកំណត់ ${t.pattern}`:`មិនត្រឹមត្រូវ៖ ${n[t.format]??e.format}`}case"not_multiple_of":return`លេខមិនត្រឹមត្រូវ៖ ត្រូវតែជាពហុគុណនៃ ${e.divisor}`;case"unrecognized_keys":return`រកឃើញសោមិនស្គាល់៖ ${Wt(e.keys,", ")}`;case"invalid_key":return`សោមិនត្រឹមត្រូវនៅក្នុង ${e.origin}`;case"invalid_union":default:return"ទិន្នន័យមិនត្រឹមត្រូវ";case"invalid_element":return`ទិន្នន័យមិនត្រឹមត្រូវនៅក្នុង ${e.origin}`}}};const ns=()=>{const e={string:{unit:"문자",verb:"to have"},file:{unit:"바이트",verb:"to have"},array:{unit:"개",verb:"to have"},set:{unit:"개",verb:"to have"}};function t(t){return e[t]??null}const n={regex:"입력",email:"이메일 주소",url:"URL",emoji:"이모지",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 날짜시간",date:"ISO 날짜",time:"ISO 시간",duration:"ISO 기간",ipv4:"IPv4 주소",ipv6:"IPv6 주소",cidrv4:"IPv4 범위",cidrv6:"IPv6 범위",base64:"base64 인코딩 문자열",base64url:"base64url 인코딩 문자열",json_string:"JSON 문자열",e164:"E.164 번호",jwt:"JWT",template_literal:"입력"};return e=>{switch(e.code){case"invalid_type":return`잘못된 입력: 예상 타입은 ${e.expected}, 받은 타입은 ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}입니다`;case"invalid_value":return 1===e.values.length?`잘못된 입력: 값은 ${mn(e.values[0])} 이어야 합니다`:`잘못된 옵션: ${Wt(e.values,"또는 ")} 중 하나여야 합니다`;case"too_big":{const n=e.inclusive?"이하":"미만",r="미만"===n?"이어야 합니다":"여야 합니다",o=t(e.origin),i=(null==o?void 0:o.unit)??"요소";return o?`${e.origin??"값"}이 너무 큽니다: ${e.maximum.toString()}${i} ${n}${r}`:`${e.origin??"값"}이 너무 큽니다: ${e.maximum.toString()} ${n}${r}`}case"too_small":{const n=e.inclusive?"이상":"초과",r="이상"===n?"이어야 합니다":"여야 합니다",o=t(e.origin),i=(null==o?void 0:o.unit)??"요소";return o?`${e.origin??"값"}이 너무 작습니다: ${e.minimum.toString()}${i} ${n}${r}`:`${e.origin??"값"}이 너무 작습니다: ${e.minimum.toString()} ${n}${r}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`잘못된 문자열: "${t.prefix}"(으)로 시작해야 합니다`:"ends_with"===t.format?`잘못된 문자열: "${t.suffix}"(으)로 끝나야 합니다`:"includes"===t.format?`잘못된 문자열: "${t.includes}"을(를) 포함해야 합니다`:"regex"===t.format?`잘못된 문자열: 정규식 ${t.pattern} 패턴과 일치해야 합니다`:`잘못된 ${n[t.format]??e.format}`}case"not_multiple_of":return`잘못된 숫자: ${e.divisor}의 배수여야 합니다`;case"unrecognized_keys":return`인식할 수 없는 키: ${Wt(e.keys,", ")}`;case"invalid_key":return`잘못된 키: ${e.origin}`;case"invalid_union":default:return"잘못된 입력";case"invalid_element":return`잘못된 값: ${e.origin}`}}};const rs=()=>{const e={string:{unit:"знаци",verb:"да имаат"},file:{unit:"бајти",verb:"да имаат"},array:{unit:"ставки",verb:"да имаат"},set:{unit:"ставки",verb:"да имаат"}};function t(t){return e[t]??null}const n={regex:"внес",email:"адреса на е-пошта",url:"URL",emoji:"емоџи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO датум и време",date:"ISO датум",time:"ISO време",duration:"ISO времетраење",ipv4:"IPv4 адреса",ipv6:"IPv6 адреса",cidrv4:"IPv4 опсег",cidrv6:"IPv6 опсег",base64:"base64-енкодирана низа",base64url:"base64url-енкодирана низа",json_string:"JSON низа",e164:"E.164 број",jwt:"JWT",template_literal:"внес"};return e=>{switch(e.code){case"invalid_type":return`Грешен внес: се очекува ${e.expected}, примено ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"број";case"object":if(Array.isArray(e))return"низа";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Invalid input: expected ${mn(e.values[0])}`:`Грешана опција: се очекува една ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Премногу голем: се очекува ${e.origin??"вредноста"} да има ${n}${e.maximum.toString()} ${r.unit??"елементи"}`:`Премногу голем: се очекува ${e.origin??"вредноста"} да биде ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Премногу мал: се очекува ${e.origin} да има ${n}${e.minimum.toString()} ${r.unit}`:`Премногу мал: се очекува ${e.origin} да биде ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Неважечка низа: мора да започнува со "${t.prefix}"`:"ends_with"===t.format?`Неважечка низа: мора да завршува со "${t.suffix}"`:"includes"===t.format?`Неважечка низа: мора да вклучува "${t.includes}"`:"regex"===t.format?`Неважечка низа: мора да одгоара на патернот ${t.pattern}`:`Invalid ${n[t.format]??e.format}`}case"not_multiple_of":return`Грешен број: мора да биде делив со ${e.divisor}`;case"unrecognized_keys":return`${e.keys.length>1?"Непрепознаени клучеви":"Непрепознаен клуч"}: ${Wt(e.keys,", ")}`;case"invalid_key":return`Грешен клуч во ${e.origin}`;case"invalid_union":default:return"Грешен внес";case"invalid_element":return`Грешна вредност во ${e.origin}`}}};const os=()=>{const e={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function t(t){return e[t]??null}const n={regex:"input",email:"alamat e-mel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tarikh masa ISO",date:"tarikh ISO",time:"masa ISO",duration:"tempoh ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"julat IPv4",cidrv6:"julat IPv6",base64:"string dikodkan base64",base64url:"string dikodkan base64url",json_string:"string JSON",e164:"nombor E.164",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Input tidak sah: dijangka ${e.expected}, diterima ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"nombor";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Input tidak sah: dijangka ${mn(e.values[0])}`:`Pilihan tidak sah: dijangka salah satu daripada ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Terlalu besar: dijangka ${e.origin??"nilai"} ${r.verb} ${n}${e.maximum.toString()} ${r.unit??"elemen"}`:`Terlalu besar: dijangka ${e.origin??"nilai"} adalah ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Terlalu kecil: dijangka ${e.origin} ${r.verb} ${n}${e.minimum.toString()} ${r.unit}`:`Terlalu kecil: dijangka ${e.origin} adalah ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`String tidak sah: mesti bermula dengan "${t.prefix}"`:"ends_with"===t.format?`String tidak sah: mesti berakhir dengan "${t.suffix}"`:"includes"===t.format?`String tidak sah: mesti mengandungi "${t.includes}"`:"regex"===t.format?`String tidak sah: mesti sepadan dengan corak ${t.pattern}`:`${n[t.format]??e.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${e.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${Wt(e.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${e.origin}`;case"invalid_union":default:return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${e.origin}`}}};const is=()=>{const e={string:{unit:"tekens"},file:{unit:"bytes"},array:{unit:"elementen"},set:{unit:"elementen"}};function t(t){return e[t]??null}const n={regex:"invoer",email:"emailadres",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum en tijd",date:"ISO datum",time:"ISO tijd",duration:"ISO duur",ipv4:"IPv4-adres",ipv6:"IPv6-adres",cidrv4:"IPv4-bereik",cidrv6:"IPv6-bereik",base64:"base64-gecodeerde tekst",base64url:"base64 URL-gecodeerde tekst",json_string:"JSON string",e164:"E.164-nummer",jwt:"JWT",template_literal:"invoer"};return e=>{switch(e.code){case"invalid_type":return`Ongeldige invoer: verwacht ${e.expected}, ontving ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"getal";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Ongeldige invoer: verwacht ${mn(e.values[0])}`:`Ongeldige optie: verwacht één van ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Te lang: verwacht dat ${e.origin??"waarde"} ${n}${e.maximum.toString()} ${r.unit??"elementen"} bevat`:`Te lang: verwacht dat ${e.origin??"waarde"} ${n}${e.maximum.toString()} is`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Te kort: verwacht dat ${e.origin} ${n}${e.minimum.toString()} ${r.unit} bevat`:`Te kort: verwacht dat ${e.origin} ${n}${e.minimum.toString()} is`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Ongeldige tekst: moet met "${t.prefix}" beginnen`:"ends_with"===t.format?`Ongeldige tekst: moet op "${t.suffix}" eindigen`:"includes"===t.format?`Ongeldige tekst: moet "${t.includes}" bevatten`:"regex"===t.format?`Ongeldige tekst: moet overeenkomen met patroon ${t.pattern}`:`Ongeldig: ${n[t.format]??e.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${e.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${e.keys.length>1?"s":""}: ${Wt(e.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${e.origin}`;case"invalid_union":default:return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${e.origin}`}}};const ss=()=>{const e={string:{unit:"tegn",verb:"å ha"},file:{unit:"bytes",verb:"å ha"},array:{unit:"elementer",verb:"å inneholde"},set:{unit:"elementer",verb:"å inneholde"}};function t(t){return e[t]??null}const n={regex:"input",email:"e-postadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varighet",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkodet streng",base64url:"base64url-enkodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Ugyldig input: forventet ${e.expected}, fikk ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"tall";case"object":if(Array.isArray(e))return"liste";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Ugyldig verdi: forventet ${mn(e.values[0])}`:`Ugyldig valg: forventet en av ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`For stor(t): forventet ${e.origin??"value"} til å ha ${n}${e.maximum.toString()} ${r.unit??"elementer"}`:`For stor(t): forventet ${e.origin??"value"} til å ha ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`For lite(n): forventet ${e.origin} til å ha ${n}${e.minimum.toString()} ${r.unit}`:`For lite(n): forventet ${e.origin} til å ha ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Ugyldig streng: må starte med "${t.prefix}"`:"ends_with"===t.format?`Ugyldig streng: må ende med "${t.suffix}"`:"includes"===t.format?`Ugyldig streng: må inneholde "${t.includes}"`:"regex"===t.format?`Ugyldig streng: må matche mønsteret ${t.pattern}`:`Ugyldig ${n[t.format]??e.format}`}case"not_multiple_of":return`Ugyldig tall: må være et multiplum av ${e.divisor}`;case"unrecognized_keys":return`${e.keys.length>1?"Ukjente nøkler":"Ukjent nøkkel"}: ${Wt(e.keys,", ")}`;case"invalid_key":return`Ugyldig nøkkel i ${e.origin}`;case"invalid_union":default:return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${e.origin}`}}};const as=()=>{const e={string:{unit:"harf",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"unsur",verb:"olmalıdır"},set:{unit:"unsur",verb:"olmalıdır"}};function t(t){return e[t]??null}const n={regex:"giren",email:"epostagâh",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO hengâmı",date:"ISO tarihi",time:"ISO zamanı",duration:"ISO müddeti",ipv4:"IPv4 nişânı",ipv6:"IPv6 nişânı",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-şifreli metin",base64url:"base64url-şifreli metin",json_string:"JSON metin",e164:"E.164 sayısı",jwt:"JWT",template_literal:"giren"};return e=>{switch(e.code){case"invalid_type":return`Fâsit giren: umulan ${e.expected}, alınan ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"numara";case"object":if(Array.isArray(e))return"saf";if(null===e)return"gayb";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Fâsit giren: umulan ${mn(e.values[0])}`:`Fâsit tercih: mûteberler ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Fazla büyük: ${e.origin??"value"}, ${n}${e.maximum.toString()} ${r.unit??"elements"} sahip olmalıydı.`:`Fazla büyük: ${e.origin??"value"}, ${n}${e.maximum.toString()} olmalıydı.`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Fazla küçük: ${e.origin}, ${n}${e.minimum.toString()} ${r.unit} sahip olmalıydı.`:`Fazla küçük: ${e.origin}, ${n}${e.minimum.toString()} olmalıydı.`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Fâsit metin: "${t.prefix}" ile başlamalı.`:"ends_with"===t.format?`Fâsit metin: "${t.suffix}" ile bitmeli.`:"includes"===t.format?`Fâsit metin: "${t.includes}" ihtivâ etmeli.`:"regex"===t.format?`Fâsit metin: ${t.pattern} nakşına uymalı.`:`Fâsit ${n[t.format]??e.format}`}case"not_multiple_of":return`Fâsit sayı: ${e.divisor} katı olmalıydı.`;case"unrecognized_keys":return`Tanınmayan anahtar ${e.keys.length>1?"s":""}: ${Wt(e.keys,", ")}`;case"invalid_key":return`${e.origin} için tanınmayan anahtar var.`;case"invalid_union":return"Giren tanınamadı.";case"invalid_element":return`${e.origin} için tanınmayan kıymet var.`;default:return"Kıymet tanınamadı."}}};const us=()=>{const e={string:{unit:"توکي",verb:"ولري"},file:{unit:"بایټس",verb:"ولري"},array:{unit:"توکي",verb:"ولري"},set:{unit:"توکي",verb:"ولري"}};function t(t){return e[t]??null}const n={regex:"ورودي",email:"بریښنالیک",url:"یو آر ال",emoji:"ایموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"نیټه او وخت",date:"نېټه",time:"وخت",duration:"موده",ipv4:"د IPv4 پته",ipv6:"د IPv6 پته",cidrv4:"د IPv4 ساحه",cidrv6:"د IPv6 ساحه",base64:"base64-encoded متن",base64url:"base64url-encoded متن",json_string:"JSON متن",e164:"د E.164 شمېره",jwt:"JWT",template_literal:"ورودي"};return e=>{switch(e.code){case"invalid_type":return`ناسم ورودي: باید ${e.expected} وای, مګر ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"عدد";case"object":if(Array.isArray(e))return"ارې";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)} ترلاسه شو`;case"invalid_value":return 1===e.values.length?`ناسم ورودي: باید ${mn(e.values[0])} وای`:`ناسم انتخاب: باید یو له ${Wt(e.values,"|")} څخه وای`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`ډیر لوی: ${e.origin??"ارزښت"} باید ${n}${e.maximum.toString()} ${r.unit??"عنصرونه"} ولري`:`ډیر لوی: ${e.origin??"ارزښت"} باید ${n}${e.maximum.toString()} وي`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`ډیر کوچنی: ${e.origin} باید ${n}${e.minimum.toString()} ${r.unit} ولري`:`ډیر کوچنی: ${e.origin} باید ${n}${e.minimum.toString()} وي`}case"invalid_format":{const t=e;return"starts_with"===t.format?`ناسم متن: باید د "${t.prefix}" سره پیل شي`:"ends_with"===t.format?`ناسم متن: باید د "${t.suffix}" سره پای ته ورسيږي`:"includes"===t.format?`ناسم متن: باید "${t.includes}" ولري`:"regex"===t.format?`ناسم متن: باید د ${t.pattern} سره مطابقت ولري`:`${n[t.format]??e.format} ناسم دی`}case"not_multiple_of":return`ناسم عدد: باید د ${e.divisor} مضرب وي`;case"unrecognized_keys":return`ناسم ${e.keys.length>1?"کلیډونه":"کلیډ"}: ${Wt(e.keys,", ")}`;case"invalid_key":return`ناسم کلیډ په ${e.origin} کې`;case"invalid_union":default:return"ناسمه ورودي";case"invalid_element":return`ناسم عنصر په ${e.origin} کې`}}};const ls=()=>{const e={string:{unit:"znaków",verb:"mieć"},file:{unit:"bajtów",verb:"mieć"},array:{unit:"elementów",verb:"mieć"},set:{unit:"elementów",verb:"mieć"}};function t(t){return e[t]??null}const n={regex:"wyrażenie",email:"adres email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i godzina w formacie ISO",date:"data w formacie ISO",time:"godzina w formacie ISO",duration:"czas trwania ISO",ipv4:"adres IPv4",ipv6:"adres IPv6",cidrv4:"zakres IPv4",cidrv6:"zakres IPv6",base64:"ciąg znaków zakodowany w formacie base64",base64url:"ciąg znaków zakodowany w formacie base64url",json_string:"ciąg znaków w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wejście"};return e=>{switch(e.code){case"invalid_type":return`Nieprawidłowe dane wejściowe: oczekiwano ${e.expected}, otrzymano ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"liczba";case"object":if(Array.isArray(e))return"tablica";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Nieprawidłowe dane wejściowe: oczekiwano ${mn(e.values[0])}`:`Nieprawidłowa opcja: oczekiwano jednej z wartości ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Za duża wartość: oczekiwano, że ${e.origin??"wartość"} będzie mieć ${n}${e.maximum.toString()} ${r.unit??"elementów"}`:`Zbyt duż(y/a/e): oczekiwano, że ${e.origin??"wartość"} będzie wynosić ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Za mała wartość: oczekiwano, że ${e.origin??"wartość"} będzie mieć ${n}${e.minimum.toString()} ${r.unit??"elementów"}`:`Zbyt mał(y/a/e): oczekiwano, że ${e.origin??"wartość"} będzie wynosić ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Nieprawidłowy ciąg znaków: musi zaczynać się od "${t.prefix}"`:"ends_with"===t.format?`Nieprawidłowy ciąg znaków: musi kończyć się na "${t.suffix}"`:"includes"===t.format?`Nieprawidłowy ciąg znaków: musi zawierać "${t.includes}"`:"regex"===t.format?`Nieprawidłowy ciąg znaków: musi odpowiadać wzorcowi ${t.pattern}`:`Nieprawidłow(y/a/e) ${n[t.format]??e.format}`}case"not_multiple_of":return`Nieprawidłowa liczba: musi być wielokrotnością ${e.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${e.keys.length>1?"s":""}: ${Wt(e.keys,", ")}`;case"invalid_key":return`Nieprawidłowy klucz w ${e.origin}`;case"invalid_union":default:return"Nieprawidłowe dane wejściowe";case"invalid_element":return`Nieprawidłowa wartość w ${e.origin}`}}};const cs=()=>{const e={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function t(t){return e[t]??null}const n={regex:"padrão",email:"endereço de e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e hora ISO",date:"data ISO",time:"hora ISO",duration:"duração ISO",ipv4:"endereço IPv4",ipv6:"endereço IPv6",cidrv4:"faixa de IPv4",cidrv6:"faixa de IPv6",base64:"texto codificado em base64",base64url:"URL codificada em base64",json_string:"texto JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"};return e=>{switch(e.code){case"invalid_type":return`Tipo inválido: esperado ${e.expected}, recebido ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"número";case"object":if(Array.isArray(e))return"array";if(null===e)return"nulo";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Entrada inválida: esperado ${mn(e.values[0])}`:`Opção inválida: esperada uma das ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Muito grande: esperado que ${e.origin??"valor"} tivesse ${n}${e.maximum.toString()} ${r.unit??"elementos"}`:`Muito grande: esperado que ${e.origin??"valor"} fosse ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Muito pequeno: esperado que ${e.origin} tivesse ${n}${e.minimum.toString()} ${r.unit}`:`Muito pequeno: esperado que ${e.origin} fosse ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Texto inválido: deve começar com "${t.prefix}"`:"ends_with"===t.format?`Texto inválido: deve terminar com "${t.suffix}"`:"includes"===t.format?`Texto inválido: deve incluir "${t.includes}"`:"regex"===t.format?`Texto inválido: deve corresponder ao padrão ${t.pattern}`:`${n[t.format]??e.format} inválido`}case"not_multiple_of":return`Número inválido: deve ser múltiplo de ${e.divisor}`;case"unrecognized_keys":return`Chave${e.keys.length>1?"s":""} desconhecida${e.keys.length>1?"s":""}: ${Wt(e.keys,", ")}`;case"invalid_key":return`Chave inválida em ${e.origin}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido em ${e.origin}`;default:return"Campo inválido"}}};function ds(e,t,n,r){const o=Math.abs(e),i=o%10,s=o%100;return s>=11&&s<=19?r:1===i?t:i>=2&&i<=4?n:r}const ps=()=>{const e={string:{unit:{one:"символ",few:"символа",many:"символов"},verb:"иметь"},file:{unit:{one:"байт",few:"байта",many:"байт"},verb:"иметь"},array:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"},set:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"}};function t(t){return e[t]??null}const n={regex:"ввод",email:"email адрес",url:"URL",emoji:"эмодзи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата и время",date:"ISO дата",time:"ISO время",duration:"ISO длительность",ipv4:"IPv4 адрес",ipv6:"IPv6 адрес",cidrv4:"IPv4 диапазон",cidrv6:"IPv6 диапазон",base64:"строка в формате base64",base64url:"строка в формате base64url",json_string:"JSON строка",e164:"номер E.164",jwt:"JWT",template_literal:"ввод"};return e=>{switch(e.code){case"invalid_type":return`Неверный ввод: ожидалось ${e.expected}, получено ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"число";case"object":if(Array.isArray(e))return"массив";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Неверный ввод: ожидалось ${mn(e.values[0])}`:`Неверный вариант: ожидалось одно из ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);if(r){const t=ds(Number(e.maximum),r.unit.one,r.unit.few,r.unit.many);return`Слишком большое значение: ожидалось, что ${e.origin??"значение"} будет иметь ${n}${e.maximum.toString()} ${t}`}return`Слишком большое значение: ожидалось, что ${e.origin??"значение"} будет ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);if(r){const t=ds(Number(e.minimum),r.unit.one,r.unit.few,r.unit.many);return`Слишком маленькое значение: ожидалось, что ${e.origin} будет иметь ${n}${e.minimum.toString()} ${t}`}return`Слишком маленькое значение: ожидалось, что ${e.origin} будет ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Неверная строка: должна начинаться с "${t.prefix}"`:"ends_with"===t.format?`Неверная строка: должна заканчиваться на "${t.suffix}"`:"includes"===t.format?`Неверная строка: должна содержать "${t.includes}"`:"regex"===t.format?`Неверная строка: должна соответствовать шаблону ${t.pattern}`:`Неверный ${n[t.format]??e.format}`}case"not_multiple_of":return`Неверное число: должно быть кратным ${e.divisor}`;case"unrecognized_keys":return`Нераспознанн${e.keys.length>1?"ые":"ый"} ключ${e.keys.length>1?"и":""}: ${Wt(e.keys,", ")}`;case"invalid_key":return`Неверный ключ в ${e.origin}`;case"invalid_union":default:return"Неверные входные данные";case"invalid_element":return`Неверное значение в ${e.origin}`}}};const ms=()=>{const e={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function t(t){return e[t]??null}const n={regex:"vnos",email:"e-poštni naslov",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum in čas",date:"ISO datum",time:"ISO čas",duration:"ISO trajanje",ipv4:"IPv4 naslov",ipv6:"IPv6 naslov",cidrv4:"obseg IPv4",cidrv6:"obseg IPv6",base64:"base64 kodiran niz",base64url:"base64url kodiran niz",json_string:"JSON niz",e164:"E.164 številka",jwt:"JWT",template_literal:"vnos"};return e=>{switch(e.code){case"invalid_type":return`Neveljaven vnos: pričakovano ${e.expected}, prejeto ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"število";case"object":if(Array.isArray(e))return"tabela";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Neveljaven vnos: pričakovano ${mn(e.values[0])}`:`Neveljavna možnost: pričakovano eno izmed ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Preveliko: pričakovano, da bo ${e.origin??"vrednost"} imelo ${n}${e.maximum.toString()} ${r.unit??"elementov"}`:`Preveliko: pričakovano, da bo ${e.origin??"vrednost"} ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Premajhno: pričakovano, da bo ${e.origin} imelo ${n}${e.minimum.toString()} ${r.unit}`:`Premajhno: pričakovano, da bo ${e.origin} ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Neveljaven niz: mora se začeti z "${t.prefix}"`:"ends_with"===t.format?`Neveljaven niz: mora se končati z "${t.suffix}"`:"includes"===t.format?`Neveljaven niz: mora vsebovati "${t.includes}"`:"regex"===t.format?`Neveljaven niz: mora ustrezati vzorcu ${t.pattern}`:`Neveljaven ${n[t.format]??e.format}`}case"not_multiple_of":return`Neveljavno število: mora biti večkratnik ${e.divisor}`;case"unrecognized_keys":return`Neprepoznan${e.keys.length>1?"i ključi":" ključ"}: ${Wt(e.keys,", ")}`;case"invalid_key":return`Neveljaven ključ v ${e.origin}`;case"invalid_union":default:return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${e.origin}`}}};const _s=()=>{const e={string:{unit:"tecken",verb:"att ha"},file:{unit:"bytes",verb:"att ha"},array:{unit:"objekt",verb:"att innehålla"},set:{unit:"objekt",verb:"att innehålla"}};function t(t){return e[t]??null}const n={regex:"reguljärt uttryck",email:"e-postadress",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datum och tid",date:"ISO-datum",time:"ISO-tid",duration:"ISO-varaktighet",ipv4:"IPv4-intervall",ipv6:"IPv6-intervall",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodad sträng",base64url:"base64url-kodad sträng",json_string:"JSON-sträng",e164:"E.164-nummer",jwt:"JWT",template_literal:"mall-literal"};return e=>{switch(e.code){case"invalid_type":return`Ogiltig inmatning: förväntat ${e.expected}, fick ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"antal";case"object":if(Array.isArray(e))return"lista";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Ogiltig inmatning: förväntat ${mn(e.values[0])}`:`Ogiltigt val: förväntade en av ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`För stor(t): förväntade ${e.origin??"värdet"} att ha ${n}${e.maximum.toString()} ${r.unit??"element"}`:`För stor(t): förväntat ${e.origin??"värdet"} att ha ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`För lite(t): förväntade ${e.origin??"värdet"} att ha ${n}${e.minimum.toString()} ${r.unit}`:`För lite(t): förväntade ${e.origin??"värdet"} att ha ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Ogiltig sträng: måste börja med "${t.prefix}"`:"ends_with"===t.format?`Ogiltig sträng: måste sluta med "${t.suffix}"`:"includes"===t.format?`Ogiltig sträng: måste innehålla "${t.includes}"`:"regex"===t.format?`Ogiltig sträng: måste matcha mönstret "${t.pattern}"`:`Ogiltig(t) ${n[t.format]??e.format}`}case"not_multiple_of":return`Ogiltigt tal: måste vara en multipel av ${e.divisor}`;case"unrecognized_keys":return`${e.keys.length>1?"Okända nycklar":"Okänd nyckel"}: ${Wt(e.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${e.origin??"värdet"}`;case"invalid_union":default:return"Ogiltig input";case"invalid_element":return`Ogiltigt värde i ${e.origin??"värdet"}`}}};const hs=()=>{const e={string:{unit:"எழுத்துக்கள்",verb:"கொண்டிருக்க வேண்டும்"},file:{unit:"பைட்டுகள்",verb:"கொண்டிருக்க வேண்டும்"},array:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"},set:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"}};function t(t){return e[t]??null}const n={regex:"உள்ளீடு",email:"மின்னஞ்சல் முகவரி",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO தேதி நேரம்",date:"ISO தேதி",time:"ISO நேரம்",duration:"ISO கால அளவு",ipv4:"IPv4 முகவரி",ipv6:"IPv6 முகவரி",cidrv4:"IPv4 வரம்பு",cidrv6:"IPv6 வரம்பு",base64:"base64-encoded சரம்",base64url:"base64url-encoded சரம்",json_string:"JSON சரம்",e164:"E.164 எண்",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${e.expected}, பெறப்பட்டது ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"எண் அல்லாதது":"எண்";case"object":if(Array.isArray(e))return"அணி";if(null===e)return"வெறுமை";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${mn(e.values[0])}`:`தவறான விருப்பம்: எதிர்பார்க்கப்பட்டது ${Wt(e.values,"|")} இல் ஒன்று`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${e.origin??"மதிப்பு"} ${n}${e.maximum.toString()} ${r.unit??"உறுப்புகள்"} ஆக இருக்க வேண்டும்`:`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${e.origin??"மதிப்பு"} ${n}${e.maximum.toString()} ஆக இருக்க வேண்டும்`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${e.origin} ${n}${e.minimum.toString()} ${r.unit} ஆக இருக்க வேண்டும்`:`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${e.origin} ${n}${e.minimum.toString()} ஆக இருக்க வேண்டும்`}case"invalid_format":{const t=e;return"starts_with"===t.format?`தவறான சரம்: "${t.prefix}" இல் தொடங்க வேண்டும்`:"ends_with"===t.format?`தவறான சரம்: "${t.suffix}" இல் முடிவடைய வேண்டும்`:"includes"===t.format?`தவறான சரம்: "${t.includes}" ஐ உள்ளடக்க வேண்டும்`:"regex"===t.format?`தவறான சரம்: ${t.pattern} முறைபாட்டுடன் பொருந்த வேண்டும்`:`தவறான ${n[t.format]??e.format}`}case"not_multiple_of":return`தவறான எண்: ${e.divisor} இன் பலமாக இருக்க வேண்டும்`;case"unrecognized_keys":return`அடையாளம் தெரியாத விசை${e.keys.length>1?"கள்":""}: ${Wt(e.keys,", ")}`;case"invalid_key":return`${e.origin} இல் தவறான விசை`;case"invalid_union":default:return"தவறான உள்ளீடு";case"invalid_element":return`${e.origin} இல் தவறான மதிப்பு`}}};const gs=()=>{const e={string:{unit:"ตัวอักษร",verb:"ควรมี"},file:{unit:"ไบต์",verb:"ควรมี"},array:{unit:"รายการ",verb:"ควรมี"},set:{unit:"รายการ",verb:"ควรมี"}};function t(t){return e[t]??null}const n={regex:"ข้อมูลที่ป้อน",email:"ที่อยู่อีเมล",url:"URL",emoji:"อิโมจิ",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"วันที่เวลาแบบ ISO",date:"วันที่แบบ ISO",time:"เวลาแบบ ISO",duration:"ช่วงเวลาแบบ ISO",ipv4:"ที่อยู่ IPv4",ipv6:"ที่อยู่ IPv6",cidrv4:"ช่วง IP แบบ IPv4",cidrv6:"ช่วง IP แบบ IPv6",base64:"ข้อความแบบ Base64",base64url:"ข้อความแบบ Base64 สำหรับ URL",json_string:"ข้อความแบบ JSON",e164:"เบอร์โทรศัพท์ระหว่างประเทศ (E.164)",jwt:"โทเคน JWT",template_literal:"ข้อมูลที่ป้อน"};return e=>{switch(e.code){case"invalid_type":return`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น ${e.expected} แต่ได้รับ ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"ไม่ใช่ตัวเลข (NaN)":"ตัวเลข";case"object":if(Array.isArray(e))return"อาร์เรย์ (Array)";if(null===e)return"ไม่มีค่า (null)";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`ค่าไม่ถูกต้อง: ควรเป็น ${mn(e.values[0])}`:`ตัวเลือกไม่ถูกต้อง: ควรเป็นหนึ่งใน ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"ไม่เกิน":"น้อยกว่า",r=t(e.origin);return r?`เกินกำหนด: ${e.origin??"ค่า"} ควรมี${n} ${e.maximum.toString()} ${r.unit??"รายการ"}`:`เกินกำหนด: ${e.origin??"ค่า"} ควรมี${n} ${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?"อย่างน้อย":"มากกว่า",r=t(e.origin);return r?`น้อยกว่ากำหนด: ${e.origin} ควรมี${n} ${e.minimum.toString()} ${r.unit}`:`น้อยกว่ากำหนด: ${e.origin} ควรมี${n} ${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`รูปแบบไม่ถูกต้อง: ข้อความต้องขึ้นต้นด้วย "${t.prefix}"`:"ends_with"===t.format?`รูปแบบไม่ถูกต้อง: ข้อความต้องลงท้ายด้วย "${t.suffix}"`:"includes"===t.format?`รูปแบบไม่ถูกต้อง: ข้อความต้องมี "${t.includes}" อยู่ในข้อความ`:"regex"===t.format?`รูปแบบไม่ถูกต้อง: ต้องตรงกับรูปแบบที่กำหนด ${t.pattern}`:`รูปแบบไม่ถูกต้อง: ${n[t.format]??e.format}`}case"not_multiple_of":return`ตัวเลขไม่ถูกต้อง: ต้องเป็นจำนวนที่หารด้วย ${e.divisor} ได้ลงตัว`;case"unrecognized_keys":return`พบคีย์ที่ไม่รู้จัก: ${Wt(e.keys,", ")}`;case"invalid_key":return`คีย์ไม่ถูกต้องใน ${e.origin}`;case"invalid_union":return"ข้อมูลไม่ถูกต้อง: ไม่ตรงกับรูปแบบยูเนียนที่กำหนดไว้";case"invalid_element":return`ข้อมูลไม่ถูกต้องใน ${e.origin}`;default:return"ข้อมูลไม่ถูกต้อง"}}};const fs=()=>{const e={string:{unit:"karakter",verb:"olmalı"},file:{unit:"bayt",verb:"olmalı"},array:{unit:"öğe",verb:"olmalı"},set:{unit:"öğe",verb:"olmalı"}};function t(t){return e[t]??null}const n={regex:"girdi",email:"e-posta adresi",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO tarih ve saat",date:"ISO tarih",time:"ISO saat",duration:"ISO süre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aralığı",cidrv6:"IPv6 aralığı",base64:"base64 ile şifrelenmiş metin",base64url:"base64url ile şifrelenmiş metin",json_string:"JSON dizesi",e164:"E.164 sayısı",jwt:"JWT",template_literal:"Şablon dizesi"};return e=>{switch(e.code){case"invalid_type":return`Geçersiz değer: beklenen ${e.expected}, alınan ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Geçersiz değer: beklenen ${mn(e.values[0])}`:`Geçersiz seçenek: aşağıdakilerden biri olmalı: ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Çok büyük: beklenen ${e.origin??"değer"} ${n}${e.maximum.toString()} ${r.unit??"öğe"}`:`Çok büyük: beklenen ${e.origin??"değer"} ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Çok küçük: beklenen ${e.origin} ${n}${e.minimum.toString()} ${r.unit}`:`Çok küçük: beklenen ${e.origin} ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Geçersiz metin: "${t.prefix}" ile başlamalı`:"ends_with"===t.format?`Geçersiz metin: "${t.suffix}" ile bitmeli`:"includes"===t.format?`Geçersiz metin: "${t.includes}" içermeli`:"regex"===t.format?`Geçersiz metin: ${t.pattern} desenine uymalı`:`Geçersiz ${n[t.format]??e.format}`}case"not_multiple_of":return`Geçersiz sayı: ${e.divisor} ile tam bölünebilmeli`;case"unrecognized_keys":return`Tanınmayan anahtar${e.keys.length>1?"lar":""}: ${Wt(e.keys,", ")}`;case"invalid_key":return`${e.origin} içinde geçersiz anahtar`;case"invalid_union":default:return"Geçersiz değer";case"invalid_element":return`${e.origin} içinde geçersiz değer`}}};const vs=()=>{const e={string:{unit:"символів",verb:"матиме"},file:{unit:"байтів",verb:"матиме"},array:{unit:"елементів",verb:"матиме"},set:{unit:"елементів",verb:"матиме"}};function t(t){return e[t]??null}const n={regex:"вхідні дані",email:"адреса електронної пошти",url:"URL",emoji:"емодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"дата та час ISO",date:"дата ISO",time:"час ISO",duration:"тривалість ISO",ipv4:"адреса IPv4",ipv6:"адреса IPv6",cidrv4:"діапазон IPv4",cidrv6:"діапазон IPv6",base64:"рядок у кодуванні base64",base64url:"рядок у кодуванні base64url",json_string:"рядок JSON",e164:"номер E.164",jwt:"JWT",template_literal:"вхідні дані"};return e=>{switch(e.code){case"invalid_type":return`Неправильні вхідні дані: очікується ${e.expected}, отримано ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"число";case"object":if(Array.isArray(e))return"масив";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Неправильні вхідні дані: очікується ${mn(e.values[0])}`:`Неправильна опція: очікується одне з ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Занадто велике: очікується, що ${e.origin??"значення"} ${r.verb} ${n}${e.maximum.toString()} ${r.unit??"елементів"}`:`Занадто велике: очікується, що ${e.origin??"значення"} буде ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Занадто мале: очікується, що ${e.origin} ${r.verb} ${n}${e.minimum.toString()} ${r.unit}`:`Занадто мале: очікується, що ${e.origin} буде ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Неправильний рядок: повинен починатися з "${t.prefix}"`:"ends_with"===t.format?`Неправильний рядок: повинен закінчуватися на "${t.suffix}"`:"includes"===t.format?`Неправильний рядок: повинен містити "${t.includes}"`:"regex"===t.format?`Неправильний рядок: повинен відповідати шаблону ${t.pattern}`:`Неправильний ${n[t.format]??e.format}`}case"not_multiple_of":return`Неправильне число: повинно бути кратним ${e.divisor}`;case"unrecognized_keys":return`Нерозпізнаний ключ${e.keys.length>1?"і":""}: ${Wt(e.keys,", ")}`;case"invalid_key":return`Неправильний ключ у ${e.origin}`;case"invalid_union":default:return"Неправильні вхідні дані";case"invalid_element":return`Неправильне значення у ${e.origin}`}}};const ys=()=>{const e={string:{unit:"حروف",verb:"ہونا"},file:{unit:"بائٹس",verb:"ہونا"},array:{unit:"آئٹمز",verb:"ہونا"},set:{unit:"آئٹمز",verb:"ہونا"}};function t(t){return e[t]??null}const n={regex:"ان پٹ",email:"ای میل ایڈریس",url:"یو آر ایل",emoji:"ایموجی",uuid:"یو یو آئی ڈی",uuidv4:"یو یو آئی ڈی وی 4",uuidv6:"یو یو آئی ڈی وی 6",nanoid:"نینو آئی ڈی",guid:"جی یو آئی ڈی",cuid:"سی یو آئی ڈی",cuid2:"سی یو آئی ڈی 2",ulid:"یو ایل آئی ڈی",xid:"ایکس آئی ڈی",ksuid:"کے ایس یو آئی ڈی",datetime:"آئی ایس او ڈیٹ ٹائم",date:"آئی ایس او تاریخ",time:"آئی ایس او وقت",duration:"آئی ایس او مدت",ipv4:"آئی پی وی 4 ایڈریس",ipv6:"آئی پی وی 6 ایڈریس",cidrv4:"آئی پی وی 4 رینج",cidrv6:"آئی پی وی 6 رینج",base64:"بیس 64 ان کوڈڈ سٹرنگ",base64url:"بیس 64 یو آر ایل ان کوڈڈ سٹرنگ",json_string:"جے ایس او این سٹرنگ",e164:"ای 164 نمبر",jwt:"جے ڈبلیو ٹی",template_literal:"ان پٹ"};return e=>{switch(e.code){case"invalid_type":return`غلط ان پٹ: ${e.expected} متوقع تھا، ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"نمبر";case"object":if(Array.isArray(e))return"آرے";if(null===e)return"نل";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)} موصول ہوا`;case"invalid_value":return 1===e.values.length?`غلط ان پٹ: ${mn(e.values[0])} متوقع تھا`:`غلط آپشن: ${Wt(e.values,"|")} میں سے ایک متوقع تھا`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`بہت بڑا: ${e.origin??"ویلیو"} کے ${n}${e.maximum.toString()} ${r.unit??"عناصر"} ہونے متوقع تھے`:`بہت بڑا: ${e.origin??"ویلیو"} کا ${n}${e.maximum.toString()} ہونا متوقع تھا`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`بہت چھوٹا: ${e.origin} کے ${n}${e.minimum.toString()} ${r.unit} ہونے متوقع تھے`:`بہت چھوٹا: ${e.origin} کا ${n}${e.minimum.toString()} ہونا متوقع تھا`}case"invalid_format":{const t=e;return"starts_with"===t.format?`غلط سٹرنگ: "${t.prefix}" سے شروع ہونا چاہیے`:"ends_with"===t.format?`غلط سٹرنگ: "${t.suffix}" پر ختم ہونا چاہیے`:"includes"===t.format?`غلط سٹرنگ: "${t.includes}" شامل ہونا چاہیے`:"regex"===t.format?`غلط سٹرنگ: پیٹرن ${t.pattern} سے میچ ہونا چاہیے`:`غلط ${n[t.format]??e.format}`}case"not_multiple_of":return`غلط نمبر: ${e.divisor} کا مضاعف ہونا چاہیے`;case"unrecognized_keys":return`غیر تسلیم شدہ کی${e.keys.length>1?"ز":""}: ${Wt(e.keys,"، ")}`;case"invalid_key":return`${e.origin} میں غلط کی`;case"invalid_union":default:return"غلط ان پٹ";case"invalid_element":return`${e.origin} میں غلط ویلیو`}}};const bs=()=>{const e={string:{unit:"ký tự",verb:"có"},file:{unit:"byte",verb:"có"},array:{unit:"phần tử",verb:"có"},set:{unit:"phần tử",verb:"có"}};function t(t){return e[t]??null}const n={regex:"đầu vào",email:"địa chỉ email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ngày giờ ISO",date:"ngày ISO",time:"giờ ISO",duration:"khoảng thời gian ISO",ipv4:"địa chỉ IPv4",ipv6:"địa chỉ IPv6",cidrv4:"dải IPv4",cidrv6:"dải IPv6",base64:"chuỗi mã hóa base64",base64url:"chuỗi mã hóa base64url",json_string:"chuỗi JSON",e164:"số E.164",jwt:"JWT",template_literal:"đầu vào"};return e=>{switch(e.code){case"invalid_type":return`Đầu vào không hợp lệ: mong đợi ${e.expected}, nhận được ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"số";case"object":if(Array.isArray(e))return"mảng";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Đầu vào không hợp lệ: mong đợi ${mn(e.values[0])}`:`Tùy chọn không hợp lệ: mong đợi một trong các giá trị ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Quá lớn: mong đợi ${e.origin??"giá trị"} ${r.verb} ${n}${e.maximum.toString()} ${r.unit??"phần tử"}`:`Quá lớn: mong đợi ${e.origin??"giá trị"} ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Quá nhỏ: mong đợi ${e.origin} ${r.verb} ${n}${e.minimum.toString()} ${r.unit}`:`Quá nhỏ: mong đợi ${e.origin} ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Chuỗi không hợp lệ: phải bắt đầu bằng "${t.prefix}"`:"ends_with"===t.format?`Chuỗi không hợp lệ: phải kết thúc bằng "${t.suffix}"`:"includes"===t.format?`Chuỗi không hợp lệ: phải bao gồm "${t.includes}"`:"regex"===t.format?`Chuỗi không hợp lệ: phải khớp với mẫu ${t.pattern}`:`${n[t.format]??e.format} không hợp lệ`}case"not_multiple_of":return`Số không hợp lệ: phải là bội số của ${e.divisor}`;case"unrecognized_keys":return`Khóa không được nhận dạng: ${Wt(e.keys,", ")}`;case"invalid_key":return`Khóa không hợp lệ trong ${e.origin}`;case"invalid_union":default:return"Đầu vào không hợp lệ";case"invalid_element":return`Giá trị không hợp lệ trong ${e.origin}`}}};const ks=()=>{const e={string:{unit:"字符",verb:"包含"},file:{unit:"字节",verb:"包含"},array:{unit:"项",verb:"包含"},set:{unit:"项",verb:"包含"}};function t(t){return e[t]??null}const n={regex:"输入",email:"电子邮件",url:"URL",emoji:"表情符号",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日期时间",date:"ISO日期",time:"ISO时间",duration:"ISO时长",ipv4:"IPv4地址",ipv6:"IPv6地址",cidrv4:"IPv4网段",cidrv6:"IPv6网段",base64:"base64编码字符串",base64url:"base64url编码字符串",json_string:"JSON字符串",e164:"E.164号码",jwt:"JWT",template_literal:"输入"};return e=>{switch(e.code){case"invalid_type":return`无效输入:期望 ${e.expected},实际接收 ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"非数字(NaN)":"数字";case"object":if(Array.isArray(e))return"数组";if(null===e)return"空值(null)";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`无效输入:期望 ${mn(e.values[0])}`:`无效选项:期望以下之一 ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`数值过大:期望 ${e.origin??"值"} ${n}${e.maximum.toString()} ${r.unit??"个元素"}`:`数值过大:期望 ${e.origin??"值"} ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`数值过小:期望 ${e.origin} ${n}${e.minimum.toString()} ${r.unit}`:`数值过小:期望 ${e.origin} ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`无效字符串:必须以 "${t.prefix}" 开头`:"ends_with"===t.format?`无效字符串:必须以 "${t.suffix}" 结尾`:"includes"===t.format?`无效字符串:必须包含 "${t.includes}"`:"regex"===t.format?`无效字符串:必须满足正则表达式 ${t.pattern}`:`无效${n[t.format]??e.format}`}case"not_multiple_of":return`无效数字:必须是 ${e.divisor} 的倍数`;case"unrecognized_keys":return`出现未知的键(key): ${Wt(e.keys,", ")}`;case"invalid_key":return`${e.origin} 中的键(key)无效`;case"invalid_union":default:return"无效输入";case"invalid_element":return`${e.origin} 中包含无效值(value)`}}};const ws=()=>{const e={string:{unit:"字元",verb:"擁有"},file:{unit:"位元組",verb:"擁有"},array:{unit:"項目",verb:"擁有"},set:{unit:"項目",verb:"擁有"}};function t(t){return e[t]??null}const n={regex:"輸入",email:"郵件地址",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 日期時間",date:"ISO 日期",time:"ISO 時間",duration:"ISO 期間",ipv4:"IPv4 位址",ipv6:"IPv6 位址",cidrv4:"IPv4 範圍",cidrv6:"IPv6 範圍",base64:"base64 編碼字串",base64url:"base64url 編碼字串",json_string:"JSON 字串",e164:"E.164 數值",jwt:"JWT",template_literal:"輸入"};return e=>{switch(e.code){case"invalid_type":return`無效的輸入值:預期為 ${e.expected},但收到 ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`無效的輸入值:預期為 ${mn(e.values[0])}`:`無效的選項:預期為以下其中之一 ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`數值過大:預期 ${e.origin??"值"} 應為 ${n}${e.maximum.toString()} ${r.unit??"個元素"}`:`數值過大:預期 ${e.origin??"值"} 應為 ${n}${e.maximum.toString()}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`數值過小:預期 ${e.origin} 應為 ${n}${e.minimum.toString()} ${r.unit}`:`數值過小:預期 ${e.origin} 應為 ${n}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`無效的字串:必須以 "${t.prefix}" 開頭`:"ends_with"===t.format?`無效的字串:必須以 "${t.suffix}" 結尾`:"includes"===t.format?`無效的字串:必須包含 "${t.includes}"`:"regex"===t.format?`無效的字串:必須符合格式 ${t.pattern}`:`無效的 ${n[t.format]??e.format}`}case"not_multiple_of":return`無效的數字:必須為 ${e.divisor} 的倍數`;case"unrecognized_keys":return`無法識別的鍵值${e.keys.length>1?"們":""}:${Wt(e.keys,"、")}`;case"invalid_key":return`${e.origin} 中有無效的鍵值`;case"invalid_union":default:return"無效的輸入值";case"invalid_element":return`${e.origin} 中有無效的值`}}};const xs=()=>{const e={string:{unit:"àmi",verb:"ní"},file:{unit:"bytes",verb:"ní"},array:{unit:"nkan",verb:"ní"},set:{unit:"nkan",verb:"ní"}};function t(t){return e[t]??null}const n={regex:"ẹ̀rọ ìbáwọlé",email:"àdírẹ́sì ìmẹ́lì",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"àkókò ISO",date:"ọjọ́ ISO",time:"àkókò ISO",duration:"àkókò tó pé ISO",ipv4:"àdírẹ́sì IPv4",ipv6:"àdírẹ́sì IPv6",cidrv4:"àgbègbè IPv4",cidrv6:"àgbègbè IPv6",base64:"ọ̀rọ̀ tí a kọ́ ní base64",base64url:"ọ̀rọ̀ base64url",json_string:"ọ̀rọ̀ JSON",e164:"nọ́mbà E.164",jwt:"JWT",template_literal:"ẹ̀rọ ìbáwọlé"};return e=>{switch(e.code){case"invalid_type":return`Ìbáwọlé aṣìṣe: a ní láti fi ${e.expected}, àmọ̀ a rí ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"nọ́mbà";case"object":if(Array.isArray(e))return"akopọ";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Ìbáwọlé aṣìṣe: a ní láti fi ${mn(e.values[0])}`:`Àṣàyàn aṣìṣe: yan ọ̀kan lára ${Wt(e.values,"|")}`;case"too_big":{const n=e.inclusive?"<=":"<",r=t(e.origin);return r?`Tó pọ̀ jù: a ní láti jẹ́ pé ${e.origin??"iye"} ${r.verb} ${n}${e.maximum} ${r.unit}`:`Tó pọ̀ jù: a ní láti jẹ́ ${n}${e.maximum}`}case"too_small":{const n=e.inclusive?">=":">",r=t(e.origin);return r?`Kéré ju: a ní láti jẹ́ pé ${e.origin} ${r.verb} ${n}${e.minimum} ${r.unit}`:`Kéré ju: a ní láti jẹ́ ${n}${e.minimum}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bẹ̀rẹ̀ pẹ̀lú "${t.prefix}"`:"ends_with"===t.format?`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ parí pẹ̀lú "${t.suffix}"`:"includes"===t.format?`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ ní "${t.includes}"`:"regex"===t.format?`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bá àpẹẹrẹ mu ${t.pattern}`:`Aṣìṣe: ${n[t.format]??e.format}`}case"not_multiple_of":return`Nọ́mbà aṣìṣe: gbọ́dọ̀ jẹ́ èyà pípín ti ${e.divisor}`;case"unrecognized_keys":return`Bọtìnì àìmọ̀: ${Wt(e.keys,", ")}`;case"invalid_key":return`Bọtìnì aṣìṣe nínú ${e.origin}`;case"invalid_union":default:return"Ìbáwọlé aṣìṣe";case"invalid_element":return`Iye aṣìṣe nínú ${e.origin}`}}};const Is=Object.freeze(Object.defineProperty({__proto__:null,ar:function(){return{localeError:Ci()}},az:function(){return{localeError:Pi()}},be:function(){return{localeError:ji()}},ca:function(){return{localeError:zi()}},cs:function(){return{localeError:Di()}},da:function(){return{localeError:Mi()}},de:function(){return{localeError:Li()}},en:Zi,eo:function(){return{localeError:Fi()}},es:function(){return{localeError:Wi()}},fa:function(){return{localeError:Ji()}},fi:function(){return{localeError:Bi()}},fr:function(){return{localeError:Hi()}},frCA:function(){return{localeError:Vi()}},he:function(){return{localeError:Gi()}},hu:function(){return{localeError:Ki()}},id:function(){return{localeError:Yi()}},is:function(){return{localeError:Xi()}},it:function(){return{localeError:Qi()}},ja:function(){return{localeError:es()}},kh:function(){return{localeError:ts()}},ko:function(){return{localeError:ns()}},mk:function(){return{localeError:rs()}},ms:function(){return{localeError:os()}},nl:function(){return{localeError:is()}},no:function(){return{localeError:ss()}},ota:function(){return{localeError:as()}},pl:function(){return{localeError:ls()}},ps:function(){return{localeError:us()}},pt:function(){return{localeError:cs()}},ru:function(){return{localeError:ps()}},sl:function(){return{localeError:ms()}},sv:function(){return{localeError:_s()}},ta:function(){return{localeError:hs()}},th:function(){return{localeError:gs()}},tr:function(){return{localeError:fs()}},ua:function(){return{localeError:vs()}},ur:function(){return{localeError:ys()}},vi:function(){return{localeError:bs()}},yo:function(){return{localeError:xs()}},zhCN:function(){return{localeError:ks()}},zhTW:function(){return{localeError:ws()}}},Symbol.toStringTag,{value:"Module"})),Ss=Symbol("ZodOutput"),$s=Symbol("ZodInput");class Os{constructor(){this._map=new Map,this._idmap=new Map}add(e,...t){const n=t[0];if(this._map.set(e,n),n&&"object"==typeof n&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const n={...this.get(t)??{}};delete n.id;const r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function Es(){return new Os}const Ts=Es();function Rs(e,t){return new e({type:"string",...pn(t)})}function Ns(e,t){return new e({type:"string",coerce:!0,...pn(t)})}function As(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...pn(t)})}function Cs(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...pn(t)})}function Ps(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...pn(t)})}function Us(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...pn(t)})}function js(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...pn(t)})}function zs(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...pn(t)})}function Ds(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...pn(t)})}function Ms(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...pn(t)})}function Ls(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...pn(t)})}function qs(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...pn(t)})}function Zs(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...pn(t)})}function Fs(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...pn(t)})}function Ws(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...pn(t)})}function Js(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...pn(t)})}function Bs(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...pn(t)})}function Hs(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...pn(t)})}function Vs(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...pn(t)})}function Gs(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...pn(t)})}function Ks(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...pn(t)})}function Ys(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...pn(t)})}function Xs(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...pn(t)})}function Qs(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...pn(t)})}const ea={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function ta(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...pn(t)})}function na(e,t){return new e({type:"string",format:"date",check:"string_format",...pn(t)})}function ra(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...pn(t)})}function oa(e,t){return new e({type:"string",format:"duration",check:"string_format",...pn(t)})}function ia(e,t){return new e({type:"number",checks:[],...pn(t)})}function sa(e,t){return new e({type:"number",coerce:!0,checks:[],...pn(t)})}function aa(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...pn(t)})}function ua(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...pn(t)})}function la(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...pn(t)})}function ca(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...pn(t)})}function da(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...pn(t)})}function pa(e,t){return new e({type:"boolean",...pn(t)})}function ma(e,t){return new e({type:"boolean",coerce:!0,...pn(t)})}function _a(e,t){return new e({type:"bigint",...pn(t)})}function ha(e,t){return new e({type:"bigint",coerce:!0,...pn(t)})}function ga(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...pn(t)})}function fa(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...pn(t)})}function va(e,t){return new e({type:"symbol",...pn(t)})}function ya(e,t){return new e({type:"undefined",...pn(t)})}function ba(e,t){return new e({type:"null",...pn(t)})}function ka(e){return new e({type:"any"})}function wa(e){return new e({type:"unknown"})}function xa(e,t){return new e({type:"never",...pn(t)})}function Ia(e,t){return new e({type:"void",...pn(t)})}function Sa(e,t){return new e({type:"date",...pn(t)})}function $a(e,t){return new e({type:"date",coerce:!0,...pn(t)})}function Oa(e,t){return new e({type:"nan",...pn(t)})}function Ea(e,t){return new Ar({check:"less_than",...pn(t),value:e,inclusive:!1})}function Ta(e,t){return new Ar({check:"less_than",...pn(t),value:e,inclusive:!0})}function Ra(e,t){return new Cr({check:"greater_than",...pn(t),value:e,inclusive:!1})}function Na(e,t){return new Cr({check:"greater_than",...pn(t),value:e,inclusive:!0})}function Aa(e){return Ra(0,e)}function Ca(e){return Ea(0,e)}function Pa(e){return Ta(0,e)}function Ua(e){return Na(0,e)}function ja(e,t){return new Pr({check:"multiple_of",...pn(t),value:e})}function za(e,t){return new zr({check:"max_size",...pn(t),maximum:e})}function Da(e,t){return new Dr({check:"min_size",...pn(t),minimum:e})}function Ma(e,t){return new Mr({check:"size_equals",...pn(t),size:e})}function La(e,t){return new Lr({check:"max_length",...pn(t),maximum:e})}function qa(e,t){return new qr({check:"min_length",...pn(t),minimum:e})}function Za(e,t){return new Zr({check:"length_equals",...pn(t),length:e})}function Fa(e,t){return new Wr({check:"string_format",format:"regex",...pn(t),pattern:e})}function Wa(e){return new Jr({check:"string_format",format:"lowercase",...pn(e)})}function Ja(e){return new Br({check:"string_format",format:"uppercase",...pn(e)})}function Ba(e,t){return new Hr({check:"string_format",format:"includes",...pn(t),includes:e})}function Ha(e,t){return new Vr({check:"string_format",format:"starts_with",...pn(t),prefix:e})}function Va(e,t){return new Gr({check:"string_format",format:"ends_with",...pn(t),suffix:e})}function Ga(e,t,n){return new Yr({check:"property",property:e,schema:t,...pn(n)})}function Ka(e,t){return new Xr({check:"mime_type",mime:e,...pn(t)})}function Ya(e){return new Qr({check:"overwrite",tx:e})}function Xa(e){return Ya((t=>t.normalize(e)))}function Qa(){return Ya((e=>e.trim()))}function eu(){return Ya((e=>e.toLowerCase()))}function tu(){return Ya((e=>e.toUpperCase()))}function nu(e,t,n){return new e({type:"array",element:t,...pn(n)})}function ru(e,t,n,r){const o=n instanceof no;return new e({type:"tuple",items:t,rest:o?n:null,...pn(o?r:n)})}function ou(e,t){return new e({type:"file",...pn(t)})}function iu(e,t,n){const r=pn(n);r.abort??(r.abort=!0);return new e({type:"custom",check:"custom",fn:t,...r})}function su(e,t,n){return new e({type:"custom",check:"custom",fn:t,...pn(n)})}function au(e){const t=uu((n=>(n.addIssue=e=>{if("string"==typeof e)n.issues.push(Tn(e,n.value,t._zod.def));else{const r=e;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=n.value),r.inst??(r.inst=t),r.continue??(r.continue=!t._zod.def.abort),n.issues.push(Tn(r))}},e(n.value,n))));return t}function uu(e,t){const n=new Rr({check:"custom",...pn(t)});return n._zod.check=e,n}function lu(e,t){const n=pn(t);let r=n.truthy??["true","1","yes","on","y","enabled"],o=n.falsy??["false","0","no","off","n","disabled"];"sensitive"!==n.case&&(r=r.map((e=>"string"==typeof e?e.toLowerCase():e)),o=o.map((e=>"string"==typeof e?e.toLowerCase():e)));const i=new Set(r),s=new Set(o),a=e.Pipe??Ii,u=e.Boolean??Uo,l=e.String??ro,c=new(e.Transform??pi)({type:"transform",transform:(e,t)=>{let r=e;return"sensitive"!==n.case&&(r=r.toLowerCase()),!!i.has(r)||!s.has(r)&&(t.issues.push({code:"invalid_value",expected:"stringbool",values:[...i,...s],input:t.value,inst:c,continue:!1}),{})},error:n.error}),d=new a({type:"pipe",in:new l({type:"string",error:n.error}),out:c,error:n.error});return new a({type:"pipe",in:d,out:new u({type:"boolean",error:n.error}),error:n.error})}function cu(e,t,n,r={}){const o=pn(r),i={...pn(r),check:"string_format",type:"string",format:t,fn:"function"==typeof n?n:e=>n.test(e),...o};n instanceof RegExp&&(i.pattern=n);return new e(i)}class du{constructor(e){this._def=e,this.def=e}implement(e){if("function"!=typeof e)throw new Error("implement() must be called with a function");const t=(...n)=>{const r=this._def.input?Ln(this._def.input,n,void 0,{callee:t}):n;if(!Array.isArray(r))throw new Error("Invalid arguments schema: not an array or tuple schema.");const o=e(...r);return this._def.output?Ln(this._def.output,o,void 0,{callee:t}):o};return t}implementAsync(e){if("function"!=typeof e)throw new Error("implement() must be called with a function");const t=async(...n)=>{const r=this._def.input?await Zn(this._def.input,n,void 0,{callee:t}):n;if(!Array.isArray(r))throw new Error("Invalid arguments schema: not an array or tuple schema.");const o=await e(...r);return this._def.output?Zn(this._def.output,o,void 0,{callee:t}):o};return t}input(...e){const t=this.constructor;return Array.isArray(e[0])?new t({type:"function",input:new ni({type:"tuple",items:e[0],rest:e[1]}),output:this._def.output}):new t({type:"function",input:e[0],output:this._def.output})}output(e){return new(0,this.constructor)({type:"function",input:this._def.input,output:e})}}function pu(e){return new du({type:"function",input:Array.isArray(null==e?void 0:e.input)?ru(ni,null==e?void 0:e.input):(null==e?void 0:e.input)??nu(Ho,wa(Zo)),output:(null==e?void 0:e.output)??wa(Zo)})}class mu{constructor(e){this.counter=0,this.metadataRegistry=(null==e?void 0:e.metadata)??Ts,this.target=(null==e?void 0:e.target)??"draft-2020-12",this.unrepresentable=(null==e?void 0:e.unrepresentable)??"throw",this.override=(null==e?void 0:e.override)??(()=>{}),this.io=(null==e?void 0:e.io)??"output",this.seen=new Map}process(e,t={path:[],schemaPath:[]}){var n,r,o,i;const s=e._zod.def,a={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},u=this.seen.get(e);if(u){u.count++;return t.schemaPath.includes(e)&&(u.cycle=t.path),u.schema}const l={schema:{},count:1,cycle:void 0,path:t.path};this.seen.set(e,l);const c=null==(r=(n=e._zod).toJSONSchema)?void 0:r.call(n);if(c)l.schema=c;else{const n={...t,schemaPath:[...t.schemaPath,e],path:t.path},r=e._zod.parent;if(r)l.ref=r,this.process(r,n),this.seen.get(r).isParent=!0;else{const t=l.schema;switch(s.type){case"string":{const n=t;n.type="string";const{minimum:r,maximum:o,format:i,patterns:s,contentEncoding:u}=e._zod.bag;if("number"==typeof r&&(n.minLength=r),"number"==typeof o&&(n.maxLength=o),i&&(n.format=a[i]??i,""===n.format&&delete n.format),u&&(n.contentEncoding=u),s&&s.size>0){const e=[...s];1===e.length?n.pattern=e[0].source:e.length>1&&(l.schema.allOf=[...e.map((e=>({..."draft-7"===this.target||"draft-4"===this.target?{type:"string"}:{},pattern:e.source})))])}break}case"number":{const n=t,{minimum:r,maximum:o,format:i,multipleOf:s,exclusiveMaximum:a,exclusiveMinimum:u}=e._zod.bag;"string"==typeof i&&i.includes("int")?n.type="integer":n.type="number","number"==typeof u&&("draft-4"===this.target?(n.minimum=u,n.exclusiveMinimum=!0):n.exclusiveMinimum=u),"number"==typeof r&&(n.minimum=r,"number"==typeof u&&"draft-4"!==this.target&&(u>=r?delete n.minimum:delete n.exclusiveMinimum)),"number"==typeof a&&("draft-4"===this.target?(n.maximum=a,n.exclusiveMaximum=!0):n.exclusiveMaximum=a),"number"==typeof o&&(n.maximum=o,"number"==typeof a&&"draft-4"!==this.target&&(a<=o?delete n.maximum:delete n.exclusiveMaximum)),"number"==typeof s&&(n.multipleOf=s);break}case"boolean":t.type="boolean";break;case"bigint":if("throw"===this.unrepresentable)throw new Error("BigInt cannot be represented in JSON Schema");break;case"symbol":if("throw"===this.unrepresentable)throw new Error("Symbols cannot be represented in JSON Schema");break;case"null":t.type="null";break;case"any":case"unknown":break;case"undefined":if("throw"===this.unrepresentable)throw new Error("Undefined cannot be represented in JSON Schema");break;case"void":if("throw"===this.unrepresentable)throw new Error("Void cannot be represented in JSON Schema");break;case"never":t.not={};break;case"date":if("throw"===this.unrepresentable)throw new Error("Date cannot be represented in JSON Schema");break;case"array":{const r=t,{minimum:o,maximum:i}=e._zod.bag;"number"==typeof o&&(r.minItems=o),"number"==typeof i&&(r.maxItems=i),r.type="array",r.items=this.process(s.element,{...n,path:[...n.path,"items"]});break}case"object":{const e=t;e.type="object",e.properties={};const r=s.shape;for(const t in r)e.properties[t]=this.process(r[t],{...n,path:[...n.path,"properties",t]});const i=new Set(Object.keys(r)),a=new Set([...i].filter((e=>{const t=s.shape[e]._zod;return"input"===this.io?void 0===t.optin:void 0===t.optout})));a.size>0&&(e.required=Array.from(a)),"never"===(null==(o=s.catchall)?void 0:o._zod.def.type)?e.additionalProperties=!1:s.catchall?s.catchall&&(e.additionalProperties=this.process(s.catchall,{...n,path:[...n.path,"additionalProperties"]})):"output"===this.io&&(e.additionalProperties=!1);break}case"union":t.anyOf=s.options.map(((e,t)=>this.process(e,{...n,path:[...n.path,"anyOf",t]})));break;case"intersection":{const e=t,r=this.process(s.left,{...n,path:[...n.path,"allOf",0]}),o=this.process(s.right,{...n,path:[...n.path,"allOf",1]}),i=e=>"allOf"in e&&1===Object.keys(e).length,a=[...i(r)?r.allOf:[r],...i(o)?o.allOf:[o]];e.allOf=a;break}case"tuple":{const r=t;r.type="array";const o=s.items.map(((e,t)=>this.process(e,{...n,path:[...n.path,"prefixItems",t]})));if("draft-2020-12"===this.target?r.prefixItems=o:r.items=o,s.rest){const e=this.process(s.rest,{...n,path:[...n.path,"items"]});"draft-2020-12"===this.target?r.items=e:r.additionalItems=e}s.rest&&(r.items=this.process(s.rest,{...n,path:[...n.path,"items"]}));const{minimum:i,maximum:a}=e._zod.bag;"number"==typeof i&&(r.minItems=i),"number"==typeof a&&(r.maxItems=a);break}case"record":{const e=t;e.type="object","draft-4"!==this.target&&(e.propertyNames=this.process(s.keyType,{...n,path:[...n.path,"propertyNames"]})),e.additionalProperties=this.process(s.valueType,{...n,path:[...n.path,"additionalProperties"]});break}case"map":if("throw"===this.unrepresentable)throw new Error("Map cannot be represented in JSON Schema");break;case"set":if("throw"===this.unrepresentable)throw new Error("Set cannot be represented in JSON Schema");break;case"enum":{const e=t,n=Ft(s.entries);n.every((e=>"number"==typeof e))&&(e.type="number"),n.every((e=>"string"==typeof e))&&(e.type="string"),e.enum=n;break}case"literal":{const e=t,n=[];for(const t of s.values)if(void 0===t){if("throw"===this.unrepresentable)throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if("bigint"==typeof t){if("throw"===this.unrepresentable)throw new Error("BigInt literals cannot be represented in JSON Schema");n.push(Number(t))}else n.push(t);if(0===n.length);else if(1===n.length){const t=n[0];e.type=null===t?"null":typeof t,"draft-4"===this.target?e.enum=[t]:e.const=t}else n.every((e=>"number"==typeof e))&&(e.type="number"),n.every((e=>"string"==typeof e))&&(e.type="string"),n.every((e=>"boolean"==typeof e))&&(e.type="string"),n.every((e=>null===e))&&(e.type="null"),e.enum=n;break}case"file":{const n=t,r={type:"string",format:"binary",contentEncoding:"binary"},{minimum:o,maximum:i,mime:s}=e._zod.bag;void 0!==o&&(r.minLength=o),void 0!==i&&(r.maxLength=i),s?1===s.length?(r.contentMediaType=s[0],Object.assign(n,r)):n.anyOf=s.map((e=>({...r,contentMediaType:e}))):Object.assign(n,r);break}case"transform":if("throw"===this.unrepresentable)throw new Error("Transforms cannot be represented in JSON Schema");break;case"nullable":{const e=this.process(s.innerType,n);t.anyOf=[e,{type:"null"}];break}case"nonoptional":case"promise":case"optional":this.process(s.innerType,n),l.ref=s.innerType;break;case"success":t.type="boolean";break;case"default":this.process(s.innerType,n),l.ref=s.innerType,t.default=JSON.parse(JSON.stringify(s.defaultValue));break;case"prefault":this.process(s.innerType,n),l.ref=s.innerType,"input"===this.io&&(t._prefault=JSON.parse(JSON.stringify(s.defaultValue)));break;case"catch":{let e;this.process(s.innerType,n),l.ref=s.innerType;try{e=s.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}t.default=e;break}case"nan":if("throw"===this.unrepresentable)throw new Error("NaN cannot be represented in JSON Schema");break;case"template_literal":{const n=t,r=e._zod.pattern;if(!r)throw new Error("Pattern not found in template literal");n.type="string",n.pattern=r.source;break}case"pipe":{const e="input"===this.io?"transform"===s.in._zod.def.type?s.out:s.in:s.out;this.process(e,n),l.ref=e;break}case"readonly":this.process(s.innerType,n),l.ref=s.innerType,t.readOnly=!0;break;case"lazy":{const t=e._zod.innerType;this.process(t,n),l.ref=t;break}case"custom":if("throw"===this.unrepresentable)throw new Error("Custom types cannot be represented in JSON Schema")}}}const d=this.metadataRegistry.get(e);d&&Object.assign(l.schema,d),"input"===this.io&&hu(e)&&(delete l.schema.examples,delete l.schema.default),"input"===this.io&&l.schema._prefault&&((i=l.schema).default??(i.default=l.schema._prefault)),delete l.schema._prefault;return this.seen.get(e).schema}emit(e,t){var n,r,o,i,s,a;const u={cycles:(null==t?void 0:t.cycles)??"ref",reused:(null==t?void 0:t.reused)??"inline",external:(null==t?void 0:t.external)??void 0},l=this.seen.get(e);if(!l)throw new Error("Unprocessed schema. This is a bug in Zod.");const c=e=>{var t;const n="draft-2020-12"===this.target?"$defs":"definitions";if(u.external){const r=null==(t=u.external.registry.get(e[0]))?void 0:t.id,o=u.external.uri??(e=>e);if(r)return{ref:o(r)};const i=e[1].defId??e[1].schema.id??"schema"+this.counter++;return e[1].defId=i,{defId:i,ref:`${o("__shared")}#/${n}/${i}`}}if(e[1]===l)return{ref:"#"};const r=`#/${n}/`,o=e[1].schema.id??"__schema"+this.counter++;return{defId:o,ref:r+o}},d=e=>{if(e[1].schema.$ref)return;const t=e[1],{ref:n,defId:r}=c(e);t.def={...t.schema},r&&(t.defId=r);const o=t.schema;for(const i in o)delete o[i];o.$ref=n};if("throw"===u.cycles)for(const g of this.seen.entries()){const e=g[1];if(e.cycle)throw new Error(`Cycle detected: #/${null==(n=e.cycle)?void 0:n.join("/")}/<root>\n\nSet the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const g of this.seen.entries()){const t=g[1];if(e===g[0]){d(g);continue}if(u.external){const t=null==(r=u.external.registry.get(g[0]))?void 0:r.id;if(e!==g[0]&&t){d(g);continue}}(null==(o=this.metadataRegistry.get(g[0]))?void 0:o.id)?d(g):(t.cycle||t.count>1&&"ref"===u.reused)&&d(g)}const p=(e,t)=>{const n=this.seen.get(e),r=n.def??n.schema,o={...r};if(null===n.ref)return;const i=n.ref;if(n.ref=null,i){p(i,t);const e=this.seen.get(i).schema;!e.$ref||"draft-7"!==t.target&&"draft-4"!==t.target?(Object.assign(r,e),Object.assign(r,o)):(r.allOf=r.allOf??[],r.allOf.push(e))}n.isParent||this.override({zodSchema:e,jsonSchema:r,path:n.path??[]})};for(const g of[...this.seen.entries()].reverse())p(g[0],{target:this.target});const m={};if("draft-2020-12"===this.target?m.$schema="https://json-schema.org/draft/2020-12/schema":"draft-7"===this.target?m.$schema="http://json-schema.org/draft-07/schema#":"draft-4"===this.target?m.$schema="http://json-schema.org/draft-04/schema#":console.warn(`Invalid target: ${this.target}`),null==(i=u.external)?void 0:i.uri){const t=null==(s=u.external.registry.get(e))?void 0:s.id;if(!t)throw new Error("Schema is missing an `id` property");m.$id=u.external.uri(t)}Object.assign(m,l.def);const _=(null==(a=u.external)?void 0:a.defs)??{};for(const g of this.seen.entries()){const e=g[1];e.def&&e.defId&&(_[e.defId]=e.def)}u.external||Object.keys(_).length>0&&("draft-2020-12"===this.target?m.$defs=_:m.definitions=_);try{return JSON.parse(JSON.stringify(m))}catch(h){throw new Error("Error converting schema to JSON.")}}}function _u(e,t){if(e instanceof Os){const n=new mu(t),r={};for(const t of e._idmap.entries()){const[e,r]=t;n.process(r)}const o={},i={registry:e,uri:null==t?void 0:t.uri,defs:r};for(const s of e._idmap.entries()){const[e,r]=s;o[e]=n.emit(r,{...t,external:i})}if(Object.keys(r).length>0){const e="draft-2020-12"===n.target?"$defs":"definitions";o.__shared={[e]:r}}return{schemas:o}}const n=new mu(t);return n.process(e),n.emit(e,t)}function hu(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;switch(r.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":case"custom":case"success":case"catch":return!1;case"array":return hu(r.element,n);case"object":for(const e in r.shape)if(hu(r.shape[e],n))return!0;return!1;case"union":for(const e of r.options)if(hu(e,n))return!0;return!1;case"intersection":return hu(r.left,n)||hu(r.right,n);case"tuple":for(const e of r.items)if(hu(e,n))return!0;return!(!r.rest||!hu(r.rest,n));case"record":case"map":return hu(r.keyType,n)||hu(r.valueType,n);case"set":return hu(r.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":case"default":case"prefault":return hu(r.innerType,n);case"lazy":return hu(r.getter(),n);case"transform":return!0;case"pipe":return hu(r.in,n)||hu(r.out,n)}throw new Error(`Unknown schema type: ${r.type}`)}const gu=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"})),fu=Object.freeze(Object.defineProperty({__proto__:null,$ZodAny:qo,$ZodArray:Ho,$ZodAsyncError:Lt,$ZodBase64:$o,$ZodBase64URL:Eo,$ZodBigInt:jo,$ZodBigIntFormat:zo,$ZodBoolean:Uo,$ZodCIDRv4:xo,$ZodCIDRv6:Io,$ZodCUID:po,$ZodCUID2:mo,$ZodCatch:wi,$ZodCheck:Rr,$ZodCheckBigIntFormat:jr,$ZodCheckEndsWith:Gr,$ZodCheckGreaterThan:Cr,$ZodCheckIncludes:Hr,$ZodCheckLengthEquals:Zr,$ZodCheckLessThan:Ar,$ZodCheckLowerCase:Jr,$ZodCheckMaxLength:Lr,$ZodCheckMaxSize:zr,$ZodCheckMimeType:Xr,$ZodCheckMinLength:qr,$ZodCheckMinSize:Dr,$ZodCheckMultipleOf:Pr,$ZodCheckNumberFormat:Ur,$ZodCheckOverwrite:Qr,$ZodCheckProperty:Yr,$ZodCheckRegex:Wr,$ZodCheckSizeEquals:Mr,$ZodCheckStartsWith:Vr,$ZodCheckStringFormat:Fr,$ZodCheckUpperCase:Br,$ZodCustom:Ni,$ZodCustomStringFormat:Ao,$ZodDate:Jo,$ZodDefault:gi,$ZodDiscriminatedUnion:Xo,$ZodE164:To,$ZodEmail:ao,$ZodEmoji:lo,$ZodEnum:li,$ZodError:An,$ZodFile:di,$ZodFunction:du,$ZodGUID:io,$ZodIPv4:ko,$ZodIPv6:wo,$ZodISODate:vo,$ZodISODateTime:fo,$ZodISODuration:bo,$ZodISOTime:yo,$ZodIntersection:Qo,$ZodJWT:No,$ZodKSUID:go,$ZodLazy:Ri,$ZodLiteral:ci,$ZodMap:ii,$ZodNaN:xi,$ZodNanoID:co,$ZodNever:Fo,$ZodNonOptional:yi,$ZodNull:Lo,$ZodNullable:hi,$ZodNumber:Co,$ZodNumberFormat:Po,$ZodObject:Go,$ZodOptional:_i,$ZodPipe:Ii,$ZodPrefault:vi,$ZodPromise:Ti,$ZodReadonly:$i,$ZodRealError:Cn,$ZodRecord:oi,$ZodRegistry:Os,$ZodSet:ai,$ZodString:ro,$ZodStringFormat:oo,$ZodSuccess:ki,$ZodSymbol:Do,$ZodTemplateLiteral:Ei,$ZodTransform:pi,$ZodTuple:ni,$ZodType:no,$ZodULID:_o,$ZodURL:uo,$ZodUUID:so,$ZodUndefined:Mo,$ZodUnion:Yo,$ZodUnknown:Zo,$ZodVoid:Wo,$ZodXID:ho,$brand:Mt,$constructor:Dt,$input:$s,$output:Ss,Doc:eo,JSONSchema:gu,JSONSchemaGenerator:mu,NEVER:zt,TimePrecision:ea,_any:ka,_array:nu,_base64:Ks,_base64url:Ys,_bigint:_a,_boolean:pa,_catch:function(e,t,n){return new e({type:"catch",innerType:t,catchValue:"function"==typeof n?n:()=>n})},_check:uu,_cidrv4:Vs,_cidrv6:Gs,_coercedBigint:ha,_coercedBoolean:ma,_coercedDate:$a,_coercedNumber:sa,_coercedString:Ns,_cuid:qs,_cuid2:Zs,_custom:iu,_date:Sa,_default:function(e,t,n){return new e({type:"default",innerType:t,get defaultValue(){return"function"==typeof n?n():an(n)}})},_discriminatedUnion:function(e,t,n,r){return new e({type:"union",options:n,discriminator:t,...pn(r)})},_e164:Xs,_email:As,_emoji:Ms,_endsWith:Va,_enum:function(e,t,n){return new e({type:"enum",entries:Array.isArray(t)?Object.fromEntries(t.map((e=>[e,e]))):t,...pn(n)})},_file:ou,_float32:ua,_float64:la,_gt:Ra,_gte:Na,_guid:Cs,_includes:Ba,_int:aa,_int32:ca,_int64:ga,_intersection:function(e,t,n){return new e({type:"intersection",left:t,right:n})},_ipv4:Bs,_ipv6:Hs,_isoDate:na,_isoDateTime:ta,_isoDuration:oa,_isoTime:ra,_jwt:Qs,_ksuid:Js,_lazy:function(e,t){return new e({type:"lazy",getter:t})},_length:Za,_literal:function(e,t,n){return new e({type:"literal",values:Array.isArray(t)?t:[t],...pn(n)})},_lowercase:Wa,_lt:Ea,_lte:Ta,_map:function(e,t,n,r){return new e({type:"map",keyType:t,valueType:n,...pn(r)})},_max:Ta,_maxLength:La,_maxSize:za,_mime:Ka,_min:Na,_minLength:qa,_minSize:Da,_multipleOf:ja,_nan:Oa,_nanoid:Ls,_nativeEnum:function(e,t,n){return new e({type:"enum",entries:t,...pn(n)})},_negative:Ca,_never:xa,_nonnegative:Ua,_nonoptional:function(e,t,n){return new e({type:"nonoptional",innerType:t,...pn(n)})},_nonpositive:Pa,_normalize:Xa,_null:ba,_nullable:function(e,t){return new e({type:"nullable",innerType:t})},_number:ia,_optional:function(e,t){return new e({type:"optional",innerType:t})},_overwrite:Ya,_parse:Mn,_parseAsync:qn,_pipe:function(e,t,n){return new e({type:"pipe",in:t,out:n})},_positive:Aa,_promise:function(e,t){return new e({type:"promise",innerType:t})},_property:Ga,_readonly:function(e,t){return new e({type:"readonly",innerType:t})},_record:function(e,t,n,r){return new e({type:"record",keyType:t,valueType:n,...pn(r)})},_refine:su,_regex:Fa,_safeParse:Fn,_safeParseAsync:Jn,_set:function(e,t,n){return new e({type:"set",valueType:t,...pn(n)})},_size:Ma,_startsWith:Ha,_string:Rs,_stringFormat:cu,_stringbool:lu,_success:function(e,t){return new e({type:"success",innerType:t})},_superRefine:au,_symbol:va,_templateLiteral:function(e,t,n){return new e({type:"template_literal",parts:t,...pn(n)})},_toLowerCase:eu,_toUpperCase:tu,_transform:function(e,t){return new e({type:"transform",transform:t})},_trim:Qa,_tuple:ru,_uint32:da,_uint64:fa,_ulid:Fs,_undefined:ya,_union:function(e,t,n){return new e({type:"union",options:t,...pn(n)})},_unknown:wa,_uppercase:Ja,_url:Ds,_uuid:Ps,_uuidv4:Us,_uuidv6:js,_uuidv7:zs,_void:Ia,_xid:Ws,clone:dn,config:Zt,flattenError:Pn,formatError:Un,function:pu,globalConfig:qt,globalRegistry:Ts,isValidBase64:So,isValidBase64URL:Oo,isValidJWT:Ro,locales:Is,parse:Ln,parseAsync:Zn,prettifyError:Dn,regexes:Tr,registry:Es,safeParse:Wn,safeParseAsync:Bn,toDotPath:zn,toJSONSchema:_u,treeifyError:jn,util:Rn,version:to},Symbol.toStringTag,{value:"Module"})),vu=Dt("ZodISODateTime",((e,t)=>{fo.init(e,t),Du.init(e,t)}));function yu(e){return ta(vu,e)}const bu=Dt("ZodISODate",((e,t)=>{vo.init(e,t),Du.init(e,t)}));function ku(e){return na(bu,e)}const wu=Dt("ZodISOTime",((e,t)=>{yo.init(e,t),Du.init(e,t)}));function xu(e){return ra(wu,e)}const Iu=Dt("ZodISODuration",((e,t)=>{bo.init(e,t),Du.init(e,t)}));function Su(e){return oa(Iu,e)}const $u=Object.freeze(Object.defineProperty({__proto__:null,ZodISODate:bu,ZodISODateTime:vu,ZodISODuration:Iu,ZodISOTime:wu,date:ku,datetime:yu,duration:Su,time:xu},Symbol.toStringTag,{value:"Module"})),Ou=(e,t)=>{An.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>Un(e,t)},flatten:{value:t=>Pn(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Jt,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Jt,2)}},isEmpty:{get:()=>0===e.issues.length}})},Eu=Dt("ZodError",Ou),Tu=Dt("ZodError",Ou,{Parent:Error}),Ru=Mn(Tu),Nu=qn(Tu),Au=Fn(Tu),Cu=Jn(Tu),Pu=Dt("ZodType",((e,t)=>(no.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map((e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e))]}),e.clone=(t,n)=>dn(e,t,n),e.brand=()=>e,e.register=(t,n)=>(t.add(e,n),e),e.parse=(t,n)=>Ru(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Au(e,t,n),e.parseAsync=async(t,n)=>Nu(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Cu(e,t,n),e.spa=e.safeParseAsync,e.refine=(t,n)=>e.check(kc(t,n)),e.superRefine=t=>e.check(wc(t)),e.overwrite=t=>e.check(Ya(t)),e.optional=()=>Xl(e),e.nullable=()=>ec(e),e.nullish=()=>Xl(ec(e)),e.nonoptional=t=>sc(e,t),e.array=()=>Ol(e),e.or=t=>Cl([e,t]),e.and=t=>zl(e,t),e.transform=t=>pc(e,Kl(t)),e.default=t=>nc(e,t),e.prefault=t=>oc(e,t),e.catch=t=>lc(e,t),e.pipe=t=>pc(e,t),e.readonly=()=>_c(e),e.describe=t=>{const n=e.clone();return Ts.add(n,{description:t}),n},Object.defineProperty(e,"description",{get(){var t;return null==(t=Ts.get(e))?void 0:t.description},configurable:!0}),e.meta=(...t)=>{if(0===t.length)return Ts.get(e);const n=e.clone();return Ts.add(n,t[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e))),Uu=Dt("_ZodString",((e,t)=>{ro.init(e,t),Pu.init(e,t);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...t)=>e.check(Fa(...t)),e.includes=(...t)=>e.check(Ba(...t)),e.startsWith=(...t)=>e.check(Ha(...t)),e.endsWith=(...t)=>e.check(Va(...t)),e.min=(...t)=>e.check(qa(...t)),e.max=(...t)=>e.check(La(...t)),e.length=(...t)=>e.check(Za(...t)),e.nonempty=(...t)=>e.check(qa(1,...t)),e.lowercase=t=>e.check(Wa(t)),e.uppercase=t=>e.check(Ja(t)),e.trim=()=>e.check(Qa()),e.normalize=(...t)=>e.check(Xa(...t)),e.toLowerCase=()=>e.check(eu()),e.toUpperCase=()=>e.check(tu())})),ju=Dt("ZodString",((e,t)=>{ro.init(e,t),Uu.init(e,t),e.email=t=>e.check(As(Mu,t)),e.url=t=>e.check(Ds(Zu,t)),e.jwt=t=>e.check(Qs(ol,t)),e.emoji=t=>e.check(Ms(Fu,t)),e.guid=t=>e.check(Cs(Lu,t)),e.uuid=t=>e.check(Ps(qu,t)),e.uuidv4=t=>e.check(Us(qu,t)),e.uuidv6=t=>e.check(js(qu,t)),e.uuidv7=t=>e.check(zs(qu,t)),e.nanoid=t=>e.check(Ls(Wu,t)),e.guid=t=>e.check(Cs(Lu,t)),e.cuid=t=>e.check(qs(Ju,t)),e.cuid2=t=>e.check(Zs(Bu,t)),e.ulid=t=>e.check(Fs(Hu,t)),e.base64=t=>e.check(Ks(el,t)),e.base64url=t=>e.check(Ys(nl,t)),e.xid=t=>e.check(Ws(Vu,t)),e.ksuid=t=>e.check(Js(Gu,t)),e.ipv4=t=>e.check(Bs(Ku,t)),e.ipv6=t=>e.check(Hs(Yu,t)),e.cidrv4=t=>e.check(Vs(Xu,t)),e.cidrv6=t=>e.check(Gs(Qu,t)),e.e164=t=>e.check(Xs(rl,t)),e.datetime=t=>e.check(yu(t)),e.date=t=>e.check(ku(t)),e.time=t=>e.check(xu(t)),e.duration=t=>e.check(Su(t))}));function zu(e){return Rs(ju,e)}const Du=Dt("ZodStringFormat",((e,t)=>{oo.init(e,t),Uu.init(e,t)})),Mu=Dt("ZodEmail",((e,t)=>{ao.init(e,t),Du.init(e,t)}));const Lu=Dt("ZodGUID",((e,t)=>{io.init(e,t),Du.init(e,t)}));const qu=Dt("ZodUUID",((e,t)=>{so.init(e,t),Du.init(e,t)}));const Zu=Dt("ZodURL",((e,t)=>{uo.init(e,t),Du.init(e,t)}));const Fu=Dt("ZodEmoji",((e,t)=>{lo.init(e,t),Du.init(e,t)}));const Wu=Dt("ZodNanoID",((e,t)=>{co.init(e,t),Du.init(e,t)}));const Ju=Dt("ZodCUID",((e,t)=>{po.init(e,t),Du.init(e,t)}));const Bu=Dt("ZodCUID2",((e,t)=>{mo.init(e,t),Du.init(e,t)}));const Hu=Dt("ZodULID",((e,t)=>{_o.init(e,t),Du.init(e,t)}));const Vu=Dt("ZodXID",((e,t)=>{ho.init(e,t),Du.init(e,t)}));const Gu=Dt("ZodKSUID",((e,t)=>{go.init(e,t),Du.init(e,t)}));const Ku=Dt("ZodIPv4",((e,t)=>{ko.init(e,t),Du.init(e,t)}));const Yu=Dt("ZodIPv6",((e,t)=>{wo.init(e,t),Du.init(e,t)}));const Xu=Dt("ZodCIDRv4",((e,t)=>{xo.init(e,t),Du.init(e,t)}));const Qu=Dt("ZodCIDRv6",((e,t)=>{Io.init(e,t),Du.init(e,t)}));const el=Dt("ZodBase64",((e,t)=>{$o.init(e,t),Du.init(e,t)}));function tl(e){return Ks(el,e)}const nl=Dt("ZodBase64URL",((e,t)=>{Eo.init(e,t),Du.init(e,t)}));const rl=Dt("ZodE164",((e,t)=>{To.init(e,t),Du.init(e,t)}));const ol=Dt("ZodJWT",((e,t)=>{No.init(e,t),Du.init(e,t)}));const il=Dt("ZodCustomStringFormat",((e,t)=>{Ao.init(e,t),Du.init(e,t)}));const sl=Dt("ZodNumber",((e,t)=>{Co.init(e,t),Pu.init(e,t),e.gt=(t,n)=>e.check(Ra(t,n)),e.gte=(t,n)=>e.check(Na(t,n)),e.min=(t,n)=>e.check(Na(t,n)),e.lt=(t,n)=>e.check(Ea(t,n)),e.lte=(t,n)=>e.check(Ta(t,n)),e.max=(t,n)=>e.check(Ta(t,n)),e.int=t=>e.check(ll(t)),e.safe=t=>e.check(ll(t)),e.positive=t=>e.check(Ra(0,t)),e.nonnegative=t=>e.check(Na(0,t)),e.negative=t=>e.check(Ea(0,t)),e.nonpositive=t=>e.check(Ta(0,t)),e.multipleOf=(t,n)=>e.check(ja(t,n)),e.step=(t,n)=>e.check(ja(t,n)),e.finite=()=>e;const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null}));function al(e){return ia(sl,e)}const ul=Dt("ZodNumberFormat",((e,t)=>{Po.init(e,t),sl.init(e,t)}));function ll(e){return aa(ul,e)}const cl=Dt("ZodBoolean",((e,t)=>{Uo.init(e,t),Pu.init(e,t)}));function dl(e){return pa(cl,e)}const pl=Dt("ZodBigInt",((e,t)=>{jo.init(e,t),Pu.init(e,t),e.gte=(t,n)=>e.check(Na(t,n)),e.min=(t,n)=>e.check(Na(t,n)),e.gt=(t,n)=>e.check(Ra(t,n)),e.gte=(t,n)=>e.check(Na(t,n)),e.min=(t,n)=>e.check(Na(t,n)),e.lt=(t,n)=>e.check(Ea(t,n)),e.lte=(t,n)=>e.check(Ta(t,n)),e.max=(t,n)=>e.check(Ta(t,n)),e.positive=t=>e.check(Ra(BigInt(0),t)),e.negative=t=>e.check(Ea(BigInt(0),t)),e.nonpositive=t=>e.check(Ta(BigInt(0),t)),e.nonnegative=t=>e.check(Na(BigInt(0),t)),e.multipleOf=(t,n)=>e.check(ja(t,n));const n=e._zod.bag;e.minValue=n.minimum??null,e.maxValue=n.maximum??null,e.format=n.format??null}));const ml=Dt("ZodBigIntFormat",((e,t)=>{zo.init(e,t),pl.init(e,t)}));const _l=Dt("ZodSymbol",((e,t)=>{Do.init(e,t),Pu.init(e,t)}));const hl=Dt("ZodUndefined",((e,t)=>{Mo.init(e,t),Pu.init(e,t)}));const gl=Dt("ZodNull",((e,t)=>{Lo.init(e,t),Pu.init(e,t)}));function fl(e){return ba(gl,e)}const vl=Dt("ZodAny",((e,t)=>{qo.init(e,t),Pu.init(e,t)}));function yl(){return ka(vl)}const bl=Dt("ZodUnknown",((e,t)=>{Zo.init(e,t),Pu.init(e,t)}));function kl(){return wa(bl)}const wl=Dt("ZodNever",((e,t)=>{Fo.init(e,t),Pu.init(e,t)}));function xl(e){return xa(wl,e)}const Il=Dt("ZodVoid",((e,t)=>{Wo.init(e,t),Pu.init(e,t)}));const Sl=Dt("ZodDate",((e,t)=>{Jo.init(e,t),Pu.init(e,t),e.min=(t,n)=>e.check(Na(t,n)),e.max=(t,n)=>e.check(Ta(t,n));const n=e._zod.bag;e.minDate=n.minimum?new Date(n.minimum):null,e.maxDate=n.maximum?new Date(n.maximum):null}));const $l=Dt("ZodArray",((e,t)=>{Ho.init(e,t),Pu.init(e,t),e.element=t.element,e.min=(t,n)=>e.check(qa(t,n)),e.nonempty=t=>e.check(qa(1,t)),e.max=(t,n)=>e.check(La(t,n)),e.length=(t,n)=>e.check(Za(t,n)),e.unwrap=()=>e.element}));function Ol(e,t){return nu($l,e,t)}const El=Dt("ZodObject",((e,t)=>{Go.init(e,t),Pu.init(e,t),Yt(e,"shape",(()=>t.shape)),e.keyof=()=>Jl(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:kl()}),e.loose=()=>e.clone({...e._zod.def,catchall:kl()}),e.strict=()=>e.clone({...e._zod.def,catchall:xl()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>yn(e,t),e.merge=t=>bn(e,t),e.pick=t=>fn(e,t),e.omit=t=>vn(e,t),e.partial=(...t)=>kn(Yl,e,t[0]),e.required=(...t)=>wn(ic,e,t[0])}));function Tl(e,t){const n={type:"object",get shape(){return Qt(this,"shape",e?Xt(e):{}),this.shape},...pn(t)};return new El(n)}function Rl(e,t){return new El({type:"object",get shape(){return Qt(this,"shape",Xt(e)),this.shape},catchall:xl(),...pn(t)})}function Nl(e,t){return new El({type:"object",get shape(){return Qt(this,"shape",Xt(e)),this.shape},catchall:kl(),...pn(t)})}const Al=Dt("ZodUnion",((e,t)=>{Yo.init(e,t),Pu.init(e,t),e.options=t.options}));function Cl(e,t){return new Al({type:"union",options:e,...pn(t)})}const Pl=Dt("ZodDiscriminatedUnion",((e,t)=>{Al.init(e,t),Xo.init(e,t)}));function Ul(e,t,n){return new Pl({type:"union",options:t,discriminator:e,...pn(n)})}const jl=Dt("ZodIntersection",((e,t)=>{Qo.init(e,t),Pu.init(e,t)}));function zl(e,t){return new jl({type:"intersection",left:e,right:t})}const Dl=Dt("ZodTuple",((e,t)=>{ni.init(e,t),Pu.init(e,t),e.rest=t=>e.clone({...e._zod.def,rest:t})}));function Ml(e,t,n){const r=t instanceof no;return new Dl({type:"tuple",items:e,rest:r?t:null,...pn(r?n:t)})}const Ll=Dt("ZodRecord",((e,t)=>{oi.init(e,t),Pu.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType}));function ql(e,t,n){return new Ll({type:"record",keyType:e,valueType:t,...pn(n)})}const Zl=Dt("ZodMap",((e,t)=>{ii.init(e,t),Pu.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType}));const Fl=Dt("ZodSet",((e,t)=>{ai.init(e,t),Pu.init(e,t),e.min=(...t)=>e.check(Da(...t)),e.nonempty=t=>e.check(Da(1,t)),e.max=(...t)=>e.check(za(...t)),e.size=(...t)=>e.check(Ma(...t))}));const Wl=Dt("ZodEnum",((e,t)=>{li.init(e,t),Pu.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{const o={};for(const i of e){if(!n.has(i))throw new Error(`Key ${i} not found in enum`);o[i]=t.entries[i]}return new Wl({...t,checks:[],...pn(r),entries:o})},e.exclude=(e,r)=>{const o={...t.entries};for(const t of e){if(!n.has(t))throw new Error(`Key ${t} not found in enum`);delete o[t]}return new Wl({...t,checks:[],...pn(r),entries:o})}}));function Jl(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map((e=>[e,e]))):e;return new Wl({type:"enum",entries:n,...pn(t)})}const Bl=Dt("ZodLiteral",((e,t)=>{ci.init(e,t),Pu.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})}));function Hl(e,t){return new Bl({type:"literal",values:Array.isArray(e)?e:[e],...pn(t)})}const Vl=Dt("ZodFile",((e,t)=>{di.init(e,t),Pu.init(e,t),e.min=(t,n)=>e.check(Da(t,n)),e.max=(t,n)=>e.check(za(t,n)),e.mime=(t,n)=>e.check(Ka(Array.isArray(t)?t:[t],n))}));const Gl=Dt("ZodTransform",((e,t)=>{pi.init(e,t),Pu.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=r=>{if("string"==typeof r)n.issues.push(Tn(r,n.value,t));else{const t=r;t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=n.value),t.inst??(t.inst=e),n.issues.push(Tn(t))}};const o=t.transform(n.value,n);return o instanceof Promise?o.then((e=>(n.value=e,n))):(n.value=o,n)}}));function Kl(e){return new Gl({type:"transform",transform:e})}const Yl=Dt("ZodOptional",((e,t)=>{_i.init(e,t),Pu.init(e,t),e.unwrap=()=>e._zod.def.innerType}));function Xl(e){return new Yl({type:"optional",innerType:e})}const Ql=Dt("ZodNullable",((e,t)=>{hi.init(e,t),Pu.init(e,t),e.unwrap=()=>e._zod.def.innerType}));function ec(e){return new Ql({type:"nullable",innerType:e})}const tc=Dt("ZodDefault",((e,t)=>{gi.init(e,t),Pu.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap}));function nc(e,t){return new tc({type:"default",innerType:e,get defaultValue(){return"function"==typeof t?t():an(t)}})}const rc=Dt("ZodPrefault",((e,t)=>{vi.init(e,t),Pu.init(e,t),e.unwrap=()=>e._zod.def.innerType}));function oc(e,t){return new rc({type:"prefault",innerType:e,get defaultValue(){return"function"==typeof t?t():an(t)}})}const ic=Dt("ZodNonOptional",((e,t)=>{yi.init(e,t),Pu.init(e,t),e.unwrap=()=>e._zod.def.innerType}));function sc(e,t){return new ic({type:"nonoptional",innerType:e,...pn(t)})}const ac=Dt("ZodSuccess",((e,t)=>{ki.init(e,t),Pu.init(e,t),e.unwrap=()=>e._zod.def.innerType}));const uc=Dt("ZodCatch",((e,t)=>{wi.init(e,t),Pu.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap}));function lc(e,t){return new uc({type:"catch",innerType:e,catchValue:"function"==typeof t?t:()=>t})}const cc=Dt("ZodNaN",((e,t)=>{xi.init(e,t),Pu.init(e,t)}));const dc=Dt("ZodPipe",((e,t)=>{Ii.init(e,t),Pu.init(e,t),e.in=t.in,e.out=t.out}));function pc(e,t){return new dc({type:"pipe",in:e,out:t})}const mc=Dt("ZodReadonly",((e,t)=>{$i.init(e,t),Pu.init(e,t),e.unwrap=()=>e._zod.def.innerType}));function _c(e){return new mc({type:"readonly",innerType:e})}const hc=Dt("ZodTemplateLiteral",((e,t)=>{Ei.init(e,t),Pu.init(e,t)}));const gc=Dt("ZodLazy",((e,t)=>{Ri.init(e,t),Pu.init(e,t),e.unwrap=()=>e._zod.def.getter()}));function fc(e){return new gc({type:"lazy",getter:e})}const vc=Dt("ZodPromise",((e,t)=>{Ti.init(e,t),Pu.init(e,t),e.unwrap=()=>e._zod.def.innerType}));const yc=Dt("ZodCustom",((e,t)=>{Ni.init(e,t),Pu.init(e,t)}));function bc(e,t){return iu(yc,e??(()=>!0),t)}function kc(e,t={}){return su(yc,e,t)}function wc(e){return au(e)}function xc(e,t={error:`Input not instance of ${e.name}`}){const n=new yc({type:"custom",check:"custom",fn:t=>t instanceof e,abort:!0,...pn(t)});return n._zod.bag.Class=e,n}var Ic;function Sc(e){return sa(sl,e)}Ic||(Ic={});const $c=Object.freeze(Object.defineProperty({__proto__:null,bigint:function(e){return ha(pl,e)},boolean:function(e){return ma(cl,e)},date:function(e){return $a(Sl,e)},number:Sc,string:function(e){return Ns(ju,e)}},Symbol.toStringTag,{value:"Module"}));Zt(Zi());const Oc=Object.freeze(Object.defineProperty({__proto__:null,$brand:Mt,$input:$s,$output:Ss,NEVER:zt,TimePrecision:ea,ZodAny:vl,ZodArray:$l,ZodBase64:el,ZodBase64URL:nl,ZodBigInt:pl,ZodBigIntFormat:ml,ZodBoolean:cl,ZodCIDRv4:Xu,ZodCIDRv6:Qu,ZodCUID:Ju,ZodCUID2:Bu,ZodCatch:uc,ZodCustom:yc,ZodCustomStringFormat:il,ZodDate:Sl,ZodDefault:tc,ZodDiscriminatedUnion:Pl,ZodE164:rl,ZodEmail:Mu,ZodEmoji:Fu,ZodEnum:Wl,ZodError:Eu,ZodFile:Vl,get ZodFirstPartyTypeKind(){return Ic},ZodGUID:Lu,ZodIPv4:Ku,ZodIPv6:Yu,ZodISODate:bu,ZodISODateTime:vu,ZodISODuration:Iu,ZodISOTime:wu,ZodIntersection:jl,ZodIssueCode:{invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"},ZodJWT:ol,ZodKSUID:Gu,ZodLazy:gc,ZodLiteral:Bl,ZodMap:Zl,ZodNaN:cc,ZodNanoID:Wu,ZodNever:wl,ZodNonOptional:ic,ZodNull:gl,ZodNullable:Ql,ZodNumber:sl,ZodNumberFormat:ul,ZodObject:El,ZodOptional:Yl,ZodPipe:dc,ZodPrefault:rc,ZodPromise:vc,ZodReadonly:mc,ZodRealError:Tu,ZodRecord:Ll,ZodSet:Fl,ZodString:ju,ZodStringFormat:Du,ZodSuccess:ac,ZodSymbol:_l,ZodTemplateLiteral:hc,ZodTransform:Gl,ZodTuple:Dl,ZodType:Pu,ZodULID:Hu,ZodURL:Zu,ZodUUID:qu,ZodUndefined:hl,ZodUnion:Al,ZodUnknown:bl,ZodVoid:Il,ZodXID:Vu,_ZodString:Uu,_default:nc,any:yl,array:Ol,base64:tl,base64url:function(e){return Ys(nl,e)},bigint:function(e){return _a(pl,e)},boolean:dl,catch:lc,check:function(e){const t=new Rr({check:"custom"});return t._zod.check=e,t},cidrv4:function(e){return Vs(Xu,e)},cidrv6:function(e){return Gs(Qu,e)},clone:dn,coerce:$c,config:Zt,core:fu,cuid:function(e){return qs(Ju,e)},cuid2:function(e){return Zs(Bu,e)},custom:bc,date:function(e){return Sa(Sl,e)},discriminatedUnion:Ul,e164:function(e){return Xs(rl,e)},email:function(e){return As(Mu,e)},emoji:function(e){return Ms(Fu,e)},endsWith:Va,enum:Jl,file:function(e){return ou(Vl,e)},flattenError:Pn,float32:function(e){return ua(ul,e)},float64:function(e){return la(ul,e)},formatError:Un,function:pu,getErrorMap:function(){return Zt().customError},globalRegistry:Ts,gt:Ra,gte:Na,guid:function(e){return Cs(Lu,e)},hostname:function(e){return cu(il,"hostname",mr,e)},includes:Ba,instanceof:xc,int:ll,int32:function(e){return ca(ul,e)},int64:function(e){return ga(ml,e)},intersection:zl,ipv4:function(e){return Bs(Ku,e)},ipv6:function(e){return Hs(Yu,e)},iso:$u,json:function(e){const t=fc((()=>Cl([zu(e),al(),dl(),fl(),Ol(t),ql(zu(),t)])));return t},jwt:function(e){return Qs(ol,e)},keyof:function(e){const t=e._zod.def.shape;return Jl(Object.keys(t))},ksuid:function(e){return Js(Gu,e)},lazy:fc,length:Za,literal:Hl,locales:Is,looseObject:Nl,lowercase:Wa,lt:Ea,lte:Ta,map:function(e,t,n){return new Zl({type:"map",keyType:e,valueType:t,...pn(n)})},maxLength:La,maxSize:za,mime:Ka,minLength:qa,minSize:Da,multipleOf:ja,nan:function(e){return Oa(cc,e)},nanoid:function(e){return Ls(Wu,e)},nativeEnum:function(e,t){return new Wl({type:"enum",entries:e,...pn(t)})},negative:Ca,never:xl,nonnegative:Ua,nonoptional:sc,nonpositive:Pa,normalize:Xa,null:fl,nullable:ec,nullish:function(e){return Xl(ec(e))},number:al,object:Tl,optional:Xl,overwrite:Ya,parse:Ru,parseAsync:Nu,partialRecord:function(e,t,n){const r=dn(e);return r._zod.values=void 0,new Ll({type:"record",keyType:r,valueType:t,...pn(n)})},pipe:pc,positive:Aa,prefault:oc,preprocess:function(e,t){return pc(Kl(e),t)},prettifyError:Dn,promise:function(e){return new vc({type:"promise",innerType:e})},property:Ga,readonly:_c,record:ql,refine:kc,regex:Fa,regexes:Tr,registry:Es,safeParse:Au,safeParseAsync:Cu,set:function(e,t){return new Fl({type:"set",valueType:e,...pn(t)})},setErrorMap:function(e){Zt({customError:e})},size:Ma,startsWith:Ha,strictObject:Rl,string:zu,stringFormat:function(e,t,n={}){return cu(il,e,t,n)},stringbool:(...e)=>lu({Pipe:dc,Boolean:cl,String:ju,Transform:Gl},...e),success:function(e){return new ac({type:"success",innerType:e})},superRefine:wc,symbol:function(e){return va(_l,e)},templateLiteral:function(e,t){return new hc({type:"template_literal",parts:e,...pn(t)})},toJSONSchema:_u,toLowerCase:eu,toUpperCase:tu,transform:Kl,treeifyError:jn,trim:Qa,tuple:Ml,uint32:function(e){return da(ul,e)},uint64:function(e){return fa(ml,e)},ulid:function(e){return Fs(Hu,e)},undefined:function(e){return ya(hl,e)},union:Cl,unknown:kl,uppercase:Ja,url:function(e){return Ds(Zu,e)},uuid:function(e){return Ps(qu,e)},uuidv4:function(e){return Us(qu,e)},uuidv6:function(e){return js(qu,e)},uuidv7:function(e){return zs(qu,e)},void:function(e){return Ia(Il,e)},xid:function(e){return Ws(Vu,e)}},Symbol.toStringTag,{value:"Module"})),Ec=Symbol("Let zodToJsonSchema decide on which parser to use"),Tc={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},Rc=e=>{const t=(e=>"string"==typeof e?{...Tc,name:e}:{...Tc,...e})(e),n=void 0!==t.name?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map((([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}])))}};function Nc(e,t,n,r){(null==r?void 0:r.errorMessages)&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function Ac(e,t,n,r,o){e[t]=n,Nc(e,t,r,o)}const Cc=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join("/")};function Pc(e){if("openAi"!==e.target)return{};const t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:"relative"===e.$refStrategy?Cc(t,e.currentPath):t.join("/")}}function Uc(e,t){return ud(e.type._def,t)}function jc(e,t,n){const r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map(((n,r)=>jc(e,t,n)))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return zc(e,t)}}const zc=(e,t)=>{const n={type:"integer",format:"unix-time"};if("openApi3"===t.target)return n;for(const r of e.checks)switch(r.kind){case"min":Ac(n,"minimum",r.value,r.message,t);break;case"max":Ac(n,"maximum",r.value,r.message,t)}return n};let Dc;const Mc=/^[cC][^\s-]{8,}$/,Lc=/^[0-9a-z]+$/,qc=/^[0-9A-HJKMNP-TV-Z]{26}$/,Zc=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,Fc=()=>(void 0===Dc&&(Dc=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Dc),Wc=/^(?:(?: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])$/,Jc=/^(([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])$/,Bc=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Hc=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Vc=/^[a-zA-Z0-9_-]{21}$/,Gc=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;function Kc(e,t){const n={type:"string"};if(e.checks)for(const r of e.checks)switch(r.kind){case"min":Ac(n,"minLength","number"==typeof n.minLength?Math.max(n.minLength,r.value):r.value,r.message,t);break;case"max":Ac(n,"maxLength","number"==typeof n.maxLength?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case"email":switch(t.emailStrategy){case"format:email":Qc(n,"email",r.message,t);break;case"format:idn-email":Qc(n,"idn-email",r.message,t);break;case"pattern:zod":ed(n,Zc,r.message,t)}break;case"url":Qc(n,"uri",r.message,t);break;case"uuid":Qc(n,"uuid",r.message,t);break;case"regex":ed(n,r.regex,r.message,t);break;case"cuid":ed(n,Mc,r.message,t);break;case"cuid2":ed(n,Lc,r.message,t);break;case"startsWith":ed(n,RegExp(`^${Yc(r.value,t)}`),r.message,t);break;case"endsWith":ed(n,RegExp(`${Yc(r.value,t)}$`),r.message,t);break;case"datetime":Qc(n,"date-time",r.message,t);break;case"date":Qc(n,"date",r.message,t);break;case"time":Qc(n,"time",r.message,t);break;case"duration":Qc(n,"duration",r.message,t);break;case"length":Ac(n,"minLength","number"==typeof n.minLength?Math.max(n.minLength,r.value):r.value,r.message,t),Ac(n,"maxLength","number"==typeof n.maxLength?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case"includes":ed(n,RegExp(Yc(r.value,t)),r.message,t);break;case"ip":"v6"!==r.version&&Qc(n,"ipv4",r.message,t),"v4"!==r.version&&Qc(n,"ipv6",r.message,t);break;case"base64url":ed(n,Hc,r.message,t);break;case"jwt":ed(n,Gc,r.message,t);break;case"cidr":"v6"!==r.version&&ed(n,Wc,r.message,t),"v4"!==r.version&&ed(n,Jc,r.message,t);break;case"emoji":ed(n,Fc(),r.message,t);break;case"ulid":ed(n,qc,r.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":Qc(n,"binary",r.message,t);break;case"contentEncoding:base64":Ac(n,"contentEncoding","base64",r.message,t);break;case"pattern:zod":ed(n,Bc,r.message,t)}break;case"nanoid":ed(n,Vc,r.message,t)}return n}function Yc(e,t){return"escape"===t.patternStrategy?function(e){let t="";for(let n=0;n<e.length;n++)Xc.has(e[n])||(t+="\\"),t+=e[n];return t}(e):e}const Xc=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Qc(e,t,n,r){var o;e.format||(null==(o=e.anyOf)?void 0:o.some((e=>e.format)))?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):Ac(e,"format",t,n,r)}function ed(e,t,n,r){var o;e.pattern||(null==(o=e.allOf)?void 0:o.some((e=>e.pattern)))?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.allOf.push({pattern:td(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):Ac(e,"pattern",td(t,r),n,r)}function td(e,t){var n;if(!t.applyRegexFlags||!e.flags)return e.source;const r=e.flags.includes("i"),o=e.flags.includes("m"),i=e.flags.includes("s"),s=r?e.source.toLowerCase():e.source;let a="",u=!1,l=!1,c=!1;for(let d=0;d<s.length;d++)if(u)a+=s[d],u=!1;else{if(r)if(l){if(s[d].match(/[a-z]/)){c?(a+=s[d],a+=`${s[d-2]}-${s[d]}`.toUpperCase(),c=!1):"-"===s[d+1]&&(null==(n=s[d+2])?void 0:n.match(/[a-z]/))?(a+=s[d],c=!0):a+=`${s[d]}${s[d].toUpperCase()}`;continue}}else if(s[d].match(/[a-z]/)){a+=`[${s[d]}${s[d].toUpperCase()}]`;continue}if(o){if("^"===s[d]){a+="(^|(?<=[\r\n]))";continue}if("$"===s[d]){a+="($|(?=[\r\n]))";continue}}i&&"."===s[d]?a+=l?`${s[d]}\r\n`:`[${s[d]}\r\n]`:(a+=s[d],"\\"===s[d]?u=!0:l&&"]"===s[d]?l=!1:l||"["!==s[d]||(l=!0))}try{new RegExp(a)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return a}function nd(e,t){var n,r,o,i,s,a;if("openAi"===t.target&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),"openApi3"===t.target&&(null==(n=e.keyType)?void 0:n._def.typeName)===Ic.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce(((n,r)=>({...n,[r]:ud(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",r]})??Pc(t)})),{}),additionalProperties:t.rejectedAdditionalProperties};const u={type:"object",additionalProperties:ud(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if("openApi3"===t.target)return u;if((null==(r=e.keyType)?void 0:r._def.typeName)===Ic.ZodString&&(null==(o=e.keyType._def.checks)?void 0:o.length)){const{type:n,...r}=Kc(e.keyType._def,t);return{...u,propertyNames:r}}if((null==(i=e.keyType)?void 0:i._def.typeName)===Ic.ZodEnum)return{...u,propertyNames:{enum:e.keyType._def.values}};if((null==(s=e.keyType)?void 0:s._def.typeName)===Ic.ZodBranded&&e.keyType._def.type._def.typeName===Ic.ZodString&&(null==(a=e.keyType._def.type._def.checks)?void 0:a.length)){const{type:n,...r}=Uc(e.keyType._def,t);return{...u,propertyNames:r}}return u}const rd={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};const od=(e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map(((e,n)=>ud(e._def,{...t,currentPath:[...t.currentPath,"anyOf",`${n}`]}))).filter((e=>!!e&&(!t.strictUnions||"object"==typeof e&&Object.keys(e).length>0)));return n.length?{anyOf:n}:void 0};function id(e,t){const n="openAi"===t.target,r={type:"object",properties:{}},o=[],i=e.shape();for(const a in i){let e=i[a];if(void 0===e||void 0===e._def)continue;let s=sd(e);s&&n&&("ZodOptional"===e._def.typeName&&(e=e._def.innerType),e.isNullable()||(e=e.nullable()),s=!1);const u=ud(e._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});void 0!==u&&(r.properties[a]=u,s||o.push(a))}o.length&&(r.required=o);const s=function(e,t){if("ZodNever"!==e.catchall._def.typeName)return ud(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return"strict"===t.removeAdditionalStrategy?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}(e,t);return void 0!==s&&(r.additionalProperties=s),r}function sd(e){try{return e.isOptional()}catch{return!0}}const ad=(e,t,n)=>{switch(t){case Ic.ZodString:return Kc(e,n);case Ic.ZodNumber:return function(e,t){const n={type:"number"};if(!e.checks)return n;for(const r of e.checks)switch(r.kind){case"int":n.type="integer",Nc(n,"type",r.message,t);break;case"min":"jsonSchema7"===t.target?r.inclusive?Ac(n,"minimum",r.value,r.message,t):Ac(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),Ac(n,"minimum",r.value,r.message,t));break;case"max":"jsonSchema7"===t.target?r.inclusive?Ac(n,"maximum",r.value,r.message,t):Ac(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),Ac(n,"maximum",r.value,r.message,t));break;case"multipleOf":Ac(n,"multipleOf",r.value,r.message,t)}return n}(e,n);case Ic.ZodObject:return id(e,n);case Ic.ZodBigInt:return function(e,t){const n={type:"integer",format:"int64"};if(!e.checks)return n;for(const r of e.checks)switch(r.kind){case"min":"jsonSchema7"===t.target?r.inclusive?Ac(n,"minimum",r.value,r.message,t):Ac(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),Ac(n,"minimum",r.value,r.message,t));break;case"max":"jsonSchema7"===t.target?r.inclusive?Ac(n,"maximum",r.value,r.message,t):Ac(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),Ac(n,"maximum",r.value,r.message,t));break;case"multipleOf":Ac(n,"multipleOf",r.value,r.message,t)}return n}(e,n);case Ic.ZodBoolean:return{type:"boolean"};case Ic.ZodDate:return jc(e,n);case Ic.ZodUndefined:return function(e){return{not:Pc(e)}}(n);case Ic.ZodNull:return function(e){return"openApi3"===e.target?{enum:["null"],nullable:!0}:{type:"null"}}(n);case Ic.ZodArray:return function(e,t){var n,r,o;const i={type:"array"};return(null==(n=e.type)?void 0:n._def)&&(null==(o=null==(r=e.type)?void 0:r._def)?void 0:o.typeName)!==Ic.ZodAny&&(i.items=ud(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&Ac(i,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&Ac(i,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(Ac(i,"minItems",e.exactLength.value,e.exactLength.message,t),Ac(i,"maxItems",e.exactLength.value,e.exactLength.message,t)),i}(e,n);case Ic.ZodUnion:case Ic.ZodDiscriminatedUnion:return function(e,t){if("openApi3"===t.target)return od(e,t);const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every((e=>e._def.typeName in rd&&(!e._def.checks||!e._def.checks.length)))){const e=n.reduce(((e,t)=>{const n=rd[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e}),[]);return{type:e.length>1?e:e[0]}}if(n.every((e=>"ZodLiteral"===e._def.typeName&&!e.description))){const e=n.reduce(((e,t)=>{const n=typeof t._def.value;switch(n){case"string":case"number":case"boolean":return[...e,n];case"bigint":return[...e,"integer"];case"object":if(null===t._def.value)return[...e,"null"];default:return e}}),[]);if(e.length===n.length){const t=e.filter(((e,t,n)=>n.indexOf(e)===t));return{type:t.length>1?t:t[0],enum:n.reduce(((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value]),[])}}}else if(n.every((e=>"ZodEnum"===e._def.typeName)))return{type:"string",enum:n.reduce(((e,t)=>[...e,...t._def.values.filter((t=>!e.includes(t)))]),[])};return od(e,t)}(e,n);case Ic.ZodIntersection:return function(e,t){const n=[ud(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),ud(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter((e=>!!e));let r="jsonSchema2019-09"===t.target?{unevaluatedProperties:!1}:void 0;const o=[];return n.forEach((e=>{if("type"in(t=e)&&"string"===t.type||!("allOf"in t)){let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){const{additionalProperties:n,...r}=e;t=r}else r=void 0;o.push(t)}else o.push(...e.allOf),void 0===e.unevaluatedProperties&&(r=void 0);var t})),o.length?{allOf:o,...r}:void 0}(e,n);case Ic.ZodTuple:return function(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map(((e,n)=>ud(e._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]}))).reduce(((e,t)=>void 0===t?e:[...e,t]),[]),additionalItems:ud(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map(((e,n)=>ud(e._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]}))).reduce(((e,t)=>void 0===t?e:[...e,t]),[])}}(e,n);case Ic.ZodRecord:return nd(e,n);case Ic.ZodLiteral:return function(e,t){const n=typeof e.value;return"bigint"!==n&&"number"!==n&&"boolean"!==n&&"string"!==n?{type:Array.isArray(e.value)?"array":"object"}:"openApi3"===t.target?{type:"bigint"===n?"integer":n,enum:[e.value]}:{type:"bigint"===n?"integer":n,const:e.value}}(e,n);case Ic.ZodEnum:return function(e){return{type:"string",enum:Array.from(e.values)}}(e);case Ic.ZodNativeEnum:return function(e){const t=e.values,n=Object.keys(e.values).filter((e=>"number"!=typeof t[t[e]])).map((e=>t[e])),r=Array.from(new Set(n.map((e=>typeof e))));return{type:1===r.length?"string"===r[0]?"string":"number":["string","number"],enum:n}}(e);case Ic.ZodNullable:return function(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return"openApi3"===t.target?{type:rd[e.innerType._def.typeName],nullable:!0}:{type:[rd[e.innerType._def.typeName],"null"]};if("openApi3"===t.target){const n=ud(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const n=ud(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}(e,n);case Ic.ZodOptional:return((e,t)=>{var n;if(t.currentPath.toString()===(null==(n=t.propertyPath)?void 0:n.toString()))return ud(e.innerType._def,t);const r=ud(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Pc(t)},r]}:Pc(t)})(e,n);case Ic.ZodMap:return function(e,t){return"record"===t.mapStrategy?nd(e,t):{type:"array",maxItems:125,items:{type:"array",items:[ud(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Pc(t),ud(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Pc(t)],minItems:2,maxItems:2}}}(e,n);case Ic.ZodSet:return function(e,t){const n={type:"array",uniqueItems:!0,items:ud(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&Ac(n,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&Ac(n,"maxItems",e.maxSize.value,e.maxSize.message,t),n}(e,n);case Ic.ZodLazy:return()=>e.getter()._def;case Ic.ZodPromise:return function(e,t){return ud(e.type._def,t)}(e,n);case Ic.ZodNaN:case Ic.ZodNever:return function(e){return"openAi"===e.target?void 0:{not:Pc({...e,currentPath:[...e.currentPath,"not"]})}}(n);case Ic.ZodEffects:return function(e,t){return"input"===t.effectStrategy?ud(e.schema._def,t):Pc(t)}(e,n);case Ic.ZodAny:return Pc(n);case Ic.ZodUnknown:return function(e){return Pc(e)}(n);case Ic.ZodDefault:return function(e,t){return{...ud(e.innerType._def,t),default:e.defaultValue()}}(e,n);case Ic.ZodBranded:return Uc(e,n);case Ic.ZodReadonly:case Ic.ZodCatch:return((e,t)=>ud(e.innerType._def,t))(e,n);case Ic.ZodPipeline:return((e,t)=>{if("input"===t.pipeStrategy)return ud(e.in._def,t);if("output"===t.pipeStrategy)return ud(e.out._def,t);const n=ud(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]});return{allOf:[n,ud(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]})].filter((e=>void 0!==e))}})(e,n);case Ic.ZodFunction:case Ic.ZodVoid:case Ic.ZodSymbol:default:return}};function ud(e,t,n=!1){var r;const o=t.seen.get(e);if(t.override){const i=null==(r=t.override)?void 0:r.call(t,e,t,o,n);if(i!==Ec)return i}if(o&&!n){const e=ld(o,t);if(void 0!==e)return e}const i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);const s=ad(e,e.typeName,t),a="function"==typeof s?ud(s(),t):s;if(a&&cd(e,t,a),t.postProcess){const n=t.postProcess(a,e,t);return i.jsonSchema=a,n}return i.jsonSchema=a,a}const ld=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Cc(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every(((e,n)=>t.currentPath[n]===e))?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Pc(t)):"seen"===t.$refStrategy?Pc(t):void 0}},cd=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),dd=(e,t)=>{const n=Rc(t);let r="object"==typeof t&&t.definitions?Object.entries(t.definitions).reduce(((e,[t,r])=>({...e,[t]:ud(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??Pc(n)})),{}):void 0;const o="string"==typeof t?t:"title"===(null==t?void 0:t.nameStrategy)||null==t?void 0:t.name,i=ud(e._def,void 0===o?n:{...n,currentPath:[...n.basePath,n.definitionPath,o]},!1)??Pc(n),s="object"==typeof t&&void 0!==t.name&&"title"===t.nameStrategy?t.name:void 0;void 0!==s&&(i.title=s),n.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:"relative"===n.$refStrategy?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));const a=void 0===o?r?{...i,[n.definitionPath]:r}:i:{$ref:[..."relative"===n.$refStrategy?[]:n.basePath,n.definitionPath,o].join("/"),[n.definitionPath]:{...r,[o]:i}};return"jsonSchema7"===n.target?a.$schema="http://json-schema.org/draft-07/schema#":"jsonSchema2019-09"!==n.target&&"openAi"!==n.target||(a.$schema="https://json-schema.org/draft/2019-09/schema#"),"openAi"===n.target&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};function pd(...e){return e.reduce(((e,t)=>({...e,...null!=t?t:{}})),{})}function md(e){return Object.fromEntries([...e.headers])}var _d=({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:r="-"}={})=>{const o=()=>{const e=n.length,r=new Array(t);for(let o=0;o<t;o++)r[o]=n[Math.random()*e|0];return r.join("")};if(null==e)return o;if(n.includes(r))throw new Be({argument:"separator",message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${o()}`},hd=_d();function gd(e){return(e instanceof Error||e instanceof DOMException)&&("AbortError"===e.name||"ResponseAborted"===e.name||"TimeoutError"===e.name)}var fd=["fetch failed","failed to fetch"];function vd({apiKey:e,environmentVariableName:t,apiKeyParameterName:n="apiKey",description:r}){if("string"==typeof e)return e;if(null!=e)throw new pt({message:`${r} API key must be a string.`});if("undefined"==typeof process)throw new pt({message:`${r} API key is missing. Pass it using the '${n}' parameter. Environment variables is not supported in this environment.`});if(null==(e=process.env[t]))throw new pt({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if("string"!=typeof e)throw new pt({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}var yd=/"__proto__"\s*:/,bd=/"constructor"\s*:/;function kd(e){const t=JSON.parse(e);return null===t||"object"!=typeof t||!1===yd.test(e)&&!1===bd.test(e)?t:function(e){let t=[e];for(;t.length;){const e=t;t=[];for(const n of e){if(Object.prototype.hasOwnProperty.call(n,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(n,"constructor")&&Object.prototype.hasOwnProperty.call(n.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const e in n){const r=n[e];r&&"object"==typeof r&&t.push(r)}}}return e}(t)}function wd(e){const{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return kd(e)}finally{Error.stackTraceLimit=t}}var xd=Symbol.for("vercel.ai.validator");function Id(e){return function(e){return"object"==typeof e&&null!==e&&xd in e&&!0===e[xd]&&"validate"in e}(e)?e:(t=e,n=async e=>{const n=await t["~standard"].validate(e);return null==n.issues?{success:!0,value:n.value}:{success:!1,error:new Et({value:e,cause:n.issues})}},{[xd]:!0,validate:n});var t,n}async function Sd({value:e,schema:t}){const n=Id(t);try{if(null==n.validate)return{success:!0,value:e,rawValue:e};const t=await n.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:Et.wrap({value:e,cause:t.error}),rawValue:e}}catch(r){return{success:!1,error:Et.wrap({value:e,cause:r}),rawValue:e}}}async function $d({text:e,schema:t}){try{const n=wd(e);return null==t?n:async function({value:e,schema:t}){const n=await Sd({value:e,schema:t});if(!n.success)throw Et.wrap({value:e,cause:n.error});return n.value}({value:n,schema:t})}catch(n){if(at.isInstance(n)||Et.isInstance(n))throw n;throw new at({text:e,cause:n})}}async function Od({text:e,schema:t}){try{const n=wd(e);return null==t?{success:!0,value:n,rawValue:n}:await Sd({value:n,schema:t})}catch(n){return{success:!1,error:at.isInstance(n)?n:new at({text:e,cause:n}),rawValue:void 0}}}function Ed(e){try{return wd(e),!0}catch(t){return!1}}function Td({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new jt).pipeThrough(new TransformStream({async transform({data:e},n){"[DONE]"!==e&&n.enqueue(await Od({text:e,schema:t}))}}))}async function Rd({provider:e,providerOptions:t,schema:n}){if(null==(null==t?void 0:t[e]))return;const r=await Sd({value:t[e],schema:n});if(!r.success)throw new Be({argument:"providerOptions",message:`invalid ${e} provider options`,cause:r.error});return r.value}var Nd=()=>globalThis.fetch,Ad=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:o,abortSignal:i,fetch:s})=>Cd({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:o,abortSignal:i,fetch:s}),Cd=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:o,abortSignal:i,fetch:s=Nd()})=>{try{const l=await s(e,{method:"POST",headers:(a=t,Object.fromEntries(Object.entries(a).filter((([e,t])=>null!=t)))),body:n.content,signal:i}),c=md(l);if(!l.ok){let t;try{t=await o({response:l,url:e,requestBodyValues:n.values})}catch(u){if(gd(u)||Ue.isInstance(u))throw u;throw new Ue({message:"Failed to process error response",cause:u,statusCode:l.status,url:e,responseHeaders:c,requestBodyValues:n.values})}throw t.value}try{return await r({response:l,url:e,requestBodyValues:n.values})}catch(u){if(u instanceof Error&&(gd(u)||Ue.isInstance(u)))throw u;throw new Ue({message:"Failed to process successful response",cause:u,statusCode:l.status,url:e,responseHeaders:c,requestBodyValues:n.values})}}catch(u){throw function({error:e,url:t,requestBodyValues:n}){if(gd(e))return e;if(e instanceof TypeError&&fd.includes(e.message.toLowerCase())){const r=e.cause;if(null!=r)return new Ue({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}({error:u,url:e,requestBodyValues:n.values})}var a};function Pd({id:e,name:t,inputSchema:n}){return({execute:r,outputSchema:o,toModelOutput:i,onInputStart:s,onInputDelta:a,onInputAvailable:u,...l})=>({type:"provider-defined",id:e,name:t,args:l,inputSchema:n,outputSchema:o,execute:r,toModelOutput:i,onInputStart:s,onInputDelta:a,onInputAvailable:u})}function Ud({id:e,name:t,inputSchema:n,outputSchema:r}){return({execute:o,toModelOutput:i,onInputStart:s,onInputDelta:a,onInputAvailable:u,...l})=>({type:"provider-defined",id:e,name:t,args:l,inputSchema:n,outputSchema:r,execute:o,toModelOutput:i,onInputStart:s,onInputDelta:a,onInputAvailable:u})}async function jd(e){return"function"==typeof e&&(e=e()),Promise.resolve(e)}var zd=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:o,requestBodyValues:i})=>{const s=await r.text(),a=md(r);if(""===s.trim())return{responseHeaders:a,value:new Ue({message:r.statusText,url:o,requestBodyValues:i,statusCode:r.status,responseHeaders:a,responseBody:s,isRetryable:null==n?void 0:n(r)})};try{const u=await $d({text:s,schema:e});return{responseHeaders:a,value:new Ue({message:t(u),url:o,requestBodyValues:i,statusCode:r.status,responseHeaders:a,responseBody:s,data:u,isRetryable:null==n?void 0:n(r,u)})}}catch(u){return{responseHeaders:a,value:new Ue({message:r.statusText,url:o,requestBodyValues:i,statusCode:r.status,responseHeaders:a,responseBody:s,isRetryable:null==n?void 0:n(r)})}}},Dd=e=>async({response:t})=>{const n=md(t);if(null==t.body)throw new Le({});return{responseHeaders:n,value:Td({stream:t.body,schema:e})}},Md=e=>async({response:t,url:n,requestBodyValues:r})=>{const o=await t.text(),i=await Od({text:o,schema:e}),s=md(t);if(!i.success)throw new Ue({message:"Invalid JSON response",cause:i.error,statusCode:t.status,responseHeaders:s,responseBody:o,url:n,requestBodyValues:r});return{responseHeaders:s,value:i.value,rawValue:i.rawValue}};function Ld(e,t){return function(e){return"_zod"in e}(e)?function(e){return Zd(_u(e,{target:"draft-7",io:"output",reused:"inline"}),{validate:async t=>{const n=await Cu(e,t);return n.success?{success:!0,value:n.data}:{success:!1,error:n.error}}})}(e):function(e){return Zd(dd(e,{$refStrategy:"none",target:"jsonSchema7"}),{validate:async t=>{const n=await e.safeParseAsync(t);return n.success?{success:!0,value:n.data}:{success:!1,error:n.error}}})}(e)}var qd=Symbol.for("vercel.ai.schema");function Zd(e,{validate:t}={}){return{[qd]:!0,_type:void 0,[xd]:!0,jsonSchema:e,validate:t}}function Fd(e){return null==e?Zd({properties:{},additionalProperties:!1}):"object"==typeof(t=e)&&null!==t&&qd in t&&!0===t[qd]&&"jsonSchema"in t&&"validate"in t?e:Ld(e);var t}var{btoa:Wd,atob:Jd}=globalThis;function Bd(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=Jd(t);return Uint8Array.from(n,(e=>e.codePointAt(0)))}function Hd(e){return e instanceof Uint8Array?function(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return Wd(t)}(e):e}function Vd(e){return null==e?void 0:e.replace(/\/$/,"")}var Gd=Tl({error:Tl({message:zu(),type:zu().nullish(),param:yl().nullish(),code:Cl([zu(),al()]).nullish()})}),Kd=zd({errorSchema:Gd,errorToMessage:e=>e.error.message});function Yd({id:e,model:t,created:n}){return{id:null!=e?e:void 0,modelId:null!=t?t:void 0,timestamp:null!=n?new Date(1e3*n):void 0}}function Xd(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var Qd=Tl({logitBias:ql(Sc(),al()).optional(),logprobs:Cl([dl(),al()]).optional(),parallelToolCalls:dl().optional(),user:zu().optional(),reasoningEffort:Jl(["minimal","low","medium","high"]).optional(),maxCompletionTokens:al().optional(),store:dl().optional(),metadata:ql(zu().max(64),zu().max(512)).optional(),prediction:ql(zu(),yl()).optional(),structuredOutputs:dl().optional(),serviceTier:Jl(["auto","flex","priority"]).optional(),strictJsonSchema:dl().optional(),textVerbosity:Jl(["low","medium","high"]).optional(),promptCacheKey:zu().optional(),safetyIdentifier:zu().optional()}),ep=Tl({key:zu(),type:Jl(["eq","ne","gt","gte","lt","lte"]),value:Cl([zu(),al(),dl()])}),tp=Tl({type:Jl(["and","or"]),filters:Ol(Cl([ep,fc((()=>tp))]))}),np=Cl([ep,tp]),rp=Tl({vectorStoreIds:Ol(zu()).optional(),maxNumResults:al().optional(),ranking:Tl({ranker:Jl(["auto","default-2024-08-21"]).optional()}).optional(),filters:np.optional()}),op=Pd({id:"openai.file_search",name:"file_search",inputSchema:Tl({query:zu()})}),ip=Tl({searchContextSize:Jl(["low","medium","high"]).optional(),userLocation:Tl({type:Hl("approximate"),country:zu().optional(),city:zu().optional(),region:zu().optional(),timezone:zu().optional()}).optional()}),sp=Pd({id:"openai.web_search_preview",name:"web_search_preview",inputSchema:Tl({action:Ul("type",[Tl({type:Hl("search"),query:zu()}),Tl({type:Hl("open_page"),url:zu()}),Tl({type:Hl("find"),url:zu(),pattern:zu()})]).nullish()})});var ap=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:o,frequencyPenalty:i,presencePenalty:s,stopSequences:a,responseFormat:u,seed:l,tools:c,toolChoice:d,providerOptions:p}){var m,_,h,g;const f=[],v=null!=(m=await Rd({provider:"openai",providerOptions:p,schema:Qd}))?m:{},y=null==(_=v.structuredOutputs)||_;null!=o&&f.push({type:"unsupported-setting",setting:"topK"}),"json"!==(null==u?void 0:u.type)||null==u.schema||y||f.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{messages:b,warnings:k}=function({prompt:e,systemMessageMode:t="system"}){const n=[],r=[];for(const{role:o,content:i}of e)switch(o){case"system":switch(t){case"system":n.push({role:"system",content:i});break;case"developer":n.push({role:"developer",content:i});break;case"remove":r.push({type:"other",message:"system messages are removed for this model"});break;default:throw new Error(`Unsupported system message mode: ${t}`)}break;case"user":if(1===i.length&&"text"===i[0].type){n.push({role:"user",content:i[0].text});break}n.push({role:"user",content:i.map(((e,t)=>{var n,r,o;switch(e.type){case"text":return{type:"text",text:e.text};case"file":if(e.mediaType.startsWith("image/")){const t="image/*"===e.mediaType?"image/jpeg":e.mediaType;return{type:"image_url",image_url:{url:e.data instanceof URL?e.data.toString():`data:${t};base64,${Hd(e.data)}`,detail:null==(r=null==(n=e.providerOptions)?void 0:n.openai)?void 0:r.imageDetail}}}if(!e.mediaType.startsWith("audio/")){if("application/pdf"===e.mediaType){if(e.data instanceof URL)throw new At({functionality:"PDF file parts with URLs"});return{type:"file",file:"string"==typeof e.data&&e.data.startsWith("file-")?{file_id:e.data}:{filename:null!=(o=e.filename)?o:`part-${t}.pdf`,file_data:`data:application/pdf;base64,${Hd(e.data)}`}}}throw new At({functionality:`file part media type ${e.mediaType}`})}if(e.data instanceof URL)throw new At({functionality:"audio file parts with URLs"});switch(e.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:Hd(e.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:Hd(e.data),format:"mp3"}};default:throw new At({functionality:`audio content parts with media type ${e.mediaType}`})}}}))});break;case"assistant":{let e="";const t=[];for(const n of i)switch(n.type){case"text":e+=n.text;break;case"tool-call":t.push({id:n.toolCallId,type:"function",function:{name:n.toolName,arguments:JSON.stringify(n.input)}})}n.push({role:"assistant",content:e,tool_calls:t.length>0?t:void 0});break}case"tool":for(const e of i){const t=e.output;let r;switch(t.type){case"text":case"error-text":r=t.value;break;case"content":case"json":case"error-json":r=JSON.stringify(t.value)}n.push({role:"tool",tool_call_id:e.toolCallId,content:r})}break;default:throw new Error(`Unsupported role: ${o}`)}return{messages:n,warnings:r}}({prompt:e,systemMessageMode:pp(this.modelId)});f.push(...k);const w=null!=(h=v.strictJsonSchema)&&h,x={model:this.modelId,logit_bias:v.logitBias,logprobs:!0===v.logprobs||"number"==typeof v.logprobs||void 0,top_logprobs:"number"==typeof v.logprobs?v.logprobs:"boolean"==typeof v.logprobs&&v.logprobs?0:void 0,user:v.user,parallel_tool_calls:v.parallelToolCalls,max_tokens:t,temperature:n,top_p:r,frequency_penalty:i,presence_penalty:s,response_format:"json"===(null==u?void 0:u.type)?y&&null!=u.schema?{type:"json_schema",json_schema:{schema:u.schema,strict:w,name:null!=(g=u.name)?g:"response",description:u.description}}:{type:"json_object"}:void 0,stop:a,seed:l,verbosity:v.textVerbosity,max_completion_tokens:v.maxCompletionTokens,store:v.store,metadata:v.metadata,prediction:v.prediction,reasoning_effort:v.reasoningEffort,service_tier:v.serviceTier,prompt_cache_key:v.promptCacheKey,safety_identifier:v.safetyIdentifier,messages:b};var I;dp(this.modelId)?(null!=x.temperature&&(x.temperature=void 0,f.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),null!=x.top_p&&(x.top_p=void 0,f.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"})),null!=x.frequency_penalty&&(x.frequency_penalty=void 0,f.push({type:"unsupported-setting",setting:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),null!=x.presence_penalty&&(x.presence_penalty=void 0,f.push({type:"unsupported-setting",setting:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),null!=x.logit_bias&&(x.logit_bias=void 0,f.push({type:"other",message:"logitBias is not supported for reasoning models"})),null!=x.logprobs&&(x.logprobs=void 0,f.push({type:"other",message:"logprobs is not supported for reasoning models"})),null!=x.top_logprobs&&(x.top_logprobs=void 0,f.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),null!=x.max_tokens&&(null==x.max_completion_tokens&&(x.max_completion_tokens=x.max_tokens),x.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&null!=x.temperature&&(x.temperature=void 0,f.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),"flex"!==v.serviceTier||((I=this.modelId).startsWith("o3")||I.startsWith("o4-mini")||I.startsWith("gpt-5")&&!I.startsWith("gpt-5-chat"))||(f.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),x.service_tier=void 0),"priority"!==v.serviceTier||function(e){return e.startsWith("gpt-4")||e.startsWith("gpt-5-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-nano")&&!e.startsWith("gpt-5-chat")||e.startsWith("o3")||e.startsWith("o4-mini")}(this.modelId)||(f.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),x.service_tier=void 0);const{tools:S,toolChoice:$,toolWarnings:O}=function({tools:e,toolChoice:t,structuredOutputs:n,strictJsonSchema:r}){const o=[];if(null==(e=(null==e?void 0:e.length)?e:void 0))return{tools:void 0,toolChoice:void 0,toolWarnings:o};const i=[];for(const a of e)switch(a.type){case"function":i.push({type:"function",function:{name:a.name,description:a.description,parameters:a.inputSchema,strict:n?r:void 0}});break;case"provider-defined":switch(a.id){case"openai.file_search":{const e=rp.parse(a.args);i.push({type:"file_search",vector_store_ids:e.vectorStoreIds,max_num_results:e.maxNumResults,ranking_options:e.ranking?{ranker:e.ranking.ranker}:void 0,filters:e.filters});break}case"openai.web_search_preview":{const e=ip.parse(a.args);i.push({type:"web_search_preview",search_context_size:e.searchContextSize,user_location:e.userLocation});break}default:o.push({type:"unsupported-tool",tool:a})}break;default:o.push({type:"unsupported-tool",tool:a})}if(null==t)return{tools:i,toolChoice:void 0,toolWarnings:o};const s=t.type;switch(s){case"auto":case"none":case"required":return{tools:i,toolChoice:s,toolWarnings:o};case"tool":return{tools:i,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:o};default:throw new At({functionality:`tool choice type: ${s}`})}}({tools:c,toolChoice:d,structuredOutputs:y,strictJsonSchema:w});return{args:{...x,tools:S,tool_choice:$},warnings:[...f,...O]}}async doGenerate(e){var t,n,r,o,i,s,a,u,l,c,d,p,m,_;const{args:h,warnings:g}=await this.getArgs(e),{responseHeaders:f,value:v,rawValue:y}=await Ad({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:pd(this.config.headers(),e.headers),body:h,failedResponseHandler:Kd,successfulResponseHandler:Md(lp),abortSignal:e.abortSignal,fetch:this.config.fetch}),b=v.choices[0],k=[],w=b.message.content;null!=w&&w.length>0&&k.push({type:"text",text:w});for(const $ of null!=(t=b.message.tool_calls)?t:[])k.push({type:"tool-call",toolCallId:null!=(n=$.id)?n:hd(),toolName:$.function.name,input:$.function.arguments});for(const $ of null!=(r=b.message.annotations)?r:[])k.push({type:"source",sourceType:"url",id:hd(),url:$.url,title:$.title});const x=null==(o=v.usage)?void 0:o.completion_tokens_details,I=null==(i=v.usage)?void 0:i.prompt_tokens_details,S={openai:{}};return null!=(null==x?void 0:x.accepted_prediction_tokens)&&(S.openai.acceptedPredictionTokens=null==x?void 0:x.accepted_prediction_tokens),null!=(null==x?void 0:x.rejected_prediction_tokens)&&(S.openai.rejectedPredictionTokens=null==x?void 0:x.rejected_prediction_tokens),null!=(null==(s=b.logprobs)?void 0:s.content)&&(S.openai.logprobs=b.logprobs.content),{content:k,finishReason:Xd(b.finish_reason),usage:{inputTokens:null!=(u=null==(a=v.usage)?void 0:a.prompt_tokens)?u:void 0,outputTokens:null!=(c=null==(l=v.usage)?void 0:l.completion_tokens)?c:void 0,totalTokens:null!=(p=null==(d=v.usage)?void 0:d.total_tokens)?p:void 0,reasoningTokens:null!=(m=null==x?void 0:x.reasoning_tokens)?m:void 0,cachedInputTokens:null!=(_=null==I?void 0:I.cached_tokens)?_:void 0},request:{body:h},response:{...Yd(v),headers:f,body:y},warnings:g,providerMetadata:S}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:o,value:i}=await Ad({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:pd(this.config.headers(),e.headers),body:r,failedResponseHandler:Kd,successfulResponseHandler:Dd(cp),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=[];let a="unknown";const u={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let l=!0,c=!1;const d={openai:{}};return{stream:i.pipeThrough(new TransformStream({start(e){e.enqueue({type:"stream-start",warnings:n})},transform(t,n){var r,o,i,p,m,_,h,g,f,v,y,b,k,w,x,I,S,$,O,E,T,R,N,A;if(e.includeRawChunks&&n.enqueue({type:"raw",rawValue:t.rawValue}),!t.success)return a="error",void n.enqueue({type:"error",error:t.error});const C=t.value;if("error"in C)return a="error",void n.enqueue({type:"error",error:C.error});l&&(l=!1,n.enqueue({type:"response-metadata",...Yd(C)})),null!=C.usage&&(u.inputTokens=null!=(r=C.usage.prompt_tokens)?r:void 0,u.outputTokens=null!=(o=C.usage.completion_tokens)?o:void 0,u.totalTokens=null!=(i=C.usage.total_tokens)?i:void 0,u.reasoningTokens=null!=(m=null==(p=C.usage.completion_tokens_details)?void 0:p.reasoning_tokens)?m:void 0,u.cachedInputTokens=null!=(h=null==(_=C.usage.prompt_tokens_details)?void 0:_.cached_tokens)?h:void 0,null!=(null==(g=C.usage.completion_tokens_details)?void 0:g.accepted_prediction_tokens)&&(d.openai.acceptedPredictionTokens=null==(f=C.usage.completion_tokens_details)?void 0:f.accepted_prediction_tokens),null!=(null==(v=C.usage.completion_tokens_details)?void 0:v.rejected_prediction_tokens)&&(d.openai.rejectedPredictionTokens=null==(y=C.usage.completion_tokens_details)?void 0:y.rejected_prediction_tokens));const P=C.choices[0];if(null!=(null==P?void 0:P.finish_reason)&&(a=Xd(P.finish_reason)),null!=(null==(b=null==P?void 0:P.logprobs)?void 0:b.content)&&(d.openai.logprobs=P.logprobs.content),null==(null==P?void 0:P.delta))return;const U=P.delta;if(null!=U.content&&(c||(n.enqueue({type:"text-start",id:"0"}),c=!0),n.enqueue({type:"text-delta",id:"0",delta:U.content})),null!=U.tool_calls)for(const e of U.tool_calls){const t=e.index;if(null==s[t]){if("function"!==e.type)throw new nt({data:e,message:"Expected 'function' type."});if(null==e.id)throw new nt({data:e,message:"Expected 'id' to be a string."});if(null==(null==(k=e.function)?void 0:k.name))throw new nt({data:e,message:"Expected 'function.name' to be a string."});n.enqueue({type:"tool-input-start",id:e.id,toolName:e.function.name}),s[t]={id:e.id,type:"function",function:{name:e.function.name,arguments:null!=(w=e.function.arguments)?w:""},hasFinished:!1};const r=s[t];null!=(null==(x=r.function)?void 0:x.name)&&null!=(null==(I=r.function)?void 0:I.arguments)&&(r.function.arguments.length>0&&n.enqueue({type:"tool-input-delta",id:r.id,delta:r.function.arguments}),Ed(r.function.arguments)&&(n.enqueue({type:"tool-input-end",id:r.id}),n.enqueue({type:"tool-call",toolCallId:null!=(S=r.id)?S:hd(),toolName:r.function.name,input:r.function.arguments}),r.hasFinished=!0));continue}const r=s[t];r.hasFinished||(null!=(null==($=e.function)?void 0:$.arguments)&&(r.function.arguments+=null!=(E=null==(O=e.function)?void 0:O.arguments)?E:""),n.enqueue({type:"tool-input-delta",id:r.id,delta:null!=(T=e.function.arguments)?T:""}),null!=(null==(R=r.function)?void 0:R.name)&&null!=(null==(N=r.function)?void 0:N.arguments)&&Ed(r.function.arguments)&&(n.enqueue({type:"tool-input-end",id:r.id}),n.enqueue({type:"tool-call",toolCallId:null!=(A=r.id)?A:hd(),toolName:r.function.name,input:r.function.arguments}),r.hasFinished=!0))}if(null!=U.annotations)for(const e of U.annotations)n.enqueue({type:"source",sourceType:"url",id:hd(),url:e.url,title:e.title})},flush(e){c&&e.enqueue({type:"text-end",id:"0"}),e.enqueue({type:"finish",finishReason:a,usage:u,...null!=d?{providerMetadata:d}:{}})}})),request:{body:r},response:{headers:o}}}},up=Tl({prompt_tokens:al().nullish(),completion_tokens:al().nullish(),total_tokens:al().nullish(),prompt_tokens_details:Tl({cached_tokens:al().nullish()}).nullish(),completion_tokens_details:Tl({reasoning_tokens:al().nullish(),accepted_prediction_tokens:al().nullish(),rejected_prediction_tokens:al().nullish()}).nullish()}).nullish(),lp=Tl({id:zu().nullish(),created:al().nullish(),model:zu().nullish(),choices:Ol(Tl({message:Tl({role:Hl("assistant").nullish(),content:zu().nullish(),tool_calls:Ol(Tl({id:zu().nullish(),type:Hl("function"),function:Tl({name:zu(),arguments:zu()})})).nullish(),annotations:Ol(Tl({type:Hl("url_citation"),start_index:al(),end_index:al(),url:zu(),title:zu()})).nullish()}),index:al(),logprobs:Tl({content:Ol(Tl({token:zu(),logprob:al(),top_logprobs:Ol(Tl({token:zu(),logprob:al()}))})).nullish()}).nullish(),finish_reason:zu().nullish()})),usage:up}),cp=Cl([Tl({id:zu().nullish(),created:al().nullish(),model:zu().nullish(),choices:Ol(Tl({delta:Tl({role:Jl(["assistant"]).nullish(),content:zu().nullish(),tool_calls:Ol(Tl({index:al(),id:zu().nullish(),type:Hl("function").nullish(),function:Tl({name:zu().nullish(),arguments:zu().nullish()})})).nullish(),annotations:Ol(Tl({type:Hl("url_citation"),start_index:al(),end_index:al(),url:zu(),title:zu()})).nullish()}).nullish(),logprobs:Tl({content:Ol(Tl({token:zu(),logprob:al(),top_logprobs:Ol(Tl({token:zu(),logprob:al()}))})).nullish()}).nullish(),finish_reason:zu().nullish(),index:al()})),usage:up}),Gd]);function dp(e){return(e.startsWith("o")||e.startsWith("gpt-5"))&&!e.startsWith("gpt-5-chat")}function pp(e){var t,n;return dp(e)?null!=(n=null==(t=mp[e])?void 0:t.systemMessageMode)?n:"developer":"system"}var mp={"o1-mini":{systemMessageMode:"remove"},"o1-mini-2024-09-12":{systemMessageMode:"remove"},"o1-preview":{systemMessageMode:"remove"},"o1-preview-2024-09-12":{systemMessageMode:"remove"},o3:{systemMessageMode:"developer"},"o3-2025-04-16":{systemMessageMode:"developer"},"o3-mini":{systemMessageMode:"developer"},"o3-mini-2025-01-31":{systemMessageMode:"developer"},"o4-mini":{systemMessageMode:"developer"},"o4-mini-2025-04-16":{systemMessageMode:"developer"}};function _p({id:e,model:t,created:n}){return{id:null!=e?e:void 0,modelId:null!=t?t:void 0,timestamp:null!=n?new Date(1e3*n):void 0}}function hp(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var gp=Tl({echo:dl().optional(),logitBias:ql(zu(),al()).optional(),suffix:zu().optional(),user:zu().optional(),logprobs:Cl([dl(),al()]).optional()}),fp=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={},this.modelId=e,this.config=t}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:o,frequencyPenalty:i,presencePenalty:s,stopSequences:a,responseFormat:u,tools:l,toolChoice:c,seed:d,providerOptions:p}){const m=[],_={...await Rd({provider:"openai",providerOptions:p,schema:gp}),...await Rd({provider:this.providerOptionsName,providerOptions:p,schema:gp})};null!=o&&m.push({type:"unsupported-setting",setting:"topK"}),(null==l?void 0:l.length)&&m.push({type:"unsupported-setting",setting:"tools"}),null!=c&&m.push({type:"unsupported-setting",setting:"toolChoice"}),null!=u&&"text"!==u.type&&m.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});const{prompt:h,stopSequences:g}=function({prompt:e,user:t="user",assistant:n="assistant"}){let r="";"system"===e[0].role&&(r+=`${e[0].content}\n\n`,e=e.slice(1));for(const{role:o,content:i}of e)switch(o){case"system":throw new Ye({message:"Unexpected system message in prompt: ${content}",prompt:e});case"user":r+=`${t}:\n${i.map((e=>{if("text"===e.type)return e.text})).filter(Boolean).join("")}\n\n`;break;case"assistant":r+=`${n}:\n${i.map((e=>{switch(e.type){case"text":return e.text;case"tool-call":throw new At({functionality:"tool-call messages"})}})).join("")}\n\n`;break;case"tool":throw new At({functionality:"tool messages"});default:throw new Error(`Unsupported role: ${o}`)}return r+=`${n}:\n`,{prompt:r,stopSequences:[`\n${t}:`]}}({prompt:e}),f=[...null!=g?g:[],...null!=a?a:[]];return{args:{model:this.modelId,echo:_.echo,logit_bias:_.logitBias,logprobs:!0===(null==_?void 0:_.logprobs)?0:!1===(null==_?void 0:_.logprobs)||null==_?void 0:_.logprobs,suffix:_.suffix,user:_.user,max_tokens:t,temperature:n,top_p:r,frequency_penalty:i,presence_penalty:s,seed:d,prompt:h,stop:f.length>0?f:void 0},warnings:m}}async doGenerate(e){var t,n,r;const{args:o,warnings:i}=await this.getArgs(e),{responseHeaders:s,value:a,rawValue:u}=await Ad({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:pd(this.config.headers(),e.headers),body:o,failedResponseHandler:Kd,successfulResponseHandler:Md(yp),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=a.choices[0],c={openai:{}};return null!=l.logprobs&&(c.openai.logprobs=l.logprobs),{content:[{type:"text",text:l.text}],usage:{inputTokens:null==(t=a.usage)?void 0:t.prompt_tokens,outputTokens:null==(n=a.usage)?void 0:n.completion_tokens,totalTokens:null==(r=a.usage)?void 0:r.total_tokens},finishReason:hp(l.finish_reason),request:{body:o},response:{..._p(a),headers:s,body:u},providerMetadata:c,warnings:i}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:o,value:i}=await Ad({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:pd(this.config.headers(),e.headers),body:r,failedResponseHandler:Kd,successfulResponseHandler:Dd(bp),abortSignal:e.abortSignal,fetch:this.config.fetch});let s="unknown";const a={openai:{}},u={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let l=!0;return{stream:i.pipeThrough(new TransformStream({start(e){e.enqueue({type:"stream-start",warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:"raw",rawValue:t.rawValue}),!t.success)return s="error",void n.enqueue({type:"error",error:t.error});const r=t.value;if("error"in r)return s="error",void n.enqueue({type:"error",error:r.error});l&&(l=!1,n.enqueue({type:"response-metadata",..._p(r)}),n.enqueue({type:"text-start",id:"0"})),null!=r.usage&&(u.inputTokens=r.usage.prompt_tokens,u.outputTokens=r.usage.completion_tokens,u.totalTokens=r.usage.total_tokens);const o=r.choices[0];null!=(null==o?void 0:o.finish_reason)&&(s=hp(o.finish_reason)),null!=(null==o?void 0:o.logprobs)&&(a.openai.logprobs=o.logprobs),null!=(null==o?void 0:o.text)&&o.text.length>0&&n.enqueue({type:"text-delta",id:"0",delta:o.text})},flush(e){l||e.enqueue({type:"text-end",id:"0"}),e.enqueue({type:"finish",finishReason:s,providerMetadata:a,usage:u})}})),request:{body:r},response:{headers:o}}}},vp=Tl({prompt_tokens:al(),completion_tokens:al(),total_tokens:al()}),yp=Tl({id:zu().nullish(),created:al().nullish(),model:zu().nullish(),choices:Ol(Tl({text:zu(),finish_reason:zu(),logprobs:Tl({tokens:Ol(zu()),token_logprobs:Ol(al()),top_logprobs:Ol(ql(zu(),al())).nullish()}).nullish()})),usage:vp.nullish()}),bp=Cl([Tl({id:zu().nullish(),created:al().nullish(),model:zu().nullish(),choices:Ol(Tl({text:zu(),finish_reason:zu().nullish(),index:al(),logprobs:Tl({tokens:Ol(zu()),token_logprobs:Ol(al()),top_logprobs:Ol(ql(zu(),al())).nullish()}).nullish()})),usage:vp.nullish()}),Gd]),kp=Tl({dimensions:al().optional(),user:zu().optional()}),wp=class{constructor(e,t){this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){var o;if(e.length>this.maxEmbeddingsPerCall)throw new wt({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const i=null!=(o=await Rd({provider:"openai",providerOptions:r,schema:kp}))?o:{},{responseHeaders:s,value:a,rawValue:u}=await Ad({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:pd(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:"float",dimensions:i.dimensions,user:i.user},failedResponseHandler:Kd,successfulResponseHandler:Md(xp),abortSignal:n,fetch:this.config.fetch});return{embeddings:a.data.map((e=>e.embedding)),usage:a.usage?{tokens:a.usage.prompt_tokens}:void 0,response:{headers:s,body:u}}}},xp=Tl({data:Ol(Tl({embedding:Ol(al())})),usage:Tl({prompt_tokens:al()}).nullish()}),Ip={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10},Sp=new Set(["gpt-image-1"]),$p=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get maxImagesPerCall(){var e;return null!=(e=Ip[this.modelId])?e:1}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:r,seed:o,providerOptions:i,headers:s,abortSignal:a}){var u,l,c,d;const p=[];null!=r&&p.push({type:"unsupported-setting",setting:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),null!=o&&p.push({type:"unsupported-setting",setting:"seed"});const m=null!=(c=null==(l=null==(u=this.config._internal)?void 0:u.currentDate)?void 0:l.call(u))?c:new Date,{value:_,responseHeaders:h}=await Ad({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:pd(this.config.headers(),s),body:{model:this.modelId,prompt:e,n:t,size:n,...null!=(d=i.openai)?d:{},...Sp.has(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:Kd,successfulResponseHandler:Md(Op),abortSignal:a,fetch:this.config.fetch});return{images:_.data.map((e=>e.b64_json)),warnings:p,response:{timestamp:m,modelId:this.modelId,headers:h},providerMetadata:{openai:{images:_.data.map((e=>e.revised_prompt?{revisedPrompt:e.revised_prompt}:null))}}}}},Op=Tl({data:Ol(Tl({b64_json:zu(),revised_prompt:zu().optional()}))}),Ep=Tl({container:Cl([zu(),Tl({fileIds:Ol(zu()).optional()})]).optional()}),Tp={codeInterpreter:Pd({id:"openai.code_interpreter",name:"code_interpreter",inputSchema:Tl({})}),fileSearch:op,webSearchPreview:sp};function Rp(e,t){return!!t&&t.some((t=>e.startsWith(t)))}var Np=Tl({itemId:zu().nullish(),reasoningEncryptedContent:zu().nullish()});function Ap({finishReason:e,hasToolCalls:t}){switch(e){case void 0:case null:return t?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return t?"tool-calls":"unknown"}}var Cp=Tl({type:Hl("web_search_call"),id:zu(),status:zu(),action:Ul("type",[Tl({type:Hl("search"),query:zu()}),Tl({type:Hl("open_page"),url:zu()}),Tl({type:Hl("find"),url:zu(),pattern:zu()})]).nullish()}),Pp=Ol(Tl({token:zu(),logprob:al(),top_logprobs:Ol(Tl({token:zu(),logprob:al()}))})),Up=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({maxOutputTokens:e,temperature:t,stopSequences:n,topP:r,topK:o,presencePenalty:i,frequencyPenalty:s,seed:a,prompt:u,providerOptions:l,tools:c,toolChoice:d,responseFormat:p}){var m,_;const h=[],g=function(e){const t=e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat"),n=e.startsWith("gpt-4")||e.startsWith("gpt-5-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-nano")&&!e.startsWith("gpt-5-chat")||e.startsWith("o3")||e.startsWith("o4-mini"),r={requiredAutoTruncation:!1,systemMessageMode:"system",supportsFlexProcessing:t,supportsPriorityProcessing:n};if(e.startsWith("gpt-5-chat"))return{...r,isReasoningModel:!1};if(e.startsWith("o")||e.startsWith("gpt-5")||e.startsWith("codex-")||e.startsWith("computer-use"))return e.startsWith("o1-mini")||e.startsWith("o1-preview")?{...r,isReasoningModel:!0,systemMessageMode:"remove"}:{...r,isReasoningModel:!0,systemMessageMode:"developer"};return{...r,isReasoningModel:!1}}(this.modelId);null!=o&&h.push({type:"unsupported-setting",setting:"topK"}),null!=a&&h.push({type:"unsupported-setting",setting:"seed"}),null!=i&&h.push({type:"unsupported-setting",setting:"presencePenalty"}),null!=s&&h.push({type:"unsupported-setting",setting:"frequencyPenalty"}),null!=n&&h.push({type:"unsupported-setting",setting:"stopSequences"});const{messages:f,warnings:v}=await async function({prompt:e,systemMessageMode:t,fileIdPrefixes:n}){var r,o,i,s,a,u;const l=[],c=[];for(const{role:d,content:p}of e)switch(d){case"system":switch(t){case"system":l.push({role:"system",content:p});break;case"developer":l.push({role:"developer",content:p});break;case"remove":c.push({type:"other",message:"system messages are removed for this model"});break;default:throw new Error(`Unsupported system message mode: ${t}`)}break;case"user":l.push({role:"user",content:p.map(((e,t)=>{var r,o,i;switch(e.type){case"text":return{type:"input_text",text:e.text};case"file":if(e.mediaType.startsWith("image/")){const t="image/*"===e.mediaType?"image/jpeg":e.mediaType;return{type:"input_image",...e.data instanceof URL?{image_url:e.data.toString()}:"string"==typeof e.data&&Rp(e.data,n)?{file_id:e.data}:{image_url:`data:${t};base64,${Hd(e.data)}`},detail:null==(o=null==(r=e.providerOptions)?void 0:r.openai)?void 0:o.imageDetail}}if("application/pdf"===e.mediaType)return e.data instanceof URL?{type:"input_file",file_url:e.data.toString()}:{type:"input_file",..."string"==typeof e.data&&Rp(e.data,n)?{file_id:e.data}:{filename:null!=(i=e.filename)?i:`part-${t}.pdf`,file_data:`data:application/pdf;base64,${Hd(e.data)}`}};throw new At({functionality:`file part media type ${e.mediaType}`})}}))});break;case"assistant":{const e={};for(const t of p)switch(t.type){case"text":l.push({role:"assistant",content:[{type:"output_text",text:t.text}],id:null!=(i=null==(o=null==(r=t.providerOptions)?void 0:r.openai)?void 0:o.itemId)?i:void 0});break;case"tool-call":if(t.providerExecuted)break;l.push({type:"function_call",call_id:t.toolCallId,name:t.toolName,arguments:JSON.stringify(t.input),id:null!=(u=null==(a=null==(s=t.providerOptions)?void 0:s.openai)?void 0:a.itemId)?u:void 0});break;case"tool-result":c.push({type:"other",message:"tool result parts in assistant messages are not supported for OpenAI responses"});break;case"reasoning":{const n=await Rd({provider:"openai",providerOptions:t.providerOptions,schema:Np}),r=null==n?void 0:n.itemId;if(null!=r){const o=e[r],i=[];t.text.length>0?i.push({type:"summary_text",text:t.text}):void 0!==o&&c.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(t)}.`}),void 0===o?(e[r]={type:"reasoning",id:r,encrypted_content:null==n?void 0:n.reasoningEncryptedContent,summary:i},l.push(e[r])):o.summary.push(...i)}else c.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(t)}.`});break}}break}case"tool":for(const e of p){const t=e.output;let n;switch(t.type){case"text":case"error-text":n=t.value;break;case"content":case"json":case"error-json":n=JSON.stringify(t.value)}l.push({type:"function_call_output",call_id:e.toolCallId,output:n})}break;default:throw new Error(`Unsupported role: ${d}`)}return{messages:l,warnings:c}}({prompt:u,systemMessageMode:g.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes});h.push(...v);const y=await Rd({provider:"openai",providerOptions:l,schema:Zp}),b=null!=(m=null==y?void 0:y.strictJsonSchema)&&m,k="number"==typeof(null==y?void 0:y.logprobs)?null==y?void 0:y.logprobs:!0===(null==y?void 0:y.logprobs)?20:void 0,w=k?Array.isArray(null==y?void 0:y.include)?[...null==y?void 0:y.include,"message.output_text.logprobs"]:["message.output_text.logprobs"]:null==y?void 0:y.include,x={model:this.modelId,input:f,temperature:t,top_p:r,max_output_tokens:e,...("json"===(null==p?void 0:p.type)||(null==y?void 0:y.textVerbosity))&&{text:{..."json"===(null==p?void 0:p.type)&&{format:null!=p.schema?{type:"json_schema",strict:b,name:null!=(_=p.name)?_:"response",description:p.description,schema:p.schema}:{type:"json_object"}},...(null==y?void 0:y.textVerbosity)&&{verbosity:y.textVerbosity}}},metadata:null==y?void 0:y.metadata,parallel_tool_calls:null==y?void 0:y.parallelToolCalls,previous_response_id:null==y?void 0:y.previousResponseId,store:null==y?void 0:y.store,user:null==y?void 0:y.user,instructions:null==y?void 0:y.instructions,service_tier:null==y?void 0:y.serviceTier,include:w,prompt_cache_key:null==y?void 0:y.promptCacheKey,safety_identifier:null==y?void 0:y.safetyIdentifier,top_logprobs:k,...g.isReasoningModel&&(null!=(null==y?void 0:y.reasoningEffort)||null!=(null==y?void 0:y.reasoningSummary))&&{reasoning:{...null!=(null==y?void 0:y.reasoningEffort)&&{effort:y.reasoningEffort},...null!=(null==y?void 0:y.reasoningSummary)&&{summary:y.reasoningSummary}}},...g.requiredAutoTruncation&&{truncation:"auto"}};g.isReasoningModel?(null!=x.temperature&&(x.temperature=void 0,h.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),null!=x.top_p&&(x.top_p=void 0,h.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"}))):(null!=(null==y?void 0:y.reasoningEffort)&&h.push({type:"unsupported-setting",setting:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),null!=(null==y?void 0:y.reasoningSummary)&&h.push({type:"unsupported-setting",setting:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),"flex"!==(null==y?void 0:y.serviceTier)||g.supportsFlexProcessing||(h.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete x.service_tier),"priority"!==(null==y?void 0:y.serviceTier)||g.supportsPriorityProcessing||(h.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete x.service_tier);const{tools:I,toolChoice:S,toolWarnings:$}=function({tools:e,toolChoice:t,strictJsonSchema:n}){const r=[];if(null==(e=(null==e?void 0:e.length)?e:void 0))return{tools:void 0,toolChoice:void 0,toolWarnings:r};const o=[];for(const s of e)switch(s.type){case"function":o.push({type:"function",name:s.name,description:s.description,parameters:s.inputSchema,strict:n});break;case"provider-defined":switch(s.id){case"openai.file_search":{const e=rp.parse(s.args);o.push({type:"file_search",vector_store_ids:e.vectorStoreIds,max_num_results:e.maxNumResults,ranking_options:e.ranking?{ranker:e.ranking.ranker}:void 0,filters:e.filters});break}case"openai.web_search_preview":{const e=ip.parse(s.args);o.push({type:"web_search_preview",search_context_size:e.searchContextSize,user_location:e.userLocation});break}case"openai.code_interpreter":{const e=Ep.parse(s.args);o.push({type:"code_interpreter",container:null==e.container?{type:"auto",file_ids:void 0}:"string"==typeof e.container?e.container:{type:"auto",file_ids:e.container.fileIds}});break}default:r.push({type:"unsupported-tool",tool:s})}break;default:r.push({type:"unsupported-tool",tool:s})}if(null==t)return{tools:o,toolChoice:void 0,toolWarnings:r};const i=t.type;switch(i){case"auto":case"none":case"required":return{tools:o,toolChoice:i,toolWarnings:r};case"tool":return{tools:o,toolChoice:"code_interpreter"===t.toolName||"file_search"===t.toolName||"web_search_preview"===t.toolName?{type:t.toolName}:{type:"function",name:t.toolName},toolWarnings:r};default:throw new At({functionality:`tool choice type: ${i}`})}}({tools:c,toolChoice:d,strictJsonSchema:b});return{args:{...x,tools:I,tool_choice:S},warnings:[...h,...$]}}async doGenerate(e){var t,n,r,o,i,s,a,u,l,c,d,p,m,_;const{args:h,warnings:g}=await this.getArgs(e),f=this.config.url({path:"/responses",modelId:this.modelId}),{responseHeaders:v,value:y,rawValue:b}=await Ad({url:f,headers:pd(this.config.headers(),e.headers),body:h,failedResponseHandler:Kd,successfulResponseHandler:Md(Tl({id:zu(),created_at:al(),error:Tl({code:zu(),message:zu()}).nullish(),model:zu(),output:Ol(Ul("type",[Tl({type:Hl("message"),role:Hl("assistant"),id:zu(),content:Ol(Tl({type:Hl("output_text"),text:zu(),logprobs:Pp.nullish(),annotations:Ol(Ul("type",[Tl({type:Hl("url_citation"),start_index:al(),end_index:al(),url:zu(),title:zu()}),Tl({type:Hl("file_citation"),start_index:al(),end_index:al(),file_id:zu(),quote:zu()})]))}))}),Tl({type:Hl("function_call"),call_id:zu(),name:zu(),arguments:zu(),id:zu()}),Cp,Tl({type:Hl("computer_call"),id:zu(),status:zu().optional()}),Tl({type:Hl("file_search_call"),id:zu(),status:zu().optional(),queries:Ol(zu()).nullish(),results:Ol(Tl({attributes:Tl({file_id:zu(),filename:zu(),score:al(),text:zu()})})).nullish()}),Tl({type:Hl("reasoning"),id:zu(),encrypted_content:zu().nullish(),summary:Ol(Tl({type:Hl("summary_text"),text:zu()}))})])),incomplete_details:Tl({reason:zu()}).nullable(),usage:jp})),abortSignal:e.abortSignal,fetch:this.config.fetch});if(y.error)throw new Ue({message:y.error.message,url:f,requestBodyValues:h,statusCode:400,responseHeaders:v,responseBody:b,isRetryable:!1});const k=[],w=[];for(const I of y.output)switch(I.type){case"reasoning":0===I.summary.length&&I.summary.push({type:"summary_text",text:""});for(const e of I.summary)k.push({type:"reasoning",text:e.text,providerMetadata:{openai:{itemId:I.id,reasoningEncryptedContent:null!=(t=I.encrypted_content)?t:null}}});break;case"message":for(const t of I.content){(null==(r=null==(n=e.providerOptions)?void 0:n.openai)?void 0:r.logprobs)&&t.logprobs&&w.push(t.logprobs),k.push({type:"text",text:t.text,providerMetadata:{openai:{itemId:I.id}}});for(const e of t.annotations)"url_citation"===e.type?k.push({type:"source",sourceType:"url",id:null!=(s=null==(i=(o=this.config).generateId)?void 0:i.call(o))?s:hd(),url:e.url,title:e.title}):"file_citation"===e.type&&k.push({type:"source",sourceType:"document",id:null!=(l=null==(u=(a=this.config).generateId)?void 0:u.call(a))?l:hd(),mediaType:"text/plain",title:e.quote,filename:e.file_id})}break;case"function_call":k.push({type:"tool-call",toolCallId:I.call_id,toolName:I.name,input:I.arguments,providerMetadata:{openai:{itemId:I.id}}});break;case"web_search_call":k.push({type:"tool-call",toolCallId:I.id,toolName:"web_search_preview",input:JSON.stringify({action:I.action}),providerExecuted:!0}),k.push({type:"tool-result",toolCallId:I.id,toolName:"web_search_preview",result:{status:I.status},providerExecuted:!0});break;case"computer_call":k.push({type:"tool-call",toolCallId:I.id,toolName:"computer_use",input:"",providerExecuted:!0}),k.push({type:"tool-result",toolCallId:I.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:I.status||"completed"},providerExecuted:!0});break;case"file_search_call":k.push({type:"tool-call",toolCallId:I.id,toolName:"file_search",input:"",providerExecuted:!0}),k.push({type:"tool-result",toolCallId:I.id,toolName:"file_search",result:{type:"file_search_tool_result",status:I.status||"completed",...I.queries&&{queries:I.queries},...I.results&&{results:I.results}},providerExecuted:!0})}const x={openai:{responseId:y.id}};return w.length>0&&(x.openai.logprobs=w),{content:k,finishReason:Ap({finishReason:null==(c=y.incomplete_details)?void 0:c.reason,hasToolCalls:k.some((e=>"tool-call"===e.type))}),usage:{inputTokens:y.usage.input_tokens,outputTokens:y.usage.output_tokens,totalTokens:y.usage.input_tokens+y.usage.output_tokens,reasoningTokens:null!=(p=null==(d=y.usage.output_tokens_details)?void 0:d.reasoning_tokens)?p:void 0,cachedInputTokens:null!=(_=null==(m=y.usage.input_tokens_details)?void 0:m.cached_tokens)?_:void 0},request:{body:h},response:{id:y.id,timestamp:new Date(1e3*y.created_at),modelId:y.model,headers:v,body:b},providerMetadata:x,warnings:g}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),{responseHeaders:r,value:o}=await Ad({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:pd(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:Kd,successfulResponseHandler:Dd(Mp),abortSignal:e.abortSignal,fetch:this.config.fetch}),i=this;let s="unknown";const a={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},u=[];let l=null;const c={};let d=!1;const p={};return{stream:o.pipeThrough(new TransformStream({start(e){e.enqueue({type:"stream-start",warnings:n})},transform(t,n){var r,o,m,_,h,g,f,v,y,b,k,w,x,I,S,$;if(e.includeRawChunks&&n.enqueue({type:"raw",rawValue:t.rawValue}),!t.success)return s="error",void n.enqueue({type:"error",error:t.error});const O=t.value;if(qp(O))"function_call"===O.item.type?(c[O.output_index]={toolName:O.item.name,toolCallId:O.item.call_id},n.enqueue({type:"tool-input-start",id:O.item.call_id,toolName:O.item.name})):"web_search_call"===O.item.type?(c[O.output_index]={toolName:"web_search_preview",toolCallId:O.item.id},n.enqueue({type:"tool-input-start",id:O.item.id,toolName:"web_search_preview"})):"computer_call"===O.item.type?(c[O.output_index]={toolName:"computer_use",toolCallId:O.item.id},n.enqueue({type:"tool-input-start",id:O.item.id,toolName:"computer_use"})):"file_search_call"===O.item.type?(c[O.output_index]={toolName:"file_search",toolCallId:O.item.id},n.enqueue({type:"tool-input-start",id:O.item.id,toolName:"file_search"})):"message"===O.item.type?n.enqueue({type:"text-start",id:O.item.id,providerMetadata:{openai:{itemId:O.item.id}}}):function(e){return qp(e)&&"reasoning"===e.item.type}(O)&&(p[O.item.id]={encryptedContent:O.item.encrypted_content,summaryParts:[0]},n.enqueue({type:"reasoning-start",id:`${O.item.id}:0`,providerMetadata:{openai:{itemId:O.item.id,reasoningEncryptedContent:null!=(r=O.item.encrypted_content)?r:null}}}));else if(Lp(O)){if("function_call"===O.item.type)c[O.output_index]=void 0,d=!0,n.enqueue({type:"tool-input-end",id:O.item.call_id}),n.enqueue({type:"tool-call",toolCallId:O.item.call_id,toolName:O.item.name,input:O.item.arguments,providerMetadata:{openai:{itemId:O.item.id}}});else if("web_search_call"===O.item.type)c[O.output_index]=void 0,d=!0,n.enqueue({type:"tool-input-end",id:O.item.id}),n.enqueue({type:"tool-call",toolCallId:O.item.id,toolName:"web_search_preview",input:JSON.stringify({action:O.item.action}),providerExecuted:!0}),n.enqueue({type:"tool-result",toolCallId:O.item.id,toolName:"web_search_preview",result:{status:O.item.status},providerExecuted:!0});else if("computer_call"===O.item.type)c[O.output_index]=void 0,d=!0,n.enqueue({type:"tool-input-end",id:O.item.id}),n.enqueue({type:"tool-call",toolCallId:O.item.id,toolName:"computer_use",input:"",providerExecuted:!0}),n.enqueue({type:"tool-result",toolCallId:O.item.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:O.item.status||"completed"},providerExecuted:!0});else if("file_search_call"===O.item.type)c[O.output_index]=void 0,d=!0,n.enqueue({type:"tool-input-end",id:O.item.id}),n.enqueue({type:"tool-call",toolCallId:O.item.id,toolName:"file_search",input:"",providerExecuted:!0}),n.enqueue({type:"tool-result",toolCallId:O.item.id,toolName:"file_search",result:{type:"file_search_tool_result",status:O.item.status||"completed",...O.item.queries&&{queries:O.item.queries},...O.item.results&&{results:O.item.results}},providerExecuted:!0});else if("message"===O.item.type)n.enqueue({type:"text-end",id:O.item.id});else if(function(e){return Lp(e)&&"reasoning"===e.item.type}(O)){const e=p[O.item.id];for(const t of e.summaryParts)n.enqueue({type:"reasoning-end",id:`${O.item.id}:${t}`,providerMetadata:{openai:{itemId:O.item.id,reasoningEncryptedContent:null!=(o=O.item.encrypted_content)?o:null}}});delete p[O.item.id]}}else if(function(e){return"response.function_call_arguments.delta"===e.type}(O)){const e=c[O.output_index];null!=e&&n.enqueue({type:"tool-input-delta",id:e.toolCallId,delta:O.delta})}else!function(e){return"response.created"===e.type}(O)?!function(e){return"response.output_text.delta"===e.type}(O)?!function(e){return"response.reasoning_summary_part.added"===e.type}(O)?!function(e){return"response.reasoning_summary_text.delta"===e.type}(O)?!function(e){return"response.completed"===e.type||"response.incomplete"===e.type}(O)?!function(e){return"response.output_text.annotation.added"===e.type}(O)?function(e){return"error"===e.type}(O)&&n.enqueue({type:"error",error:O}):"url_citation"===O.annotation.type?n.enqueue({type:"source",sourceType:"url",id:null!=(x=null==(w=(k=i.config).generateId)?void 0:w.call(k))?x:hd(),url:O.annotation.url,title:O.annotation.title}):"file_citation"===O.annotation.type&&n.enqueue({type:"source",sourceType:"document",id:null!=($=null==(S=(I=i.config).generateId)?void 0:S.call(I))?$:hd(),mediaType:"text/plain",title:O.annotation.quote,filename:O.annotation.file_id}):(s=Ap({finishReason:null==(g=O.response.incomplete_details)?void 0:g.reason,hasToolCalls:d}),a.inputTokens=O.response.usage.input_tokens,a.outputTokens=O.response.usage.output_tokens,a.totalTokens=O.response.usage.input_tokens+O.response.usage.output_tokens,a.reasoningTokens=null!=(v=null==(f=O.response.usage.output_tokens_details)?void 0:f.reasoning_tokens)?v:void 0,a.cachedInputTokens=null!=(b=null==(y=O.response.usage.input_tokens_details)?void 0:y.cached_tokens)?b:void 0):n.enqueue({type:"reasoning-delta",id:`${O.item_id}:${O.summary_index}`,delta:O.delta,providerMetadata:{openai:{itemId:O.item_id}}}):O.summary_index>0&&(null==(m=p[O.item_id])||m.summaryParts.push(O.summary_index),n.enqueue({type:"reasoning-start",id:`${O.item_id}:${O.summary_index}`,providerMetadata:{openai:{itemId:O.item_id,reasoningEncryptedContent:null!=(h=null==(_=p[O.item_id])?void 0:_.encryptedContent)?h:null}}})):(n.enqueue({type:"text-delta",id:O.item_id,delta:O.delta}),O.logprobs&&u.push(O.logprobs)):(l=O.response.id,n.enqueue({type:"response-metadata",id:O.response.id,timestamp:new Date(1e3*O.response.created_at),modelId:O.response.model}))},flush(e){const t={openai:{responseId:l}};u.length>0&&(t.openai.logprobs=u),e.enqueue({type:"finish",finishReason:s,usage:a,providerMetadata:t})}})),request:{body:t},response:{headers:r}}}},jp=Tl({input_tokens:al(),input_tokens_details:Tl({cached_tokens:al().nullish()}).nullish(),output_tokens:al(),output_tokens_details:Tl({reasoning_tokens:al().nullish()}).nullish()}),zp=Tl({type:Hl("response.output_text.delta"),item_id:zu(),delta:zu(),logprobs:Pp.nullish()}),Dp=Tl({type:Hl("error"),code:zu(),message:zu(),param:zu().nullish(),sequence_number:al()}),Mp=Cl([zp,Tl({type:Jl(["response.completed","response.incomplete"]),response:Tl({incomplete_details:Tl({reason:zu()}).nullish(),usage:jp})}),Tl({type:Hl("response.created"),response:Tl({id:zu(),created_at:al(),model:zu()})}),Tl({type:Hl("response.output_item.added"),output_index:al(),item:Ul("type",[Tl({type:Hl("message"),id:zu()}),Tl({type:Hl("reasoning"),id:zu(),encrypted_content:zu().nullish()}),Tl({type:Hl("function_call"),id:zu(),call_id:zu(),name:zu(),arguments:zu()}),Tl({type:Hl("web_search_call"),id:zu(),status:zu(),action:Tl({type:Hl("search"),query:zu().optional()}).nullish()}),Tl({type:Hl("computer_call"),id:zu(),status:zu()}),Tl({type:Hl("file_search_call"),id:zu(),status:zu(),queries:Ol(zu()).nullish(),results:Ol(Tl({attributes:Tl({file_id:zu(),filename:zu(),score:al(),text:zu()})})).optional()})])}),Tl({type:Hl("response.output_item.done"),output_index:al(),item:Ul("type",[Tl({type:Hl("message"),id:zu()}),Tl({type:Hl("reasoning"),id:zu(),encrypted_content:zu().nullish()}),Tl({type:Hl("function_call"),id:zu(),call_id:zu(),name:zu(),arguments:zu(),status:Hl("completed")}),Cp,Tl({type:Hl("computer_call"),id:zu(),status:Hl("completed")}),Tl({type:Hl("file_search_call"),id:zu(),status:Hl("completed"),queries:Ol(zu()).nullish(),results:Ol(Tl({attributes:Tl({file_id:zu(),filename:zu(),score:al(),text:zu()})})).nullish()})])}),Tl({type:Hl("response.function_call_arguments.delta"),item_id:zu(),output_index:al(),delta:zu()}),Tl({type:Hl("response.output_text.annotation.added"),annotation:Ul("type",[Tl({type:Hl("url_citation"),url:zu(),title:zu()}),Tl({type:Hl("file_citation"),file_id:zu(),quote:zu()})])}),Tl({type:Hl("response.reasoning_summary_part.added"),item_id:zu(),summary_index:al()}),Tl({type:Hl("response.reasoning_summary_text.delta"),item_id:zu(),summary_index:al(),delta:zu()}),Dp,Tl({type:zu()}).loose()]);function Lp(e){return"response.output_item.done"===e.type}function qp(e){return"response.output_item.added"===e.type}var Zp=Tl({metadata:yl().nullish(),parallelToolCalls:dl().nullish(),previousResponseId:zu().nullish(),store:dl().nullish(),user:zu().nullish(),reasoningEffort:zu().nullish(),strictJsonSchema:dl().nullish(),instructions:zu().nullish(),reasoningSummary:zu().nullish(),serviceTier:Jl(["auto","flex","priority"]).nullish(),include:Ol(Jl(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),textVerbosity:Jl(["low","medium","high"]).nullish(),promptCacheKey:zu().nullish(),safetyIdentifier:zu().nullish(),logprobs:Cl([dl(),al().min(1).max(20)]).optional()}),Fp=Tl({instructions:zu().nullish(),speed:al().min(.25).max(4).default(1).nullish()}),Wp=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({text:e,voice:t="alloy",outputFormat:n="mp3",speed:r,instructions:o,language:i,providerOptions:s}){const a=[],u=await Rd({provider:"openai",providerOptions:s,schema:Fp}),l={model:this.modelId,input:e,voice:t,response_format:"mp3",speed:r,instructions:o};if(n&&(["mp3","opus","aac","flac","wav","pcm"].includes(n)?l.response_format=n:a.push({type:"unsupported-setting",setting:"outputFormat",details:`Unsupported output format: ${n}. Using mp3 instead.`})),u){const e={};for(const t in e){const n=e[t];void 0!==n&&(l[t]=n)}}return i&&a.push({type:"unsupported-setting",setting:"language",details:`OpenAI speech models do not support language selection. Language parameter "${i}" was ignored.`}),{requestBody:l,warnings:a}}async doGenerate(e){var t,n,r;const o=null!=(r=null==(n=null==(t=this.config._internal)?void 0:t.currentDate)?void 0:n.call(t))?r:new Date,{requestBody:i,warnings:s}=await this.getArgs(e),{value:a,responseHeaders:u,rawValue:l}=await Ad({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:pd(this.config.headers(),e.headers),body:i,failedResponseHandler:Kd,successfulResponseHandler:async({response:e,url:t,requestBodyValues:n})=>{const r=md(e);if(!e.body)throw new Ue({message:"Response body is empty",url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0});try{const t=await e.arrayBuffer();return{responseHeaders:r,value:new Uint8Array(t)}}catch(o){throw new Ue({message:"Failed to read response as array buffer",url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0,cause:o})}},abortSignal:e.abortSignal,fetch:this.config.fetch});return{audio:a,warnings:s,request:{body:JSON.stringify(i)},response:{timestamp:o,modelId:this.modelId,headers:u,body:l}}}},Jp=Tl({include:Ol(zu()).optional(),language:zu().optional(),prompt:zu().optional(),temperature:al().min(0).max(1).default(0).optional(),timestampGranularities:Ol(Jl(["word","segment"])).default(["segment"]).optional()}),Bp={afrikaans:"af",arabic:"ar",armenian:"hy",azerbaijani:"az",belarusian:"be",bosnian:"bs",bulgarian:"bg",catalan:"ca",chinese:"zh",croatian:"hr",czech:"cs",danish:"da",dutch:"nl",english:"en",estonian:"et",finnish:"fi",french:"fr",galician:"gl",german:"de",greek:"el",hebrew:"he",hindi:"hi",hungarian:"hu",icelandic:"is",indonesian:"id",italian:"it",japanese:"ja",kannada:"kn",kazakh:"kk",korean:"ko",latvian:"lv",lithuanian:"lt",macedonian:"mk",malay:"ms",marathi:"mr",maori:"mi",nepali:"ne",norwegian:"no",persian:"fa",polish:"pl",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"sr",slovak:"sk",slovenian:"sl",spanish:"es",swahili:"sw",swedish:"sv",tagalog:"tl",tamil:"ta",thai:"th",turkish:"tr",ukrainian:"uk",urdu:"ur",vietnamese:"vi",welsh:"cy"},Hp=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({audio:e,mediaType:t,providerOptions:n}){const r=await Rd({provider:"openai",providerOptions:n,schema:Jp}),o=new FormData,i=e instanceof Uint8Array?new Blob([e]):new Blob([Bd(e)]);if(o.append("model",this.modelId),o.append("file",new File([i],"audio",{type:t})),r){const e={include:r.include,language:r.language,prompt:r.prompt,response_format:"verbose_json",temperature:r.temperature,timestamp_granularities:r.timestampGranularities};for(const[t,n]of Object.entries(e))null!=n&&o.append(t,String(n))}return{formData:o,warnings:[]}}async doGenerate(e){var t,n,r,o,i,s,a,u;const l=null!=(r=null==(n=null==(t=this.config._internal)?void 0:t.currentDate)?void 0:n.call(t))?r:new Date,{formData:c,warnings:d}=await this.getArgs(e),{value:p,responseHeaders:m,rawValue:_}=await(async({url:e,headers:t,formData:n,failedResponseHandler:r,successfulResponseHandler:o,abortSignal:i,fetch:s})=>Cd({url:e,headers:t,body:{content:n,values:Object.fromEntries(n.entries())},failedResponseHandler:r,successfulResponseHandler:o,abortSignal:i,fetch:s}))({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:pd(this.config.headers(),e.headers),formData:c,failedResponseHandler:Kd,successfulResponseHandler:Md(Vp),abortSignal:e.abortSignal,fetch:this.config.fetch}),h=null!=p.language&&p.language in Bp?Bp[p.language]:void 0;return{text:p.text,segments:null!=(a=null!=(s=null==(o=p.segments)?void 0:o.map((e=>({text:e.text,startSecond:e.start,endSecond:e.end}))))?s:null==(i=p.words)?void 0:i.map((e=>({text:e.word,startSecond:e.start,endSecond:e.end}))))?a:[],language:h,durationInSeconds:null!=(u=p.duration)?u:void 0,warnings:d,response:{timestamp:l,modelId:this.modelId,headers:m,body:_}}}},Vp=Tl({text:zu(),language:zu().nullish(),duration:al().nullish(),words:Ol(Tl({word:zu(),start:al(),end:al()})).nullish(),segments:Ol(Tl({id:al(),seek:al(),start:al(),end:al(),text:zu(),tokens:Ol(al()),temperature:al(),avg_logprob:al(),compression_ratio:al(),no_speech_prob:al()})).nullish()});function Gp(e={}){var t,n;const r=null!=(t=Vd(e.baseURL))?t:"https://api.openai.com/v1",o=null!=(n=e.name)?n:"openai",i=()=>({Authorization:`Bearer ${vd({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers}),s=t=>new wp(t,{provider:`${o}.embedding`,url:({path:e})=>`${r}${e}`,headers:i,fetch:e.fetch}),a=t=>new $p(t,{provider:`${o}.image`,url:({path:e})=>`${r}${e}`,headers:i,fetch:e.fetch}),u=t=>new Hp(t,{provider:`${o}.transcription`,url:({path:e})=>`${r}${e}`,headers:i,fetch:e.fetch}),l=t=>new Wp(t,{provider:`${o}.speech`,url:({path:e})=>`${r}${e}`,headers:i,fetch:e.fetch}),c=e=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return d(e)},d=t=>new Up(t,{provider:`${o}.responses`,url:({path:e})=>`${r}${e}`,headers:i,fetch:e.fetch,fileIdPrefixes:["file-"]}),p=function(e){return c(e)};return p.languageModel=c,p.chat=t=>new ap(t,{provider:`${o}.chat`,url:({path:e})=>`${r}${e}`,headers:i,fetch:e.fetch}),p.completion=t=>new fp(t,{provider:`${o}.completion`,url:({path:e})=>`${r}${e}`,headers:i,fetch:e.fetch}),p.responses=d,p.embedding=s,p.textEmbedding=s,p.textEmbeddingModel=s,p.image=a,p.imageModel=a,p.transcription=u,p.transcriptionModel=u,p.speech=l,p.speechModel=l,p.tools=Tp,p}var Kp=Gp(),Yp=zd({errorSchema:Tl({type:Hl("error"),error:Tl({type:zu(),message:zu()})}),errorToMessage:e=>e.error.message}),Xp=Tl({citations:Tl({enabled:dl()}).optional(),title:zu().optional(),context:zu().optional()}),Qp=Tl({sendReasoning:dl().optional(),thinking:Tl({type:Cl([Hl("enabled"),Hl("disabled")]),budgetTokens:al().optional()}).optional(),disableParallelToolUse:dl().optional()});function em(e){var t;const n=null==e?void 0:e.anthropic;return null!=(t=null==n?void 0:n.cacheControl)?t:null==n?void 0:n.cache_control}var tm=Tl({maxUses:al().optional(),allowedDomains:Ol(zu()).optional(),blockedDomains:Ol(zu()).optional(),userLocation:Tl({type:Hl("approximate"),city:zu().optional(),region:zu().optional(),country:zu().optional(),timezone:zu().optional()}).optional()}),nm=Ol(Tl({url:zu(),title:zu(),pageAge:zu().nullable(),encryptedContent:zu(),type:zu()})),rm=Ud({id:"anthropic.web_search_20250305",name:"web_search",inputSchema:Tl({query:zu()}),outputSchema:nm});function om(e){return"object"==typeof e&&null!==e&&"type"in e&&"web_search_20250305"===e.type}var im=Tl({type:Hl("code_execution_result"),stdout:zu(),stderr:zu(),return_code:al()}),sm=Ud({id:"anthropic.code_execution_20250522",name:"code_execution",inputSchema:Tl({code:zu()}),outputSchema:im});function am(e){if("string"==typeof e)return Buffer.from(e,"base64").toString("utf-8");if(e instanceof Uint8Array)return(new TextDecoder).decode(e);if(e instanceof URL)throw new At({functionality:"URL-based text documents are not supported for citations"});throw new At({functionality:"unsupported data type for text documents: "+typeof e})}async function um({prompt:e,sendReasoning:t,warnings:n}){var r,o,i,s,a;const u=new Set,l=function(e){const t=[];let n;for(const r of e){const{role:e}=r;switch(e){case"system":"system"!==(null==n?void 0:n.type)&&(n={type:"system",messages:[]},t.push(n)),n.messages.push(r);break;case"assistant":"assistant"!==(null==n?void 0:n.type)&&(n={type:"assistant",messages:[]},t.push(n)),n.messages.push(r);break;case"user":case"tool":"user"!==(null==n?void 0:n.type)&&(n={type:"user",messages:[]},t.push(n)),n.messages.push(r);break;default:throw new Error(`Unsupported role: ${e}`)}}return t}(e);let c;const d=[];async function p(e){var t,n;const r=await Rd({provider:"anthropic",providerOptions:e,schema:Xp});return null!=(n=null==(t=null==r?void 0:r.citations)?void 0:t.enabled)&&n}async function m(e){const t=await Rd({provider:"anthropic",providerOptions:e,schema:Xp});return{title:null==t?void 0:t.title,context:null==t?void 0:t.context}}for(let _=0;_<l.length;_++){const e=l[_],h=_===l.length-1,g=e.type;switch(g){case"system":if(null!=c)throw new At({functionality:"Multiple system messages that are separated by user/assistant messages"});c=e.messages.map((({content:e,providerOptions:t})=>({type:"text",text:e,cache_control:em(t)})));break;case"user":{const t=[];for(const n of e.messages){const{role:e,content:a}=n;switch(e){case"user":for(let e=0;e<a.length;e++){const s=a[e],l=e===a.length-1,c=null!=(r=em(s.providerOptions))?r:l?em(n.providerOptions):void 0;switch(s.type){case"text":t.push({type:"text",text:s.text,cache_control:c});break;case"file":if(s.mediaType.startsWith("image/"))t.push({type:"image",source:s.data instanceof URL?{type:"url",url:s.data.toString()}:{type:"base64",media_type:"image/*"===s.mediaType?"image/jpeg":s.mediaType,data:Hd(s.data)},cache_control:c});else if("application/pdf"===s.mediaType){u.add("pdfs-2024-09-25");const e=await p(s.providerOptions),n=await m(s.providerOptions);t.push({type:"document",source:s.data instanceof URL?{type:"url",url:s.data.toString()}:{type:"base64",media_type:"application/pdf",data:Hd(s.data)},title:null!=(o=n.title)?o:s.filename,...n.context&&{context:n.context},...e&&{citations:{enabled:!0}},cache_control:c})}else{if("text/plain"!==s.mediaType)throw new At({functionality:`media type: ${s.mediaType}`});{const e=await p(s.providerOptions),n=await m(s.providerOptions);t.push({type:"document",source:s.data instanceof URL?{type:"url",url:s.data.toString()}:{type:"text",media_type:"text/plain",data:am(s.data)},title:null!=(i=n.title)?i:s.filename,...n.context&&{context:n.context},...e&&{citations:{enabled:!0}},cache_control:c})}}}}break;case"tool":for(let e=0;e<a.length;e++){const r=a[e],o=e===a.length-1,i=null!=(s=em(r.providerOptions))?s:o?em(n.providerOptions):void 0,u=r.output;let l;switch(u.type){case"content":l=u.value.map((e=>{switch(e.type){case"text":return{type:"text",text:e.text,cache_control:void 0};case"media":if(e.mediaType.startsWith("image/"))return{type:"image",source:{type:"base64",media_type:e.mediaType,data:e.data},cache_control:void 0};throw new At({functionality:`media type: ${e.mediaType}`})}}));break;case"text":case"error-text":l=u.value;break;default:l=JSON.stringify(u.value)}t.push({type:"tool_result",tool_use_id:r.toolCallId,content:l,is_error:"error-text"===u.type||"error-json"===u.type||void 0,cache_control:i})}break;default:throw new Error(`Unsupported role: ${e}`)}}d.push({role:"user",content:t});break}case"assistant":{const r=[];for(let o=0;o<e.messages.length;o++){const i=e.messages[o],s=o===e.messages.length-1,{content:u}=i;for(let e=0;e<u.length;e++){const o=u[e],l=e===u.length-1,c=null!=(a=em(o.providerOptions))?a:l?em(i.providerOptions):void 0;switch(o.type){case"text":r.push({type:"text",text:h&&s&&l?o.text.trim():o.text,cache_control:c});break;case"reasoning":if(t){const e=await Rd({provider:"anthropic",providerOptions:o.providerOptions,schema:gm});null!=e?null!=e.signature?r.push({type:"thinking",thinking:o.text,signature:e.signature,cache_control:c}):null!=e.redactedData?r.push({type:"redacted_thinking",data:e.redactedData,cache_control:c}):n.push({type:"other",message:"unsupported reasoning metadata"}):n.push({type:"other",message:"unsupported reasoning metadata"})}else n.push({type:"other",message:"sending reasoning content is disabled for this model"});break;case"tool-call":if(o.providerExecuted){if("web_search"===o.toolName){r.push({type:"server_tool_use",id:o.toolCallId,name:"web_search",input:o.input,cache_control:c});break}if("code_execution"===o.toolName){r.push({type:"server_tool_use",id:o.toolCallId,name:"code_execution",input:o.input,cache_control:c});break}n.push({type:"other",message:`provider executed tool call for tool ${o.toolName} is not supported`});break}r.push({type:"tool_use",id:o.toolCallId,name:o.toolName,input:o.input,cache_control:c});break;case"tool-result":if("web_search"===o.toolName){const e=o.output;if("json"!==e.type){n.push({type:"other",message:`provider executed tool result output type ${e.type} for tool ${o.toolName} is not supported`});break}const t=nm.parse(e.value);r.push({type:"web_search_tool_result",tool_use_id:o.toolCallId,content:t.map((e=>({url:e.url,title:e.title,page_age:e.pageAge,encrypted_content:e.encryptedContent,type:e.type}))),cache_control:c});break}if("code_execution"===o.toolName){const e=o.output;if("json"!==e.type){n.push({type:"other",message:`provider executed tool result output type ${e.type} for tool ${o.toolName} is not supported`});break}const t=im.parse(e.value);r.push({type:"code_execution_tool_result",tool_use_id:o.toolCallId,content:{type:t.type,stdout:t.stdout,stderr:t.stderr,return_code:t.return_code},cache_control:c});break}n.push({type:"other",message:`provider executed tool result for tool ${o.toolName} is not supported`})}}}d.push({role:"assistant",content:r});break}default:throw new Error(`content type: ${g}`)}}return{prompt:{system:c,messages:d},betas:u}}function lm({finishReason:e,isJsonResponseFromTool:t}){switch(e){case"end_turn":case"stop_sequence":return"stop";case"tool_use":return t?"stop":"tool-calls";case"max_tokens":return"length";default:return"unknown"}}var cm={webSearchResult:Tl({type:Hl("web_search_result_location"),cited_text:zu(),url:zu(),title:zu(),encrypted_index:zu()}),pageLocation:Tl({type:Hl("page_location"),cited_text:zu(),document_index:al(),document_title:zu().nullable(),start_page_number:al(),end_page_number:al()}),charLocation:Tl({type:Hl("char_location"),cited_text:zu(),document_index:al(),document_title:zu().nullable(),start_char_index:al(),end_char_index:al()})},dm=Ul("type",[cm.webSearchResult,cm.pageLocation,cm.charLocation]);function pm(e,t,n,r){if("page_location"===e.type||"char_location"===e.type){const o=function(e,t,n){var r;const o=t[e.document_index];if(!o)return null;const i="page_location"===e.type?{citedText:e.cited_text,startPageNumber:e.start_page_number,endPageNumber:e.end_page_number}:{citedText:e.cited_text,startCharIndex:e.start_char_index,endCharIndex:e.end_char_index};return{type:"source",sourceType:"document",id:n(),mediaType:o.mediaType,title:null!=(r=e.document_title)?r:o.title,filename:o.filename,providerMetadata:{anthropic:i}}}(e,t,n);o&&r(o)}}Ul("type",[cm.pageLocation,cm.charLocation]);var mm=class{constructor(e,t){var n;this.specificationVersion="v2",this.modelId=e,this.config=t,this.generateId=null!=(n=t.generateId)?n:hd}supportsUrl(e){return"https:"===e.protocol}get provider(){return this.config.provider}get supportedUrls(){var e,t,n;return null!=(n=null==(t=(e=this.config).supportedUrls)?void 0:t.call(e))?n:{}}async getArgs({prompt:e,maxOutputTokens:t=4096,temperature:n,topP:r,topK:o,frequencyPenalty:i,presencePenalty:s,stopSequences:a,responseFormat:u,seed:l,tools:c,toolChoice:d,providerOptions:p}){var m,_,h;const g=[];null!=i&&g.push({type:"unsupported-setting",setting:"frequencyPenalty"}),null!=s&&g.push({type:"unsupported-setting",setting:"presencePenalty"}),null!=l&&g.push({type:"unsupported-setting",setting:"seed"}),"json"===(null==u?void 0:u.type)&&(null==u.schema?g.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format requires a schema. The response format is ignored."}):null!=c&&g.push({type:"unsupported-setting",setting:"tools",details:"JSON response format does not support tools. The provided tools are ignored."}));const f="json"===(null==u?void 0:u.type)&&null!=u.schema?{type:"function",name:"json",description:"Respond with a JSON object.",inputSchema:u.schema}:void 0,v=await Rd({provider:"anthropic",providerOptions:p,schema:Qp}),{prompt:y,betas:b}=await um({prompt:e,sendReasoning:null==(m=null==v?void 0:v.sendReasoning)||m,warnings:g}),k="enabled"===(null==(_=null==v?void 0:v.thinking)?void 0:_.type),w=null==(h=null==v?void 0:v.thinking)?void 0:h.budgetTokens,x={model:this.modelId,max_tokens:t,temperature:n,top_k:o,top_p:r,stop_sequences:a,...k&&{thinking:{type:"enabled",budget_tokens:w}},system:y.system,messages:y.messages};if(k){if(null==w)throw new At({functionality:"thinking requires a budget"});null!=x.temperature&&(x.temperature=void 0,g.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported when thinking is enabled"})),null!=o&&(x.top_k=void 0,g.push({type:"unsupported-setting",setting:"topK",details:"topK is not supported when thinking is enabled"})),null!=r&&(x.top_p=void 0,g.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported when thinking is enabled"})),x.max_tokens=t+w}const{tools:I,toolChoice:S,toolWarnings:$,betas:O}=function({tools:e,toolChoice:t,disableParallelToolUse:n}){e=(null==e?void 0:e.length)?e:void 0;const r=[],o=new Set;if(null==e)return{tools:void 0,toolChoice:void 0,toolWarnings:r,betas:o};const i=[];for(const a of e)if(om(a))i.push(a);else switch(a.type){case"function":const e=em(a.providerOptions);i.push({name:a.name,description:a.description,input_schema:a.inputSchema,cache_control:e});break;case"provider-defined":switch(a.id){case"anthropic.computer_20250124":o.add("computer-use-2025-01-24"),i.push({name:"computer",type:"computer_20250124",display_width_px:a.args.displayWidthPx,display_height_px:a.args.displayHeightPx,display_number:a.args.displayNumber});break;case"anthropic.computer_20241022":o.add("computer-use-2024-10-22"),i.push({name:"computer",type:"computer_20241022",display_width_px:a.args.displayWidthPx,display_height_px:a.args.displayHeightPx,display_number:a.args.displayNumber});break;case"anthropic.text_editor_20250124":o.add("computer-use-2025-01-24"),i.push({name:"str_replace_editor",type:"text_editor_20250124"});break;case"anthropic.text_editor_20241022":o.add("computer-use-2024-10-22"),i.push({name:"str_replace_editor",type:"text_editor_20241022"});break;case"anthropic.text_editor_20250429":o.add("computer-use-2025-01-24"),i.push({name:"str_replace_based_edit_tool",type:"text_editor_20250429"});break;case"anthropic.bash_20250124":o.add("computer-use-2025-01-24"),i.push({name:"bash",type:"bash_20250124"});break;case"anthropic.bash_20241022":o.add("computer-use-2024-10-22"),i.push({name:"bash",type:"bash_20241022"});break;case"anthropic.web_search_20250305":{const e=tm.parse(a.args);i.push({type:"web_search_20250305",name:"web_search",max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,user_location:e.userLocation});break}case"anthropic.code_execution_20250522":o.add("code-execution-2025-05-22"),i.push({type:"code_execution_20250522",name:"code_execution"});break;default:r.push({type:"unsupported-tool",tool:a})}break;default:r.push({type:"unsupported-tool",tool:a})}if(null==t)return{tools:i,toolChoice:n?{type:"auto",disable_parallel_tool_use:n}:void 0,toolWarnings:r,betas:o};const s=t.type;switch(s){case"auto":return{tools:i,toolChoice:{type:"auto",disable_parallel_tool_use:n},toolWarnings:r,betas:o};case"required":return{tools:i,toolChoice:{type:"any",disable_parallel_tool_use:n},toolWarnings:r,betas:o};case"none":return{tools:void 0,toolChoice:void 0,toolWarnings:r,betas:o};case"tool":return{tools:i,toolChoice:{type:"tool",name:t.toolName,disable_parallel_tool_use:n},toolWarnings:r,betas:o};default:throw new At({functionality:`tool choice type: ${s}`})}}(null!=f?{tools:[f],toolChoice:{type:"tool",toolName:f.name},disableParallelToolUse:null==v?void 0:v.disableParallelToolUse}:{tools:null!=c?c:[],toolChoice:d,disableParallelToolUse:null==v?void 0:v.disableParallelToolUse});return{args:{...x,tools:I,tool_choice:S},warnings:[...g,...$],betas:new Set([...b,...O]),usesJsonResponseTool:null!=f}}async getHeaders({betas:e,headers:t}){return pd(await jd(this.config.headers),e.size>0?{"anthropic-beta":Array.from(e).join(",")}:{},t)}buildRequestUrl(e){var t,n,r;return null!=(r=null==(n=(t=this.config).buildRequestUrl)?void 0:n.call(t,this.config.baseURL,e))?r:`${this.config.baseURL}/messages`}transformRequestBody(e){var t,n,r;return null!=(r=null==(n=(t=this.config).transformRequestBody)?void 0:n.call(t,e))?r:e}extractCitationDocuments(e){return e.filter((e=>"user"===e.role)).flatMap((e=>e.content)).filter((e=>{var t,n;if("file"!==e.type)return!1;if("application/pdf"!==e.mediaType&&"text/plain"!==e.mediaType)return!1;const r=null==(t=e.providerOptions)?void 0:t.anthropic,o=null==r?void 0:r.citations;return null!=(n=null==o?void 0:o.enabled)&&n})).map((e=>{var t;const n=e;return{title:null!=(t=n.filename)?t:"Untitled Document",filename:n.filename,mediaType:n.mediaType}}))}async doGenerate(e){var t,n,r,o,i;const{args:s,warnings:a,betas:u,usesJsonResponseTool:l}=await this.getArgs(e),c=this.extractCitationDocuments(e.prompt),{responseHeaders:d,value:p,rawValue:m}=await Ad({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:u,headers:e.headers}),body:this.transformRequestBody(s),failedResponseHandler:Yp,successfulResponseHandler:Md(_m),abortSignal:e.abortSignal,fetch:this.config.fetch}),_=[];for(const h of p.content)switch(h.type){case"text":if(!l&&(_.push({type:"text",text:h.text}),h.citations))for(const e of h.citations)pm(e,c,this.generateId,(e=>_.push(e)));break;case"thinking":_.push({type:"reasoning",text:h.thinking,providerMetadata:{anthropic:{signature:h.signature}}});break;case"redacted_thinking":_.push({type:"reasoning",text:"",providerMetadata:{anthropic:{redactedData:h.data}}});break;case"tool_use":_.push(l?{type:"text",text:JSON.stringify(h.input)}:{type:"tool-call",toolCallId:h.id,toolName:h.name,input:JSON.stringify(h.input)});break;case"server_tool_use":"web_search"!==h.name&&"code_execution"!==h.name||_.push({type:"tool-call",toolCallId:h.id,toolName:h.name,input:JSON.stringify(h.input),providerExecuted:!0});break;case"web_search_tool_result":if(Array.isArray(h.content)){_.push({type:"tool-result",toolCallId:h.tool_use_id,toolName:"web_search",result:h.content.map((e=>{var t;return{url:e.url,title:e.title,pageAge:null!=(t=e.page_age)?t:null,encryptedContent:e.encrypted_content,type:e.type}})),providerExecuted:!0});for(const e of h.content)_.push({type:"source",sourceType:"url",id:this.generateId(),url:e.url,title:e.title,providerMetadata:{anthropic:{pageAge:null!=(t=e.page_age)?t:null}}})}else _.push({type:"tool-result",toolCallId:h.tool_use_id,toolName:"web_search",isError:!0,result:{type:"web_search_tool_result_error",errorCode:h.content.error_code},providerExecuted:!0});break;case"code_execution_tool_result":"code_execution_result"===h.content.type?_.push({type:"tool-result",toolCallId:h.tool_use_id,toolName:"code_execution",result:{type:h.content.type,stdout:h.content.stdout,stderr:h.content.stderr,return_code:h.content.return_code},providerExecuted:!0}):"code_execution_tool_result_error"===h.content.type&&_.push({type:"tool-result",toolCallId:h.tool_use_id,toolName:"code_execution",isError:!0,result:{type:"code_execution_tool_result_error",errorCode:h.content.error_code},providerExecuted:!0})}return{content:_,finishReason:lm({finishReason:p.stop_reason,isJsonResponseFromTool:l}),usage:{inputTokens:p.usage.input_tokens,outputTokens:p.usage.output_tokens,totalTokens:p.usage.input_tokens+p.usage.output_tokens,cachedInputTokens:null!=(n=p.usage.cache_read_input_tokens)?n:void 0},request:{body:s},response:{id:null!=(r=p.id)?r:void 0,modelId:null!=(o=p.model)?o:void 0,headers:d,body:m},warnings:a,providerMetadata:{anthropic:{usage:p.usage,cacheCreationInputTokens:null!=(i=p.usage.cache_creation_input_tokens)?i:null}}}}async doStream(e){const{args:t,warnings:n,betas:r,usesJsonResponseTool:o}=await this.getArgs(e),i=this.extractCitationDocuments(e.prompt),s={...t,stream:!0},{responseHeaders:a,value:u}=await Ad({url:this.buildRequestUrl(!0),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(s),failedResponseHandler:Yp,successfulResponseHandler:Dd(hm),abortSignal:e.abortSignal,fetch:this.config.fetch});let l="unknown";const c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},d={};let p,m;const _=this.generateId;return{stream:u.pipeThrough(new TransformStream({start(e){e.enqueue({type:"stream-start",warnings:n})},transform(t,n){var r,s,a,u,h,g,f;if(e.includeRawChunks&&n.enqueue({type:"raw",rawValue:t.rawValue}),!t.success)return void n.enqueue({type:"error",error:t.error});const v=t.value;switch(v.type){case"ping":return;case"content_block_start":{const e=v.content_block.type;switch(m=e,e){case"text":return d[v.index]={type:"text"},void n.enqueue({type:"text-start",id:String(v.index)});case"thinking":return d[v.index]={type:"reasoning"},void n.enqueue({type:"reasoning-start",id:String(v.index)});case"redacted_thinking":return d[v.index]={type:"reasoning"},void n.enqueue({type:"reasoning-start",id:String(v.index),providerMetadata:{anthropic:{redactedData:v.content_block.data}}});case"tool_use":return d[v.index]=o?{type:"text"}:{type:"tool-call",toolCallId:v.content_block.id,toolName:v.content_block.name,input:""},void n.enqueue(o?{type:"text-start",id:String(v.index)}:{type:"tool-input-start",id:v.content_block.id,toolName:v.content_block.name});case"server_tool_use":return void("web_search"!==v.content_block.name&&"code_execution"!==v.content_block.name||(d[v.index]={type:"tool-call",toolCallId:v.content_block.id,toolName:v.content_block.name,input:"",providerExecuted:!0},n.enqueue({type:"tool-input-start",id:v.content_block.id,toolName:v.content_block.name,providerExecuted:!0})));case"web_search_tool_result":{const e=v.content_block;if(Array.isArray(e.content)){n.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:"web_search",result:e.content.map((e=>{var t;return{url:e.url,title:e.title,pageAge:null!=(t=e.page_age)?t:null,encryptedContent:e.encrypted_content,type:e.type}})),providerExecuted:!0});for(const t of e.content)n.enqueue({type:"source",sourceType:"url",id:_(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:null!=(r=t.page_age)?r:null}}})}else n.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:"web_search",isError:!0,result:{type:"web_search_tool_result_error",errorCode:e.content.error_code},providerExecuted:!0});return}case"code_execution_tool_result":{const e=v.content_block;return void("code_execution_result"===e.content.type?n.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:"code_execution",result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code},providerExecuted:!0}):"code_execution_tool_result_error"===e.content.type&&n.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:"code_execution",isError:!0,result:{type:"code_execution_tool_result_error",errorCode:e.content.error_code},providerExecuted:!0}))}default:throw new Error(`Unsupported content block type: ${e}`)}}case"content_block_stop":if(null!=d[v.index]){const e=d[v.index];switch(e.type){case"text":n.enqueue({type:"text-end",id:String(v.index)});break;case"reasoning":n.enqueue({type:"reasoning-end",id:String(v.index)});break;case"tool-call":o||(n.enqueue({type:"tool-input-end",id:e.toolCallId}),n.enqueue(e))}delete d[v.index]}return void(m=void 0);case"content_block_delta":{const e=v.delta.type;switch(e){case"text_delta":if(o)return;return void n.enqueue({type:"text-delta",id:String(v.index),delta:v.delta.text});case"thinking_delta":return void n.enqueue({type:"reasoning-delta",id:String(v.index),delta:v.delta.thinking});case"signature_delta":return void("thinking"===m&&n.enqueue({type:"reasoning-delta",id:String(v.index),delta:"",providerMetadata:{anthropic:{signature:v.delta.signature}}}));case"input_json_delta":{const e=d[v.index],t=v.delta.partial_json;if(o){if("text"!==(null==e?void 0:e.type))return;n.enqueue({type:"text-delta",id:String(v.index),delta:t})}else{if("tool-call"!==(null==e?void 0:e.type))return;n.enqueue({type:"tool-input-delta",id:e.toolCallId,delta:t}),e.input+=t}return}case"citations_delta":return void pm(v.delta.citation,i,_,(e=>n.enqueue(e)));default:throw new Error(`Unsupported delta type: ${e}`)}}case"message_start":return c.inputTokens=v.message.usage.input_tokens,c.cachedInputTokens=null!=(s=v.message.usage.cache_read_input_tokens)?s:void 0,p={anthropic:{usage:v.message.usage,cacheCreationInputTokens:null!=(a=v.message.usage.cache_creation_input_tokens)?a:null}},void n.enqueue({type:"response-metadata",id:null!=(u=v.message.id)?u:void 0,modelId:null!=(h=v.message.model)?h:void 0});case"message_delta":return c.outputTokens=v.usage.output_tokens,c.totalTokens=(null!=(g=c.inputTokens)?g:0)+(null!=(f=v.usage.output_tokens)?f:0),void(l=lm({finishReason:v.delta.stop_reason,isJsonResponseFromTool:o}));case"message_stop":return void n.enqueue({type:"finish",finishReason:l,usage:c,providerMetadata:p});case"error":return void n.enqueue({type:"error",error:v.error});default:throw new Error(`Unsupported chunk type: ${v}`)}}})),request:{body:s},response:{headers:a}}}},_m=Tl({type:Hl("message"),id:zu().nullish(),model:zu().nullish(),content:Ol(Ul("type",[Tl({type:Hl("text"),text:zu(),citations:Ol(dm).optional()}),Tl({type:Hl("thinking"),thinking:zu(),signature:zu()}),Tl({type:Hl("redacted_thinking"),data:zu()}),Tl({type:Hl("tool_use"),id:zu(),name:zu(),input:kl()}),Tl({type:Hl("server_tool_use"),id:zu(),name:zu(),input:ql(zu(),kl()).nullish()}),Tl({type:Hl("web_search_tool_result"),tool_use_id:zu(),content:Cl([Ol(Tl({type:Hl("web_search_result"),url:zu(),title:zu(),encrypted_content:zu(),page_age:zu().nullish()})),Tl({type:Hl("web_search_tool_result_error"),error_code:zu()})])}),Tl({type:Hl("code_execution_tool_result"),tool_use_id:zu(),content:Cl([Tl({type:Hl("code_execution_result"),stdout:zu(),stderr:zu(),return_code:al()}),Tl({type:Hl("code_execution_tool_result_error"),error_code:zu()})])})])),stop_reason:zu().nullish(),usage:Nl({input_tokens:al(),output_tokens:al(),cache_creation_input_tokens:al().nullish(),cache_read_input_tokens:al().nullish()})}),hm=Ul("type",[Tl({type:Hl("message_start"),message:Tl({id:zu().nullish(),model:zu().nullish(),usage:Nl({input_tokens:al(),output_tokens:al(),cache_creation_input_tokens:al().nullish(),cache_read_input_tokens:al().nullish()})})}),Tl({type:Hl("content_block_start"),index:al(),content_block:Ul("type",[Tl({type:Hl("text"),text:zu()}),Tl({type:Hl("thinking"),thinking:zu()}),Tl({type:Hl("tool_use"),id:zu(),name:zu()}),Tl({type:Hl("redacted_thinking"),data:zu()}),Tl({type:Hl("server_tool_use"),id:zu(),name:zu(),input:ql(zu(),kl()).nullish()}),Tl({type:Hl("web_search_tool_result"),tool_use_id:zu(),content:Cl([Ol(Tl({type:Hl("web_search_result"),url:zu(),title:zu(),encrypted_content:zu(),page_age:zu().nullish()})),Tl({type:Hl("web_search_tool_result_error"),error_code:zu()})])}),Tl({type:Hl("code_execution_tool_result"),tool_use_id:zu(),content:Cl([Tl({type:Hl("code_execution_result"),stdout:zu(),stderr:zu(),return_code:al()}),Tl({type:Hl("code_execution_tool_result_error"),error_code:zu()})])})])}),Tl({type:Hl("content_block_delta"),index:al(),delta:Ul("type",[Tl({type:Hl("input_json_delta"),partial_json:zu()}),Tl({type:Hl("text_delta"),text:zu()}),Tl({type:Hl("thinking_delta"),thinking:zu()}),Tl({type:Hl("signature_delta"),signature:zu()}),Tl({type:Hl("citations_delta"),citation:dm})])}),Tl({type:Hl("content_block_stop"),index:al()}),Tl({type:Hl("error"),error:Tl({type:zu(),message:zu()})}),Tl({type:Hl("message_delta"),delta:Tl({stop_reason:zu().nullish()}),usage:Tl({output_tokens:al()})}),Tl({type:Hl("message_stop")}),Tl({type:Hl("ping")})]),gm=Tl({signature:zu().optional(),redactedData:zu().optional()}),fm=Pd({id:"anthropic.bash_20241022",name:"bash",inputSchema:Oc.object({command:Oc.string(),restart:Oc.boolean().optional()})}),vm=Pd({id:"anthropic.bash_20250124",name:"bash",inputSchema:Oc.object({command:Oc.string(),restart:Oc.boolean().optional()})}),ym=Pd({id:"anthropic.computer_20241022",name:"computer",inputSchema:Tl({action:Jl(["key","type","mouse_move","left_click","left_click_drag","right_click","middle_click","double_click","screenshot","cursor_position"]),coordinate:Ol(al().int()).optional(),text:zu().optional()})}),bm=Pd({id:"anthropic.computer_20250124",name:"computer",inputSchema:Tl({action:Jl(["key","hold_key","type","cursor_position","mouse_move","left_mouse_down","left_mouse_up","left_click","left_click_drag","right_click","middle_click","double_click","triple_click","scroll","wait","screenshot"]),coordinate:Ml([al().int(),al().int()]).optional(),duration:al().optional(),scroll_amount:al().optional(),scroll_direction:Jl(["up","down","left","right"]).optional(),start_coordinate:Ml([al().int(),al().int()]).optional(),text:zu().optional()})}),km={bash_20241022:fm,bash_20250124:vm,textEditor_20241022:Pd({id:"anthropic.text_editor_20241022",name:"str_replace_editor",inputSchema:Tl({command:Jl(["view","create","str_replace","insert","undo_edit"]),path:zu(),file_text:zu().optional(),insert_line:al().int().optional(),new_str:zu().optional(),old_str:zu().optional(),view_range:Ol(al().int()).optional()})}),textEditor_20250124:Pd({id:"anthropic.text_editor_20250124",name:"str_replace_editor",inputSchema:Tl({command:Jl(["view","create","str_replace","insert","undo_edit"]),path:zu(),file_text:zu().optional(),insert_line:al().int().optional(),new_str:zu().optional(),old_str:zu().optional(),view_range:Ol(al().int()).optional()})}),textEditor_20250429:Pd({id:"anthropic.text_editor_20250429",name:"str_replace_based_edit_tool",inputSchema:Tl({command:Jl(["view","create","str_replace","insert"]),path:zu(),file_text:zu().optional(),insert_line:al().int().optional(),new_str:zu().optional(),old_str:zu().optional(),view_range:Ol(al().int()).optional()})}),computer_20241022:ym,computer_20250124:bm,webSearch_20250305:(e={})=>rm(e),codeExecution_20250522:(e={})=>sm(e)};function wm(e={}){var t;const n=null!=(t=Vd(e.baseURL))?t:"https://api.anthropic.com/v1",r=()=>({"anthropic-version":"2023-06-01","x-api-key":vd({apiKey:e.apiKey,environmentVariableName:"ANTHROPIC_API_KEY",description:"Anthropic"}),...e.headers}),o=t=>{var o;return new mm(t,{provider:"anthropic.messages",baseURL:n,headers:r,fetch:e.fetch,generateId:null!=(o=e.generateId)?o:hd,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/]})})},i=function(e){if(new.target)throw new Error("The Anthropic model function cannot be called with the new keyword.");return o(e)};return i.languageModel=o,i.chat=o,i.messages=o,i.textEmbeddingModel=e=>{throw new ft({modelId:e,modelType:"textEmbeddingModel"})},i.imageModel=e=>{throw new ft({modelId:e,modelType:"imageModel"})},i.tools=km,i}var xm=wm(),Im=zd({errorSchema:Tl({error:Tl({code:al().nullable(),message:zu(),status:zu()})}),errorToMessage:e=>e.error.message}),Sm=Tl({outputDimensionality:al().optional(),taskType:Jl(["SEMANTIC_SIMILARITY","CLASSIFICATION","CLUSTERING","RETRIEVAL_DOCUMENT","RETRIEVAL_QUERY","QUESTION_ANSWERING","FACT_VERIFICATION","CODE_RETRIEVAL_QUERY"]).optional()}),$m=class{constructor(e,t){this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){const o=await Rd({provider:"google",providerOptions:r,schema:Sm});if(e.length>this.maxEmbeddingsPerCall)throw new wt({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const i=pd(await jd(this.config.headers),t);if(1===e.length){const{responseHeaders:t,value:r,rawValue:s}=await Ad({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:i,body:{model:`models/${this.modelId}`,content:{parts:[{text:e[0]}]},outputDimensionality:null==o?void 0:o.outputDimensionality,taskType:null==o?void 0:o.taskType},failedResponseHandler:Im,successfulResponseHandler:Md(Em),abortSignal:n,fetch:this.config.fetch});return{embeddings:[r.embedding.values],usage:void 0,response:{headers:t,body:s}}}const{responseHeaders:s,value:a,rawValue:u}=await Ad({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:i,body:{requests:e.map((e=>({model:`models/${this.modelId}`,content:{role:"user",parts:[{text:e}]},outputDimensionality:null==o?void 0:o.outputDimensionality,taskType:null==o?void 0:o.taskType})))},failedResponseHandler:Im,successfulResponseHandler:Md(Om),abortSignal:n,fetch:this.config.fetch});return{embeddings:a.embeddings.map((e=>e.values)),usage:void 0,response:{headers:s,body:u}}}},Om=Tl({embeddings:Ol(Tl({values:Ol(al())}))}),Em=Tl({embedding:Tl({values:Ol(al())})});function Tm(e){if(null==e||function(e){return null!=e&&"object"==typeof e&&"object"===e.type&&(null==e.properties||0===Object.keys(e.properties).length)&&!e.additionalProperties}(e))return;if("boolean"==typeof e)return{type:"boolean",properties:{}};const{type:t,description:n,required:r,properties:o,items:i,allOf:s,anyOf:a,oneOf:u,format:l,const:c,minLength:d,enum:p}=e,m={};if(n&&(m.description=n),r&&(m.required=r),l&&(m.format=l),void 0!==c&&(m.enum=[c]),t&&(Array.isArray(t)?t.includes("null")?(m.type=t.filter((e=>"null"!==e))[0],m.nullable=!0):m.type=t:m.type="null"===t?"null":t),void 0!==p&&(m.enum=p),null!=o&&(m.properties=Object.entries(o).reduce(((e,[t,n])=>(e[t]=Tm(n),e)),{})),i&&(m.items=Array.isArray(i)?i.map(Tm):Tm(i)),s&&(m.allOf=s.map(Tm)),a)if(a.some((e=>"object"==typeof e&&"null"===(null==e?void 0:e.type)))){const e=a.filter((e=>!("object"==typeof e&&"null"===(null==e?void 0:e.type))));if(1===e.length){const t=Tm(e[0]);"object"==typeof t&&(m.nullable=!0,Object.assign(m,t))}else m.anyOf=e.map(Tm),m.nullable=!0}else m.anyOf=a.map(Tm);return u&&(m.oneOf=u.map(Tm)),void 0!==d&&(m.minLength=d),m}function Rm(e){return e.includes("/")?e:`models/${e}`}var Nm=Tl({responseModalities:Ol(Jl(["TEXT","IMAGE"])).optional(),thinkingConfig:Tl({thinkingBudget:al().optional(),includeThoughts:dl().optional()}).optional(),cachedContent:zu().optional(),structuredOutputs:dl().optional(),safetySettings:Ol(Tl({category:Jl(["HARM_CATEGORY_UNSPECIFIED","HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_SEXUALLY_EXPLICIT","HARM_CATEGORY_CIVIC_INTEGRITY"]),threshold:Jl(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"])})).optional(),threshold:Jl(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"]).optional(),audioTimestamp:dl().optional(),labels:ql(zu(),zu()).optional()});function Am({finishReason:e,hasToolCalls:t}){switch(e){case"STOP":return t?"tool-calls":"stop";case"MAX_TOKENS":return"length";case"IMAGE_SAFETY":case"RECITATION":case"SAFETY":case"BLOCKLIST":case"PROHIBITED_CONTENT":case"SPII":return"content-filter";case"FINISH_REASON_UNSPECIFIED":case"OTHER":return"other";case"MALFORMED_FUNCTION_CALL":return"error";default:return"unknown"}}var Cm=Tl({web:Tl({uri:zu(),title:zu()}).nullish(),retrievedContext:Tl({uri:zu(),title:zu()}).nullish()}),Pm=Tl({webSearchQueries:Ol(zu()).nullish(),retrievalQueries:Ol(zu()).nullish(),searchEntryPoint:Tl({renderedContent:zu()}).nullish(),groundingChunks:Ol(Cm).nullish(),groundingSupports:Ol(Tl({segment:Tl({startIndex:al().nullish(),endIndex:al().nullish(),text:zu().nullish()}),segment_text:zu().nullish(),groundingChunkIndices:Ol(al()).nullish(),supportChunkIndices:Ol(al()).nullish(),confidenceScores:Ol(al()).nullish(),confidenceScore:Ol(al()).nullish()})).nullish(),retrievalMetadata:Cl([Tl({webDynamicRetrievalScore:al()}),Tl({})]).nullish()}),Um=Pd({id:"google.google_search",name:"google_search",inputSchema:Tl({mode:Jl(["MODE_DYNAMIC","MODE_UNSPECIFIED"]).default("MODE_UNSPECIFIED"),dynamicThreshold:al().default(1)})}),jm=Tl({retrievedUrl:zu(),urlRetrievalStatus:zu()}),zm=Tl({urlMetadata:Ol(jm)}),Dm=Pd({id:"google.url_context",name:"url_context",inputSchema:Tl({})}),Mm=class{constructor(e,t){var n;this.specificationVersion="v2",this.modelId=e,this.config=t,this.generateId=null!=(n=t.generateId)?n:hd}get provider(){return this.config.provider}get supportedUrls(){var e,t,n;return null!=(n=null==(t=(e=this.config).supportedUrls)?void 0:t.call(e))?n:{}}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:o,frequencyPenalty:i,presencePenalty:s,stopSequences:a,responseFormat:u,seed:l,tools:c,toolChoice:d,providerOptions:p}){var m,_;const h=[],g=await Rd({provider:"google",providerOptions:p,schema:Nm});!0!==(null==(m=null==g?void 0:g.thinkingConfig)?void 0:m.includeThoughts)||this.config.provider.startsWith("google.vertex.")||h.push({type:"other",message:`The 'includeThoughts' option is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${this.config.provider}).`});const f=this.modelId.toLowerCase().startsWith("gemma-"),{contents:v,systemInstruction:y}=function(e,t){var n;const r=[],o=[];let i=!0;const s=null!=(n=null==t?void 0:t.isGemmaModel)&&n;for(const{role:a,content:u}of e)switch(a){case"system":if(!i)throw new At({functionality:"system messages are only supported at the beginning of the conversation"});r.push({text:u});break;case"user":{i=!1;const e=[];for(const t of u)switch(t.type){case"text":e.push({text:t.text});break;case"file":{const n="image/*"===t.mediaType?"image/jpeg":t.mediaType;e.push(t.data instanceof URL?{fileData:{mimeType:n,fileUri:t.data.toString()}}:{inlineData:{mimeType:n,data:Hd(t.data)}});break}}o.push({role:"user",parts:e});break}case"assistant":i=!1,o.push({role:"model",parts:u.map((e=>{var t,n,r,o,i,s;switch(e.type){case"text":return 0===e.text.length?void 0:{text:e.text,thoughtSignature:null==(n=null==(t=e.providerOptions)?void 0:t.google)?void 0:n.thoughtSignature};case"reasoning":return 0===e.text.length?void 0:{text:e.text,thought:!0,thoughtSignature:null==(o=null==(r=e.providerOptions)?void 0:r.google)?void 0:o.thoughtSignature};case"file":if("image/png"!==e.mediaType)throw new At({functionality:"Only PNG images are supported in assistant messages"});if(e.data instanceof URL)throw new At({functionality:"File data URLs in assistant messages are not supported"});return{inlineData:{mimeType:e.mediaType,data:Hd(e.data)}};case"tool-call":return{functionCall:{name:e.toolName,args:e.input},thoughtSignature:null==(s=null==(i=e.providerOptions)?void 0:i.google)?void 0:s.thoughtSignature}}})).filter((e=>void 0!==e))});break;case"tool":i=!1,o.push({role:"user",parts:u.map((e=>({functionResponse:{name:e.toolName,response:{name:e.toolName,content:e.output.value}}})))})}if(s&&r.length>0&&o.length>0&&"user"===o[0].role){const e=r.map((e=>e.text)).join("\n\n");o[0].parts.unshift({text:e+"\n\n"})}return{systemInstruction:r.length>0&&!s?{parts:r}:void 0,contents:o}}(e,{isGemmaModel:f}),{tools:b,toolConfig:k,toolWarnings:w}=function({tools:e,toolChoice:t,modelId:n}){var r;e=(null==e?void 0:e.length)?e:void 0;const o=[],i=n.includes("gemini-2"),s=n.includes("gemini-1.5-flash")&&!n.includes("-8b");if(null==e)return{tools:void 0,toolConfig:void 0,toolWarnings:o};const a=e.some((e=>"function"===e.type)),u=e.some((e=>"provider-defined"===e.type));if(a&&u&&o.push({type:"unsupported-tool",tool:e.find((e=>"function"===e.type)),details:"Cannot mix function tools with provider-defined tools in the same request. Please use either function tools or provider-defined tools, but not both."}),u){const t={};return e.filter((e=>"provider-defined"===e.type)).forEach((e=>{switch(e.id){case"google.google_search":i?t.googleSearch={}:t.googleSearchRetrieval=s?{dynamicRetrievalConfig:{mode:e.args.mode,dynamicThreshold:e.args.dynamicThreshold}}:{};break;case"google.url_context":i?t.urlContext={}:o.push({type:"unsupported-tool",tool:e,details:"The URL context tool is not supported with other Gemini models than Gemini 2."});break;case"google.code_execution":i?t.codeExecution={}:o.push({type:"unsupported-tool",tool:e,details:"The code execution tools is not supported with other Gemini models than Gemini 2."});break;default:o.push({type:"unsupported-tool",tool:e})}})),{tools:Object.keys(t).length>0?t:void 0,toolConfig:void 0,toolWarnings:o}}const l=[];for(const d of e)"function"===d.type?l.push({name:d.name,description:null!=(r=d.description)?r:"",parameters:Tm(d.inputSchema)}):o.push({type:"unsupported-tool",tool:d});if(null==t)return{tools:{functionDeclarations:l},toolConfig:void 0,toolWarnings:o};const c=t.type;switch(c){case"auto":return{tools:{functionDeclarations:l},toolConfig:{functionCallingConfig:{mode:"AUTO"}},toolWarnings:o};case"none":return{tools:{functionDeclarations:l},toolConfig:{functionCallingConfig:{mode:"NONE"}},toolWarnings:o};case"required":return{tools:{functionDeclarations:l},toolConfig:{functionCallingConfig:{mode:"ANY"}},toolWarnings:o};case"tool":return{tools:{functionDeclarations:l},toolConfig:{functionCallingConfig:{mode:"ANY",allowedFunctionNames:[t.toolName]}},toolWarnings:o};default:throw new At({functionality:`tool choice type: ${c}`})}}({tools:c,toolChoice:d,modelId:this.modelId});return{args:{generationConfig:{maxOutputTokens:t,temperature:n,topK:o,topP:r,frequencyPenalty:i,presencePenalty:s,stopSequences:a,seed:l,responseMimeType:"json"===(null==u?void 0:u.type)?"application/json":void 0,responseSchema:"json"!==(null==u?void 0:u.type)||null==u.schema||null!=(_=null==g?void 0:g.structuredOutputs)&&!_?void 0:Tm(u.schema),...(null==g?void 0:g.audioTimestamp)&&{audioTimestamp:g.audioTimestamp},responseModalities:null==g?void 0:g.responseModalities,thinkingConfig:null==g?void 0:g.thinkingConfig},contents:v,systemInstruction:f?void 0:y,safetySettings:null==g?void 0:g.safetySettings,tools:b,toolConfig:k,cachedContent:null==g?void 0:g.cachedContent,labels:null==g?void 0:g.labels},warnings:[...h,...w]}}async doGenerate(e){var t,n,r,o,i,s,a,u,l,c,d,p;const{args:m,warnings:_}=await this.getArgs(e),h=JSON.stringify(m),g=pd(await jd(this.config.headers),e.headers),{responseHeaders:f,value:v,rawValue:y}=await Ad({url:`${this.config.baseURL}/${Rm(this.modelId)}:generateContent`,headers:g,body:m,failedResponseHandler:Im,successfulResponseHandler:Md(Wm),abortSignal:e.abortSignal,fetch:this.config.fetch}),b=v.candidates[0],k=[],w=null!=(n=null==(t=b.content)?void 0:t.parts)?n:[],x=v.usageMetadata;let I;for(const $ of w)if("executableCode"in $&&(null==(r=$.executableCode)?void 0:r.code)){const e=this.config.generateId();I=e,k.push({type:"tool-call",toolCallId:e,toolName:"code_execution",input:JSON.stringify($.executableCode),providerExecuted:!0})}else"codeExecutionResult"in $&&$.codeExecutionResult?(k.push({type:"tool-result",toolCallId:I,toolName:"code_execution",result:{outcome:$.codeExecutionResult.outcome,output:$.codeExecutionResult.output},providerExecuted:!0}),I=void 0):"text"in $&&null!=$.text&&$.text.length>0?k.push({type:!0===$.thought?"reasoning":"text",text:$.text,providerMetadata:$.thoughtSignature?{google:{thoughtSignature:$.thoughtSignature}}:void 0}):"functionCall"in $?k.push({type:"tool-call",toolCallId:this.config.generateId(),toolName:$.functionCall.name,input:JSON.stringify($.functionCall.args),providerMetadata:$.thoughtSignature?{google:{thoughtSignature:$.thoughtSignature}}:void 0}):"inlineData"in $&&k.push({type:"file",data:$.inlineData.data,mediaType:$.inlineData.mimeType});const S=null!=(o=Lm({groundingMetadata:b.groundingMetadata,generateId:this.config.generateId}))?o:[];for(const $ of S)k.push($);return{content:k,finishReason:Am({finishReason:b.finishReason,hasToolCalls:k.some((e=>"tool-call"===e.type))}),usage:{inputTokens:null!=(i=null==x?void 0:x.promptTokenCount)?i:void 0,outputTokens:null!=(s=null==x?void 0:x.candidatesTokenCount)?s:void 0,totalTokens:null!=(a=null==x?void 0:x.totalTokenCount)?a:void 0,reasoningTokens:null!=(u=null==x?void 0:x.thoughtsTokenCount)?u:void 0,cachedInputTokens:null!=(l=null==x?void 0:x.cachedContentTokenCount)?l:void 0},warnings:_,providerMetadata:{google:{groundingMetadata:null!=(c=b.groundingMetadata)?c:null,urlContextMetadata:null!=(d=b.urlContextMetadata)?d:null,safetyRatings:null!=(p=b.safetyRatings)?p:null,usageMetadata:null!=x?x:null}},request:{body:h},response:{headers:f,body:y}}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),r=JSON.stringify(t),o=pd(await jd(this.config.headers),e.headers),{responseHeaders:i,value:s}=await Ad({url:`${this.config.baseURL}/${Rm(this.modelId)}:streamGenerateContent?alt=sse`,headers:o,body:t,failedResponseHandler:Im,successfulResponseHandler:Dd(Jm),abortSignal:e.abortSignal,fetch:this.config.fetch});let a="unknown";const u={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let l;const c=this.config.generateId;let d=!1,p=null,m=null,_=0;const h=new Set;let g;return{stream:s.pipeThrough(new TransformStream({start(e){e.enqueue({type:"stream-start",warnings:n})},transform(t,n){var r,o,i,s,f,v,y,b,k,w,x;if(e.includeRawChunks&&n.enqueue({type:"raw",rawValue:t.rawValue}),!t.success)return void n.enqueue({type:"error",error:t.error});const I=t.value,S=I.usageMetadata;null!=S&&(u.inputTokens=null!=(r=S.promptTokenCount)?r:void 0,u.outputTokens=null!=(o=S.candidatesTokenCount)?o:void 0,u.totalTokens=null!=(i=S.totalTokenCount)?i:void 0,u.reasoningTokens=null!=(s=S.thoughtsTokenCount)?s:void 0,u.cachedInputTokens=null!=(f=S.cachedContentTokenCount)?f:void 0);const $=null==(v=I.candidates)?void 0:v[0];if(null==$)return;const O=$.content,E=Lm({groundingMetadata:$.groundingMetadata,generateId:c});if(null!=E)for(const e of E)"url"!==e.sourceType||h.has(e.url)||(h.add(e.url),n.enqueue(e));if(null!=O){const e=null!=(y=O.parts)?y:[];for(const o of e)if("executableCode"in o&&(null==(b=o.executableCode)?void 0:b.code)){const e=c();g=e,n.enqueue({type:"tool-call",toolCallId:e,toolName:"code_execution",input:JSON.stringify(o.executableCode),providerExecuted:!0}),d=!0}else if("codeExecutionResult"in o&&o.codeExecutionResult){const e=g;e&&(n.enqueue({type:"tool-result",toolCallId:e,toolName:"code_execution",result:{outcome:o.codeExecutionResult.outcome,output:o.codeExecutionResult.output},providerExecuted:!0}),g=void 0)}else"text"in o&&null!=o.text&&o.text.length>0&&(!0===o.thought?(null!==p&&(n.enqueue({type:"text-end",id:p}),p=null),null===m&&(m=String(_++),n.enqueue({type:"reasoning-start",id:m,providerMetadata:o.thoughtSignature?{google:{thoughtSignature:o.thoughtSignature}}:void 0})),n.enqueue({type:"reasoning-delta",id:m,delta:o.text,providerMetadata:o.thoughtSignature?{google:{thoughtSignature:o.thoughtSignature}}:void 0})):(null!==m&&(n.enqueue({type:"reasoning-end",id:m}),m=null),null===p&&(p=String(_++),n.enqueue({type:"text-start",id:p,providerMetadata:o.thoughtSignature?{google:{thoughtSignature:o.thoughtSignature}}:void 0})),n.enqueue({type:"text-delta",id:p,delta:o.text,providerMetadata:o.thoughtSignature?{google:{thoughtSignature:o.thoughtSignature}}:void 0})));const t=function(e){return null==e?void 0:e.filter((e=>"inlineData"in e))}(O.parts);if(null!=t)for(const o of t)n.enqueue({type:"file",mediaType:o.inlineData.mimeType,data:o.inlineData.data});const r=function({parts:e,generateId:t}){const n=null==e?void 0:e.filter((e=>"functionCall"in e));return null==n||0===n.length?void 0:n.map((e=>({type:"tool-call",toolCallId:t(),toolName:e.functionCall.name,args:JSON.stringify(e.functionCall.args),providerMetadata:e.thoughtSignature?{google:{thoughtSignature:e.thoughtSignature}}:void 0})))}({parts:O.parts,generateId:c});if(null!=r)for(const o of r)n.enqueue({type:"tool-input-start",id:o.toolCallId,toolName:o.toolName,providerMetadata:o.providerMetadata}),n.enqueue({type:"tool-input-delta",id:o.toolCallId,delta:o.args,providerMetadata:o.providerMetadata}),n.enqueue({type:"tool-input-end",id:o.toolCallId,providerMetadata:o.providerMetadata}),n.enqueue({type:"tool-call",toolCallId:o.toolCallId,toolName:o.toolName,input:o.args,providerMetadata:o.providerMetadata}),d=!0}null!=$.finishReason&&(a=Am({finishReason:$.finishReason,hasToolCalls:d}),l={google:{groundingMetadata:null!=(k=$.groundingMetadata)?k:null,urlContextMetadata:null!=(w=$.urlContextMetadata)?w:null,safetyRatings:null!=(x=$.safetyRatings)?x:null}},null!=S&&(l.google.usageMetadata=S))},flush(e){null!==p&&e.enqueue({type:"text-end",id:p}),null!==m&&e.enqueue({type:"reasoning-end",id:m}),e.enqueue({type:"finish",finishReason:a,usage:u,providerMetadata:l})}})),response:{headers:i},request:{body:r}}}};function Lm({groundingMetadata:e,generateId:t}){var n;return null==(n=null==e?void 0:e.groundingChunks)?void 0:n.filter((e=>null!=e.web)).map((e=>({type:"source",sourceType:"url",id:t(),url:e.web.uri,title:e.web.title})))}var qm=Tl({parts:Ol(Cl([Tl({functionCall:Tl({name:zu(),args:kl()}),thoughtSignature:zu().nullish()}),Tl({inlineData:Tl({mimeType:zu(),data:zu()})}),Tl({executableCode:Tl({language:zu(),code:zu()}).nullish(),codeExecutionResult:Tl({outcome:zu(),output:zu()}).nullish(),text:zu().nullish(),thought:dl().nullish(),thoughtSignature:zu().nullish()})])).nullish()}),Zm=Tl({category:zu().nullish(),probability:zu().nullish(),probabilityScore:al().nullish(),severity:zu().nullish(),severityScore:al().nullish(),blocked:dl().nullish()}),Fm=Tl({cachedContentTokenCount:al().nullish(),thoughtsTokenCount:al().nullish(),promptTokenCount:al().nullish(),candidatesTokenCount:al().nullish(),totalTokenCount:al().nullish()}),Wm=Tl({candidates:Ol(Tl({content:qm.nullish().or(Tl({}).strict()),finishReason:zu().nullish(),safetyRatings:Ol(Zm).nullish(),groundingMetadata:Pm.nullish(),urlContextMetadata:zm.nullish()})),usageMetadata:Fm.nullish()}),Jm=Tl({candidates:Ol(Tl({content:qm.nullish(),finishReason:zu().nullish(),safetyRatings:Ol(Zm).nullish(),groundingMetadata:Pm.nullish(),urlContextMetadata:zm.nullish()})).nullish(),usageMetadata:Fm.nullish()}),Bm={googleSearch:Um,urlContext:Dm,codeExecution:Ud({id:"google.code_execution",name:"code_execution",inputSchema:Tl({language:zu().describe("The programming language of the code."),code:zu().describe("The code to be executed.")}),outputSchema:Tl({outcome:zu().describe('The outcome of the execution (e.g., "OUTCOME_OK").'),output:zu().describe("The output from the code execution.")})})},Hm=class{constructor(e,t,n){this.modelId=e,this.settings=t,this.config=n,this.specificationVersion="v2"}get maxImagesPerCall(){var e;return null!=(e=this.settings.maxImagesPerCall)?e:4}get provider(){return this.config.provider}async doGenerate(e){var t,n,r;const{prompt:o,n:i=1,size:s="1024x1024",aspectRatio:a="1:1",seed:u,providerOptions:l,headers:c,abortSignal:d}=e,p=[];null!=s&&p.push({type:"unsupported-setting",setting:"size",details:"This model does not support the `size` option. Use `aspectRatio` instead."}),null!=u&&p.push({type:"unsupported-setting",setting:"seed",details:"This model does not support the `seed` option through this provider."});const m=await Rd({provider:"google",providerOptions:l,schema:Gm}),_=null!=(r=null==(n=null==(t=this.config._internal)?void 0:t.currentDate)?void 0:n.call(t))?r:new Date,h={sampleCount:i};null!=a&&(h.aspectRatio=a),m&&Object.assign(h,m);const g={instances:[{prompt:o}],parameters:h},{responseHeaders:f,value:v}=await Ad({url:`${this.config.baseURL}/models/${this.modelId}:predict`,headers:pd(await jd(this.config.headers),c),body:g,failedResponseHandler:Im,successfulResponseHandler:Md(Vm),abortSignal:d,fetch:this.config.fetch});return{images:v.predictions.map((e=>e.bytesBase64Encoded)),warnings:null!=p?p:[],providerMetadata:{google:{images:v.predictions.map((e=>({})))}},response:{timestamp:_,modelId:this.modelId,headers:f}}}},Vm=Tl({predictions:Ol(Tl({bytesBase64Encoded:zu()})).default([])}),Gm=Tl({personGeneration:Jl(["dont_allow","allow_adult","allow_all"]).nullish(),aspectRatio:Jl(["1:1","3:4","4:3","9:16","16:9"]).nullish()});function Km(e={}){var t;const n=null!=(t=Vd(e.baseURL))?t:"https://generativelanguage.googleapis.com/v1beta",r=()=>({"x-goog-api-key":vd({apiKey:e.apiKey,environmentVariableName:"GOOGLE_GENERATIVE_AI_API_KEY",description:"Google Generative AI"}),...e.headers}),o=t=>{var o;return new Mm(t,{provider:"google.generative-ai",baseURL:n,headers:r,generateId:null!=(o=e.generateId)?o:hd,supportedUrls:()=>({"*":[new RegExp(`^${n}/files/.*$`),new RegExp("^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$"),new RegExp("^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$")]}),fetch:e.fetch})},i=t=>new $m(t,{provider:"google.generative-ai",baseURL:n,headers:r,fetch:e.fetch}),s=(t,o={})=>new Hm(t,o,{provider:"google.generative-ai",baseURL:n,headers:r,fetch:e.fetch}),a=function(e){if(new.target)throw new Error("The Google Generative AI model function cannot be called with the new keyword.");return o(e)};return a.languageModel=o,a.chat=o,a.generativeAI=o,a.embedding=i,a.textEmbedding=i,a.textEmbeddingModel=i,a.image=s,a.imageModel=s,a.tools=Bm,a}var Ym=Km(),Xm=class{constructor(e){this.apiKey=e}async getAccessToken(){return this.apiKey}async refreshToken(){return Promise.resolve()}},Qm=class{constructor(e){n(this,"getTokenFn"),n(this,"refreshTokenFn"),n(this,"onRefreshErrorFn"),this.getTokenFn=e.getTokenFn,this.refreshTokenFn=e.refreshTokenFn,this.onRefreshErrorFn=e.onRefreshErrorFn}async getAccessToken(){return this.getTokenFn()}async refreshToken(){return this.refreshTokenFn()}onRefreshError(e){this.onRefreshErrorFn&&this.onRefreshErrorFn(e)}},e_={baseUrl:"undefined"!=typeof process&&(null==(e=process.env)?void 0:e.ECHO_BASE_URL)||"https://echo.merit.systems"};var t_="https://echo.router.merit.systems",n_=class{constructor(e,t){n(this,"isRefreshing",!1),n(this,"refreshPromise",null),this.baseUrl=e,this.tokenProvider=t}async request(e,t={}){var n;const r=await this.tokenProvider.getAccessToken(),o=await fetch(`${this.baseUrl}${e}`,{...t,headers:{"Content-Type":"application/json",...t.headers,...r&&{Authorization:`Bearer ${r}`}}});if(401===o.status&&!(null==(n=t.headers)?void 0:n["X-Retry"])){await this.handleTokenRefresh();const n=await this.tokenProvider.getAccessToken();return fetch(`${this.baseUrl}${e}`,{...t,headers:{"Content-Type":"application/json",...t.headers,...n&&{Authorization:`Bearer ${n}`},"X-Retry":"true"}})}return o}async handleTokenRefresh(){if(this.isRefreshing&&this.refreshPromise)return this.refreshPromise;this.isRefreshing=!0,this.refreshPromise=this.performRefresh();try{await this.refreshPromise}finally{this.isRefreshing=!1,this.refreshPromise=null}}async performRefresh(){try{await this.tokenProvider.refreshToken()}catch(e){throw this.tokenProvider.onRefreshError&&this.tokenProvider.onRefreshError(e),e}}async get(e,t){return this.request(e,{...t,method:"GET"})}async post(e,t,n){return this.request(e,{...n,method:"POST",body:t?JSON.stringify(t):null})}async put(e,t,n){return this.request(e,{...n,method:"PUT",body:t?JSON.stringify(t):null})}async delete(e,t){return this.request(e,{...t,method:"DELETE"})}},r_=class extends Error{constructor(e,t,r){super(t),n(this,"code"),n(this,"statusCode"),n(this,"endpoint"),this.name="EchoError",this.code=e,void 0!==(null==r?void 0:r.statusCode)&&(this.statusCode=r.statusCode),void 0!==(null==r?void 0:r.endpoint)&&(this.endpoint=r.endpoint)}};function o_(e,t,n){if("TypeError"===e.name)return new r_("NETWORK_ERROR","Network error"+(t?` while ${t}`:""),n?{endpoint:n}:void 0);const r=e.message.match(/^HTTP (\d+): (.*)$/);if(r&&r[1]&&r[2]){const e=parseInt(r[1]),o=r[2];return new r_(`HTTP_${e}`,`${o}${t?` while ${t}`:""}`,n?{statusCode:e,endpoint:n}:{statusCode:e})}return new r_("UNKNOWN_ERROR",`${e.message}${t?` while ${t}`:""}`,n?{endpoint:n}:void 0)}var i_=class{constructor(e){this.http=e}async handleRequest(e,t,n){try{const t=await e();if(!t.ok){const e=await t.text();throw new Error(`HTTP ${t.status}: ${e}`)}return await t.json()}catch(r){if(r instanceof Error)throw o_(r,t,n);throw new r_("UNKNOWN_ERROR","Unknown error occurred",n?{endpoint:n}:void 0)}}},s_=class extends i_{constructor(e,t){super(e),this.baseUrl=t}async listEchoApps(){return(await this.handleRequest((()=>this.http.get("/api/v1/apps")),"listing Echo apps","/api/v1/apps")).apps}async getEchoApp(e){return this.handleRequest((()=>this.http.get(`/api/v1/apps/${e}`)),"fetching Echo app",`/api/v1/apps/${e}`)}getAppUrl(e){return`${this.baseUrl}/apps/${e}`}},a_=class extends i_{constructor(e){super(e)}async getBalance(){return this.handleRequest((()=>this.http.get("/api/v1/balance")),"fetching balance","/api/v1/balance")}async getFreeBalance(e){const t={echoAppId:e};return this.handleRequest((()=>this.http.post("/api/v1/balance/free",t)),"fetching free tier balance","/api/v1/balance/free")}},u_=[{model_id:"claude-3-5-haiku-20241022",input_cost_per_token:8e-7,output_cost_per_token:4e-6,provider:"Anthropic"},{model_id:"claude-3-5-sonnet-20240620",input_cost_per_token:3e-6,output_cost_per_token:15e-6,provider:"Anthropic"},{model_id:"claude-3-5-sonnet-20241022",input_cost_per_token:3e-6,output_cost_per_token:15e-6,provider:"Anthropic"},{model_id:"claude-3-7-sonnet-20250219",input_cost_per_token:3e-6,output_cost_per_token:15e-6,provider:"Anthropic"},{model_id:"claude-3-haiku-20240307",input_cost_per_token:25e-8,output_cost_per_token:125e-8,provider:"Anthropic"},{model_id:"claude-3-opus-20240229",input_cost_per_token:15e-6,output_cost_per_token:75e-6,provider:"Anthropic"},{model_id:"claude-opus-4-1-20250805",input_cost_per_token:15e-6,output_cost_per_token:75e-6,provider:"Anthropic"},{model_id:"claude-opus-4-20250514",input_cost_per_token:15e-6,output_cost_per_token:75e-6,provider:"Anthropic"},{model_id:"claude-sonnet-4-20250514",input_cost_per_token:3e-6,output_cost_per_token:15e-6,provider:"Anthropic"}],l_=[{model_id:"gemini-2.0-flash",input_cost_per_token:15e-8,output_cost_per_token:6e-7,provider:"Gemini"},{model_id:"gemini-2.0-flash-001",input_cost_per_token:15e-8,output_cost_per_token:6e-7,provider:"Gemini"},{model_id:"gemini-2.0-flash-exp",input_cost_per_token:15e-8,output_cost_per_token:6e-7,provider:"Gemini"},{model_id:"gemini-2.0-flash-exp-image-generation",input_cost_per_token:15e-8,output_cost_per_token:6e-7,provider:"Gemini"},{model_id:"gemini-2.0-flash-lite",input_cost_per_token:75e-9,output_cost_per_token:3e-7,provider:"Gemini"},{model_id:"gemini-2.0-flash-lite-001",input_cost_per_token:75e-9,output_cost_per_token:3e-7,provider:"Gemini"},{model_id:"gemini-2.0-flash-lite-preview",input_cost_per_token:75e-9,output_cost_per_token:3e-7,provider:"Gemini"},{model_id:"gemini-2.0-flash-lite-preview-02-05",input_cost_per_token:75e-9,output_cost_per_token:3e-7,provider:"Gemini"},{model_id:"gemini-2.0-flash-preview-image-generation",input_cost_per_token:15e-8,output_cost_per_token:6e-7,provider:"Gemini"},{model_id:"gemini-2.0-flash-thinking-exp",input_cost_per_token:15e-8,output_cost_per_token:6e-7,provider:"Gemini"},{model_id:"gemini-2.0-flash-thinking-exp-01-21",input_cost_per_token:15e-8,output_cost_per_token:6e-7,provider:"Gemini"},{model_id:"gemini-2.0-flash-thinking-exp-1219",input_cost_per_token:15e-8,output_cost_per_token:6e-7,provider:"Gemini"},{model_id:"gemini-2.5-flash",input_cost_per_token:3e-7,output_cost_per_token:25e-7,provider:"Gemini"},{model_id:"gemini-2.5-flash-image-preview",input_cost_per_token:3e-7,output_cost_per_token:25e-7,provider:"Gemini"},{model_id:"gemini-2.5-flash-lite",input_cost_per_token:1e-7,output_cost_per_token:4e-7,provider:"Gemini"},{model_id:"gemini-2.5-flash-lite-preview-06-17",input_cost_per_token:1e-7,output_cost_per_token:4e-7,provider:"Gemini"},{model_id:"gemini-2.5-flash-preview-05-20",input_cost_per_token:3e-7,output_cost_per_token:25e-7,provider:"Gemini"},{model_id:"gemini-2.5-flash-preview-tts",input_cost_per_token:3e-7,output_cost_per_token:25e-7,provider:"Gemini"},{model_id:"gemini-2.5-pro",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"Gemini"},{model_id:"gemini-2.5-pro-preview-03-25",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"Gemini"},{model_id:"gemini-2.5-pro-preview-05-06",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"Gemini"},{model_id:"gemini-2.5-pro-preview-06-05",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"Gemini"},{model_id:"gemini-2.5-pro-preview-tts",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"Gemini"}],c_=[{model_id:"gpt-3.5-turbo",input_cost_per_token:5e-7,output_cost_per_token:15e-7,provider:"OpenAI"},{model_id:"gpt-3.5-turbo-0125",input_cost_per_token:5e-7,output_cost_per_token:15e-7,provider:"OpenAI"},{model_id:"gpt-3.5-turbo-1106",input_cost_per_token:5e-7,output_cost_per_token:15e-7,provider:"OpenAI"},{model_id:"gpt-4",input_cost_per_token:4e-7,output_cost_per_token:16e-7,provider:"OpenAI"},{model_id:"gpt-4-0125-preview",input_cost_per_token:4e-7,output_cost_per_token:16e-7,provider:"OpenAI"},{model_id:"gpt-4-0613",input_cost_per_token:4e-7,output_cost_per_token:16e-7,provider:"OpenAI"},{model_id:"gpt-4-1106-preview",input_cost_per_token:4e-7,output_cost_per_token:16e-7,provider:"OpenAI"},{model_id:"gpt-4-turbo",input_cost_per_token:1e-5,output_cost_per_token:3e-5,provider:"OpenAI"},{model_id:"gpt-4-turbo-2024-04-09",input_cost_per_token:1e-5,output_cost_per_token:3e-5,provider:"OpenAI"},{model_id:"gpt-4-turbo-preview",input_cost_per_token:1e-5,output_cost_per_token:3e-5,provider:"OpenAI"},{model_id:"gpt-4.1",input_cost_per_token:2e-6,output_cost_per_token:8e-6,provider:"OpenAI"},{model_id:"gpt-4.1-2025-04-14",input_cost_per_token:2e-6,output_cost_per_token:8e-6,provider:"OpenAI"},{model_id:"gpt-4.1-mini",input_cost_per_token:4e-7,output_cost_per_token:16e-7,provider:"OpenAI"},{model_id:"gpt-4.1-mini-2025-04-14",input_cost_per_token:4e-7,output_cost_per_token:16e-7,provider:"OpenAI"},{model_id:"gpt-4.1-nano",input_cost_per_token:1e-7,output_cost_per_token:4e-7,provider:"OpenAI"},{model_id:"gpt-4.1-nano-2025-04-14",input_cost_per_token:1e-7,output_cost_per_token:4e-7,provider:"OpenAI"},{model_id:"gpt-4o",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"OpenAI"},{model_id:"gpt-4o-2024-05-13",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"OpenAI"},{model_id:"gpt-4o-2024-08-06",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"OpenAI"},{model_id:"gpt-4o-2024-11-20",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"OpenAI"},{model_id:"gpt-4o-mini",input_cost_per_token:15e-8,output_cost_per_token:6e-7,provider:"OpenAI"},{model_id:"gpt-4o-mini-2024-07-18",input_cost_per_token:15e-8,output_cost_per_token:6e-7,provider:"OpenAI"},{model_id:"gpt-5",input_cost_per_token:125e-8,output_cost_per_token:1e-5,provider:"OpenAI"},{model_id:"gpt-5-2025-08-07",input_cost_per_token:125e-8,output_cost_per_token:1e-5,provider:"OpenAI"},{model_id:"gpt-5-chat-latest",input_cost_per_token:125e-8,output_cost_per_token:1e-5,provider:"OpenAI"},{model_id:"gpt-5-mini",input_cost_per_token:25e-8,output_cost_per_token:2e-6,provider:"OpenAI"},{model_id:"gpt-5-mini-2025-08-07",input_cost_per_token:25e-8,output_cost_per_token:2e-6,provider:"OpenAI"},{model_id:"gpt-5-nano",input_cost_per_token:5e-8,output_cost_per_token:4e-7,provider:"OpenAI"},{model_id:"gpt-5-nano-2025-08-07",input_cost_per_token:5e-8,output_cost_per_token:4e-7,provider:"OpenAI"},{model_id:"o1",input_cost_per_token:15e-6,output_cost_per_token:6e-5,provider:"OpenAI"},{model_id:"o1-2024-12-17",input_cost_per_token:15e-6,output_cost_per_token:6e-5,provider:"OpenAI"},{model_id:"o1-pro",input_cost_per_token:15e-6,output_cost_per_token:6e-5,provider:"OpenAI"},{model_id:"o1-pro-2025-03-19",input_cost_per_token:15e-6,output_cost_per_token:6e-5,provider:"OpenAI"},{model_id:"o3",input_cost_per_token:2e-6,output_cost_per_token:8e-6,provider:"OpenAI"},{model_id:"o3-2025-04-16",input_cost_per_token:2e-6,output_cost_per_token:8e-6,provider:"OpenAI"},{model_id:"o3-deep-research",input_cost_per_token:2e-6,output_cost_per_token:8e-6,provider:"OpenAI"},{model_id:"o3-deep-research-2025-06-26",input_cost_per_token:2e-6,output_cost_per_token:8e-6,provider:"OpenAI"},{model_id:"o3-mini",input_cost_per_token:11e-7,output_cost_per_token:44e-7,provider:"OpenAI"},{model_id:"o3-mini-2025-01-31",input_cost_per_token:11e-7,output_cost_per_token:44e-7,provider:"OpenAI"},{model_id:"o3-pro",input_cost_per_token:2e-6,output_cost_per_token:8e-6,provider:"OpenAI"},{model_id:"o3-pro-2025-06-10",input_cost_per_token:2e-6,output_cost_per_token:8e-6,provider:"OpenAI"}],d_=[{model_id:"agentica-org/deepcoder-14b-preview",input_cost_per_token:15e-9,output_cost_per_token:15e-9,provider:"OpenRouter"},{model_id:"agentica-org/deepcoder-14b-preview:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"ai21/jamba-large-1.7",input_cost_per_token:2e-6,output_cost_per_token:8e-6,provider:"OpenRouter"},{model_id:"ai21/jamba-mini-1.7",input_cost_per_token:2e-7,output_cost_per_token:4e-7,provider:"OpenRouter"},{model_id:"aion-labs/aion-1.0",input_cost_per_token:4e-6,output_cost_per_token:8e-6,provider:"OpenRouter"},{model_id:"aion-labs/aion-1.0-mini",input_cost_per_token:7e-7,output_cost_per_token:14e-7,provider:"OpenRouter"},{model_id:"aion-labs/aion-rp-llama-3.1-8b",input_cost_per_token:2e-7,output_cost_per_token:2e-7,provider:"OpenRouter"},{model_id:"alfredpros/codellama-7b-instruct-solidity",input_cost_per_token:7e-7,output_cost_per_token:11e-7,provider:"OpenRouter"},{model_id:"alpindale/goliath-120b",input_cost_per_token:4e-6,output_cost_per_token:55e-7,provider:"OpenRouter"},{model_id:"amazon/nova-lite-v1",input_cost_per_token:6e-8,output_cost_per_token:24e-8,provider:"OpenRouter"},{model_id:"amazon/nova-micro-v1",input_cost_per_token:35e-9,output_cost_per_token:14e-8,provider:"OpenRouter"},{model_id:"amazon/nova-pro-v1",input_cost_per_token:8e-7,output_cost_per_token:32e-7,provider:"OpenRouter"},{model_id:"anthracite-org/magnum-v2-72b",input_cost_per_token:3e-6,output_cost_per_token:3e-6,provider:"OpenRouter"},{model_id:"anthracite-org/magnum-v4-72b",input_cost_per_token:2e-6,output_cost_per_token:5e-6,provider:"OpenRouter"},{model_id:"anthropic/claude-3-haiku",input_cost_per_token:25e-8,output_cost_per_token:125e-8,provider:"OpenRouter"},{model_id:"anthropic/claude-3-opus",input_cost_per_token:15e-6,output_cost_per_token:75e-6,provider:"OpenRouter"},{model_id:"anthropic/claude-3.5-haiku",input_cost_per_token:8e-7,output_cost_per_token:4e-6,provider:"OpenRouter"},{model_id:"anthropic/claude-3.5-haiku-20241022",input_cost_per_token:8e-7,output_cost_per_token:4e-6,provider:"OpenRouter"},{model_id:"anthropic/claude-3.5-sonnet",input_cost_per_token:3e-6,output_cost_per_token:15e-6,provider:"OpenRouter"},{model_id:"anthropic/claude-3.5-sonnet-20240620",input_cost_per_token:3e-6,output_cost_per_token:15e-6,provider:"OpenRouter"},{model_id:"anthropic/claude-3.7-sonnet",input_cost_per_token:3e-6,output_cost_per_token:15e-6,provider:"OpenRouter"},{model_id:"anthropic/claude-3.7-sonnet:thinking",input_cost_per_token:3e-6,output_cost_per_token:15e-6,provider:"OpenRouter"},{model_id:"anthropic/claude-opus-4",input_cost_per_token:15e-6,output_cost_per_token:75e-6,provider:"OpenRouter"},{model_id:"anthropic/claude-opus-4.1",input_cost_per_token:15e-6,output_cost_per_token:75e-6,provider:"OpenRouter"},{model_id:"anthropic/claude-sonnet-4",input_cost_per_token:3e-6,output_cost_per_token:15e-6,provider:"OpenRouter"},{model_id:"arcee-ai/coder-large",input_cost_per_token:5e-7,output_cost_per_token:8e-7,provider:"OpenRouter"},{model_id:"arcee-ai/maestro-reasoning",input_cost_per_token:9e-7,output_cost_per_token:33e-7,provider:"OpenRouter"},{model_id:"arcee-ai/spotlight",input_cost_per_token:18e-8,output_cost_per_token:18e-8,provider:"OpenRouter"},{model_id:"arcee-ai/virtuoso-large",input_cost_per_token:75e-8,output_cost_per_token:12e-7,provider:"OpenRouter"},{model_id:"arliai/qwq-32b-arliai-rpr-v1",input_cost_per_token:1e-8,output_cost_per_token:4.00032e-8,provider:"OpenRouter"},{model_id:"arliai/qwq-32b-arliai-rpr-v1:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"baidu/ernie-4.5-21b-a3b",input_cost_per_token:7e-8,output_cost_per_token:28e-8,provider:"OpenRouter"},{model_id:"baidu/ernie-4.5-300b-a47b",input_cost_per_token:28e-8,output_cost_per_token:11e-7,provider:"OpenRouter"},{model_id:"baidu/ernie-4.5-vl-28b-a3b",input_cost_per_token:14e-8,output_cost_per_token:56e-8,provider:"OpenRouter"},{model_id:"baidu/ernie-4.5-vl-424b-a47b",input_cost_per_token:42e-8,output_cost_per_token:125e-8,provider:"OpenRouter"},{model_id:"bytedance/ui-tars-1.5-7b",input_cost_per_token:1e-7,output_cost_per_token:2e-7,provider:"OpenRouter"},{model_id:"cognitivecomputations/dolphin-mistral-24b-venice-edition:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"cognitivecomputations/dolphin-mixtral-8x22b",input_cost_per_token:9e-7,output_cost_per_token:9e-7,provider:"OpenRouter"},{model_id:"cognitivecomputations/dolphin3.0-mistral-24b",input_cost_per_token:3.7022e-8,output_cost_per_token:1.4816e-7,provider:"OpenRouter"},{model_id:"cognitivecomputations/dolphin3.0-mistral-24b:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"cognitivecomputations/dolphin3.0-r1-mistral-24b",input_cost_per_token:1e-8,output_cost_per_token:3.40768e-8,provider:"OpenRouter"},{model_id:"cognitivecomputations/dolphin3.0-r1-mistral-24b:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"cohere/command",input_cost_per_token:1e-6,output_cost_per_token:2e-6,provider:"OpenRouter"},{model_id:"cohere/command-a",input_cost_per_token:2e-6,output_cost_per_token:8e-6,provider:"OpenRouter"},{model_id:"cohere/command-r",input_cost_per_token:5e-7,output_cost_per_token:15e-7,provider:"OpenRouter"},{model_id:"cohere/command-r-03-2024",input_cost_per_token:5e-7,output_cost_per_token:15e-7,provider:"OpenRouter"},{model_id:"cohere/command-r-08-2024",input_cost_per_token:15e-8,output_cost_per_token:6e-7,provider:"OpenRouter"},{model_id:"cohere/command-r-plus",input_cost_per_token:3e-6,output_cost_per_token:15e-6,provider:"OpenRouter"},{model_id:"cohere/command-r-plus-04-2024",input_cost_per_token:3e-6,output_cost_per_token:15e-6,provider:"OpenRouter"},{model_id:"cohere/command-r-plus-08-2024",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"OpenRouter"},{model_id:"cohere/command-r7b-12-2024",input_cost_per_token:3.75e-8,output_cost_per_token:15e-8,provider:"OpenRouter"},{model_id:"deepseek/deepseek-chat",input_cost_per_token:1.999188e-7,output_cost_per_token:8.00064e-7,provider:"OpenRouter"},{model_id:"deepseek/deepseek-chat-v3-0324",input_cost_per_token:1.999188e-7,output_cost_per_token:8.00064e-7,provider:"OpenRouter"},{model_id:"deepseek/deepseek-chat-v3-0324:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"deepseek/deepseek-chat-v3.1",input_cost_per_token:2e-7,output_cost_per_token:8e-7,provider:"OpenRouter"},{model_id:"deepseek/deepseek-prover-v2",input_cost_per_token:5e-7,output_cost_per_token:218e-8,provider:"OpenRouter"},{model_id:"deepseek/deepseek-r1",input_cost_per_token:4e-7,output_cost_per_token:2e-6,provider:"OpenRouter"},{model_id:"deepseek/deepseek-r1-0528",input_cost_per_token:1.999188e-7,output_cost_per_token:8.00064e-7,provider:"OpenRouter"},{model_id:"deepseek/deepseek-r1-0528-qwen3-8b",input_cost_per_token:1e-8,output_cost_per_token:2e-8,provider:"OpenRouter"},{model_id:"deepseek/deepseek-r1-0528-qwen3-8b:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"deepseek/deepseek-r1-0528:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"deepseek/deepseek-r1-distill-llama-70b",input_cost_per_token:2.59154e-8,output_cost_per_token:1.03712e-7,provider:"OpenRouter"},{model_id:"deepseek/deepseek-r1-distill-llama-70b:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"deepseek/deepseek-r1-distill-llama-8b",input_cost_per_token:4e-8,output_cost_per_token:4e-8,provider:"OpenRouter"},{model_id:"deepseek/deepseek-r1-distill-qwen-1.5b",input_cost_per_token:18e-8,output_cost_per_token:18e-8,provider:"OpenRouter"},{model_id:"deepseek/deepseek-r1-distill-qwen-14b",input_cost_per_token:15e-8,output_cost_per_token:15e-8,provider:"OpenRouter"},{model_id:"deepseek/deepseek-r1-distill-qwen-14b:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"deepseek/deepseek-r1-distill-qwen-32b",input_cost_per_token:75e-9,output_cost_per_token:15e-8,provider:"OpenRouter"},{model_id:"deepseek/deepseek-r1:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"deepseek/deepseek-v3.1-base",input_cost_per_token:2e-7,output_cost_per_token:8e-7,provider:"OpenRouter"},{model_id:"eleutherai/llemma_7b",input_cost_per_token:8e-7,output_cost_per_token:12e-7,provider:"OpenRouter"},{model_id:"google/gemini-2.0-flash-001",input_cost_per_token:1e-7,output_cost_per_token:4e-7,provider:"OpenRouter"},{model_id:"google/gemini-2.0-flash-exp:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"google/gemini-2.0-flash-lite-001",input_cost_per_token:75e-9,output_cost_per_token:3e-7,provider:"OpenRouter"},{model_id:"google/gemini-2.5-flash",input_cost_per_token:3e-7,output_cost_per_token:25e-7,provider:"OpenRouter"},{model_id:"google/gemini-2.5-flash-lite",input_cost_per_token:1e-7,output_cost_per_token:4e-7,provider:"OpenRouter"},{model_id:"google/gemini-2.5-flash-lite-preview-06-17",input_cost_per_token:1e-7,output_cost_per_token:4e-7,provider:"OpenRouter"},{model_id:"google/gemini-2.5-pro",input_cost_per_token:125e-8,output_cost_per_token:1e-5,provider:"OpenRouter"},{model_id:"google/gemini-2.5-pro-exp-03-25",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"google/gemini-2.5-pro-preview",input_cost_per_token:125e-8,output_cost_per_token:1e-5,provider:"OpenRouter"},{model_id:"google/gemini-2.5-pro-preview-05-06",input_cost_per_token:125e-8,output_cost_per_token:1e-5,provider:"OpenRouter"},{model_id:"google/gemini-flash-1.5",input_cost_per_token:75e-9,output_cost_per_token:3e-7,provider:"OpenRouter"},{model_id:"google/gemini-flash-1.5-8b",input_cost_per_token:3.75e-8,output_cost_per_token:15e-8,provider:"OpenRouter"},{model_id:"google/gemini-pro-1.5",input_cost_per_token:125e-8,output_cost_per_token:5e-6,provider:"OpenRouter"},{model_id:"google/gemma-2-27b-it",input_cost_per_token:65e-8,output_cost_per_token:65e-8,provider:"OpenRouter"},{model_id:"google/gemma-2-9b-it",input_cost_per_token:1e-8,output_cost_per_token:1.00008e-8,provider:"OpenRouter"},{model_id:"google/gemma-2-9b-it:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"google/gemma-3-12b-it",input_cost_per_token:4.81286e-8,output_cost_per_token:1.92608e-7,provider:"OpenRouter"},{model_id:"google/gemma-3-12b-it:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"google/gemma-3-27b-it",input_cost_per_token:6.66396e-8,output_cost_per_token:2.66688e-7,provider:"OpenRouter"},{model_id:"google/gemma-3-27b-it:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"google/gemma-3-4b-it",input_cost_per_token:2e-8,output_cost_per_token:4e-8,provider:"OpenRouter"},{model_id:"google/gemma-3-4b-it:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"google/gemma-3n-e2b-it:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"google/gemma-3n-e4b-it",input_cost_per_token:2e-8,output_cost_per_token:4e-8,provider:"OpenRouter"},{model_id:"google/gemma-3n-e4b-it:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"gryphe/mythomax-l2-13b",input_cost_per_token:6e-8,output_cost_per_token:6e-8,provider:"OpenRouter"},{model_id:"inception/mercury",input_cost_per_token:25e-8,output_cost_per_token:1e-6,provider:"OpenRouter"},{model_id:"inception/mercury-coder",input_cost_per_token:25e-8,output_cost_per_token:1e-6,provider:"OpenRouter"},{model_id:"infermatic/mn-inferor-12b",input_cost_per_token:6e-7,output_cost_per_token:1e-6,provider:"OpenRouter"},{model_id:"inflection/inflection-3-pi",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"OpenRouter"},{model_id:"inflection/inflection-3-productivity",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"OpenRouter"},{model_id:"liquid/lfm-3b",input_cost_per_token:2e-8,output_cost_per_token:2e-8,provider:"OpenRouter"},{model_id:"liquid/lfm-7b",input_cost_per_token:1e-8,output_cost_per_token:1e-8,provider:"OpenRouter"},{model_id:"mancer/weaver",input_cost_per_token:1125e-9,output_cost_per_token:1125e-9,provider:"OpenRouter"},{model_id:"meta-llama/llama-3-70b-instruct",input_cost_per_token:3e-7,output_cost_per_token:4e-7,provider:"OpenRouter"},{model_id:"meta-llama/llama-3-8b-instruct",input_cost_per_token:3e-8,output_cost_per_token:6e-8,provider:"OpenRouter"},{model_id:"meta-llama/llama-3.1-405b",input_cost_per_token:2e-6,output_cost_per_token:2e-6,provider:"OpenRouter"},{model_id:"meta-llama/llama-3.1-405b-instruct",input_cost_per_token:8e-7,output_cost_per_token:8e-7,provider:"OpenRouter"},{model_id:"meta-llama/llama-3.1-405b-instruct:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"meta-llama/llama-3.1-70b-instruct",input_cost_per_token:1e-7,output_cost_per_token:28e-8,provider:"OpenRouter"},{model_id:"meta-llama/llama-3.1-8b-instruct",input_cost_per_token:15e-9,output_cost_per_token:2e-8,provider:"OpenRouter"},{model_id:"meta-llama/llama-3.2-11b-vision-instruct",input_cost_per_token:49e-9,output_cost_per_token:49e-9,provider:"OpenRouter"},{model_id:"meta-llama/llama-3.2-11b-vision-instruct:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"meta-llama/llama-3.2-1b-instruct",input_cost_per_token:5e-9,output_cost_per_token:1e-8,provider:"OpenRouter"},{model_id:"meta-llama/llama-3.2-3b-instruct",input_cost_per_token:3e-9,output_cost_per_token:6e-9,provider:"OpenRouter"},{model_id:"meta-llama/llama-3.2-3b-instruct:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"meta-llama/llama-3.2-90b-vision-instruct",input_cost_per_token:12e-7,output_cost_per_token:12e-7,provider:"OpenRouter"},{model_id:"meta-llama/llama-3.3-70b-instruct",input_cost_per_token:38e-9,output_cost_per_token:12e-8,provider:"OpenRouter"},{model_id:"meta-llama/llama-3.3-70b-instruct:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"meta-llama/llama-3.3-8b-instruct:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"meta-llama/llama-4-maverick",input_cost_per_token:15e-8,output_cost_per_token:6e-7,provider:"OpenRouter"},{model_id:"meta-llama/llama-4-maverick:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"meta-llama/llama-4-scout",input_cost_per_token:8e-8,output_cost_per_token:3e-7,provider:"OpenRouter"},{model_id:"meta-llama/llama-4-scout:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"meta-llama/llama-guard-2-8b",input_cost_per_token:2e-7,output_cost_per_token:2e-7,provider:"OpenRouter"},{model_id:"meta-llama/llama-guard-3-8b",input_cost_per_token:2e-8,output_cost_per_token:6e-8,provider:"OpenRouter"},{model_id:"meta-llama/llama-guard-4-12b",input_cost_per_token:18e-8,output_cost_per_token:18e-8,provider:"OpenRouter"},{model_id:"microsoft/mai-ds-r1",input_cost_per_token:1.999188e-7,output_cost_per_token:8.00064e-7,provider:"OpenRouter"},{model_id:"microsoft/mai-ds-r1:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"microsoft/phi-3-medium-128k-instruct",input_cost_per_token:1e-6,output_cost_per_token:1e-6,provider:"OpenRouter"},{model_id:"microsoft/phi-3-mini-128k-instruct",input_cost_per_token:1e-7,output_cost_per_token:1e-7,provider:"OpenRouter"},{model_id:"microsoft/phi-3.5-mini-128k-instruct",input_cost_per_token:1e-7,output_cost_per_token:1e-7,provider:"OpenRouter"},{model_id:"microsoft/phi-4",input_cost_per_token:6e-8,output_cost_per_token:14e-8,provider:"OpenRouter"},{model_id:"microsoft/phi-4-multimodal-instruct",input_cost_per_token:5e-8,output_cost_per_token:1e-7,provider:"OpenRouter"},{model_id:"microsoft/phi-4-reasoning-plus",input_cost_per_token:7e-8,output_cost_per_token:35e-8,provider:"OpenRouter"},{model_id:"microsoft/wizardlm-2-8x22b",input_cost_per_token:48e-8,output_cost_per_token:48e-8,provider:"OpenRouter"},{model_id:"minimax/minimax-01",input_cost_per_token:2e-7,output_cost_per_token:11e-7,provider:"OpenRouter"},{model_id:"minimax/minimax-m1",input_cost_per_token:3e-7,output_cost_per_token:165e-8,provider:"OpenRouter"},{model_id:"mistralai/codestral-2501",input_cost_per_token:3e-7,output_cost_per_token:9e-7,provider:"OpenRouter"},{model_id:"mistralai/codestral-2508",input_cost_per_token:3e-7,output_cost_per_token:9e-7,provider:"OpenRouter"},{model_id:"mistralai/devstral-medium",input_cost_per_token:4e-7,output_cost_per_token:2e-6,provider:"OpenRouter"},{model_id:"mistralai/devstral-small",input_cost_per_token:7e-8,output_cost_per_token:28e-8,provider:"OpenRouter"},{model_id:"mistralai/devstral-small-2505",input_cost_per_token:1.999188e-8,output_cost_per_token:8.00064e-8,provider:"OpenRouter"},{model_id:"mistralai/devstral-small-2505:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"mistralai/magistral-medium-2506",input_cost_per_token:2e-6,output_cost_per_token:5e-6,provider:"OpenRouter"},{model_id:"mistralai/magistral-medium-2506:thinking",input_cost_per_token:2e-6,output_cost_per_token:5e-6,provider:"OpenRouter"},{model_id:"mistralai/magistral-small-2506",input_cost_per_token:5e-7,output_cost_per_token:15e-7,provider:"OpenRouter"},{model_id:"mistralai/ministral-3b",input_cost_per_token:4e-8,output_cost_per_token:4e-8,provider:"OpenRouter"},{model_id:"mistralai/ministral-8b",input_cost_per_token:1e-7,output_cost_per_token:1e-7,provider:"OpenRouter"},{model_id:"mistralai/mistral-7b-instruct",input_cost_per_token:28e-9,output_cost_per_token:54e-9,provider:"OpenRouter"},{model_id:"mistralai/mistral-7b-instruct-v0.1",input_cost_per_token:11e-8,output_cost_per_token:19e-8,provider:"OpenRouter"},{model_id:"mistralai/mistral-7b-instruct-v0.3",input_cost_per_token:28e-9,output_cost_per_token:54e-9,provider:"OpenRouter"},{model_id:"mistralai/mistral-7b-instruct:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"mistralai/mistral-large",input_cost_per_token:2e-6,output_cost_per_token:6e-6,provider:"OpenRouter"},{model_id:"mistralai/mistral-large-2407",input_cost_per_token:2e-6,output_cost_per_token:6e-6,provider:"OpenRouter"},{model_id:"mistralai/mistral-large-2411",input_cost_per_token:2e-6,output_cost_per_token:6e-6,provider:"OpenRouter"},{model_id:"mistralai/mistral-medium-3",input_cost_per_token:4e-7,output_cost_per_token:2e-6,provider:"OpenRouter"},{model_id:"mistralai/mistral-medium-3.1",input_cost_per_token:4e-7,output_cost_per_token:2e-6,provider:"OpenRouter"},{model_id:"mistralai/mistral-nemo",input_cost_per_token:7.5e-9,output_cost_per_token:5e-8,provider:"OpenRouter"},{model_id:"mistralai/mistral-nemo:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"mistralai/mistral-saba",input_cost_per_token:2e-7,output_cost_per_token:6e-7,provider:"OpenRouter"},{model_id:"mistralai/mistral-small",input_cost_per_token:2e-7,output_cost_per_token:6e-7,provider:"OpenRouter"},{model_id:"mistralai/mistral-small-24b-instruct-2501",input_cost_per_token:1.999188e-8,output_cost_per_token:8.00064e-8,provider:"OpenRouter"},{model_id:"mistralai/mistral-small-24b-instruct-2501:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"mistralai/mistral-small-3.1-24b-instruct",input_cost_per_token:1.999188e-8,output_cost_per_token:8.00064e-8,provider:"OpenRouter"},{model_id:"mistralai/mistral-small-3.1-24b-instruct:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"mistralai/mistral-small-3.2-24b-instruct",input_cost_per_token:5e-8,output_cost_per_token:1e-7,provider:"OpenRouter"},{model_id:"mistralai/mistral-small-3.2-24b-instruct:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"mistralai/mistral-tiny",input_cost_per_token:25e-8,output_cost_per_token:25e-8,provider:"OpenRouter"},{model_id:"mistralai/mixtral-8x22b-instruct",input_cost_per_token:9e-7,output_cost_per_token:9e-7,provider:"OpenRouter"},{model_id:"mistralai/mixtral-8x7b-instruct",input_cost_per_token:8e-8,output_cost_per_token:24e-8,provider:"OpenRouter"},{model_id:"mistralai/pixtral-12b",input_cost_per_token:1e-7,output_cost_per_token:1e-7,provider:"OpenRouter"},{model_id:"mistralai/pixtral-large-2411",input_cost_per_token:2e-6,output_cost_per_token:6e-6,provider:"OpenRouter"},{model_id:"moonshotai/kimi-dev-72b:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"moonshotai/kimi-k2",input_cost_per_token:14e-8,output_cost_per_token:249e-8,provider:"OpenRouter"},{model_id:"moonshotai/kimi-k2:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"moonshotai/kimi-vl-a3b-thinking",input_cost_per_token:2.498985e-8,output_cost_per_token:1.00008e-7,provider:"OpenRouter"},{model_id:"moonshotai/kimi-vl-a3b-thinking:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"morph/morph-v3-fast",input_cost_per_token:9e-7,output_cost_per_token:19e-7,provider:"OpenRouter"},{model_id:"morph/morph-v3-large",input_cost_per_token:9e-7,output_cost_per_token:19e-7,provider:"OpenRouter"},{model_id:"neversleep/llama-3-lumimaid-70b",input_cost_per_token:4e-6,output_cost_per_token:6e-6,provider:"OpenRouter"},{model_id:"neversleep/llama-3.1-lumimaid-8b",input_cost_per_token:9e-8,output_cost_per_token:6e-7,provider:"OpenRouter"},{model_id:"neversleep/noromaid-20b",input_cost_per_token:1e-6,output_cost_per_token:175e-8,provider:"OpenRouter"},{model_id:"nousresearch/deephermes-3-llama-3-8b-preview:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"nousresearch/deephermes-3-mistral-24b-preview",input_cost_per_token:9.329544e-8,output_cost_per_token:3.733632e-7,provider:"OpenRouter"},{model_id:"nousresearch/hermes-2-pro-llama-3-8b",input_cost_per_token:25e-9,output_cost_per_token:4e-8,provider:"OpenRouter"},{model_id:"nousresearch/hermes-3-llama-3.1-405b",input_cost_per_token:7e-7,output_cost_per_token:8e-7,provider:"OpenRouter"},{model_id:"nousresearch/hermes-3-llama-3.1-70b",input_cost_per_token:1e-7,output_cost_per_token:28e-8,provider:"OpenRouter"},{model_id:"nousresearch/hermes-4-405b",input_cost_per_token:1e-6,output_cost_per_token:3e-6,provider:"OpenRouter"},{model_id:"nousresearch/hermes-4-70b",input_cost_per_token:13e-8,output_cost_per_token:4e-7,provider:"OpenRouter"},{model_id:"nousresearch/nous-hermes-2-mixtral-8x7b-dpo",input_cost_per_token:6e-7,output_cost_per_token:6e-7,provider:"OpenRouter"},{model_id:"nvidia/llama-3.1-nemotron-70b-instruct",input_cost_per_token:12e-8,output_cost_per_token:3e-7,provider:"OpenRouter"},{model_id:"nvidia/llama-3.1-nemotron-ultra-253b-v1",input_cost_per_token:6e-7,output_cost_per_token:18e-7,provider:"OpenRouter"},{model_id:"nvidia/llama-3.1-nemotron-ultra-253b-v1:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"nvidia/llama-3.3-nemotron-super-49b-v1",input_cost_per_token:13e-8,output_cost_per_token:4e-7,provider:"OpenRouter"},{model_id:"openai/chatgpt-4o-latest",input_cost_per_token:5e-6,output_cost_per_token:15e-6,provider:"OpenRouter"},{model_id:"openai/codex-mini",input_cost_per_token:15e-7,output_cost_per_token:6e-6,provider:"OpenRouter"},{model_id:"openai/gpt-3.5-turbo",input_cost_per_token:5e-7,output_cost_per_token:15e-7,provider:"OpenRouter"},{model_id:"openai/gpt-3.5-turbo-0613",input_cost_per_token:1e-6,output_cost_per_token:2e-6,provider:"OpenRouter"},{model_id:"openai/gpt-3.5-turbo-16k",input_cost_per_token:3e-6,output_cost_per_token:4e-6,provider:"OpenRouter"},{model_id:"openai/gpt-3.5-turbo-instruct",input_cost_per_token:15e-7,output_cost_per_token:2e-6,provider:"OpenRouter"},{model_id:"openai/gpt-4",input_cost_per_token:3e-5,output_cost_per_token:6e-5,provider:"OpenRouter"},{model_id:"openai/gpt-4-0314",input_cost_per_token:3e-5,output_cost_per_token:6e-5,provider:"OpenRouter"},{model_id:"openai/gpt-4-1106-preview",input_cost_per_token:1e-5,output_cost_per_token:3e-5,provider:"OpenRouter"},{model_id:"openai/gpt-4-turbo",input_cost_per_token:1e-5,output_cost_per_token:3e-5,provider:"OpenRouter"},{model_id:"openai/gpt-4-turbo-preview",input_cost_per_token:1e-5,output_cost_per_token:3e-5,provider:"OpenRouter"},{model_id:"openai/gpt-4.1",input_cost_per_token:2e-6,output_cost_per_token:8e-6,provider:"OpenRouter"},{model_id:"openai/gpt-4.1-mini",input_cost_per_token:4e-7,output_cost_per_token:16e-7,provider:"OpenRouter"},{model_id:"openai/gpt-4.1-nano",input_cost_per_token:1e-7,output_cost_per_token:4e-7,provider:"OpenRouter"},{model_id:"openai/gpt-4o",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"OpenRouter"},{model_id:"openai/gpt-4o-2024-05-13",input_cost_per_token:5e-6,output_cost_per_token:15e-6,provider:"OpenRouter"},{model_id:"openai/gpt-4o-2024-08-06",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"OpenRouter"},{model_id:"openai/gpt-4o-2024-11-20",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"OpenRouter"},{model_id:"openai/gpt-4o-audio-preview",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"OpenRouter"},{model_id:"openai/gpt-4o-mini",input_cost_per_token:15e-8,output_cost_per_token:6e-7,provider:"OpenRouter"},{model_id:"openai/gpt-4o-mini-2024-07-18",input_cost_per_token:15e-8,output_cost_per_token:6e-7,provider:"OpenRouter"},{model_id:"openai/gpt-4o-mini-search-preview",input_cost_per_token:15e-8,output_cost_per_token:6e-7,provider:"OpenRouter"},{model_id:"openai/gpt-4o-search-preview",input_cost_per_token:25e-7,output_cost_per_token:1e-5,provider:"OpenRouter"},{model_id:"openai/gpt-4o:extended",input_cost_per_token:6e-6,output_cost_per_token:18e-6,provider:"OpenRouter"},{model_id:"openai/gpt-5",input_cost_per_token:125e-8,output_cost_per_token:1e-5,provider:"OpenRouter"},{model_id:"openai/gpt-5-chat",input_cost_per_token:125e-8,output_cost_per_token:1e-5,provider:"OpenRouter"},{model_id:"openai/gpt-5-mini",input_cost_per_token:25e-8,output_cost_per_token:2e-6,provider:"OpenRouter"},{model_id:"openai/gpt-5-nano",input_cost_per_token:5e-8,output_cost_per_token:4e-7,provider:"OpenRouter"},{model_id:"openai/gpt-oss-120b",input_cost_per_token:72e-9,output_cost_per_token:28e-8,provider:"OpenRouter"},{model_id:"openai/gpt-oss-20b",input_cost_per_token:4e-8,output_cost_per_token:15e-8,provider:"OpenRouter"},{model_id:"openai/gpt-oss-20b:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"openai/o1",input_cost_per_token:15e-6,output_cost_per_token:6e-5,provider:"OpenRouter"},{model_id:"openai/o1-mini",input_cost_per_token:11e-7,output_cost_per_token:44e-7,provider:"OpenRouter"},{model_id:"openai/o1-mini-2024-09-12",input_cost_per_token:11e-7,output_cost_per_token:44e-7,provider:"OpenRouter"},{model_id:"openai/o1-pro",input_cost_per_token:15e-5,output_cost_per_token:6e-4,provider:"OpenRouter"},{model_id:"openai/o3",input_cost_per_token:2e-6,output_cost_per_token:8e-6,provider:"OpenRouter"},{model_id:"openai/o3-mini",input_cost_per_token:11e-7,output_cost_per_token:44e-7,provider:"OpenRouter"},{model_id:"openai/o3-mini-high",input_cost_per_token:11e-7,output_cost_per_token:44e-7,provider:"OpenRouter"},{model_id:"openai/o3-pro",input_cost_per_token:2e-5,output_cost_per_token:8e-5,provider:"OpenRouter"},{model_id:"openai/o4-mini",input_cost_per_token:11e-7,output_cost_per_token:44e-7,provider:"OpenRouter"},{model_id:"openai/o4-mini-high",input_cost_per_token:11e-7,output_cost_per_token:44e-7,provider:"OpenRouter"},{model_id:"opengvlab/internvl3-14b",input_cost_per_token:2e-7,output_cost_per_token:4e-7,provider:"OpenRouter"},{model_id:"openrouter/auto",input_cost_per_token:-1,output_cost_per_token:-1,provider:"OpenRouter"},{model_id:"perplexity/r1-1776",input_cost_per_token:2e-6,output_cost_per_token:8e-6,provider:"OpenRouter"},{model_id:"perplexity/sonar",input_cost_per_token:1e-6,output_cost_per_token:1e-6,provider:"OpenRouter"},{model_id:"perplexity/sonar-deep-research",input_cost_per_token:2e-6,output_cost_per_token:8e-6,provider:"OpenRouter"},{model_id:"perplexity/sonar-pro",input_cost_per_token:3e-6,output_cost_per_token:15e-6,provider:"OpenRouter"},{model_id:"perplexity/sonar-reasoning",input_cost_per_token:1e-6,output_cost_per_token:5e-6,provider:"OpenRouter"},{model_id:"perplexity/sonar-reasoning-pro",input_cost_per_token:2e-6,output_cost_per_token:8e-6,provider:"OpenRouter"},{model_id:"pygmalionai/mythalion-13b",input_cost_per_token:7e-7,output_cost_per_token:11e-7,provider:"OpenRouter"},{model_id:"qwen/qwen-2-72b-instruct",input_cost_per_token:9e-7,output_cost_per_token:9e-7,provider:"OpenRouter"},{model_id:"qwen/qwen-2.5-72b-instruct",input_cost_per_token:5.18308e-8,output_cost_per_token:2.07424e-7,provider:"OpenRouter"},{model_id:"qwen/qwen-2.5-72b-instruct:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"qwen/qwen-2.5-7b-instruct",input_cost_per_token:4e-8,output_cost_per_token:1e-7,provider:"OpenRouter"},{model_id:"qwen/qwen-2.5-coder-32b-instruct",input_cost_per_token:4.99797e-8,output_cost_per_token:2.00016e-7,provider:"OpenRouter"},{model_id:"qwen/qwen-2.5-coder-32b-instruct:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"qwen/qwen-2.5-vl-7b-instruct",input_cost_per_token:2e-7,output_cost_per_token:2e-7,provider:"OpenRouter"},{model_id:"qwen/qwen-max",input_cost_per_token:16e-7,output_cost_per_token:64e-7,provider:"OpenRouter"},{model_id:"qwen/qwen-plus",input_cost_per_token:4e-7,output_cost_per_token:12e-7,provider:"OpenRouter"},{model_id:"qwen/qwen-turbo",input_cost_per_token:5e-8,output_cost_per_token:2e-7,provider:"OpenRouter"},{model_id:"qwen/qwen-vl-max",input_cost_per_token:8e-7,output_cost_per_token:32e-7,provider:"OpenRouter"},{model_id:"qwen/qwen-vl-plus",input_cost_per_token:21e-8,output_cost_per_token:63e-8,provider:"OpenRouter"},{model_id:"qwen/qwen2.5-vl-32b-instruct",input_cost_per_token:1.999188e-8,output_cost_per_token:8.00064e-8,provider:"OpenRouter"},{model_id:"qwen/qwen2.5-vl-32b-instruct:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"qwen/qwen2.5-vl-72b-instruct",input_cost_per_token:9.99594e-8,output_cost_per_token:4.00032e-7,provider:"OpenRouter"},{model_id:"qwen/qwen2.5-vl-72b-instruct:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"qwen/qwen3-14b",input_cost_per_token:6e-8,output_cost_per_token:24e-8,provider:"OpenRouter"},{model_id:"qwen/qwen3-14b:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"qwen/qwen3-235b-a22b",input_cost_per_token:13e-8,output_cost_per_token:6e-7,provider:"OpenRouter"},{model_id:"qwen/qwen3-235b-a22b-2507",input_cost_per_token:7.7968332e-8,output_cost_per_token:3.1202496e-7,provider:"OpenRouter"},{model_id:"qwen/qwen3-235b-a22b-thinking-2507",input_cost_per_token:7.7968332e-8,output_cost_per_token:3.1202496e-7,provider:"OpenRouter"},{model_id:"qwen/qwen3-235b-a22b:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"qwen/qwen3-30b-a3b",input_cost_per_token:1.999188e-8,output_cost_per_token:8.00064e-8,provider:"OpenRouter"},{model_id:"qwen/qwen3-30b-a3b-instruct-2507",input_cost_per_token:1e-7,output_cost_per_token:3e-7,provider:"OpenRouter"},{model_id:"qwen/qwen3-30b-a3b:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"qwen/qwen3-32b",input_cost_per_token:1.7992692e-8,output_cost_per_token:7.200576e-8,provider:"OpenRouter"},{model_id:"qwen/qwen3-4b:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"qwen/qwen3-8b",input_cost_per_token:35e-9,output_cost_per_token:138e-9,provider:"OpenRouter"},{model_id:"qwen/qwen3-8b:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"qwen/qwen3-coder",input_cost_per_token:2e-7,output_cost_per_token:8e-7,provider:"OpenRouter"},{model_id:"qwen/qwen3-coder:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"qwen/qwq-32b",input_cost_per_token:75e-9,output_cost_per_token:15e-8,provider:"OpenRouter"},{model_id:"qwen/qwq-32b-preview",input_cost_per_token:2e-7,output_cost_per_token:2e-7,provider:"OpenRouter"},{model_id:"qwen/qwq-32b:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"raifle/sorcererlm-8x22b",input_cost_per_token:45e-7,output_cost_per_token:45e-7,provider:"OpenRouter"},{model_id:"rekaai/reka-flash-3:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"sao10k/l3-euryale-70b",input_cost_per_token:148e-8,output_cost_per_token:148e-8,provider:"OpenRouter"},{model_id:"sao10k/l3-lunaris-8b",input_cost_per_token:2e-8,output_cost_per_token:5e-8,provider:"OpenRouter"},{model_id:"sao10k/l3.1-euryale-70b",input_cost_per_token:65e-8,output_cost_per_token:75e-8,provider:"OpenRouter"},{model_id:"sao10k/l3.3-euryale-70b",input_cost_per_token:65e-8,output_cost_per_token:75e-8,provider:"OpenRouter"},{model_id:"sarvamai/sarvam-m:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"scb10x/llama3.1-typhoon2-70b-instruct",input_cost_per_token:88e-8,output_cost_per_token:88e-8,provider:"OpenRouter"},{model_id:"shisa-ai/shisa-v2-llama3.3-70b",input_cost_per_token:1.999188e-8,output_cost_per_token:8.00064e-8,provider:"OpenRouter"},{model_id:"shisa-ai/shisa-v2-llama3.3-70b:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"sophosympatheia/midnight-rose-70b",input_cost_per_token:8e-7,output_cost_per_token:8e-7,provider:"OpenRouter"},{model_id:"switchpoint/router",input_cost_per_token:85e-8,output_cost_per_token:34e-7,provider:"OpenRouter"},{model_id:"tencent/hunyuan-a13b-instruct",input_cost_per_token:3e-8,output_cost_per_token:3e-8,provider:"OpenRouter"},{model_id:"tencent/hunyuan-a13b-instruct:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"thedrummer/anubis-70b-v1.1",input_cost_per_token:4e-7,output_cost_per_token:7e-7,provider:"OpenRouter"},{model_id:"thedrummer/anubis-pro-105b-v1",input_cost_per_token:5e-7,output_cost_per_token:1e-6,provider:"OpenRouter"},{model_id:"thedrummer/rocinante-12b",input_cost_per_token:17e-8,output_cost_per_token:43e-8,provider:"OpenRouter"},{model_id:"thedrummer/skyfall-36b-v2",input_cost_per_token:4.81286e-8,output_cost_per_token:1.92608e-7,provider:"OpenRouter"},{model_id:"thedrummer/unslopnemo-12b",input_cost_per_token:4e-7,output_cost_per_token:4e-7,provider:"OpenRouter"},{model_id:"thudm/glm-4-32b",input_cost_per_token:55e-8,output_cost_per_token:166e-8,provider:"OpenRouter"},{model_id:"thudm/glm-4.1v-9b-thinking",input_cost_per_token:35e-9,output_cost_per_token:138e-9,provider:"OpenRouter"},{model_id:"thudm/glm-z1-32b",input_cost_per_token:1.999188e-8,output_cost_per_token:8.00064e-8,provider:"OpenRouter"},{model_id:"tngtech/deepseek-r1t-chimera",input_cost_per_token:1.999188e-7,output_cost_per_token:8.00064e-7,provider:"OpenRouter"},{model_id:"tngtech/deepseek-r1t-chimera:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"tngtech/deepseek-r1t2-chimera:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"undi95/remm-slerp-l2-13b",input_cost_per_token:45e-8,output_cost_per_token:65e-8,provider:"OpenRouter"},{model_id:"x-ai/grok-2-1212",input_cost_per_token:2e-6,output_cost_per_token:1e-5,provider:"OpenRouter"},{model_id:"x-ai/grok-2-vision-1212",input_cost_per_token:2e-6,output_cost_per_token:1e-5,provider:"OpenRouter"},{model_id:"x-ai/grok-3",input_cost_per_token:3e-6,output_cost_per_token:15e-6,provider:"OpenRouter"},{model_id:"x-ai/grok-3-beta",input_cost_per_token:3e-6,output_cost_per_token:15e-6,provider:"OpenRouter"},{model_id:"x-ai/grok-3-mini",input_cost_per_token:3e-7,output_cost_per_token:5e-7,provider:"OpenRouter"},{model_id:"x-ai/grok-3-mini-beta",input_cost_per_token:3e-7,output_cost_per_token:5e-7,provider:"OpenRouter"},{model_id:"x-ai/grok-4",input_cost_per_token:3e-6,output_cost_per_token:15e-6,provider:"OpenRouter"},{model_id:"x-ai/grok-vision-beta",input_cost_per_token:5e-6,output_cost_per_token:15e-6,provider:"OpenRouter"},{model_id:"z-ai/glm-4-32b",input_cost_per_token:1e-7,output_cost_per_token:1e-7,provider:"OpenRouter"},{model_id:"z-ai/glm-4.5",input_cost_per_token:1.999188e-7,output_cost_per_token:8.00064e-7,provider:"OpenRouter"},{model_id:"z-ai/glm-4.5-air",input_cost_per_token:2e-7,output_cost_per_token:11e-7,provider:"OpenRouter"},{model_id:"z-ai/glm-4.5-air:free",input_cost_per_token:0,output_cost_per_token:0,provider:"OpenRouter"},{model_id:"z-ai/glm-4.5v",input_cost_per_token:5e-7,output_cost_per_token:18e-7,provider:"OpenRouter"}],p_=[{model_id:"gpt-image-1",image_input_cost_per_token:1e-5,image_output_cost_per_token:4e-5,text_input_cost_per_token:5e-6,provider:"OpenAI"}],m_=class extends i_{constructor(e){super(e)}async listSupportedChatModels(){return[...c_,...u_,...l_,...d_]}async listSupportedImageModels(){return p_}},__=class extends i_{constructor(e){super(e)}async createPaymentLink(e){return this.handleRequest((()=>this.http.post("/api/v1/stripe/payment-link",e)),"creating payment link","/api/v1/stripe/payment-link")}async getPaymentUrl(e,t,n){const r={amount:e,description:t||"Echo Credits"};n&&(r.successUrl=n);try{return(await this.createPaymentLink(r)).paymentLink.url}catch(o){throw o}}},h_=class extends i_{constructor(e){super(e)}async getUserInfo(){return this.handleRequest((()=>this.http.get("/api/v1/user")),"fetching user info","/api/v1/user")}async registerReferralCode(e,t){const n={echoAppId:e,code:t};return this.handleRequest((()=>this.http.post("/api/v1/user/referral",n)),"registering referral code","/api/v1/user/referral")}},g_=class{constructor(e){var t;if(n(this,"http"),n(this,"config"),n(this,"tokenProvider"),n(this,"balance"),n(this,"payments"),n(this,"apps"),n(this,"users"),n(this,"models"),this.config=(t=e,{...e_,...t}),null==e?void 0:e.tokenProvider)this.tokenProvider=e.tokenProvider;else{const e=this.config.apiKey||process.env.ECHO_API_KEY;if(!e)throw new Error("No API key or token provider provided");this.tokenProvider=new Xm(e)}this.http=new n_(this.config.baseUrl,this.tokenProvider),this.balance=new a_(this.http),this.payments=new __(this.http),this.apps=new s_(this.http,this.config.baseUrl),this.users=new h_(this.http),this.models=new m_(this.http)}};function f_({appId:e,baseRouterUrl:t=t_},n){const r=async()=>{const r=await n(e);return Gp({baseURL:t,apiKey:r??""})};return Object.assign((async e=>(await r())(e)),{languageModel:async e=>(await r()).languageModel(e),chat:async e=>(await r()).chat(e),responses:async e=>(await r()).responses(e),completion:async e=>(await r()).completion(e),embedding:async e=>(await r()).embedding(e),textEmbedding:async e=>(await r()).textEmbedding(e),textEmbeddingModel:async e=>(await r()).textEmbeddingModel(e),image:async e=>(await r()).image(e),imageModel:async e=>(await r()).imageModel(e),transcription:async e=>(await r()).transcription(e),speech:async e=>(await r()).speech(e),tools:Kp.tools})}function v_({appId:e,baseRouterUrl:t=t_},n){const r=async()=>{const r=await n(e);return wm({baseURL:t,apiKey:r??""})};return Object.assign((async e=>(await r())(e)),{languageModel:async e=>(await r()).languageModel(e),chat:async e=>(await r()).chat(e),messages:async e=>(await r()).messages(e),textEmbeddingModel:async e=>(await r()).textEmbeddingModel(e),imageModel:async e=>(await r()).imageModel(e),tools:xm.tools})}function y_({appId:e,baseRouterUrl:t=t_},n){const r=async()=>{const r=await n(e);return Km({baseURL:t,apiKey:r??""})};return Object.assign((async e=>(await r())(e)),{languageModel:async e=>(await r()).languageModel(e),chat:async e=>(await r()).chat(e),image:async(e,t)=>(await r()).image(e,t),imageModel:async e=>(await r()).imageModel(e),textEmbedding:async e=>(await r()).textEmbedding(e),textEmbeddingModel:async e=>(await r()).textEmbeddingModel(e),generativeAI:async e=>(await r()).generativeAI(e),embedding:async e=>(await r()).embedding(e),tools:Ym.tools})}function b_({apiUrl:e}){var t,n;const r=$e(),[i,s]=o.useState(null);return o.useEffect((()=>{if(!r.user)return void s(null);const t=new Qm({getTokenFn:()=>{var e;return Promise.resolve((null==(e=r.user)?void 0:e.access_token)||null)},refreshTokenFn:async()=>{const e=await r.signinSilent();if(!e)throw new Error("Silent renew did not yield a new access token");return e.access_token},onRefreshErrorFn:async e=>{console.error("Token refresh failed:",e),await r.removeUser(),await r.clearStaleState()}}),n=new g_({baseUrl:e,tokenProvider:t});return s(n),()=>{s(null)}}),[e,r.user,null==(n=null==(t=r.user)?void 0:t.profile)?void 0:n.sub,r.signinSilent,r.signoutSilent]),i}const k_=o.createContext(null),w_=o.createContext(null);function x_({config:e,children:t}){var n,i,s;const a=$e(),u=a.user,l=u?function(e){return{id:e.profile.sub||"",email:e.profile.email||"",name:e.profile.name||e.profile.preferred_username||"",picture:e.profile.picture||""}}(u):null,c=e.baseEchoUrl||"https://echo.merit.systems",d=(null==(n=a.user)?void 0:n.access_token)||null,p=b_({apiUrl:c}),{balance:m,freeTierBalance:_,refreshBalance:h,error:g,isLoading:f}=function(e,t){const[n,r]=o.useState(null),[i,s]=o.useState(null),[a,u]=o.useState(null),[l,c]=o.useState(!1),d=o.useCallback((async()=>{if(!e)throw new Error("Not authenticated");c(!0);try{const[n,o]=await Promise.all([e.balance.getBalance(),e.balance.getFreeBalance(t)]);r(n),s(o),u(null)}catch(n){const e=o_(n instanceof Error?n:new Error(String(n)),"refreshing balance");throw u(e.message),e}finally{c(!1)}}),[e,t]);return o.useEffect((()=>{e&&t?d().catch((e=>{console.error("Error loading initial balance:",e)})):(r(null),s(null),u(null))}),[e,t,d]),{balance:n,freeTierBalance:i,error:a,isLoading:l,refreshBalance:d}}(p,e.appId),{createPaymentLink:v,error:y,isLoading:b}=function(e){const[t,n]=o.useState(null),[r,i]=o.useState(!1);return{createPaymentLink:o.useCallback((async(t,r,o)=>{if(!e)throw new Error("Not authenticated");i(!0);try{const i=await e.payments.createPaymentLink({amount:t,description:r||"Echo Credits",successUrl:o||window.location.origin});return n(null),i.paymentLink.url}catch(s){const e=o_(s instanceof Error?s:new Error(String(s)),"creating payment link");throw n(e.message),e}finally{i(!1)}}),[e]),error:t,isLoading:r}}(p),k=o.useCallback((async()=>{try{await a.removeUser()}catch(e){console.error("Error during auth cleanup:",e)}}),[a.removeUser]),w=o.useCallback((async()=>{var e;return(null==(e=a.user)?void 0:e.access_token)||null}),[null==(i=a.user)?void 0:i.access_token]),x=(null==(s=a.error)?void 0:s.message)||g||y||null,I=a.isLoading&&!a.isAuthenticated,S=a.isLoading&&a.isAuthenticated,$=I||f||b,O=o.useMemo((()=>({user:l||null,rawUser:u,balance:m,freeTierBalance:_,isAuthenticated:a.isAuthenticated,isLoading:$,error:x,token:d,echoClient:p,signIn:a.signinRedirect,signOut:k,refreshBalance:h,createPaymentLink:v,getToken:w,clearAuth:k,config:e})),[l,u,m,_,a.isAuthenticated,$,x,d,p,a.signinRedirect,k,h,v,w,e]),E=o.useMemo((()=>({isRefreshing:S})),[S]);return r.jsx(k_.Provider,{value:O,children:r.jsx(w_.Provider,{value:E,children:t})})}function I_(){const e=o.useContext(k_);if(!e)throw new Error("useEcho must be used within an EchoProvider");return e}
|
|
2
|
+
/*! @license DOMPurify 3.2.6 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.2.6/LICENSE */const{entries:S_,setPrototypeOf:$_,isFrozen:O_,getPrototypeOf:E_,getOwnPropertyDescriptor:T_}=Object;let{freeze:R_,seal:N_,create:A_}=Object,{apply:C_,construct:P_}="undefined"!=typeof Reflect&&Reflect;R_||(R_=function(e){return e}),N_||(N_=function(e){return e}),C_||(C_=function(e,t,n){return e.apply(t,n)}),P_||(P_=function(e,t){return new e(...t)});const U_=K_(Array.prototype.forEach),j_=K_(Array.prototype.lastIndexOf),z_=K_(Array.prototype.pop),D_=K_(Array.prototype.push),M_=K_(Array.prototype.splice),L_=K_(String.prototype.toLowerCase),q_=K_(String.prototype.toString),Z_=K_(String.prototype.match),F_=K_(String.prototype.replace),W_=K_(String.prototype.indexOf),J_=K_(String.prototype.trim),B_=K_(Object.prototype.hasOwnProperty),H_=K_(RegExp.prototype.test),V_=(G_=TypeError,function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return P_(G_,t)});var G_;function K_(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var n=arguments.length,r=new Array(n>1?n-1:0),o=1;o<n;o++)r[o-1]=arguments[o];return C_(e,t,r)}}function Y_(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:L_;$_&&$_(e,null);let r=t.length;for(;r--;){let o=t[r];if("string"==typeof o){const e=n(o);e!==o&&(O_(t)||(t[r]=e),o=e)}e[o]=!0}return e}function X_(e){for(let t=0;t<e.length;t++){B_(e,t)||(e[t]=null)}return e}function Q_(e){const t=A_(null);for(const[n,r]of S_(e)){B_(e,n)&&(Array.isArray(r)?t[n]=X_(r):r&&"object"==typeof r&&r.constructor===Object?t[n]=Q_(r):t[n]=r)}return t}function eh(e,t){for(;null!==e;){const n=T_(e,t);if(n){if(n.get)return K_(n.get);if("function"==typeof n.value)return K_(n.value)}e=E_(e)}return function(){return null}}const th=R_(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","section","select","shadow","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),nh=R_(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","filter","font","g","glyph","glyphref","hkern","image","line","lineargradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),rh=R_(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),oh=R_(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),ih=R_(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),sh=R_(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),ah=R_(["#text"]),uh=R_(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","face","for","headers","height","hidden","high","href","hreflang","id","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),lh=R_(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),ch=R_(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),dh=R_(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),ph=N_(/\{\{[\w\W]*|[\w\W]*\}\}/gm),mh=N_(/<%[\w\W]*|[\w\W]*%>/gm),_h=N_(/\$\{[\w\W]*/gm),hh=N_(/^data-[\-\w.\u00B7-\uFFFF]+$/),gh=N_(/^aria-[\-\w]+$/),fh=N_(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),vh=N_(/^(?:\w+script|data):/i),yh=N_(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),bh=N_(/^html$/i),kh=N_(/^[a-z][.\w]*(-[.\w]+)+$/i);var wh=Object.freeze({__proto__:null,ARIA_ATTR:gh,ATTR_WHITESPACE:yh,CUSTOM_ELEMENT:kh,DATA_ATTR:hh,DOCTYPE_NAME:bh,ERB_EXPR:mh,IS_ALLOWED_URI:fh,IS_SCRIPT_OR_DATA:vh,MUSTACHE_EXPR:ph,TMPLIT_EXPR:_h});const xh=1,Ih=3,Sh=7,$h=8,Oh=9;var Eh=function e(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"undefined"==typeof window?null:window;const n=t=>e(t);if(n.version="3.2.6",n.removed=[],!t||!t.document||t.document.nodeType!==Oh||!t.Element)return n.isSupported=!1,n;let{document:r}=t;const o=r,i=o.currentScript,{DocumentFragment:s,HTMLTemplateElement:a,Node:u,Element:l,NodeFilter:c,NamedNodeMap:d=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:p,DOMParser:m,trustedTypes:_}=t,h=l.prototype,g=eh(h,"cloneNode"),f=eh(h,"remove"),v=eh(h,"nextSibling"),y=eh(h,"childNodes"),b=eh(h,"parentNode");if("function"==typeof a){const e=r.createElement("template");e.content&&e.content.ownerDocument&&(r=e.content.ownerDocument)}let k,w="";const{implementation:x,createNodeIterator:I,createDocumentFragment:S,getElementsByTagName:$}=r,{importNode:O}=o;let E={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]};n.isSupported="function"==typeof S_&&"function"==typeof b&&x&&void 0!==x.createHTMLDocument;const{MUSTACHE_EXPR:T,ERB_EXPR:R,TMPLIT_EXPR:N,DATA_ATTR:A,ARIA_ATTR:C,IS_SCRIPT_OR_DATA:P,ATTR_WHITESPACE:U,CUSTOM_ELEMENT:j}=wh;let{IS_ALLOWED_URI:z}=wh,D=null;const M=Y_({},[...th,...nh,...rh,...ih,...ah]);let L=null;const q=Y_({},[...uh,...lh,...ch,...dh]);let Z=Object.seal(A_(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),F=null,W=null,J=!0,B=!0,H=!1,V=!0,G=!1,K=!0,Y=!1,X=!1,Q=!1,ee=!1,te=!1,ne=!1,re=!0,oe=!1,ie=!0,se=!1,ae={},ue=null;const le=Y_({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let ce=null;const de=Y_({},["audio","video","img","source","image","track"]);let pe=null;const me=Y_({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),_e="http://www.w3.org/1998/Math/MathML",he="http://www.w3.org/2000/svg",ge="http://www.w3.org/1999/xhtml";let fe=ge,ve=!1,ye=null;const be=Y_({},[_e,he,ge],q_);let ke=Y_({},["mi","mo","mn","ms","mtext"]),we=Y_({},["annotation-xml"]);const xe=Y_({},["title","style","font","a","script"]);let Ie=null;const Se=["application/xhtml+xml","text/html"];let $e=null,Oe=null;const Ee=r.createElement("form"),Te=function(e){return e instanceof RegExp||e instanceof Function},Re=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!Oe||Oe!==e){if(e&&"object"==typeof e||(e={}),e=Q_(e),Ie=-1===Se.indexOf(e.PARSER_MEDIA_TYPE)?"text/html":e.PARSER_MEDIA_TYPE,$e="application/xhtml+xml"===Ie?q_:L_,D=B_(e,"ALLOWED_TAGS")?Y_({},e.ALLOWED_TAGS,$e):M,L=B_(e,"ALLOWED_ATTR")?Y_({},e.ALLOWED_ATTR,$e):q,ye=B_(e,"ALLOWED_NAMESPACES")?Y_({},e.ALLOWED_NAMESPACES,q_):be,pe=B_(e,"ADD_URI_SAFE_ATTR")?Y_(Q_(me),e.ADD_URI_SAFE_ATTR,$e):me,ce=B_(e,"ADD_DATA_URI_TAGS")?Y_(Q_(de),e.ADD_DATA_URI_TAGS,$e):de,ue=B_(e,"FORBID_CONTENTS")?Y_({},e.FORBID_CONTENTS,$e):le,F=B_(e,"FORBID_TAGS")?Y_({},e.FORBID_TAGS,$e):Q_({}),W=B_(e,"FORBID_ATTR")?Y_({},e.FORBID_ATTR,$e):Q_({}),ae=!!B_(e,"USE_PROFILES")&&e.USE_PROFILES,J=!1!==e.ALLOW_ARIA_ATTR,B=!1!==e.ALLOW_DATA_ATTR,H=e.ALLOW_UNKNOWN_PROTOCOLS||!1,V=!1!==e.ALLOW_SELF_CLOSE_IN_ATTR,G=e.SAFE_FOR_TEMPLATES||!1,K=!1!==e.SAFE_FOR_XML,Y=e.WHOLE_DOCUMENT||!1,ee=e.RETURN_DOM||!1,te=e.RETURN_DOM_FRAGMENT||!1,ne=e.RETURN_TRUSTED_TYPE||!1,Q=e.FORCE_BODY||!1,re=!1!==e.SANITIZE_DOM,oe=e.SANITIZE_NAMED_PROPS||!1,ie=!1!==e.KEEP_CONTENT,se=e.IN_PLACE||!1,z=e.ALLOWED_URI_REGEXP||fh,fe=e.NAMESPACE||ge,ke=e.MATHML_TEXT_INTEGRATION_POINTS||ke,we=e.HTML_INTEGRATION_POINTS||we,Z=e.CUSTOM_ELEMENT_HANDLING||{},e.CUSTOM_ELEMENT_HANDLING&&Te(e.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(Z.tagNameCheck=e.CUSTOM_ELEMENT_HANDLING.tagNameCheck),e.CUSTOM_ELEMENT_HANDLING&&Te(e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(Z.attributeNameCheck=e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),e.CUSTOM_ELEMENT_HANDLING&&"boolean"==typeof e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements&&(Z.allowCustomizedBuiltInElements=e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),G&&(B=!1),te&&(ee=!0),ae&&(D=Y_({},ah),L=[],!0===ae.html&&(Y_(D,th),Y_(L,uh)),!0===ae.svg&&(Y_(D,nh),Y_(L,lh),Y_(L,dh)),!0===ae.svgFilters&&(Y_(D,rh),Y_(L,lh),Y_(L,dh)),!0===ae.mathMl&&(Y_(D,ih),Y_(L,ch),Y_(L,dh))),e.ADD_TAGS&&(D===M&&(D=Q_(D)),Y_(D,e.ADD_TAGS,$e)),e.ADD_ATTR&&(L===q&&(L=Q_(L)),Y_(L,e.ADD_ATTR,$e)),e.ADD_URI_SAFE_ATTR&&Y_(pe,e.ADD_URI_SAFE_ATTR,$e),e.FORBID_CONTENTS&&(ue===le&&(ue=Q_(ue)),Y_(ue,e.FORBID_CONTENTS,$e)),ie&&(D["#text"]=!0),Y&&Y_(D,["html","head","body"]),D.table&&(Y_(D,["tbody"]),delete F.tbody),e.TRUSTED_TYPES_POLICY){if("function"!=typeof e.TRUSTED_TYPES_POLICY.createHTML)throw V_('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw V_('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');k=e.TRUSTED_TYPES_POLICY,w=k.createHTML("")}else void 0===k&&(k=function(e,t){if("object"!=typeof e||"function"!=typeof e.createPolicy)return null;let n=null;const r="data-tt-policy-suffix";t&&t.hasAttribute(r)&&(n=t.getAttribute(r));const o="dompurify"+(n?"#"+n:"");try{return e.createPolicy(o,{createHTML:e=>e,createScriptURL:e=>e})}catch(i){return console.warn("TrustedTypes policy "+o+" could not be created."),null}}(_,i)),null!==k&&"string"==typeof w&&(w=k.createHTML(""));R_&&R_(e),Oe=e}},Ne=Y_({},[...nh,...rh,...oh]),Ae=Y_({},[...ih,...sh]),Ce=function(e){D_(n.removed,{element:e});try{b(e).removeChild(e)}catch(t){f(e)}},Pe=function(e,t){try{D_(n.removed,{attribute:t.getAttributeNode(e),from:t})}catch(r){D_(n.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e)if(ee||te)try{Ce(t)}catch(r){}else try{t.setAttribute(e,"")}catch(r){}},Ue=function(e){let t=null,n=null;if(Q)e="<remove></remove>"+e;else{const t=Z_(e,/^[\r\n\t ]+/);n=t&&t[0]}"application/xhtml+xml"===Ie&&fe===ge&&(e='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+e+"</body></html>");const o=k?k.createHTML(e):e;if(fe===ge)try{t=(new m).parseFromString(o,Ie)}catch(s){}if(!t||!t.documentElement){t=x.createDocument(fe,"template",null);try{t.documentElement.innerHTML=ve?w:o}catch(s){}}const i=t.body||t.documentElement;return e&&n&&i.insertBefore(r.createTextNode(n),i.childNodes[0]||null),fe===ge?$.call(t,Y?"html":"body")[0]:Y?t.documentElement:i},je=function(e){return I.call(e.ownerDocument||e,e,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},ze=function(e){return e instanceof p&&("string"!=typeof e.nodeName||"string"!=typeof e.textContent||"function"!=typeof e.removeChild||!(e.attributes instanceof d)||"function"!=typeof e.removeAttribute||"function"!=typeof e.setAttribute||"string"!=typeof e.namespaceURI||"function"!=typeof e.insertBefore||"function"!=typeof e.hasChildNodes)},De=function(e){return"function"==typeof u&&e instanceof u};function Me(e,t,r){U_(e,(e=>{e.call(n,t,r,Oe)}))}const Le=function(e){let t=null;if(Me(E.beforeSanitizeElements,e,null),ze(e))return Ce(e),!0;const r=$e(e.nodeName);if(Me(E.uponSanitizeElement,e,{tagName:r,allowedTags:D}),K&&e.hasChildNodes()&&!De(e.firstElementChild)&&H_(/<[/\w!]/g,e.innerHTML)&&H_(/<[/\w!]/g,e.textContent))return Ce(e),!0;if(e.nodeType===Sh)return Ce(e),!0;if(K&&e.nodeType===$h&&H_(/<[/\w]/g,e.data))return Ce(e),!0;if(!D[r]||F[r]){if(!F[r]&&Ze(r)){if(Z.tagNameCheck instanceof RegExp&&H_(Z.tagNameCheck,r))return!1;if(Z.tagNameCheck instanceof Function&&Z.tagNameCheck(r))return!1}if(ie&&!ue[r]){const t=b(e)||e.parentNode,n=y(e)||e.childNodes;if(n&&t){for(let r=n.length-1;r>=0;--r){const o=g(n[r],!0);o.__removalCount=(e.__removalCount||0)+1,t.insertBefore(o,v(e))}}}return Ce(e),!0}return e instanceof l&&!function(e){let t=b(e);t&&t.tagName||(t={namespaceURI:fe,tagName:"template"});const n=L_(e.tagName),r=L_(t.tagName);return!!ye[e.namespaceURI]&&(e.namespaceURI===he?t.namespaceURI===ge?"svg"===n:t.namespaceURI===_e?"svg"===n&&("annotation-xml"===r||ke[r]):Boolean(Ne[n]):e.namespaceURI===_e?t.namespaceURI===ge?"math"===n:t.namespaceURI===he?"math"===n&&we[r]:Boolean(Ae[n]):e.namespaceURI===ge?!(t.namespaceURI===he&&!we[r])&&!(t.namespaceURI===_e&&!ke[r])&&!Ae[n]&&(xe[n]||!Ne[n]):!("application/xhtml+xml"!==Ie||!ye[e.namespaceURI]))}(e)?(Ce(e),!0):"noscript"!==r&&"noembed"!==r&&"noframes"!==r||!H_(/<\/no(script|embed|frames)/i,e.innerHTML)?(G&&e.nodeType===Ih&&(t=e.textContent,U_([T,R,N],(e=>{t=F_(t,e," ")})),e.textContent!==t&&(D_(n.removed,{element:e.cloneNode()}),e.textContent=t)),Me(E.afterSanitizeElements,e,null),!1):(Ce(e),!0)},qe=function(e,t,n){if(re&&("id"===t||"name"===t)&&(n in r||n in Ee))return!1;if(B&&!W[t]&&H_(A,t));else if(J&&H_(C,t));else if(!L[t]||W[t]){if(!(Ze(e)&&(Z.tagNameCheck instanceof RegExp&&H_(Z.tagNameCheck,e)||Z.tagNameCheck instanceof Function&&Z.tagNameCheck(e))&&(Z.attributeNameCheck instanceof RegExp&&H_(Z.attributeNameCheck,t)||Z.attributeNameCheck instanceof Function&&Z.attributeNameCheck(t))||"is"===t&&Z.allowCustomizedBuiltInElements&&(Z.tagNameCheck instanceof RegExp&&H_(Z.tagNameCheck,n)||Z.tagNameCheck instanceof Function&&Z.tagNameCheck(n))))return!1}else if(pe[t]);else if(H_(z,F_(n,U,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==W_(n,"data:")||!ce[e]){if(H&&!H_(P,F_(n,U,"")));else if(n)return!1}else;return!0},Ze=function(e){return"annotation-xml"!==e&&Z_(e,j)},Fe=function(e){Me(E.beforeSanitizeAttributes,e,null);const{attributes:t}=e;if(!t||ze(e))return;const r={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:L,forceKeepAttr:void 0};let o=t.length;for(;o--;){const s=t[o],{name:a,namespaceURI:u,value:l}=s,c=$e(a),d=l;let p="value"===a?d:J_(d);if(r.attrName=c,r.attrValue=p,r.keepAttr=!0,r.forceKeepAttr=void 0,Me(E.uponSanitizeAttribute,e,r),p=r.attrValue,!oe||"id"!==c&&"name"!==c||(Pe(a,e),p="user-content-"+p),K&&H_(/((--!?|])>)|<\/(style|title)/i,p)){Pe(a,e);continue}if(r.forceKeepAttr)continue;if(!r.keepAttr){Pe(a,e);continue}if(!V&&H_(/\/>/i,p)){Pe(a,e);continue}G&&U_([T,R,N],(e=>{p=F_(p,e," ")}));const m=$e(e.nodeName);if(qe(m,c,p)){if(k&&"object"==typeof _&&"function"==typeof _.getAttributeType)if(u);else switch(_.getAttributeType(m,c)){case"TrustedHTML":p=k.createHTML(p);break;case"TrustedScriptURL":p=k.createScriptURL(p)}if(p!==d)try{u?e.setAttributeNS(u,a,p):e.setAttribute(a,p),ze(e)?Ce(e):z_(n.removed)}catch(i){Pe(a,e)}}else Pe(a,e)}Me(E.afterSanitizeAttributes,e,null)},We=function e(t){let n=null;const r=je(t);for(Me(E.beforeSanitizeShadowDOM,t,null);n=r.nextNode();)Me(E.uponSanitizeShadowNode,n,null),Le(n),Fe(n),n.content instanceof s&&e(n.content);Me(E.afterSanitizeShadowDOM,t,null)};return n.sanitize=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=null,i=null,a=null,l=null;if(ve=!e,ve&&(e="\x3c!--\x3e"),"string"!=typeof e&&!De(e)){if("function"!=typeof e.toString)throw V_("toString is not a function");if("string"!=typeof(e=e.toString()))throw V_("dirty is not a string, aborting")}if(!n.isSupported)return e;if(X||Re(t),n.removed=[],"string"==typeof e&&(se=!1),se){if(e.nodeName){const t=$e(e.nodeName);if(!D[t]||F[t])throw V_("root node is forbidden and cannot be sanitized in-place")}}else if(e instanceof u)r=Ue("\x3c!----\x3e"),i=r.ownerDocument.importNode(e,!0),i.nodeType===xh&&"BODY"===i.nodeName||"HTML"===i.nodeName?r=i:r.appendChild(i);else{if(!ee&&!G&&!Y&&-1===e.indexOf("<"))return k&&ne?k.createHTML(e):e;if(r=Ue(e),!r)return ee?null:ne?w:""}r&&Q&&Ce(r.firstChild);const c=je(se?e:r);for(;a=c.nextNode();)Le(a),Fe(a),a.content instanceof s&&We(a.content);if(se)return e;if(ee){if(te)for(l=S.call(r.ownerDocument);r.firstChild;)l.appendChild(r.firstChild);else l=r;return(L.shadowroot||L.shadowrootmode)&&(l=O.call(o,l,!0)),l}let d=Y?r.outerHTML:r.innerHTML;return Y&&D["!doctype"]&&r.ownerDocument&&r.ownerDocument.doctype&&r.ownerDocument.doctype.name&&H_(bh,r.ownerDocument.doctype.name)&&(d="<!DOCTYPE "+r.ownerDocument.doctype.name+">\n"+d),G&&U_([T,R,N],(e=>{d=F_(d,e," ")})),k&&ne?k.createHTML(d):d},n.setConfig=function(){Re(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),X=!0},n.clearConfig=function(){Oe=null,X=!1},n.isValidAttribute=function(e,t,n){Oe||Re({});const r=$e(e),o=$e(t);return qe(r,o,n)},n.addHook=function(e,t){"function"==typeof t&&D_(E[e],t)},n.removeHook=function(e,t){if(void 0!==t){const n=j_(E[e],t);return-1===n?void 0:M_(E[e],n,1)[0]}return z_(E[e])},n.removeHooks=function(e){E[e]=[]},n.removeAllHooks=function(){E={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},n}();const Th=(()=>{if("undefined"!=typeof window)return Eh;try{const{JSDOM:e}=require("jsdom"),{window:t}=new e("");return Eh(t)}catch{return{sanitize:e=>String(e||"").replace(/<[^>]*>/g,"")}}})();function Rh(e){if(!e)return"";const t=String(e);try{let e=Th.sanitize(t,{ALLOWED_TAGS:[],ALLOWED_ATTR:[],KEEP_CONTENT:!0,RETURN_DOM:!1,RETURN_DOM_FRAGMENT:!1,FORCE_BODY:!0});if(!e.trim()&&t){t.replace(/<[^>]*>/g,"").trim()&&(e=t.replace(/<[^>]*>/g,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"").trim())}return e.trim().slice(0,1e3)}catch{return t.replace(/<[^>]*>/g,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"").trim().slice(0,1e3)}}async function Nh(e,t={}){const{onComplete:n,onCancel:r,onError:o}=t,i=function(e){if(!e)return"";const t=Rh(e);try{const e=new URL(t);return"http:"===e.protocol||"https:"===e.protocol?t:""}catch{return""}}(e);if(!i){const e=new Error("Invalid payment URL provided");throw null==o||o(e),e}try{const e=window.open(i,"echo-payment","width=600,height=700,scrollbars=yes,resizable=yes");if(e&&!e.closed)return new Promise((t=>{const o=()=>{try{if(e.closed)return null==n||n(),void t();setTimeout(o,1e3)}catch{null==n||n(),t()}};o(),setTimeout((()=>{e.close(),null==r||r(),t()}),6e5)}));return confirm("Payment will open in a new tab. Click OK to continue, or Cancel to abort.")?(sessionStorage.setItem("echo_payment_flow","true"),window.location.href=i,new Promise((e=>{const t=()=>{"completed"===sessionStorage.getItem("echo_payment_flow")&&(sessionStorage.removeItem("echo_payment_flow"),null==n||n(),window.removeEventListener("focus",t),e())};window.addEventListener("focus",t),setTimeout((()=>{window.removeEventListener("focus",t),sessionStorage.removeItem("echo_payment_flow"),null==r||r(),e()}),18e5)}))):(null==r||r(),Promise.resolve())}catch(s){const e=s instanceof Error?s:new Error("Payment flow failed");throw null==o||o(e),e}}const Ah=({className:e="",width:t=16,height:n=16,variant:o="light"})=>{const i="dark"===o?"#DFE2D9":"#232323";return r.jsxs("svg",{id:"Layer_1","data-name":"Layer 1",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 226.03 261",className:e,width:t,height:n,"aria-label":"Echo Logo",children:[r.jsx("defs",{children:r.jsx("style",{children:`\n .cls-1 {\n fill: none;\n }\n .cls-3 {\n fill: #7f0404;\n }\n .cls-4 {\n fill: ${i};\n }\n .cls-5 {\n fill: #a50404;\n }\n .cls-6 {\n fill: #cd0202;\n opacity: .9;\n }\n `})}),r.jsx("polygon",{className:"cls-6",points:"59.23 99.45 59.23 161.55 113.02 192.61 113.02 130.5 59.23 99.45"}),r.jsx("polygon",{className:"cls-5",points:"113.02 68.39 113.02 68.39 59.23 99.45 113.02 130.5 166.8 99.45 113.02 68.39"}),r.jsx("polygon",{className:"cls-3",points:"166.8 99.45 113.02 130.5 113.02 192.61 113.02 192.61 166.8 161.55 166.8 99.45"}),r.jsxs("g",{children:[r.jsx("path",{className:"cls-4",d:"m113.02,196.41l-57.08-32.95v-65.91l57.08-32.95,57.08,32.95v65.91l-57.08,32.95Zm-52.53-35.58l52.53,30.33,52.53-30.33v-60.66l-52.53-30.33-52.53,30.33v60.66Z"}),r.jsx("path",{className:"cls-4",d:"m113.02,261L0,195.75V65.25L113.02,0l113.02,65.25v130.5l-113.02,65.25ZM6.82,191.81l106.2,61.31,106.2-61.31v-122.62L113.02,7.88,6.82,69.19v122.62Z"}),r.jsx("rect",{className:"cls-4",x:"111.88",y:"3.94",width:"2.27",height:"63.28"}),r.jsx("rect",{className:"cls-4",x:"-.83",y:"176.82",width:"63.28",height:"2.27",transform:"translate(-84.84 39.24) rotate(-29.99)"}),r.jsx("rect",{className:"cls-4",x:"194.08",y:"146.32",width:"2.27",height:"63.28",transform:"translate(-56.51 258.05) rotate(-60)"}),r.jsx("rect",{className:"cls-4",x:"111.88",y:"130.5",width:"2.27",height:"126.56"}),r.jsx("rect",{className:"cls-4",x:"104.54",y:"97.72",width:"126.56",height:"2.27",transform:"translate(-26.95 97.14) rotate(-29.99)"}),r.jsx("rect",{className:"cls-4",x:"57.08",y:"35.58",width:"2.27",height:"126.56",transform:"translate(-56.51 99.84) rotate(-60)"})]})]})};const Ch=({onAddCredits:e,onCancel:t,isProcessing:n})=>{const[i,s]=o.useState(""),a=o.useRef(null);o.useEffect((()=>{a.current&&a.current.focus()}),[]);const u=""!==i&&Number(i)>0;return r.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:"8px"},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[r.jsx("span",{style:{fontSize:"14px",color:"#6b7280",fontFamily:"HelveticaNowDisplay, sans-serif"},children:"$"}),r.jsx("input",{ref:a,type:"number",placeholder:"0.00",value:i,onChange:e=>s(e.target.value),style:{width:"96px",textAlign:"right",padding:"8px 12px",border:"1px solid #e5e7eb",borderRadius:"6px",fontSize:"14px",fontFamily:"HelveticaNowDisplay, sans-serif",outline:"none",backgroundColor:"#ffffff"},min:"1",step:"0.01"})]}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[r.jsx("button",{onClick:t,style:{padding:"8px 12px",backgroundColor:"transparent",color:"#6b7280",border:"none",borderRadius:"6px",fontSize:"14px",cursor:"pointer",fontFamily:"HelveticaNowDisplay, sans-serif",textDecoration:"none"},onMouseEnter:e=>{e.currentTarget.style.color="#111827"},onMouseLeave:e=>{e.currentTarget.style.color="#6b7280"},children:"Cancel"}),r.jsx("button",{onClick:()=>{const t=Number(i);t>0&&e(t)},disabled:n||!u,style:{padding:"8px 16px",backgroundColor:n||!u?"#9ca3af":"#dc2626",color:"white",border:"none",borderRadius:"6px",fontSize:"14px",fontWeight:"500",cursor:n||!u?"not-allowed":"pointer",fontFamily:"HelveticaNowDisplay, sans-serif"},onMouseEnter:e=>{!n&&u&&(e.currentTarget.style.backgroundColor="#b91c1c")},onMouseLeave:e=>{!n&&u&&(e.currentTarget.style.backgroundColor="#dc2626")},children:n?"Processing...":"Add Credits"})]})]})};const Ph=o.createContext(null);var Uh=({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:r="-"}={})=>{const o=()=>{const e=n.length,r=new Array(t);for(let o=0;o<t;o++)r[o]=n[Math.random()*e|0];return r.join("")};if(null==e)return o;if(n.includes(r))throw new Be({argument:"separator",message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${o()}`},jh=Uh(),zh=/"__proto__"\s*:/,Dh=/"constructor"\s*:/;function Mh(e){const t=JSON.parse(e);return null===t||"object"!=typeof t||!1===zh.test(e)&&!1===Dh.test(e)?t:function(e){let t=[e];for(;t.length;){const e=t;t=[];for(const n of e){if(Object.prototype.hasOwnProperty.call(n,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(n,"constructor")&&Object.prototype.hasOwnProperty.call(n.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const e in n){const r=n[e];r&&"object"==typeof r&&t.push(r)}}}return e}(t)}var Lh=Symbol.for("vercel.ai.validator");function qh(e){return function(e){return"object"==typeof e&&null!==e&&Lh in e&&!0===e[Lh]&&"validate"in e}(e)?e:(t=e,n=async e=>{const n=await t["~standard"].validate(e);return null==n.issues?{success:!0,value:n.value}:{success:!1,error:new Et({value:e,cause:n.issues})}},{[Lh]:!0,validate:n});var t,n}async function Zh({value:e,schema:t}){const n=await Fh({value:e,schema:t});if(!n.success)throw Et.wrap({value:e,cause:n.error});return n.value}async function Fh({value:e,schema:t}){const n=qh(t);try{if(null==n.validate)return{success:!0,value:e,rawValue:e};const t=await n.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:Et.wrap({value:e,cause:t.error}),rawValue:e}}catch(r){return{success:!1,error:Et.wrap({value:e,cause:r}),rawValue:e}}}async function Wh({text:e,schema:t}){try{const n=function(e){const{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return Mh(e)}finally{Error.stackTraceLimit=t}}(e);return null==t?{success:!0,value:n,rawValue:n}:await Fh({value:n,schema:t})}catch(n){return{success:!1,error:at.isInstance(n)?n:new at({text:e,cause:n}),rawValue:void 0}}}async function Jh(e){return"function"==typeof e&&(e=e()),Promise.resolve(e)}function Bh(e,t){return function(e){return"_zod"in e}(e)?function(e){return Vh(_u(e,{target:"draft-7",io:"output",reused:"inline"}),{validate:async t=>{const n=await Cu(e,t);return n.success?{success:!0,value:n.data}:{success:!1,error:n.error}}})}(e):function(e){return Vh(dd(e,{$refStrategy:"none",target:"jsonSchema7"}),{validate:async t=>{const n=await e.safeParseAsync(t);return n.success?{success:!0,value:n.data}:{success:!1,error:n.error}}})}(e)}var Hh=Symbol.for("vercel.ai.schema");function Vh(e,{validate:t}={}){return{[Hh]:!0,_type:void 0,[Lh]:!0,jsonSchema:e,validate:t}}function Gh(e){return null==e?Vh({properties:{},additionalProperties:!1}):"object"==typeof(t=e)&&null!==t&&Hh in t&&!0===t[Hh]&&"jsonSchema"in t&&"validate"in t?e:Bh(e);var t}var Kh,Yh=Object.defineProperty,Xh="AI_NoObjectGeneratedError",Qh=`vercel.ai.error.${Xh}`,eg=Symbol.for(Qh),tg=class extends Ne{constructor({message:e="No object generated.",cause:t,text:n,response:r,usage:o,finishReason:i}){super({name:Xh,message:e,cause:t}),this[Kh]=!0,this.text=n,this.response=r,this.usage=o,this.finishReason=i}static isInstance(e){return Ne.hasMarker(e,Qh)}};Kh=eg;var ng=Cl([zu(),xc(Uint8Array),xc(ArrayBuffer),bc((e=>{var t,n;return null!=(n=null==(t=globalThis.Buffer)?void 0:t.isBuffer(e))&&n}),{message:"Must be a Buffer"})]),rg=fc((()=>Cl([fl(),zu(),al(),dl(),ql(zu(),rg),Ol(rg)]))),og=ql(zu(),ql(zu(),rg)),ig=Tl({type:Hl("text"),text:zu(),providerOptions:og.optional()}),sg=Tl({type:Hl("image"),image:Cl([ng,xc(URL)]),mediaType:zu().optional(),providerOptions:og.optional()}),ag=Tl({type:Hl("file"),data:Cl([ng,xc(URL)]),filename:zu().optional(),mediaType:zu(),providerOptions:og.optional()}),ug=Tl({type:Hl("reasoning"),text:zu(),providerOptions:og.optional()}),lg=Tl({type:Hl("tool-call"),toolCallId:zu(),toolName:zu(),input:kl(),providerOptions:og.optional(),providerExecuted:dl().optional()}),cg=Ul("type",[Tl({type:Hl("text"),value:zu()}),Tl({type:Hl("json"),value:rg}),Tl({type:Hl("error-text"),value:zu()}),Tl({type:Hl("error-json"),value:rg}),Tl({type:Hl("content"),value:Ol(Cl([Tl({type:Hl("text"),text:zu()}),Tl({type:Hl("media"),data:zu(),mediaType:zu()})]))})]),dg=Tl({type:Hl("tool-result"),toolCallId:zu(),toolName:zu(),output:cg,providerOptions:og.optional()}),pg=Tl({role:Hl("system"),content:zu(),providerOptions:og.optional()}),mg=Tl({role:Hl("user"),content:Cl([zu(),Ol(Cl([ig,sg,ag]))]),providerOptions:og.optional()}),_g=Tl({role:Hl("assistant"),content:Cl([zu(),Ol(Cl([ig,ag,ug,lg,dg]))]),providerOptions:og.optional()});Cl([pg,mg,_g,Tl({role:Hl("tool"),content:Ol(dg),providerOptions:og.optional()})]),Uh({prefix:"aitxt",size:24}),TransformStream;var hg=Cl([Rl({type:Hl("text-start"),id:zu(),providerMetadata:og.optional()}),Rl({type:Hl("text-delta"),id:zu(),delta:zu(),providerMetadata:og.optional()}),Rl({type:Hl("text-end"),id:zu(),providerMetadata:og.optional()}),Rl({type:Hl("error"),errorText:zu()}),Rl({type:Hl("tool-input-start"),toolCallId:zu(),toolName:zu(),providerExecuted:dl().optional(),dynamic:dl().optional()}),Rl({type:Hl("tool-input-delta"),toolCallId:zu(),inputTextDelta:zu()}),Rl({type:Hl("tool-input-available"),toolCallId:zu(),toolName:zu(),input:kl(),providerExecuted:dl().optional(),providerMetadata:og.optional(),dynamic:dl().optional()}),Rl({type:Hl("tool-input-error"),toolCallId:zu(),toolName:zu(),input:kl(),providerExecuted:dl().optional(),providerMetadata:og.optional(),dynamic:dl().optional(),errorText:zu()}),Rl({type:Hl("tool-output-available"),toolCallId:zu(),output:kl(),providerExecuted:dl().optional(),dynamic:dl().optional(),preliminary:dl().optional()}),Rl({type:Hl("tool-output-error"),toolCallId:zu(),errorText:zu(),providerExecuted:dl().optional(),dynamic:dl().optional()}),Rl({type:Hl("reasoning"),text:zu(),providerMetadata:og.optional()}),Rl({type:Hl("reasoning-start"),id:zu(),providerMetadata:og.optional()}),Rl({type:Hl("reasoning-delta"),id:zu(),delta:zu(),providerMetadata:og.optional()}),Rl({type:Hl("reasoning-end"),id:zu(),providerMetadata:og.optional()}),Rl({type:Hl("reasoning-part-finish")}),Rl({type:Hl("source-url"),sourceId:zu(),url:zu(),title:zu().optional(),providerMetadata:og.optional()}),Rl({type:Hl("source-document"),sourceId:zu(),mediaType:zu(),title:zu(),filename:zu().optional(),providerMetadata:og.optional()}),Rl({type:Hl("file"),url:zu(),mediaType:zu(),providerMetadata:og.optional()}),Rl({type:zu().startsWith("data-"),id:zu().optional(),data:kl(),transient:dl().optional()}),Rl({type:Hl("start-step")}),Rl({type:Hl("finish-step")}),Rl({type:Hl("start"),messageId:zu().optional(),messageMetadata:kl().optional()}),Rl({type:Hl("finish"),messageMetadata:kl().optional()}),Rl({type:Hl("abort")}),Rl({type:Hl("message-metadata"),messageMetadata:kl()})]);function gg(e,t){if(void 0===e&&void 0===t)return;if(void 0===e)return t;if(void 0===t)return e;const n={...e};for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const o=t[r];if(void 0===o)continue;const i=r in e?e[r]:void 0,s=!(null===o||"object"!=typeof o||Array.isArray(o)||o instanceof Date||o instanceof RegExp),a=!(null==i||"object"!=typeof i||Array.isArray(i)||i instanceof Date||i instanceof RegExp);n[r]=s&&a?gg(i,o):o}return n}function fg(e){const t=["ROOT"];let n=-1,r=null;function o(e,o,i){switch(e){case'"':n=o,t.pop(),t.push(i),t.push("INSIDE_STRING");break;case"f":case"t":case"n":n=o,r=o,t.pop(),t.push(i),t.push("INSIDE_LITERAL");break;case"-":t.pop(),t.push(i),t.push("INSIDE_NUMBER");break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":n=o,t.pop(),t.push(i),t.push("INSIDE_NUMBER");break;case"{":n=o,t.pop(),t.push(i),t.push("INSIDE_OBJECT_START");break;case"[":n=o,t.pop(),t.push(i),t.push("INSIDE_ARRAY_START")}}function i(e,r){switch(e){case",":t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break;case"}":n=r,t.pop()}}function s(e,r){switch(e){case",":t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break;case"]":n=r,t.pop()}}for(let u=0;u<e.length;u++){const a=e[u];switch(t[t.length-1]){case"ROOT":o(a,u,"FINISH");break;case"INSIDE_OBJECT_START":switch(a){case'"':t.pop(),t.push("INSIDE_OBJECT_KEY");break;case"}":n=u,t.pop()}break;case"INSIDE_OBJECT_AFTER_COMMA":if('"'===a)t.pop(),t.push("INSIDE_OBJECT_KEY");break;case"INSIDE_OBJECT_KEY":if('"'===a)t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break;case"INSIDE_OBJECT_AFTER_KEY":if(":"===a)t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break;case"INSIDE_OBJECT_BEFORE_VALUE":o(a,u,"INSIDE_OBJECT_AFTER_VALUE");break;case"INSIDE_OBJECT_AFTER_VALUE":i(a,u);break;case"INSIDE_STRING":switch(a){case'"':t.pop(),n=u;break;case"\\":t.push("INSIDE_STRING_ESCAPE");break;default:n=u}break;case"INSIDE_ARRAY_START":if("]"===a)n=u,t.pop();else n=u,o(a,u,"INSIDE_ARRAY_AFTER_VALUE");break;case"INSIDE_ARRAY_AFTER_VALUE":switch(a){case",":t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break;case"]":n=u,t.pop();break;default:n=u}break;case"INSIDE_ARRAY_AFTER_COMMA":o(a,u,"INSIDE_ARRAY_AFTER_VALUE");break;case"INSIDE_STRING_ESCAPE":t.pop(),n=u;break;case"INSIDE_NUMBER":switch(a){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":n=u;break;case"e":case"E":case"-":case".":break;case",":t.pop(),"INSIDE_ARRAY_AFTER_VALUE"===t[t.length-1]&&s(a,u),"INSIDE_OBJECT_AFTER_VALUE"===t[t.length-1]&&i(a,u);break;case"}":t.pop(),"INSIDE_OBJECT_AFTER_VALUE"===t[t.length-1]&&i(a,u);break;case"]":t.pop(),"INSIDE_ARRAY_AFTER_VALUE"===t[t.length-1]&&s(a,u);break;default:t.pop()}break;case"INSIDE_LITERAL":{const o=e.substring(r,u+1);"false".startsWith(o)||"true".startsWith(o)||"null".startsWith(o)?n=u:(t.pop(),"INSIDE_OBJECT_AFTER_VALUE"===t[t.length-1]?i(a,u):"INSIDE_ARRAY_AFTER_VALUE"===t[t.length-1]&&s(a,u));break}}}let a=e.slice(0,n+1);for(let u=t.length-1;u>=0;u--){switch(t[u]){case"INSIDE_STRING":a+='"';break;case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":a+="}";break;case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":a+="]";break;case"INSIDE_LITERAL":{const t=e.substring(r,e.length);"true".startsWith(t)?a+="true".slice(t.length):"false".startsWith(t)?a+="false".slice(t.length):"null".startsWith(t)&&(a+="null".slice(t.length))}}}return a}async function vg(e){if(void 0===e)return{value:void 0,state:"undefined-input"};let t=await Wh({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await Wh({text:fg(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function yg(e){return e.type.startsWith("tool-")}function bg(e){return e.type.split("-").slice(1).join("-")}function kg({lastMessage:e,messageId:t}){return{message:"assistant"===(null==e?void 0:e.role)?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function wg({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:o,onToolCall:i,onData:s}){return e.pipeThrough(new TransformStream({async transform(e,a){await r((async({state:r,write:u})=>{var l,c,d,p;function m(e){const t=r.message.parts.filter(yg).find((t=>t.toolCallId===e));if(null==t)throw new Error("tool-output-error must be preceded by a tool-input-available");return t}function _(e){const t=r.message.parts.filter((e=>"dynamic-tool"===e.type)).find((t=>t.toolCallId===e));if(null==t)throw new Error("tool-output-error must be preceded by a tool-input-available");return t}function h(e){var t;const n=r.message.parts.find((t=>yg(t)&&t.toolCallId===e.toolCallId)),o=e,i=n;null!=n?(n.state=e.state,i.input=o.input,i.output=o.output,i.errorText=o.errorText,i.rawInput=o.rawInput,i.preliminary=o.preliminary,i.providerExecuted=null!=(t=o.providerExecuted)?t:n.providerExecuted,null!=o.providerMetadata&&"input-available"===n.state&&(n.callProviderMetadata=o.providerMetadata)):r.message.parts.push({type:`tool-${e.toolName}`,toolCallId:e.toolCallId,state:e.state,input:o.input,output:o.output,rawInput:o.rawInput,errorText:o.errorText,providerExecuted:o.providerExecuted,preliminary:o.preliminary,...null!=o.providerMetadata?{callProviderMetadata:o.providerMetadata}:{}})}function g(e){var t;const n=r.message.parts.find((t=>"dynamic-tool"===t.type&&t.toolCallId===e.toolCallId)),o=e,i=n;null!=n?(n.state=e.state,i.toolName=e.toolName,i.input=o.input,i.output=o.output,i.errorText=o.errorText,i.rawInput=null!=(t=o.rawInput)?t:i.rawInput,i.preliminary=o.preliminary,null!=o.providerMetadata&&"input-available"===n.state&&(n.callProviderMetadata=o.providerMetadata)):r.message.parts.push({type:"dynamic-tool",toolName:e.toolName,toolCallId:e.toolCallId,state:e.state,input:o.input,output:o.output,errorText:o.errorText,preliminary:o.preliminary,...null!=o.providerMetadata?{callProviderMetadata:o.providerMetadata}:{}})}async function f(e){if(null!=e){const n=null!=r.message.metadata?gg(r.message.metadata,e):e;null!=t&&await Zh({value:n,schema:t}),r.message.metadata=n}}switch(e.type){case"text-start":{const t={type:"text",text:"",providerMetadata:e.providerMetadata,state:"streaming"};r.activeTextParts[e.id]=t,r.message.parts.push(t),u();break}case"text-delta":{const t=r.activeTextParts[e.id];t.text+=e.delta,t.providerMetadata=null!=(l=e.providerMetadata)?l:t.providerMetadata,u();break}case"text-end":{const t=r.activeTextParts[e.id];t.state="done",t.providerMetadata=null!=(c=e.providerMetadata)?c:t.providerMetadata,delete r.activeTextParts[e.id],u();break}case"reasoning-start":{const t={type:"reasoning",text:"",providerMetadata:e.providerMetadata,state:"streaming"};r.activeReasoningParts[e.id]=t,r.message.parts.push(t),u();break}case"reasoning-delta":{const t=r.activeReasoningParts[e.id];t.text+=e.delta,t.providerMetadata=null!=(d=e.providerMetadata)?d:t.providerMetadata,u();break}case"reasoning-end":{const t=r.activeReasoningParts[e.id];t.providerMetadata=null!=(p=e.providerMetadata)?p:t.providerMetadata,t.state="done",delete r.activeReasoningParts[e.id],u();break}case"file":r.message.parts.push({type:"file",mediaType:e.mediaType,url:e.url}),u();break;case"source-url":r.message.parts.push({type:"source-url",sourceId:e.sourceId,url:e.url,title:e.title,providerMetadata:e.providerMetadata}),u();break;case"source-document":r.message.parts.push({type:"source-document",sourceId:e.sourceId,mediaType:e.mediaType,title:e.title,filename:e.filename,providerMetadata:e.providerMetadata}),u();break;case"tool-input-start":{const t=r.message.parts.filter(yg);r.partialToolCalls[e.toolCallId]={text:"",toolName:e.toolName,index:t.length,dynamic:e.dynamic},e.dynamic?g({toolCallId:e.toolCallId,toolName:e.toolName,state:"input-streaming",input:void 0}):h({toolCallId:e.toolCallId,toolName:e.toolName,state:"input-streaming",input:void 0,providerExecuted:e.providerExecuted}),u();break}case"tool-input-delta":{const t=r.partialToolCalls[e.toolCallId];t.text+=e.inputTextDelta;const{value:n}=await vg(t.text);t.dynamic?g({toolCallId:e.toolCallId,toolName:t.toolName,state:"input-streaming",input:n}):h({toolCallId:e.toolCallId,toolName:t.toolName,state:"input-streaming",input:n}),u();break}case"tool-input-available":e.dynamic?g({toolCallId:e.toolCallId,toolName:e.toolName,state:"input-available",input:e.input,providerMetadata:e.providerMetadata}):h({toolCallId:e.toolCallId,toolName:e.toolName,state:"input-available",input:e.input,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}),u(),i&&!e.providerExecuted&&await i({toolCall:e});break;case"tool-input-error":e.dynamic?g({toolCallId:e.toolCallId,toolName:e.toolName,state:"output-error",input:e.input,errorText:e.errorText,providerMetadata:e.providerMetadata}):h({toolCallId:e.toolCallId,toolName:e.toolName,state:"output-error",input:void 0,rawInput:e.input,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}),u();break;case"tool-output-available":if(e.dynamic){const t=_(e.toolCallId);g({toolCallId:e.toolCallId,toolName:t.toolName,state:"output-available",input:t.input,output:e.output,preliminary:e.preliminary})}else{const t=m(e.toolCallId);h({toolCallId:e.toolCallId,toolName:bg(t),state:"output-available",input:t.input,output:e.output,providerExecuted:e.providerExecuted,preliminary:e.preliminary})}u();break;case"tool-output-error":if(e.dynamic){const t=_(e.toolCallId);g({toolCallId:e.toolCallId,toolName:t.toolName,state:"output-error",input:t.input,errorText:e.errorText})}else{const t=m(e.toolCallId);h({toolCallId:e.toolCallId,toolName:bg(t),state:"output-error",input:t.input,rawInput:t.rawInput,errorText:e.errorText})}u();break;case"start-step":r.message.parts.push({type:"step-start"});break;case"finish-step":r.activeTextParts={},r.activeReasoningParts={};break;case"start":null!=e.messageId&&(r.message.id=e.messageId),await f(e.messageMetadata),null==e.messageId&&null==e.messageMetadata||u();break;case"finish":case"message-metadata":await f(e.messageMetadata),null!=e.messageMetadata&&u();break;case"error":null==o||o(new Error(e.errorText));break;default:if(function(e){return e.type.startsWith("data-")}(e)){null!=(null==n?void 0:n[e.type])&&await Zh({value:e.data,schema:n[e.type]});const t=e;if(t.transient){null==s||s(t);break}const o=null!=t.id?r.message.parts.find((e=>t.type===e.type&&t.id===e.id)):void 0;null!=o?o.data=t.data:r.message.parts.push(t),null==s||s(t),u()}}a.enqueue(e)}))}}))}Uh({prefix:"aitxt",size:24}),Uh({prefix:"aiobj",size:24});var xg=class{constructor(){this.queue=[],this.isProcessing=!1}async processQueue(){if(!this.isProcessing){for(this.isProcessing=!0;this.queue.length>0;)await this.queue[0](),this.queue.shift();this.isProcessing=!1}}async run(e){return new Promise(((t,n)=>{this.queue.push((async()=>{try{await e(),t()}catch(r){n(r)}})),this.processQueue()}))}};Uh({prefix:"aiobj",size:24});((e,t)=>{for(var n in t)Yh(e,n,{get:t[n],enumerable:!0})})({},{object:()=>Sg,text:()=>Ig});var Ig=()=>({type:"text",responseFormat:{type:"text"},parsePartial:async({text:e})=>({partial:e}),parseOutput:async({text:e})=>e}),Sg=({schema:e})=>{const t=Gh(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:e}){const t=await vg(e);switch(t.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:t.value};default:{const e=t.state;throw new Error(`Unsupported parse state: ${e}`)}}},async parseOutput({text:e},n){const r=await Wh({text:e});if(!r.success)throw new tg({message:"No object generated: could not parse the response.",cause:r.error,text:e,response:n.response,usage:n.usage,finishReason:n.finishReason});const o=await Fh({value:r.value,schema:t});if(!o.success)throw new tg({message:"No object generated: response did not match schema.",cause:o.error,text:e,response:n.response,usage:n.usage,finishReason:n.finishReason});return o.value}}},$g=Nl({name:zu(),version:zu()}),Og=Nl({_meta:Xl(Tl({}).loose())}),Eg=Og,Tg=Tl({method:zu(),params:Xl(Og)}),Rg=Nl({experimental:Xl(Tl({}).loose()),logging:Xl(Tl({}).loose()),prompts:Xl(Nl({listChanged:Xl(dl())})),resources:Xl(Nl({subscribe:Xl(dl()),listChanged:Xl(dl())})),tools:Xl(Nl({listChanged:Xl(dl())}))});Eg.extend({protocolVersion:zu(),capabilities:Rg,serverInfo:$g,instructions:Xl(zu())});var Ng=Eg.extend({nextCursor:Xl(zu())}),Ag=Tl({name:zu(),description:Xl(zu()),inputSchema:Tl({type:Hl("object"),properties:Xl(Tl({}).loose())}).loose()}).loose();Ng.extend({tools:Ol(Ag)});var Cg=Tl({type:Hl("text"),text:zu()}).loose(),Pg=Tl({type:Hl("image"),data:tl(),mimeType:zu()}).loose(),Ug=Tl({uri:zu(),mimeType:Xl(zu())}).loose(),jg=Ug.extend({text:zu()}),zg=Ug.extend({blob:tl()}),Dg=Tl({type:Hl("resource"),resource:Cl([jg,zg])}).loose();Eg.extend({content:Ol(Cl([Cg,Pg,Dg])),isError:dl().default(!1).optional()}).or(Eg.extend({toolResult:kl()}));var Mg="2.0",Lg=Tl({jsonrpc:Hl(Mg),id:Cl([zu(),al().int()])}).merge(Tg).strict(),qg=Tl({jsonrpc:Hl(Mg),id:Cl([zu(),al().int()]),result:Eg}).strict(),Zg=Tl({jsonrpc:Hl(Mg),id:Cl([zu(),al().int()]),error:Tl({code:al().int(),message:zu(),data:Xl(kl())})}).strict();Cl([Lg,Tl({jsonrpc:Hl(Mg)}).merge(Tl({method:zu(),params:Xl(Og)})).strict(),qg,Zg]);var Fg,Wg,Jg=class{constructor({api:e="/api/chat",credentials:t,headers:n,body:r,fetch:o,prepareSendMessagesRequest:i,prepareReconnectToStreamRequest:s}){this.api=e,this.credentials=t,this.headers=n,this.body=r,this.fetch=o,this.prepareSendMessagesRequest=i,this.prepareReconnectToStreamRequest=s}async sendMessages({abortSignal:e,...t}){var n,r,o,i,s;const a=await Jh(this.body),u=await Jh(this.headers),l=await Jh(this.credentials),c=await(null==(n=this.prepareSendMessagesRequest)?void 0:n.call(this,{api:this.api,id:t.chatId,messages:t.messages,body:{...a,...t.body},headers:{...u,...t.headers},credentials:l,requestMetadata:t.metadata,trigger:t.trigger,messageId:t.messageId})),d=null!=(r=null==c?void 0:c.api)?r:this.api,p=void 0!==(null==c?void 0:c.headers)?c.headers:{...u,...t.headers},m=void 0!==(null==c?void 0:c.body)?c.body:{...a,...t.body,id:t.chatId,messages:t.messages,trigger:t.trigger,messageId:t.messageId},_=null!=(o=null==c?void 0:c.credentials)?o:l,h=null!=(i=this.fetch)?i:globalThis.fetch,g=await h(d,{method:"POST",headers:{"Content-Type":"application/json",...p},body:JSON.stringify(m),credentials:_,signal:e});if(!g.ok)throw new Error(null!=(s=await g.text())?s:"Failed to fetch the chat response.");if(!g.body)throw new Error("The response body is empty.");return this.processResponseStream(g.body)}async reconnectToStream(e){var t,n,r,o,i;const s=await Jh(this.body),a=await Jh(this.headers),u=await Jh(this.credentials),l=await(null==(t=this.prepareReconnectToStreamRequest)?void 0:t.call(this,{api:this.api,id:e.chatId,body:{...s,...e.body},headers:{...a,...e.headers},credentials:u,requestMetadata:e.metadata})),c=null!=(n=null==l?void 0:l.api)?n:`${this.api}/${e.chatId}/stream`,d=void 0!==(null==l?void 0:l.headers)?l.headers:{...a,...e.headers},p=null!=(r=null==l?void 0:l.credentials)?r:u,m=null!=(o=this.fetch)?o:globalThis.fetch,_=await m(c,{method:"GET",headers:d,credentials:p});if(204===_.status)return null;if(!_.ok)throw new Error(null!=(i=await _.text())?i:"Failed to fetch the chat response.");if(!_.body)throw new Error("The response body is empty.");return this.processResponseStream(_.body)}},Bg=class extends Jg{constructor(e={}){super(e)}processResponseStream(e){return function({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new jt).pipeThrough(new TransformStream({async transform({data:e},n){"[DONE]"!==e&&n.enqueue(await Wh({text:e,schema:t}))}}))}({stream:e,schema:hg}).pipeThrough(new TransformStream({async transform(e,t){if(!e.success)throw e.error;t.enqueue(e.value)}}))}},Hg=class{constructor({generateId:e=jh,id:t=e(),transport:n=new Bg,messageMetadataSchema:r,dataPartSchemas:o,state:i,onError:s,onToolCall:a,onFinish:u,onData:l,sendAutomaticallyWhen:c}){this.activeResponse=void 0,this.jobExecutor=new xg,this.sendMessage=async(e,t)=>{var n,r,o,i;if(null==e)return void(await this.makeRequest({trigger:"submit-message",messageId:null==(n=this.lastMessage)?void 0:n.id,...t}));let s;if("text"in e||"files"in e){const t=Array.isArray(e.files)?e.files:await async function(e){if(null==e)return[];if(!(globalThis.FileList&&e instanceof globalThis.FileList))throw new Error("FileList is not supported in the current environment");return Promise.all(Array.from(e).map((async e=>{const{name:t,type:n}=e;return{type:"file",mediaType:n,filename:t,url:await new Promise(((t,n)=>{const r=new FileReader;r.onload=e=>{var n;t(null==(n=e.target)?void 0:n.result)},r.onerror=e=>n(e),r.readAsDataURL(e)}))}})))}(e.files);s={parts:[...t,..."text"in e&&null!=e.text?[{type:"text",text:e.text}]:[]]}}else s=e;if(null!=e.messageId){const t=this.state.messages.findIndex((t=>t.id===e.messageId));if(-1===t)throw new Error(`message with id ${e.messageId} not found`);if("user"!==this.state.messages[t].role)throw new Error(`message with id ${e.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,t+1),this.state.replaceMessage(t,{...s,id:e.messageId,role:null!=(r=s.role)?r:"user",metadata:e.metadata})}else this.state.pushMessage({...s,id:null!=(o=s.id)?o:this.generateId(),role:null!=(i=s.role)?i:"user",metadata:e.metadata});await this.makeRequest({trigger:"submit-message",messageId:e.messageId,...t})},this.regenerate=async({messageId:e,...t}={})=>{const n=null==e?this.state.messages.length-1:this.state.messages.findIndex((t=>t.id===e));if(-1===n)throw new Error(`message ${e} not found`);this.state.messages=this.state.messages.slice(0,"assistant"===this.messages[n].role?n:n+1),await this.makeRequest({trigger:"regenerate-message",messageId:e,...t})},this.resumeStream=async(e={})=>{await this.makeRequest({trigger:"resume-stream",...e})},this.clearError=()=>{"error"===this.status&&(this.state.error=void 0,this.setStatus({status:"ready"}))},this.addToolResult=async({tool:e,toolCallId:t,output:n})=>this.jobExecutor.run((async()=>{var e,r;const o=this.state.messages,i=o[o.length-1];this.state.replaceMessage(o.length-1,{...i,parts:i.parts.map((e=>yg(e)&&e.toolCallId===t?{...e,state:"output-available",output:n}:e))}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map((e=>yg(e)&&e.toolCallId===t?{...e,state:"output-available",output:n,errorText:void 0}:e))),"streaming"!==this.status&&"submitted"!==this.status&&(null==(e=this.sendAutomaticallyWhen)?void 0:e.call(this,{messages:this.state.messages}))&&this.makeRequest({trigger:"submit-message",messageId:null==(r=this.lastMessage)?void 0:r.id})})),this.stop=async()=>{var e;"streaming"!==this.status&&"submitted"!==this.status||(null==(e=this.activeResponse)?void 0:e.abortController)&&this.activeResponse.abortController.abort()},this.id=t,this.transport=n,this.generateId=e,this.messageMetadataSchema=r,this.dataPartSchemas=o,this.state=i,this.onError=s,this.onToolCall=a,this.onFinish=u,this.onData=l,this.sendAutomaticallyWhen=c}get status(){return this.state.status}setStatus({status:e,error:t}){this.status!==e&&(this.state.status=e,this.state.error=t)}get error(){return this.state.error}get messages(){return this.state.messages}get lastMessage(){return this.state.messages[this.state.messages.length-1]}set messages(e){this.state.messages=e}async makeRequest({trigger:e,metadata:t,headers:n,body:r,messageId:o}){var i,s,a;this.setStatus({status:"submitted",error:void 0});const u=this.lastMessage;try{const s={state:kg({lastMessage:this.state.snapshot(u),messageId:this.generateId()}),abortController:new AbortController};let a;if(this.activeResponse=s,"resume-stream"===e){const e=await this.transport.reconnectToStream({chatId:this.id,metadata:t,headers:n,body:r});if(null==e)return void this.setStatus({status:"ready"});a=e}else a=await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:s.abortController.signal,metadata:t,headers:n,body:r,trigger:e,messageId:o});const l=e=>this.jobExecutor.run((()=>e({state:s.state,write:()=>{var e;this.setStatus({status:"streaming"});s.state.message.id===(null==(e=this.lastMessage)?void 0:e.id)?this.state.replaceMessage(this.state.messages.length-1,s.state.message):this.state.pushMessage(s.state.message)}})));await async function({stream:e,onError:t}){const n=e.getReader();try{for(;;){const{done:e}=await n.read();if(e)break}}catch(r){null==t||t(r)}finally{n.releaseLock()}}({stream:wg({stream:a,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:l,onError:e=>{throw e}}),onError:e=>{throw e}}),null==(i=this.onFinish)||i.call(this,{message:s.state.message}),this.setStatus({status:"ready"})}catch(l){if("AbortError"===l.name)return this.setStatus({status:"ready"}),null;this.onError&&l instanceof Error&&this.onError(l),this.setStatus({status:"error",error:l})}finally{this.activeResponse=void 0}(null==(s=this.sendAutomaticallyWhen)?void 0:s.call(this,{messages:this.state.messages}))&&await this.makeRequest({trigger:"submit-message",messageId:null==(a=this.lastMessage)?void 0:a.id,metadata:t,headers:n,body:r})}},Vg=Tl({type:Hl("text"),text:zu(),state:Jl(["streaming","done"]).optional(),providerMetadata:og.optional()}),Gg=Tl({type:Hl("reasoning"),text:zu(),state:Jl(["streaming","done"]).optional(),providerMetadata:og.optional()}),Kg=Tl({type:Hl("source-url"),sourceId:zu(),url:zu(),title:zu().optional(),providerMetadata:og.optional()}),Yg=Tl({type:Hl("source-document"),sourceId:zu(),mediaType:zu(),title:zu(),filename:zu().optional(),providerMetadata:og.optional()}),Xg=Tl({type:Hl("file"),mediaType:zu(),filename:zu().optional(),url:zu(),providerMetadata:og.optional()}),Qg=Tl({type:Hl("step-start")}),ef=Tl({type:zu().startsWith("data-"),id:zu().optional(),data:kl()}),tf=[Tl({type:Hl("dynamic-tool"),toolName:zu(),toolCallId:zu(),state:Hl("input-streaming"),input:kl().optional(),output:xl().optional(),errorText:xl().optional()}),Tl({type:Hl("dynamic-tool"),toolName:zu(),toolCallId:zu(),state:Hl("input-available"),input:kl(),output:xl().optional(),errorText:xl().optional(),callProviderMetadata:og.optional()}),Tl({type:Hl("dynamic-tool"),toolName:zu(),toolCallId:zu(),state:Hl("output-available"),input:kl(),output:kl(),errorText:xl().optional(),callProviderMetadata:og.optional(),preliminary:dl().optional()}),Tl({type:Hl("dynamic-tool"),toolName:zu(),toolCallId:zu(),state:Hl("output-error"),input:kl(),output:xl().optional(),errorText:zu(),callProviderMetadata:og.optional()})],nf=[Tl({type:zu().startsWith("tool-"),toolCallId:zu(),state:Hl("input-streaming"),input:kl().optional(),output:xl().optional(),errorText:xl().optional()}),Tl({type:zu().startsWith("tool-"),toolCallId:zu(),state:Hl("input-available"),input:kl(),output:xl().optional(),errorText:xl().optional(),callProviderMetadata:og.optional()}),Tl({type:zu().startsWith("tool-"),toolCallId:zu(),state:Hl("output-available"),input:kl(),output:kl(),errorText:xl().optional(),callProviderMetadata:og.optional(),preliminary:dl().optional()}),Tl({type:zu().startsWith("tool-"),toolCallId:zu(),state:Hl("output-error"),input:kl(),output:xl().optional(),errorText:zu(),callProviderMetadata:og.optional()})];function rf(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function of(){if(Wg)return Fg;return Wg=1,Fg=function(e,t){if("function"!=typeof e)throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof e}\`.`);let n,r=0;return function(...o){clearTimeout(n);const i=Date.now(),s=t-(i-r);s<=0?(r=i,e.apply(this,o)):n=setTimeout((()=>{r=Date.now(),e.apply(this,o)}),s)}}}Tl({id:zu(),role:Jl(["system","user","assistant"]),metadata:kl().optional(),parts:Ol(Cl([Vg,Gg,Kg,Yg,Xg,Qg,ef,...tf,...nf]))});const sf=rf(of());var af,uf,lf,cf,df,pf,mf,_f,hf,gf=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},ff=(e,t,n)=>(gf(e,t,"read from private field"),n?n.call(e):t.get(e)),vf=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},yf=(e,t,n,r)=>(gf(e,t,"write to private field"),t.set(e,n),n);var bf,kf=class{constructor(e=[]){vf(this,af,void 0),vf(this,uf,"ready"),vf(this,lf,void 0),vf(this,cf,new Set),vf(this,df,new Set),vf(this,pf,new Set),this.pushMessage=e=>{yf(this,af,ff(this,af).concat(e)),ff(this,mf).call(this)},this.popMessage=()=>{yf(this,af,ff(this,af).slice(0,-1)),ff(this,mf).call(this)},this.replaceMessage=(e,t)=>{yf(this,af,[...ff(this,af).slice(0,e),this.snapshot(t),...ff(this,af).slice(e+1)]),ff(this,mf).call(this)},this.snapshot=e=>structuredClone(e),this["~registerMessagesCallback"]=(e,t)=>{const n=t?(r=e,null!=(o=t)?sf(r,o):r):e;var r,o;return ff(this,cf).add(n),()=>{ff(this,cf).delete(n)}},this["~registerStatusCallback"]=e=>(ff(this,df).add(e),()=>{ff(this,df).delete(e)}),this["~registerErrorCallback"]=e=>(ff(this,pf).add(e),()=>{ff(this,pf).delete(e)}),vf(this,mf,(()=>{ff(this,cf).forEach((e=>e()))})),vf(this,_f,(()=>{ff(this,df).forEach((e=>e()))})),vf(this,hf,(()=>{ff(this,pf).forEach((e=>e()))})),yf(this,af,e)}get status(){return ff(this,uf)}set status(e){yf(this,uf,e),ff(this,_f).call(this)}get error(){return ff(this,lf)}set error(e){yf(this,lf,e),ff(this,hf).call(this)}get messages(){return ff(this,af)}set messages(e){yf(this,af,[...e]),ff(this,mf).call(this)}};af=new WeakMap,uf=new WeakMap,lf=new WeakMap,cf=new WeakMap,df=new WeakMap,pf=new WeakMap,mf=new WeakMap,_f=new WeakMap,hf=new WeakMap;var wf=class extends Hg{constructor({messages:e,...t}){const n=new kf(e);super({...t,state:n}),vf(this,bf,void 0),this["~registerMessagesCallback"]=(e,t)=>ff(this,bf)["~registerMessagesCallback"](e,t),this["~registerStatusCallback"]=e=>ff(this,bf)["~registerStatusCallback"](e),this["~registerErrorCallback"]=e=>ff(this,bf)["~registerErrorCallback"](e),yf(this,bf,n)}};bf=new WeakMap;var xf,If=Object.defineProperty,Sf="AI_NoObjectGeneratedError",$f=`vercel.ai.error.${Sf}`,Of=Symbol.for($f),Ef=class extends Ne{constructor({message:e="No object generated.",cause:t,text:n,response:r,usage:o,finishReason:i}){super({name:Sf,message:e,cause:t}),this[xf]=!0,this.text=n,this.response=r,this.usage=o,this.finishReason=i}static isInstance(e){return Ne.hasMarker(e,$f)}};xf=Of;var Tf,Rf="AI_MessageConversionError",Nf=`vercel.ai.error.${Rf}`,Af=Symbol.for(Nf),Cf=class extends Ne{constructor({originalMessage:e,message:t}){super({name:Rf,message:t}),this[Tf]=!0,this.originalMessage=e}static isInstance(e){return Ne.hasMarker(e,Nf)}};Tf=Af;var Pf=Cl([zu(),xc(Uint8Array),xc(ArrayBuffer),bc((e=>{var t,n;return null!=(n=null==(t=globalThis.Buffer)?void 0:t.isBuffer(e))&&n}),{message:"Must be a Buffer"})]),Uf=fc((()=>Cl([fl(),zu(),al(),dl(),ql(zu(),Uf),Ol(Uf)]))),jf=ql(zu(),ql(zu(),Uf)),zf=Tl({type:Hl("text"),text:zu(),providerOptions:jf.optional()}),Df=Tl({type:Hl("image"),image:Cl([Pf,xc(URL)]),mediaType:zu().optional(),providerOptions:jf.optional()}),Mf=Tl({type:Hl("file"),data:Cl([Pf,xc(URL)]),filename:zu().optional(),mediaType:zu(),providerOptions:jf.optional()}),Lf=Tl({type:Hl("reasoning"),text:zu(),providerOptions:jf.optional()}),qf=Tl({type:Hl("tool-call"),toolCallId:zu(),toolName:zu(),input:kl(),providerOptions:jf.optional(),providerExecuted:dl().optional()}),Zf=Ul("type",[Tl({type:Hl("text"),value:zu()}),Tl({type:Hl("json"),value:Uf}),Tl({type:Hl("error-text"),value:zu()}),Tl({type:Hl("error-json"),value:Uf}),Tl({type:Hl("content"),value:Ol(Cl([Tl({type:Hl("text"),text:zu()}),Tl({type:Hl("media"),data:zu(),mediaType:zu()})]))})]),Ff=Tl({type:Hl("tool-result"),toolCallId:zu(),toolName:zu(),output:Zf,providerOptions:jf.optional()}),Wf=Tl({role:Hl("system"),content:zu(),providerOptions:jf.optional()}),Jf=Tl({role:Hl("user"),content:Cl([zu(),Ol(Cl([zf,Df,Mf]))]),providerOptions:jf.optional()}),Bf=Tl({role:Hl("assistant"),content:Cl([zu(),Ol(Cl([zf,Mf,Lf,qf,Ff]))]),providerOptions:jf.optional()});function Hf({output:e,tool:t,errorMode:n}){return"text"===n?{type:"error-text",value:qe(e)}:"json"===n?{type:"error-json",value:Vf(e)}:(null==t?void 0:t.toModelOutput)?t.toModelOutput(e):"string"==typeof e?{type:"text",value:e}:{type:"json",value:Vf(e)}}function Vf(e){return void 0===e?null:e}function Gf(e){const t=["ROOT"];let n=-1,r=null;function o(e,o,i){switch(e){case'"':n=o,t.pop(),t.push(i),t.push("INSIDE_STRING");break;case"f":case"t":case"n":n=o,r=o,t.pop(),t.push(i),t.push("INSIDE_LITERAL");break;case"-":t.pop(),t.push(i),t.push("INSIDE_NUMBER");break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":n=o,t.pop(),t.push(i),t.push("INSIDE_NUMBER");break;case"{":n=o,t.pop(),t.push(i),t.push("INSIDE_OBJECT_START");break;case"[":n=o,t.pop(),t.push(i),t.push("INSIDE_ARRAY_START")}}function i(e,r){switch(e){case",":t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break;case"}":n=r,t.pop()}}function s(e,r){switch(e){case",":t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break;case"]":n=r,t.pop()}}for(let u=0;u<e.length;u++){const a=e[u];switch(t[t.length-1]){case"ROOT":o(a,u,"FINISH");break;case"INSIDE_OBJECT_START":switch(a){case'"':t.pop(),t.push("INSIDE_OBJECT_KEY");break;case"}":n=u,t.pop()}break;case"INSIDE_OBJECT_AFTER_COMMA":if('"'===a)t.pop(),t.push("INSIDE_OBJECT_KEY");break;case"INSIDE_OBJECT_KEY":if('"'===a)t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break;case"INSIDE_OBJECT_AFTER_KEY":if(":"===a)t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break;case"INSIDE_OBJECT_BEFORE_VALUE":o(a,u,"INSIDE_OBJECT_AFTER_VALUE");break;case"INSIDE_OBJECT_AFTER_VALUE":i(a,u);break;case"INSIDE_STRING":switch(a){case'"':t.pop(),n=u;break;case"\\":t.push("INSIDE_STRING_ESCAPE");break;default:n=u}break;case"INSIDE_ARRAY_START":if("]"===a)n=u,t.pop();else n=u,o(a,u,"INSIDE_ARRAY_AFTER_VALUE");break;case"INSIDE_ARRAY_AFTER_VALUE":switch(a){case",":t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break;case"]":n=u,t.pop();break;default:n=u}break;case"INSIDE_ARRAY_AFTER_COMMA":o(a,u,"INSIDE_ARRAY_AFTER_VALUE");break;case"INSIDE_STRING_ESCAPE":t.pop(),n=u;break;case"INSIDE_NUMBER":switch(a){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":n=u;break;case"e":case"E":case"-":case".":break;case",":t.pop(),"INSIDE_ARRAY_AFTER_VALUE"===t[t.length-1]&&s(a,u),"INSIDE_OBJECT_AFTER_VALUE"===t[t.length-1]&&i(a,u);break;case"}":t.pop(),"INSIDE_OBJECT_AFTER_VALUE"===t[t.length-1]&&i(a,u);break;case"]":t.pop(),"INSIDE_ARRAY_AFTER_VALUE"===t[t.length-1]&&s(a,u);break;default:t.pop()}break;case"INSIDE_LITERAL":{const o=e.substring(r,u+1);"false".startsWith(o)||"true".startsWith(o)||"null".startsWith(o)?n=u:(t.pop(),"INSIDE_OBJECT_AFTER_VALUE"===t[t.length-1]?i(a,u):"INSIDE_ARRAY_AFTER_VALUE"===t[t.length-1]&&s(a,u));break}}}let a=e.slice(0,n+1);for(let u=t.length-1;u>=0;u--){switch(t[u]){case"INSIDE_STRING":a+='"';break;case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":a+="}";break;case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":a+="]";break;case"INSIDE_LITERAL":{const t=e.substring(r,e.length);"true".startsWith(t)?a+="true".slice(t.length):"false".startsWith(t)?a+="false".slice(t.length):"null".startsWith(t)&&(a+="null".slice(t.length))}}}return a}function Kf(e){return e.type.startsWith("tool-")}function Yf(e){return e.type.split("-").slice(1).join("-")}Cl([Wf,Jf,Bf,Tl({role:Hl("tool"),content:Ol(Ff),providerOptions:jf.optional()})]),_d({prefix:"aitxt",size:24}),TransformStream,Cl([Rl({type:Hl("text-start"),id:zu(),providerMetadata:jf.optional()}),Rl({type:Hl("text-delta"),id:zu(),delta:zu(),providerMetadata:jf.optional()}),Rl({type:Hl("text-end"),id:zu(),providerMetadata:jf.optional()}),Rl({type:Hl("error"),errorText:zu()}),Rl({type:Hl("tool-input-start"),toolCallId:zu(),toolName:zu(),providerExecuted:dl().optional(),dynamic:dl().optional()}),Rl({type:Hl("tool-input-delta"),toolCallId:zu(),inputTextDelta:zu()}),Rl({type:Hl("tool-input-available"),toolCallId:zu(),toolName:zu(),input:kl(),providerExecuted:dl().optional(),providerMetadata:jf.optional(),dynamic:dl().optional()}),Rl({type:Hl("tool-input-error"),toolCallId:zu(),toolName:zu(),input:kl(),providerExecuted:dl().optional(),providerMetadata:jf.optional(),dynamic:dl().optional(),errorText:zu()}),Rl({type:Hl("tool-output-available"),toolCallId:zu(),output:kl(),providerExecuted:dl().optional(),dynamic:dl().optional(),preliminary:dl().optional()}),Rl({type:Hl("tool-output-error"),toolCallId:zu(),errorText:zu(),providerExecuted:dl().optional(),dynamic:dl().optional()}),Rl({type:Hl("reasoning"),text:zu(),providerMetadata:jf.optional()}),Rl({type:Hl("reasoning-start"),id:zu(),providerMetadata:jf.optional()}),Rl({type:Hl("reasoning-delta"),id:zu(),delta:zu(),providerMetadata:jf.optional()}),Rl({type:Hl("reasoning-end"),id:zu(),providerMetadata:jf.optional()}),Rl({type:Hl("reasoning-part-finish")}),Rl({type:Hl("source-url"),sourceId:zu(),url:zu(),title:zu().optional(),providerMetadata:jf.optional()}),Rl({type:Hl("source-document"),sourceId:zu(),mediaType:zu(),title:zu(),filename:zu().optional(),providerMetadata:jf.optional()}),Rl({type:Hl("file"),url:zu(),mediaType:zu(),providerMetadata:jf.optional()}),Rl({type:zu().startsWith("data-"),id:zu().optional(),data:kl(),transient:dl().optional()}),Rl({type:Hl("start-step")}),Rl({type:Hl("finish-step")}),Rl({type:Hl("start"),messageId:zu().optional(),messageMetadata:kl().optional()}),Rl({type:Hl("finish"),messageMetadata:kl().optional()}),Rl({type:Hl("abort")}),Rl({type:Hl("message-metadata"),messageMetadata:kl()})]),_d({prefix:"aitxt",size:24}),_d({prefix:"aiobj",size:24}),_d({prefix:"aiobj",size:24});((e,t)=>{for(var n in t)If(e,n,{get:t[n],enumerable:!0})})({},{object:()=>Qf,text:()=>Xf});var Xf=()=>({type:"text",responseFormat:{type:"text"},parsePartial:async({text:e})=>({partial:e}),parseOutput:async({text:e})=>e}),Qf=({schema:e})=>{const t=Fd(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:e}){const t=await async function(e){if(void 0===e)return{value:void 0,state:"undefined-input"};let t=await Od({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await Od({text:Gf(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}(e);switch(t.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:t.value};default:{const e=t.state;throw new Error(`Unsupported parse state: ${e}`)}}},async parseOutput({text:e},n){const r=await Od({text:e});if(!r.success)throw new Ef({message:"No object generated: could not parse the response.",cause:r.error,text:e,response:n.response,usage:n.usage,finishReason:n.finishReason});const o=await Sd({value:r.value,schema:t});if(!o.success)throw new Ef({message:"No object generated: response did not match schema.",cause:o.error,text:e,response:n.response,usage:n.usage,finishReason:n.finishReason});return o.value}}},ev=Nl({name:zu(),version:zu()}),tv=Nl({_meta:Xl(Tl({}).loose())}),nv=tv,rv=Tl({method:zu(),params:Xl(tv)}),ov=Nl({experimental:Xl(Tl({}).loose()),logging:Xl(Tl({}).loose()),prompts:Xl(Nl({listChanged:Xl(dl())})),resources:Xl(Nl({subscribe:Xl(dl()),listChanged:Xl(dl())})),tools:Xl(Nl({listChanged:Xl(dl())}))});nv.extend({protocolVersion:zu(),capabilities:ov,serverInfo:ev,instructions:Xl(zu())});var iv=nv.extend({nextCursor:Xl(zu())}),sv=Tl({name:zu(),description:Xl(zu()),inputSchema:Tl({type:Hl("object"),properties:Xl(Tl({}).loose())}).loose()}).loose();iv.extend({tools:Ol(sv)});var av=Tl({type:Hl("text"),text:zu()}).loose(),uv=Tl({type:Hl("image"),data:tl(),mimeType:zu()}).loose(),lv=Tl({uri:zu(),mimeType:Xl(zu())}).loose(),cv=lv.extend({text:zu()}),dv=lv.extend({blob:tl()}),pv=Tl({type:Hl("resource"),resource:Cl([cv,dv])}).loose();nv.extend({content:Ol(Cl([av,uv,pv])),isError:dl().default(!1).optional()}).or(nv.extend({toolResult:kl()}));var mv="2.0",_v=Tl({jsonrpc:Hl(mv),id:Cl([zu(),al().int()])}).merge(rv).strict(),hv=Tl({jsonrpc:Hl(mv),id:Cl([zu(),al().int()]),result:nv}).strict(),gv=Tl({jsonrpc:Hl(mv),id:Cl([zu(),al().int()]),error:Tl({code:al().int(),message:zu(),data:Xl(kl())})}).strict();Cl([_v,Tl({jsonrpc:Hl(mv)}).merge(Tl({method:zu(),params:Xl(tv)})).strict(),hv,gv]);var fv=Tl({type:Hl("text"),text:zu(),state:Jl(["streaming","done"]).optional(),providerMetadata:jf.optional()}),vv=Tl({type:Hl("reasoning"),text:zu(),state:Jl(["streaming","done"]).optional(),providerMetadata:jf.optional()}),yv=Tl({type:Hl("source-url"),sourceId:zu(),url:zu(),title:zu().optional(),providerMetadata:jf.optional()}),bv=Tl({type:Hl("source-document"),sourceId:zu(),mediaType:zu(),title:zu(),filename:zu().optional(),providerMetadata:jf.optional()}),kv=Tl({type:Hl("file"),mediaType:zu(),filename:zu().optional(),url:zu(),providerMetadata:jf.optional()}),wv=Tl({type:Hl("step-start")}),xv=Tl({type:zu().startsWith("data-"),id:zu().optional(),data:kl()}),Iv=[Tl({type:Hl("dynamic-tool"),toolName:zu(),toolCallId:zu(),state:Hl("input-streaming"),input:kl().optional(),output:xl().optional(),errorText:xl().optional()}),Tl({type:Hl("dynamic-tool"),toolName:zu(),toolCallId:zu(),state:Hl("input-available"),input:kl(),output:xl().optional(),errorText:xl().optional(),callProviderMetadata:jf.optional()}),Tl({type:Hl("dynamic-tool"),toolName:zu(),toolCallId:zu(),state:Hl("output-available"),input:kl(),output:kl(),errorText:xl().optional(),callProviderMetadata:jf.optional(),preliminary:dl().optional()}),Tl({type:Hl("dynamic-tool"),toolName:zu(),toolCallId:zu(),state:Hl("output-error"),input:kl(),output:xl().optional(),errorText:zu(),callProviderMetadata:jf.optional()})],Sv=[Tl({type:zu().startsWith("tool-"),toolCallId:zu(),state:Hl("input-streaming"),input:kl().optional(),output:xl().optional(),errorText:xl().optional()}),Tl({type:zu().startsWith("tool-"),toolCallId:zu(),state:Hl("input-available"),input:kl(),output:xl().optional(),errorText:xl().optional(),callProviderMetadata:jf.optional()}),Tl({type:zu().startsWith("tool-"),toolCallId:zu(),state:Hl("output-available"),input:kl(),output:kl(),errorText:xl().optional(),callProviderMetadata:jf.optional(),preliminary:dl().optional()}),Tl({type:zu().startsWith("tool-"),toolCallId:zu(),state:Hl("output-error"),input:kl(),output:xl().optional(),errorText:zu(),callProviderMetadata:jf.optional()})];function $v(){const e=function(){const e=o.useContext(Ph);if(!e)throw new Error("useChat must be used within an EchoChatProvider");return e}();return{async sendMessages(t){const{messages:n,abortSignal:r,...o}=t,i=function(e,t){const n=[];(null==t?void 0:t.ignoreIncompleteToolCalls)&&(e=e.map((e=>({...e,parts:e.parts.filter((e=>!Kf(e)||"input-streaming"!==e.state&&"input-available"!==e.state))}))));for(const r of e)switch(r.role){case"system":{const e=r.parts.filter((e=>"text"===e.type)),t=e.reduce(((e,t)=>null!=t.providerMetadata?{...e,...t.providerMetadata}:e),{});n.push({role:"system",content:e.map((e=>e.text)).join(""),...Object.keys(t).length>0?{providerOptions:t}:{}});break}case"user":n.push({role:"user",content:r.parts.filter((e=>"text"===e.type||"file"===e.type)).map((e=>{switch(e.type){case"text":return{type:"text",text:e.text,...null!=e.providerMetadata?{providerOptions:e.providerMetadata}:{}};case"file":return{type:"file",mediaType:e.mediaType,filename:e.filename,data:e.url,...null!=e.providerMetadata?{providerOptions:e.providerMetadata}:{}};default:return e}}))});break;case"assistant":if(null!=r.parts){let e=function(){var e,i;if(0===o.length)return;const s=[];for(const n of o)if("text"===n.type)s.push({type:"text",text:n.text,...null!=n.providerMetadata?{providerOptions:n.providerMetadata}:{}});else if("file"===n.type)s.push({type:"file",mediaType:n.mediaType,filename:n.filename,data:n.url});else if("reasoning"===n.type)s.push({type:"reasoning",text:n.text,providerOptions:n.providerMetadata});else if("dynamic-tool"===n.type){const e=n.toolName;if("input-streaming"===n.state)throw new Cf({originalMessage:r,message:`incomplete tool input is not supported: ${n.toolCallId}`});s.push({type:"tool-call",toolCallId:n.toolCallId,toolName:e,input:n.input,...null!=n.callProviderMetadata?{providerOptions:n.callProviderMetadata}:{}})}else{if(!Kf(n))throw new Error(`Unsupported part: ${n}`);{const o=Yf(n);if("input-streaming"===n.state)throw new Cf({originalMessage:r,message:`incomplete tool input is not supported: ${n.toolCallId}`});s.push({type:"tool-call",toolCallId:n.toolCallId,toolName:o,input:"output-error"===n.state?null!=(e=n.input)?e:n.rawInput:n.input,providerExecuted:n.providerExecuted,...null!=n.callProviderMetadata?{providerOptions:n.callProviderMetadata}:{}}),!0!==n.providerExecuted||"output-available"!==n.state&&"output-error"!==n.state||s.push({type:"tool-result",toolCallId:n.toolCallId,toolName:o,output:Hf({output:"output-error"===n.state?n.errorText:n.output,tool:null==(i=null==t?void 0:t.tools)?void 0:i[o],errorMode:"output-error"===n.state?"json":"none"})})}}n.push({role:"assistant",content:s});const a=o.filter((e=>Kf(e)&&!0!==e.providerExecuted||"dynamic-tool"===e.type));a.length>0&&n.push({role:"tool",content:a.map((e=>{var n;switch(e.state){case"output-error":case"output-available":{const r="dynamic-tool"===e.type?e.toolName:Yf(e);return{type:"tool-result",toolCallId:e.toolCallId,toolName:r,output:Hf({output:"output-error"===e.state?e.errorText:e.output,tool:null==(n=null==t?void 0:t.tools)?void 0:n[r],errorMode:"output-error"===e.state?"text":"none"})}}default:throw new Cf({originalMessage:r,message:`Unsupported tool part state: ${e.state}`})}}))}),o=[]},o=[];for(const t of r.parts)"text"===t.type||"reasoning"===t.type||"file"===t.type||"dynamic-tool"===t.type||Kf(t)?o.push(t):"step-start"===t.type&&e();e();break}break;default:{const e=r.role;throw new Cf({originalMessage:r,message:`Unsupported role: ${e}`})}}return n}(n.map((({role:e,parts:t,metadata:n})=>({role:e,parts:t,metadata:n}))));return await e({uiMessages:n,modelMessages:i,abortSignal:r,...o})},reconnectToStream:async()=>null}}Tl({id:zu(),role:Jl(["system","user","assistant"]),metadata:kl().optional(),parts:Ol(Cl([fv,vv,yv,bv,kv,wv,xv,...Iv,...Sv]))}),exports.EchoChatProvider=function({chatFn:e,children:t}){return r.jsx(Ph.Provider,{value:e,children:t})},exports.EchoProvider=function({config:e,children:t}){const[n,i]=o.useState(!1);if(o.useEffect((()=>{i(!0)}),[]),!n)return null;const s=e.baseEchoUrl||"https://echo.merit.systems",a={userManager:"undefined"!=typeof window&&window.__echoUserManager||new ce({authority:s,client_id:e.appId,redirect_uri:e.redirectUri||window.location.origin,scope:e.scope||"llm:invoke offline_access",silentRequestTimeoutInSeconds:10,automaticSilentRenew:!0,silent_redirect_uri:e.redirectUri||window.location.origin,includeIdTokenInSilentRenew:!1,validateSubOnSilentRenew:!0,loadUserInfo:!0,metadata:{authorization_endpoint:`${s}/api/oauth/authorize`,token_endpoint:`${s}/api/oauth/token`,userinfo_endpoint:`${s}/api/oauth/userinfo`,issuer:s,jwks_uri:`${s}/.well-known/jwks.json`,end_session_endpoint:`${s}/api/oauth/logout`},userStore:new R({store:window.localStorage})}),onSigninCallback:()=>{window.location.search.includes("code=")&&window.history.replaceState({},document.title,window.location.pathname)}};return r.jsx(Se,{...a,children:r.jsx(x_,{config:e,children:t})})},exports.EchoSignIn=function({onSuccess:e,onError:t,className:n="",children:i}){const{signIn:s,isLoading:a,user:u,error:l}=I_(),[c,d]=o.useState(!1);o.useEffect((()=>{u&&e&&e(u)}),[u,e]),o.useEffect((()=>{l&&t&&t(new Error(l))}),[l,t]);const p=async()=>{try{await s()}catch(e){t&&t(e instanceof Error?e:new Error("Sign in failed"))}};return u?r.jsx("div",{className:`echo-signin-success ${n}`,children:r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"12px 16px",backgroundColor:"#f8fafc",border:"1px solid #e2e8f0",borderRadius:"8px",color:"#334155",fontSize:"14px",fontFamily:"HelveticaNowDisplay, sans-serif",fontWeight:"800",width:"fit-content"},children:[r.jsx(Ah,{width:16,height:16,variant:"light"}),r.jsxs("span",{children:["Signed in as ",Rh((null==u?void 0:u.name)||(null==u?void 0:u.email))]})]})}):r.jsx("div",{className:`echo-signin ${n}`,children:i?r.jsx("div",{onClick:p,style:{cursor:"pointer"},children:i}):r.jsxs("button",{onClick:p,disabled:a,className:"echo-signin-button",style:{display:"flex",alignItems:"center",gap:"8px",padding:"12px 20px",backgroundColor:a?"#f3f4f6":c?"#f1f5f9":"#ffffff",color:a?"#9ca3af":"#09090b",border:"1px solid #e2e8f0",borderRadius:"8px",cursor:a?"not-allowed":"pointer",fontSize:"14px",fontWeight:"800",fontFamily:"HelveticaNowDisplay, sans-serif",transition:"all 0.2s ease",boxShadow:"0 1px 2px 0 rgba(0, 0, 0, 0.05)",backdropFilter:"blur(8px)"},onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),children:[r.jsx(Ah,{width:16,height:16,variant:"light"}),r.jsx("span",{children:a?"Signing in...":"Sign in"})]})})},exports.EchoTokenPurchase=function({onPurchaseComplete:e,onError:t,className:n="",children:i}){const{createPaymentLink:s,user:a,balance:u,freeTierBalance:l,refreshBalance:c}=I_(),[d,p]=o.useState(!1),[m,_]=o.useState(null),[h,g]=o.useState(!1),[f,v]=o.useState(!1),y=e=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(e),b=()=>{var e,t;return(((null==(e=null==l?void 0:l.userSpendInfo)?void 0:e.amountLeft)||0)<0?0:(null==(t=null==l?void 0:l.userSpendInfo)?void 0:t.amountLeft)||0)+((null==u?void 0:u.balance)||0)},k=async n=>{if(!a){const e=new Error("Please sign in to purchase tokens");return _(e.message),void(t&&t(e))}try{p(!0),_(null);const r=await s(n);await Nh(r,{onComplete:async()=>{try{await c(),g(!1),v(!1),e&&u&&e(u)}catch(n){const e=n instanceof Error?n:new Error("Failed to refresh balance");_(e.message),t&&t(e)}finally{p(!1)}},onCancel:()=>{p(!1)},onError:e=>{_(e.message),t&&t(e),p(!1)}})}catch(r){const e=r instanceof Error?r:new Error("Failed to create payment link");_(e.message),t&&t(e),p(!1)}},w=()=>{g(!1),v(!1),_(null)};if(!a)return r.jsx("div",{className:`echo-token-purchase ${n}`,children:r.jsx("div",{className:"echo-token-purchase-unauthorized",style:{padding:"12px",backgroundColor:"#fef3c7",color:"#92400e",borderRadius:"8px",fontSize:"14px"},children:"Please sign in to purchase tokens"})});const x=()=>{const[e,t]=o.useState(!1);return r.jsxs("button",{onClick:()=>g(!0),className:`echo-token-purchase-compact ${n}`,style:{display:"flex",alignItems:"center",gap:"8px",padding:"10px 12px",borderRadius:"8px",backgroundColor:e?"#f1f5f9":"#ffffff",border:"1px solid #e5e7eb",color:"#09090b",fontSize:"14px",fontWeight:"800",cursor:"pointer",backdropFilter:"blur(8px)",transition:"all 0.2s ease",boxShadow:"0 1px 2px 0 rgba(0, 0, 0, 0.05)",height:"40px",fontFamily:"HelveticaNowDisplay, sans-serif"},onMouseEnter:()=>t(!0),onMouseLeave:()=>t(!1),children:[r.jsx(Ah,{width:16,height:16,variant:"light"}),r.jsx("span",{children:y(b())}),r.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:e?"#dc2626":"#6b7280",transition:"color 0.2s ease"},children:[r.jsx("path",{d:"M7 7h10v10"}),r.jsx("path",{d:"M7 17 17 7"})]})]})},I=()=>r.jsx("div",{style:{position:"fixed",top:0,left:0,right:0,bottom:0,backgroundColor:"rgba(0, 0, 0, 0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,padding:"16px"},onClick:e=>{e.target===e.currentTarget&&w()},children:r.jsxs("div",{style:{backgroundColor:"#ffffff",borderRadius:"12px",border:"1px solid #e5e7eb",padding:"0",width:"100%",maxWidth:"450px",maxHeight:"90vh",overflow:"hidden",boxShadow:"0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)",fontFamily:"HelveticaNowDisplay, sans-serif",display:"flex",flexDirection:"column",minHeight:"320px"},children:[r.jsx("div",{style:{padding:"16px 16px 0 16px",marginBottom:"12px"},children:r.jsx("h2",{style:{fontSize:"18px",fontWeight:"500",color:"#111827",margin:0,fontFamily:"HelveticaNowDisplay, sans-serif"},children:"Credits"})}),r.jsxs("div",{style:{padding:"0 16px",marginBottom:"16px"},children:[r.jsx("p",{style:{fontSize:"14px",color:"#6b7280",margin:"0 0 4px 0",fontFamily:"HelveticaNowDisplay, sans-serif"},children:"Total Available"}),r.jsx("p",{style:{fontSize:"28px",fontWeight:"700",color:"#111827",margin:"0 0 12px 0",fontFamily:"HelveticaNowDisplay, sans-serif"},children:y(b())}),r.jsxs("div",{style:{marginBottom:"8px"},children:[l&&b()>0&&r.jsxs("div",{style:{marginBottom:"8px"},children:[r.jsxs("div",{style:{fontSize:"12px",color:"#6b7280",fontFamily:"HelveticaNowDisplay, sans-serif",display:"flex",alignItems:"center",gap:"6px",marginBottom:"4px"},children:[r.jsx("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:"#3b82f6"}}),r.jsxs("span",{children:[y(l.userSpendInfo.amountLeft<0?0:l.userSpendInfo.amountLeft)," ","Free Tier",l.userSpendInfo&&l.userSpendInfo.spendLimit&&r.jsxs("span",{style:{color:"#9ca3af",marginLeft:"8px"},children:["(",y(l.userSpendInfo.amountSpent>l.userSpendInfo.spendLimit?l.userSpendInfo.spendLimit:l.userSpendInfo.amountSpent)," ","of"," ",y(l.userSpendInfo.spendLimit)," ","spent)"]})]})]}),l.userSpendInfo&&l.userSpendInfo.spendLimit&&r.jsx("div",{style:{width:"100%",height:"4px",backgroundColor:"#e5e7eb",borderRadius:"2px",overflow:"hidden",marginBottom:"4px",border:"1px solid #d1d5db"},children:r.jsx("div",{style:{width:`${Math.max(0,Math.min(100,Math.max(0,l.userSpendInfo.amountLeft)/(l.userSpendInfo.spendLimit||1)*100))}%`,height:"100%",backgroundColor:"#3b82f6"}})})]}),u&&u.balance>0&&r.jsxs("div",{style:{fontSize:"12px",color:"#6b7280",fontFamily:"HelveticaNowDisplay, sans-serif"},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",marginBottom:"4px"},children:[r.jsx("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:"#dc2626"}}),r.jsxs("span",{children:[y(u.balance)," Paid Credits",u.totalSpent&&r.jsxs("span",{style:{color:"#9ca3af",marginLeft:"8px"},children:["(",y(u.totalSpent)," /"," ",y(u.totalPaid)," spent)"]})]})]}),u.totalPaid>0&&r.jsx("div",{style:{width:"100%",height:"4px",backgroundColor:"#e5e7eb",borderRadius:"2px",overflow:"hidden",border:"1px solid #d1d5db"},children:r.jsx("div",{style:{width:`${Math.max(0,Math.min(100,u.balance/u.totalPaid*100))}%`,height:"100%",backgroundColor:"#dc2626"}})})]})]})]}),r.jsxs("div",{style:{padding:"0 16px 16px 16px",borderTop:"1px solid #f3f4f6",paddingTop:"16px"},children:[r.jsx("p",{style:{fontSize:"14px",color:"#6b7280",margin:"0 0 12px 0",fontFamily:"HelveticaNowDisplay, sans-serif"},children:"Add Credits"}),f?r.jsx(Ch,{onAddCredits:k,onCancel:()=>v(!1),isProcessing:d}):r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[r.jsx("button",{onClick:()=>k(10),disabled:d,style:{width:"100%",padding:"12px 16px",backgroundColor:d?"#9ca3af":"#dc2626",color:"white",border:"none",borderRadius:"6px",fontSize:"14px",fontWeight:"600",cursor:d?"not-allowed":"pointer",transition:"background-color 0.2s ease",fontFamily:"HelveticaNowDisplay, sans-serif"},onMouseEnter:e=>{d||(e.currentTarget.style.backgroundColor="#b91c1c")},onMouseLeave:e=>{d||(e.currentTarget.style.backgroundColor="#dc2626")},children:d?"Processing...":"Add $10 Credits"}),r.jsx("button",{onClick:()=>v(!0),style:{width:"100%",padding:"8px 16px",fontSize:"14px",color:"#6b7280",backgroundColor:"transparent",border:"1px solid #e5e7eb",borderRadius:"6px",cursor:"pointer",fontFamily:"HelveticaNowDisplay, sans-serif"},onMouseEnter:e=>{e.currentTarget.style.color="#111827",e.currentTarget.style.borderColor="#d1d5db"},onMouseLeave:e=>{e.currentTarget.style.color="#6b7280",e.currentTarget.style.borderColor="#e5e7eb"},children:"Choose different amount"})]})]}),m&&r.jsx("div",{style:{margin:"0 16px 12px 16px",padding:"8px 12px",backgroundColor:"#fee2e2",color:"#dc2626",borderRadius:"6px",fontSize:"14px",fontFamily:"HelveticaNowDisplay, sans-serif"},children:m}),r.jsx("div",{style:{padding:"12px 16px",display:"flex",justifyContent:"flex-end",borderTop:"1px solid #f3f4f6"},children:r.jsx("button",{onClick:w,style:{padding:"8px 16px",backgroundColor:"#f3f4f6",color:"#374151",border:"none",borderRadius:"6px",fontSize:"14px",cursor:"pointer",fontFamily:"HelveticaNowDisplay, sans-serif"},onMouseEnter:e=>{e.currentTarget.style.backgroundColor="#e5e7eb"},onMouseLeave:e=>{e.currentTarget.style.backgroundColor="#f3f4f6"},children:"Close"})})]})});return r.jsxs(r.Fragment,{children:[i?r.jsx("div",{onClick:()=>g(!0),style:{cursor:"pointer"},children:i}):r.jsx(x,{}),h&&r.jsx(I,{})]})},exports.Logo=Ah,exports.useChat=function(){return function({experimental_throttle:e,resume:t=!1,...n}={}){const r=o.useRef("chat"in n?n.chat:new wf(n));("chat"in n&&n.chat!==r.current||"id"in n&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new wf(n));const i="id"in n?n.id:null,s=o.useCallback((t=>r.current["~registerMessagesCallback"](t,e)),[e,i]),a=o.useSyncExternalStore(s,(()=>r.current.messages),(()=>r.current.messages)),u=o.useSyncExternalStore(r.current["~registerStatusCallback"],(()=>r.current.status),(()=>r.current.status)),l=o.useSyncExternalStore(r.current["~registerErrorCallback"],(()=>r.current.error),(()=>r.current.error)),c=o.useCallback((e=>{"function"==typeof e&&(e=e(r.current.messages)),r.current.messages=e}),[r]);return o.useEffect((()=>{t&&r.current.resumeStream()}),[t,r]),{id:r.current.id,messages:a,setMessages:c,sendMessage:r.current.sendMessage,regenerate:r.current.regenerate,clearError:r.current.clearError,stop:r.current.stop,error:l,resumeStream:r.current.resumeStream,status:u,addToolResult:r.current.addToolResult}}({transport:$v()})},exports.useEcho=I_,exports.useEchoClient=b_,exports.useEchoModelProviders=()=>{const{token:e,config:t}=I_();return o.useMemo((()=>{const n={appId:t.appId,baseRouterUrl:t.baseRouterUrl},r=async()=>e;return{openai:f_(n,r),anthropic:v_(n,r),google:y_(n,r)}}),[e,t.appId,t.baseRouterUrl])},exports.useEchoOpenAI=function(e={}){const{baseURL:t="https://echo.router.merit.systems",enabled:n=!0}=e,{token:r,user:i}=I_(),[s,a]=o.useState(void 0),[u,l]=o.useState(null),[c,d]=o.useState(!1),p=o.useRef(null);return o.useEffect((()=>{if(p.current&&p.current.abort(),!n||!r)return a(void 0),l(null),void d(!1);return(async()=>{const e=new AbortController;p.current=e,d(!0),l(null);try{if(e.signal.aborted)return;const{default:n}=await import("openai");if(e.signal.aborted)return;const o=new n({apiKey:r,baseURL:t,dangerouslyAllowBrowser:!0});e.signal.aborted||a(o)}catch(n){if(!e.signal.aborted){const e=n instanceof Error?n.message:"Failed to load OpenAI";e.includes("Cannot resolve module")||e.includes("Module not found")||e.includes("openai")?l("OpenAI package not found. Please install it with: pnpm add openai"):l(`Failed to initialize OpenAI client: ${e}`),console.error("Error loading OpenAI:",n),a(void 0)}}finally{e.signal.aborted||d(!1)}})(),()=>{p.current&&p.current.abort()}}),[r,i,t,n]),{openai:s,isReady:void 0!==s&&!c,error:u,isLoading:c}};
|
|
3
3
|
//# sourceMappingURL=index.cjs.map
|