@merit-systems/echo-react-sdk 1.0.9 → 1.0.12
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 -3
- package/dist/echo-react-sdk.umd.js.map +1 -1
- package/dist/index.cjs +2 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +34 -0
- package/dist/index.js +25300 -5858
- package/dist/index.js.map +1 -1
- package/package.json +4 -2
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
"use strict";Object.create;var e,t=Object.defineProperty,r=(Object.getOwnPropertyDescriptor,Object.getOwnPropertyNames,Object.getPrototypeOf,Object.prototype.hasOwnProperty,(e,r,n)=>((e,r,n)=>r in e?t(e,r,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[r]=n)(e,"symbol"!=typeof r?r+"":r,n));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("react/jsx-runtime"),s=require("react");class i extends Error{}function o(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 r=t.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r})))}(t)}catch(r){return atob(t)}}i.prototype.name="InvalidTokenError";var a,c,l,u={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,c=u},l.setLevel=function(e){if(!(0<=e&&e<=4))throw new Error("Invalid log level");a=e},l.setLogger=function(e){c=e};var h=class e{constructor(e){this._name=e}debug(...t){a>=4&&c.debug(e._format(this._name,this._method),...t)}info(...t){a>=3&&c.info(e._format(this._name,this._method),...t)}warn(...t){a>=2&&c.warn(e._format(this._name,this._method),...t)}error(...t){a>=1&&c.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,r){const n=new e(`${t}.${r}`);return n.debug("begin"),n}static _format(e,t){const r=`[${e}]`;return t?`${r} ${t}:`:r}static debug(t,...r){a>=4&&c.debug(e._format(t),...r)}static info(t,...r){a>=3&&c.info(e._format(t),...r)}static warn(t,...r){a>=2&&c.warn(e._format(t),...r)}static error(t,...r){a>=1&&c.error(e._format(t),...r)}};d.reset();var p=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 r=!0===t.header?0:1,n=e.split(".")[r];if("string"!=typeof n)throw new i(`Invalid token specified: missing part #${r+1}`);let s;try{s=o(n)}catch(en){throw new i(`Invalid token specified: invalid base64 for part #${r+1} (${en.message})`)}try{return JSON.parse(s)}catch(en){throw new i(`Invalid token specified: invalid json for part #${r+1} (${en.message})`)}}(e)}catch(t){throw h.error("JwtUtils.decode",t),t}}static async generateSignedJwt(e,t,r){const n=`${m.encodeBase64Url((new TextEncoder).encode(JSON.stringify(e)))}.${m.encodeBase64Url((new TextEncoder).encode(JSON.stringify(t)))}`,s=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},r,(new TextEncoder).encode(n));return`${n}.${m.encodeBase64Url(new Uint8Array(s))}`}},f=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),r=await crypto.subtle.digest("SHA-256",t);return f(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(t){throw h.error("CryptoUtils.generateCodeChallenge",t),t}}static generateBasicAuth(e,t){const r=(new TextEncoder).encode([e,t].join(":"));return f(r)}static async hash(e,t){const r=(new TextEncoder).encode(t),n=await crypto.subtle.digest(e,r);return new Uint8Array(n)}static async customCalculateJwkThumbprint(t){let r;switch(t.kty){case"RSA":r={e:t.e,kty:t.kty,n:t.n};break;case"EC":r={crv:t.crv,kty:t.kty,x:t.x,y:t.y};break;case"OKP":r={crv:t.crv,kty:t.kty,x:t.x};break;case"oct":r={crv:t.k,kty:t.kty};break;default:throw new Error("Unknown jwk type")}const n=await e.hash("SHA-256",JSON.stringify(r));return e.encodeBase64Url(n)}static async generateDPoPProof({url:t,accessToken:r,httpMethod:n,keyPair:s,nonce:i}){let o,a;const c={jti:window.crypto.randomUUID(),htm:null!=n?n:"GET",htu:t,iat:Math.floor(Date.now()/1e3)};r&&(o=await e.hash("SHA-256",r),a=e.encodeBase64Url(o),c.ath=a),i&&(c.nonce=i);try{const e=await crypto.subtle.exportKey("jwk",s.publicKey),t={alg:"ES256",typ:"dpop+jwt",jwk:{crv:e.crv,kty:e.kty,x:e.x,y:e.y}};return await p.generateSignedJwt(t,c,s.privateKey)}catch(l){throw l instanceof TypeError?new Error(`Error exporting dpop public key: ${l.message}`):l}}static async generateDPoPJkt(t){try{const r=await crypto.subtle.exportKey("jwk",t.publicKey);return await e.customCalculateJwkThumbprint(r)}catch(r){throw r instanceof TypeError?new Error(`Could not retrieve dpop keys from storage: ${r.message}`):r}}static async generateDPoPKeys(){return await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign","verify"])}};g.encodeBase64Url=e=>f(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");var m=g,_=class{constructor(e){this._name=e,this._callbacks=[],this._logger=new h(`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)}},w=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 _{constructor(){super(...arguments),this._logger=new h(`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 r=this._logger.create("init");t=Math.max(Math.floor(t),1);const n=e.getEpochTime()+t;if(this.expiration===n&&this._timerHandle)return void r.debug("skipping since already initialized for expiration at",this.expiration);this.cancel(),r.debug("using duration",t),this._expiration=n;const s=Math.min(t,5);this._timerHandle=setInterval(this._callback,1e3*s)}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 r=new URL(e,"http://127.0.0.1")["fragment"===t?"hash":"search"];return new URLSearchParams(r.slice(1))}},S=";",v=class extends Error{constructor(e,t){var r,n,s;if(super(e.error_description||e.error||""),this.form=t,this.name="ErrorResponse",!e.error)throw h.error("ErrorResponse","No error passed"),new Error("No error passed");this.error=e.error,this.error_description=null!=(r=e.error_description)?r:null,this.error_uri=null!=(n=e.error_uri)?n:null,this.state=e.userState,this.session_state=null!=(s=e.session_state)?s:null,this.url_state=e.url_state}},E=class extends Error{constructor(e){super(e),this.name="ErrorTimeout"}},k=class{constructor(e){this._logger=new h("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 r=e.expires_in;if(t.debug("access token present, remaining duration:",r),r>0){let e=r-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 n=r+1;t.debug("registering expired timer, raising in",n,"seconds"),this._expiredTimer.init(n)}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)}},R=class{constructor(e,t,r,n,s){this._callback=e,this._client_id=t,this._intervalInSeconds=n,this._stopOnError=s,this._logger=new h("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(r);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)}},x=class{constructor(){this._logger=new h("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]}},T=class extends Error{constructor(e,t){super(t),this.name="ErrorDPoPNonce",this.nonce=e}},O=class{constructor(e=[],t=null,r={}){this._jwtHandler=t,this._extraHeaders=r,this._logger=new h("JsonService"),this._contentTypes=[],this._contentTypes.push(...e,"application/json"),t&&this._contentTypes.push("application/jwt")}async fetchWithTimeout(e,t={}){const{timeoutInSeconds:r,...n}=t;if(!r)return await fetch(e,n);const s=new AbortController,i=setTimeout((()=>s.abort()),1e3*r);try{return await fetch(e,{...t,signal:s.signal})}catch(o){if(o instanceof DOMException&&"AbortError"===o.name)throw new E("Network timed out");throw o}finally{clearTimeout(i)}}async getJson(e,{token:t,credentials:r,timeoutInSeconds:n}={}){const s=this._logger.create("getJson"),i={Accept:this._contentTypes.join(", ")};let o;t&&(s.debug("token passed, setting Authorization header"),i.Authorization="Bearer "+t),this._appendExtraHeaders(i);try{s.debug("url:",e),o=await this.fetchWithTimeout(e,{method:"GET",headers:i,timeoutInSeconds:n,credentials:r})}catch(l){throw s.error("Network Error"),l}s.debug("HTTP response received, status",o.status);const a=o.headers.get("Content-Type");if(a&&!this._contentTypes.find((e=>a.startsWith(e)))&&s.throw(new Error(`Invalid response Content-Type: ${null!=a?a:"undefined"}, from URL: ${e}`)),o.ok&&this._jwtHandler&&(null==a?void 0:a.startsWith("application/jwt")))return await this._jwtHandler(await o.text());let c;try{c=await o.json()}catch(l){if(s.error("Error parsing JSON response",l),o.ok)throw l;throw new Error(`${o.statusText} (${o.status})`)}if(!o.ok){if(s.error("Error from server:",c),c.error)throw new v(c);throw new Error(`${o.statusText} (${o.status}): ${JSON.stringify(c)}`)}return c}async postForm(e,{body:t,basicAuth:r,timeoutInSeconds:n,initCredentials:s,extraHeaders:i}){const o=this._logger.create("postForm"),a={Accept:this._contentTypes.join(", "),"Content-Type":"application/x-www-form-urlencoded",...i};let c;void 0!==r&&(a.Authorization="Basic "+r),this._appendExtraHeaders(a);try{o.debug("url:",e),c=await this.fetchWithTimeout(e,{method:"POST",headers:a,body:t,timeoutInSeconds:n,credentials:s})}catch(h){throw o.error("Network error"),h}o.debug("HTTP response received, status",c.status);const l=c.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 u=await c.text();let d={};if(u)try{d=JSON.parse(u)}catch(h){if(o.error("Error parsing JSON response",h),c.ok)throw h;throw new Error(`${c.statusText} (${c.status})`)}if(!c.ok){if(o.error("Error from server:",d),c.headers.has("dpop-nonce")){const e=c.headers.get("dpop-nonce");throw new T(e,`${JSON.stringify(d)}`)}if(d.error)throw new v(d,t);throw new Error(`${c.statusText} (${c.status}): ${JSON.stringify(d)}`)}return d}_appendExtraHeaders(e){const t=this._logger.create("appendExtraHeaders"),r=Object.keys(this._extraHeaders),n=["accept","content-type"],s=["authorization"];0!==r.length&&r.forEach((r=>{if(n.includes(r.toLocaleLowerCase()))return void t.warn("Protected header could not be set",r,n);if(s.includes(r.toLocaleLowerCase())&&Object.keys(e).includes(r))return void t.warn("Header could not be overridden",r,s);const i="function"==typeof this._extraHeaders[r]?this._extraHeaders[r]():this._extraHeaders[r];i&&""!==i&&(e[r]=i)}))}},A=class{constructor(e){this._settings=e,this._logger=new h("MetadataService"),this._signingKeys=null,this._metadata=null,this._metadataUrl=this._settings.metadataUrl,this._jsonService=new O(["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 r=this._logger.create(`_getMetadataProperty('${e}')`),n=await this.getMetadata();if(r.debug("resolved"),void 0===n[e]){if(!0===t)return void r.warn("Metadata does not contain optional property");r.throw(new Error("Metadata does not contain property "+e))}return n[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 r=await this._jsonService.getJson(t,{timeoutInSeconds:this._settings.requestTimeoutInSeconds});if(e.debug("got key set",r),!Array.isArray(r.keys))throw e.throw(new Error("Missing keys on keyset")),null;return this._signingKeys=r.keys,this._signingKeys}},C=class{constructor({prefix:e="oidc.",store:t=localStorage}={}){this._logger=new h("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 r=0;r<e;r++){const e=await this._store.key(r);e&&0===e.indexOf(this._prefix)&&t.push(e.substr(this._prefix.length))}return t}},N=class{constructor({authority:e,metadataUrl:t,metadata:r,signingKeys:n,metadataSeed:s,client_id:i,client_secret:o,response_type:a="code",scope:c="openid",redirect_uri:l,post_logout_redirect_uri:u,client_authentication:d="client_secret_post",prompt:h,display:p,max_age:f,ui_locales:g,acr_values:m,resource:_,response_mode:w,filterProtocolClaims:y=!0,loadUserInfo:b=!1,requestTimeoutInSeconds:S,staleStateAgeInSeconds:v=900,mergeClaimsStrategy:E={array:"replace"},disablePKCE:k=!1,stateStore:R,revokeTokenAdditionalContentTypes:T,fetchRequestCredentials:O,refreshTokenAllowedScope:A,extraQueryParams:N={},extraTokenParams:P={},extraHeaders:I={},dpop:U,omitScopeWhenRequesting:j=!1}){var L;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=r,this.metadataSeed=s,this.signingKeys=n,this.client_id=i,this.client_secret=o,this.response_type=a,this.scope=c,this.redirect_uri=l,this.post_logout_redirect_uri=u,this.client_authentication=d,this.prompt=h,this.display=p,this.max_age=f,this.ui_locales=g,this.acr_values=m,this.resource=_,this.response_mode=w,this.filterProtocolClaims=null==y||y,this.loadUserInfo=!!b,this.staleStateAgeInSeconds=v,this.mergeClaimsStrategy=E,this.omitScopeWhenRequesting=j,this.disablePKCE=!!k,this.revokeTokenAdditionalContentTypes=T,this.fetchRequestCredentials=O||"same-origin",this.requestTimeoutInSeconds=S,R)this.stateStore=R;else{const e="undefined"!=typeof window?window.localStorage:new x;this.stateStore=new C({store:e})}if(this.refreshTokenAllowedScope=A,this.extraQueryParams=N,this.extraTokenParams=P,this.extraHeaders=I,this.dpop=U,this.dpop&&!(null==(L=this.dpop)?void 0:L.store))throw new Error("A DPoPStore is required when dpop is enabled")}},P=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new h("UserInfoService"),this._getClaimsFromJwt=async e=>{const t=this._logger.create("_getClaimsFromJwt");try{const r=p.decode(e);return t.debug("JWT decoding successful"),r}catch(r){throw t.error("Error parsing JWT response"),r}},this._jsonService=new O(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 r=await this._metadataService.getUserInfoEndpoint();t.debug("got userinfo url",r);const n=await this._jsonService.getJson(r,{token:e,credentials:this._settings.fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return t.debug("got claims",n),n}},I=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new h("TokenClient"),this._jsonService=new O(this._settings.revokeTokenAdditionalContentTypes,null,this._settings.extraHeaders)}async exchangeCode({grant_type:e="authorization_code",redirect_uri:t=this._settings.redirect_uri,client_id:r=this._settings.client_id,client_secret:n=this._settings.client_secret,extraHeaders:s,...i}){const o=this._logger.create("exchangeCode");r||o.throw(new Error("A client_id is required")),t||o.throw(new Error("A redirect_uri is required")),i.code||o.throw(new Error("A code is required"));const a=new URLSearchParams({grant_type:e,redirect_uri:t});for(const[d,h]of Object.entries(i))null!=h&&a.set(d,h);let c;switch(this._settings.client_authentication){case"client_secret_basic":if(null==n)throw o.throw(new Error("A client_secret is required")),null;c=m.generateBasicAuth(r,n);break;case"client_secret_post":a.append("client_id",r),n&&a.append("client_secret",n)}const l=await this._metadataService.getTokenEndpoint(!1);o.debug("got token endpoint");const u=await this._jsonService.postForm(l,{body:a,basicAuth:c,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:s});return o.debug("got response"),u}async exchangeCredentials({grant_type:e="password",client_id:t=this._settings.client_id,client_secret:r=this._settings.client_secret,scope:n=this._settings.scope,...s}){const i=this._logger.create("exchangeCredentials");t||i.throw(new Error("A client_id is required"));const o=new URLSearchParams({grant_type:e});this._settings.omitScopeWhenRequesting||o.set("scope",n);for(const[u,d]of Object.entries(s))null!=d&&o.set(u,d);let a;switch(this._settings.client_authentication){case"client_secret_basic":if(null==r)throw i.throw(new Error("A client_secret is required")),null;a=m.generateBasicAuth(t,r);break;case"client_secret_post":o.append("client_id",t),r&&o.append("client_secret",r)}const c=await this._metadataService.getTokenEndpoint(!1);i.debug("got token endpoint");const l=await this._jsonService.postForm(c,{body:o,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:r=this._settings.client_secret,timeoutInSeconds:n,extraHeaders:s,...i}){const o=this._logger.create("exchangeRefreshToken");t||o.throw(new Error("A client_id is required")),i.refresh_token||o.throw(new Error("A refresh_token is required"));const a=new URLSearchParams({grant_type:e});for(const[d,h]of Object.entries(i))Array.isArray(h)?h.forEach((e=>a.append(d,e))):null!=h&&a.set(d,h);let c;switch(this._settings.client_authentication){case"client_secret_basic":if(null==r)throw o.throw(new Error("A client_secret is required")),null;c=m.generateBasicAuth(t,r);break;case"client_secret_post":a.append("client_id",t),r&&a.append("client_secret",r)}const l=await this._metadataService.getTokenEndpoint(!1);o.debug("got token endpoint");const u=await this._jsonService.postForm(l,{body:a,basicAuth:c,timeoutInSeconds:n,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:s});return o.debug("got response"),u}async revoke(e){var t;const r=this._logger.create("revoke");e.token||r.throw(new Error("A token is required"));const n=await this._metadataService.getRevocationEndpoint(!1);r.debug(`got revocation endpoint, revoking ${null!=(t=e.token_type_hint)?t:"default token type"}`);const s=new URLSearchParams;for(const[i,o]of Object.entries(e))null!=o&&s.set(i,o);s.set("client_id",this._settings.client_id),this._settings.client_secret&&s.set("client_secret",this._settings.client_secret),await this._jsonService.postForm(n,{body:s,timeoutInSeconds:this._settings.requestTimeoutInSeconds}),r.debug("got response")}},U=class{constructor(e,t,r){this._settings=e,this._metadataService=t,this._claimsService=r,this._logger=new h("ResponseValidator"),this._userInfoService=new P(this._settings,this._metadataService),this._tokenClient=new I(this._settings,this._metadataService)}async validateSigninResponse(e,t,r){const n=this._logger.create("validateSigninResponse");this._processSigninState(e,t),n.debug("state processed"),await this._processCode(e,t,r),n.debug("code processed"),e.isOpenId&&this._validateIdTokenAttributes(e),n.debug("tokens validated"),await this._processClaims(e,null==t?void 0:t.skipUserInfo,e.isOpenId),n.debug("claims processed")}async validateCredentialsResponse(e,t){const r=this._logger.create("validateCredentialsResponse"),n=e.isOpenId&&!!e.id_token;n&&this._validateIdTokenAttributes(e),r.debug("tokens validated"),await this._processClaims(e,t,n),r.debug("claims processed")}async validateRefreshResponse(e,t){const r=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),r.debug("ID Token validated")),e.id_token||(e.id_token=t.id_token,e.profile=t.profile);const n=e.isOpenId&&!!e.id_token;await this._processClaims(e,!1,n),r.debug("claims processed")}validateSignoutResponse(e,t){const r=this._logger.create("validateSignoutResponse");if(t.id!==e.state&&r.throw(new Error("State does not match")),r.debug("state validated"),e.userState=t.data,e.error)throw r.warn("Response was error",e.error),new v(e)}_processSigninState(e,t){const r=this._logger.create("_processSigninState");if(t.id!==e.state&&r.throw(new Error("State does not match")),t.client_id||r.throw(new Error("No client_id on state")),t.authority||r.throw(new Error("No authority on state")),this._settings.authority!==t.authority&&r.throw(new Error("authority mismatch on settings vs. signin state")),this._settings.client_id&&this._settings.client_id!==t.client_id&&r.throw(new Error("client_id mismatch on settings vs. signin state")),r.debug("state validated"),e.userState=t.data,e.url_state=t.url_state,null!=e.scope||(e.scope=t.scope),e.error)throw r.warn("Response was error",e.error),new v(e);t.code_verifier&&!e.code&&r.throw(new Error("Expected code in response"))}async _processClaims(e,t=!1,r=!0){const n=this._logger.create("_processClaims");if(e.profile=this._claimsService.filterProtocolClaims(e.profile),t||!this._settings.loadUserInfo||!e.access_token)return void n.debug("not loading user info");n.debug("loading user info");const s=await this._userInfoService.getClaims(e.access_token);n.debug("user info claims received from user info endpoint"),r&&s.sub!==e.profile.sub&&n.throw(new Error("subject from UserInfo response does not match subject in ID Token")),e.profile=this._claimsService.mergeClaims(e.profile,this._claimsService.filterProtocolClaims(s)),n.debug("user info claims received, updated profile:",e.profile)}async _processCode(e,t,r){const n=this._logger.create("_processCode");if(e.code){n.debug("Validating code");const s=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:r,...t.extraTokenParams});Object.assign(e,s)}else n.debug("No code to process")}_validateIdTokenAttributes(e,t){var r;const n=this._logger.create("_validateIdTokenAttributes");n.debug("decoding ID Token JWT");const s=p.decode(null!=(r=e.id_token)?r:"");if(s.sub||n.throw(new Error("ID Token is missing a subject claim")),t){const e=p.decode(t);s.sub!==e.sub&&n.throw(new Error("sub in id_token does not match current sub")),s.auth_time&&s.auth_time!==e.auth_time&&n.throw(new Error("auth_time in id_token does not match original auth_time")),s.azp&&s.azp!==e.azp&&n.throw(new Error("azp in id_token does not match original azp")),!s.azp&&e.azp&&n.throw(new Error("azp not in id_token, but present in original id_token"))}e.profile=s}},j=class e{constructor(e){this.id=e.id||m.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 h("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 h.createStatic("State","fromStorageString"),Promise.resolve(new e(JSON.parse(t)))}static async clearStaleState(t,r){const n=h.createStatic("State","clearStaleState"),s=y.getEpochTime()-r,i=await t.getAllKeys();n.debug("got keys",i);for(let a=0;a<i.length;a++){const r=i[a],c=await t.get(r);let l=!1;if(c)try{const t=await e.fromStorageString(c);n.debug("got item from key:",r,t.created),t.created<=s&&(l=!0)}catch(o){n.error("Error parsing state for key:",r,o),l=!0}else n.debug("no item in storage for key:",r),l=!0;l&&(n.debug("removed item for key:",r),t.remove(r))}}},L=class e extends j{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 r=!0===t.code_verifier?m.generateCodeVerifier():t.code_verifier||void 0,n=r?await m.generateCodeChallenge(r):void 0;return new e({...t,code_verifier:r,code_challenge:n})}toStorageString(){return new h("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){h.createStatic("SigninState","fromStorageString");const r=JSON.parse(t);return e.create(r)}},D=class e{constructor(e){this.url=e.url,this.state=e.state}static async create({url:t,authority:r,client_id:n,redirect_uri:s,response_type:i,scope:o,state_data:a,response_mode:c,request_type:l,client_secret:u,nonce:d,url_state:h,resource:p,skipUserInfo:f,extraQueryParams:g,extraTokenParams:m,disablePKCE:_,dpopJkt:w,omitScopeWhenRequesting:y,...b}){if(!t)throw this._logger.error("create: No url passed"),new Error("url");if(!n)throw this._logger.error("create: No client_id passed"),new Error("client_id");if(!s)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(!o)throw this._logger.error("create: No scope passed"),new Error("scope");if(!r)throw this._logger.error("create: No authority passed"),new Error("authority");const v=await L.create({data:a,request_type:l,url_state:h,code_verifier:!_,client_id:n,authority:r,redirect_uri:s,response_mode:c,client_secret:u,scope:o,extraTokenParams:m,skipUserInfo:f}),E=new URL(t);E.searchParams.append("client_id",n),E.searchParams.append("redirect_uri",s),E.searchParams.append("response_type",i),y||E.searchParams.append("scope",o),d&&E.searchParams.append("nonce",d),w&&E.searchParams.append("dpop_jkt",w);let k=v.id;if(h&&(k=`${k}${S}${h}`),E.searchParams.append("state",k),v.code_challenge&&(E.searchParams.append("code_challenge",v.code_challenge),E.searchParams.append("code_challenge_method","S256")),p){(Array.isArray(p)?p:[p]).forEach((e=>E.searchParams.append("resource",e)))}for(const[e,S]of Object.entries({response_mode:c,...b,...g}))null!=S&&E.searchParams.append(e,S.toString());return new e({url:E.href,state:v})}};D._logger=new h("SigninRequest");var F=D,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(S);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(S))}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}},q=class{constructor({url:e,state_data:t,id_token_hint:r,post_logout_redirect_uri:n,extraQueryParams:s,request_type:i,client_id:o,url_state:a}){if(this._logger=new h("SignoutRequest"),!e)throw this._logger.error("ctor: No url passed"),new Error("url");const c=new URL(e);if(r&&c.searchParams.append("id_token_hint",r),o&&c.searchParams.append("client_id",o),n&&(c.searchParams.append("post_logout_redirect_uri",n),t||a)){this.state=new j({data:t,request_type:i,url_state:a});let e=this.state.id;a&&(e=`${e}${S}${a}`),c.searchParams.append("state",e)}for(const[l,u]of Object.entries({...s}))null!=u&&c.searchParams.append(l,u.toString());this.url=c.href}},B=class{constructor(e){if(this.state=e.get("state"),this.state){const e=decodeURIComponent(this.state).split(S);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(S))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri")}},H=["nbf","jti","auth_time","nonce","acr","amr","azp","at_hash"],z=["sub","iss","aud","exp","iat"],W=class{constructor(e){this._settings=e,this._logger=new h("ClaimsService")}filterProtocolClaims(e){const t={...e};if(this._settings.filterProtocolClaims){let e;e=Array.isArray(this._settings.filterProtocolClaims)?this._settings.filterProtocolClaims:H;for(const r of e)z.includes(r)||delete t[r]}return t}mergeClaims(e,t){const r={...e};for(const[n,s]of Object.entries(t))if(r[n]!==s)if(Array.isArray(r[n])||Array.isArray(s))if("replace"==this._settings.mergeClaimsStrategy.array)r[n]=s;else{const e=Array.isArray(r[n])?r[n]:[r[n]];for(const t of Array.isArray(s)?s:[s])e.includes(t)||e.push(t);r[n]=e}else"object"==typeof r[n]&&"object"==typeof s?r[n]=this.mergeClaims(r[n],s):r[n]=s;return r}},$=class{constructor(e,t){this.keys=e,this.nonce=t}},K=class{constructor(e,t){this._logger=new h("OidcClient"),this.settings=e instanceof N?e:new N(e),this.metadataService=null!=t?t:new A(this.settings),this._claimsService=new W(this.settings),this._validator=new U(this.settings,this.metadataService,this._claimsService),this._tokenClient=new I(this.settings,this.metadataService)}async createSigninRequest({state:e,request:t,request_uri:r,request_type:n,id_token_hint:s,login_hint:i,skipUserInfo:o,nonce:a,url_state:c,response_type:l=this.settings.response_type,scope:u=this.settings.scope,redirect_uri:d=this.settings.redirect_uri,prompt:h=this.settings.prompt,display:p=this.settings.display,max_age:f=this.settings.max_age,ui_locales:g=this.settings.ui_locales,acr_values:m=this.settings.acr_values,resource:_=this.settings.resource,response_mode:w=this.settings.response_mode,extraQueryParams:y=this.settings.extraQueryParams,extraTokenParams:b=this.settings.extraTokenParams,dpopJkt:S,omitScopeWhenRequesting:v=this.settings.omitScopeWhenRequesting}){const E=this._logger.create("createSigninRequest");if("code"!==l)throw new Error("Only the Authorization Code flow (with PKCE) is supported");const k=await this.metadataService.getAuthorizationEndpoint();E.debug("Received authorization endpoint",k);const R=await F.create({url:k,authority:this.settings.authority,client_id:this.settings.client_id,redirect_uri:d,response_type:l,scope:u,state_data:e,url_state:c,prompt:h,display:p,max_age:f,ui_locales:g,id_token_hint:s,login_hint:i,acr_values:m,dpopJkt:S,resource:_,request:t,request_uri:r,extraQueryParams:y,extraTokenParams:b,request_type:n,response_mode:w,client_secret:this.settings.client_secret,skipUserInfo:o,nonce:a,disablePKCE:this.settings.disablePKCE,omitScopeWhenRequesting:v});await this.clearStaleState();const x=R.state;return await this.settings.stateStore.set(x.id,x.toStorageString()),R}async readSigninResponseState(e,t=!1){const r=this._logger.create("readSigninResponseState"),n=new M(b.readParams(e,this.settings.response_mode));if(!n.state)throw r.throw(new Error("No state in response")),null;const s=await this.settings.stateStore[t?"remove":"get"](n.state);if(!s)throw r.throw(new Error("No matching state found in storage")),null;return{state:await L.fromStorageString(s),response:n}}async processSigninResponse(e,t,r=!0){const n=this._logger.create("processSigninResponse"),{state:s,response:i}=await this.readSigninResponseState(e,r);if(n.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,s,t)}catch(o){if(!(o instanceof T&&this.settings.dpop))throw o;{const e=await this.getDpopProof(this.settings.dpop.store,o.nonce);t.DPoP=e,await this._validator.validateSigninResponse(i,s,t)}}return i}async getDpopProof(e,t){let r,n;return(await e.getAllKeys()).includes(this.settings.client_id)?(n=await e.get(this.settings.client_id),n.nonce!==t&&t&&(n.nonce=t,await e.set(this.settings.client_id,n))):(r=await m.generateDPoPKeys(),n=new $(r,t),await e.set(this.settings.client_id,n)),await m.generateDPoPProof({url:await this.metadataService.getTokenEndpoint(!1),httpMethod:"POST",keyPair:n.keys,nonce:n.nonce})}async processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:r=!1,extraTokenParams:n={}}){const s=await this._tokenClient.exchangeCredentials({username:e,password:t,...n}),i=new M(new URLSearchParams);return Object.assign(i,s),await this._validator.validateCredentialsResponse(i,r),i}async useRefreshToken({state:e,redirect_uri:t,resource:r,timeoutInSeconds:n,extraHeaders:s,extraTokenParams:i}){var o;const a=this._logger.create("useRefreshToken");let c,l;if(void 0===this.settings.refreshTokenAllowedScope)c=e.scope;else{const t=this.settings.refreshTokenAllowedScope.split(" ");c=((null==(o=e.scope)?void 0:o.split(" "))||[]).filter((e=>t.includes(e))).join(" ")}if(this.settings.dpop&&this.settings.dpop.store){const e=await this.getDpopProof(this.settings.dpop.store);s={...s,DPoP:e}}try{l=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:c,redirect_uri:t,resource:r,timeoutInSeconds:n,extraHeaders:s,...i})}catch(d){if(!(d instanceof T&&this.settings.dpop))throw d;s.DPoP=await this.getDpopProof(this.settings.dpop.store,d.nonce),l=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:c,redirect_uri:t,resource:r,timeoutInSeconds:n,extraHeaders:s,...i})}const u=new M(new URLSearchParams);return Object.assign(u,l),a.debug("validating response",u),await this._validator.validateRefreshResponse(u,{...e,scope:c}),u}async createSignoutRequest({state:e,id_token_hint:t,client_id:r,request_type:n,url_state:s,post_logout_redirect_uri:i=this.settings.post_logout_redirect_uri,extraQueryParams:o=this.settings.extraQueryParams}={}){const a=this._logger.create("createSignoutRequest"),c=await this.metadataService.getEndSessionEndpoint();if(!c)throw a.throw(new Error("No end session endpoint")),null;a.debug("Received end session endpoint",c),r||!i||t||(r=this.settings.client_id);const l=new q({url:c,id_token_hint:t,client_id:r,post_logout_redirect_uri:i,state_data:e,extraQueryParams:o,request_type:n,url_state:s});await this.clearStaleState();const u=l.state;return u&&(a.debug("Signout request has state to persist"),await this.settings.stateStore.set(u.id,u.toStorageString())),l}async readSignoutResponseState(e,t=!1){const r=this._logger.create("readSignoutResponseState"),n=new B(b.readParams(e,this.settings.response_mode));if(!n.state){if(r.debug("No state in response"),n.error)throw r.warn("Response was error:",n.error),new v(n);return{state:void 0,response:n}}const s=await this.settings.stateStore[t?"remove":"get"](n.state);if(!s)throw r.throw(new Error("No matching state found in storage")),null;return{state:await j.fromStorageString(s),response:n}}async processSignoutResponse(e){const t=this._logger.create("processSignoutResponse"),{state:r,response:n}=await this.readSignoutResponseState(e,!0);return r?(t.debug("Received state from storage; validating response"),this._validator.validateSignoutResponse(n,r)):t.debug("No state from storage; skipping response validation"),n}clearStaleState(){return this._logger.create("clearStaleState"),j.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})}},J=class{constructor(e){this._userManager=e,this._logger=new h("SessionMonitor"),this._start=async e=>{const t=e.session_state;if(!t)return;const r=this._logger.create("_start");if(e.profile?(this._sub=e.profile.sub,r.debug("session_state",t,", sub",this._sub)):(this._sub=void 0,r.debug("session_state",t,", anonymous user")),this._checkSessionIFrame)this._checkSessionIFrame.start(t);else try{const e=await this._userManager.metadataService.getCheckSessionIframe();if(e){r.debug("initializing check session iframe");const n=this._userManager.settings.client_id,s=this._userManager.settings.checkSessionIntervalInSeconds,i=this._userManager.settings.stopCheckSessionOnError,o=new R(this._callback,n,e,s,i);await o.load(),this._checkSessionIFrame=o,o.start(t)}else r.warn("no check session iframe found in the metadata")}catch(n){r.error("Error from getCheckSessionIframe:",n instanceof Error?n.message:n)}},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(r){e.error("error from querySessionStatus",r instanceof Error?r.message:r)}}),1e3)}},this._callback=async()=>{const e=this._logger.create("_callback");try{const t=await this._userManager.querySessionStatus();let r=!0;t&&this._checkSessionIFrame?t.sub===this._sub?(r=!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"),r?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 h("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 h.createStatic("User","fromStorageString"),new e(JSON.parse(t))}},G="oidc-client",X=class{constructor(){this._abort=new _("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:r,keepOpen:n}=await new Promise(((r,n)=>{const s=s=>{var i;const o=s.data,a=null!=(i=e.scriptOrigin)?i:window.location.origin;if(s.origin===a&&(null==o?void 0:o.source)===G){try{const r=b.readParams(o.url,e.response_mode).get("state");if(r||t.warn("no state found in response url"),s.source!==this._window&&r!==e.state)return}catch{this._dispose(),n(new Error("Invalid response from window"))}r(o)}};window.addEventListener("message",s,!1),this._disposeHandlers.add((()=>window.removeEventListener("message",s,!1)));const i=new BroadcastChannel(`oidc-client-popup-${e.state}`);i.addEventListener("message",s,!1),this._disposeHandlers.add((()=>i.close())),this._disposeHandlers.add(this._abort.addHandler((e=>{this._dispose(),n(e)})))}));return t.debug("got response from window"),this._dispose(),n||this.close(),{url:r}}_dispose(){this._logger.create("_dispose");for(const e of this._disposeHandlers)e();this._disposeHandlers.clear()}static _notifyParent(e,t,r=!1,n=window.location.origin){const s={source:G,url:t,keepOpen:r},i=new h("_notifyParent");if(e)i.debug("With parent. Using parent.postMessage."),e.postMessage(s,n);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 r=new BroadcastChannel(`oidc-client-popup-${e}`);r.postMessage(s),r.close()}}},Q={location:!1,toolbar:!1,height:640,closePopupWindowAfterInSeconds:-1},Y="_blank",Z=60,ee=2,te=class extends N{constructor(e){const{popup_redirect_uri:t=e.redirect_uri,popup_post_logout_redirect_uri:r=e.post_logout_redirect_uri,popupWindowFeatures:n=Q,popupWindowTarget:s=Y,redirectMethod:i="assign",redirectTarget:o="self",iframeNotifyParentOrigin:a=e.iframeNotifyParentOrigin,iframeScriptOrigin:c=e.iframeScriptOrigin,requestTimeoutInSeconds:l,silent_redirect_uri:u=e.redirect_uri,silentRequestTimeoutInSeconds:d,automaticSilentRenew:h=!0,validateSubOnSilentRenew:p=!0,includeIdTokenInSilentRenew:f=!1,monitorSession:g=!1,monitorAnonymousSession:m=!1,checkSessionIntervalInSeconds:_=ee,query_status_response_type:w="code",stopCheckSessionOnError:y=!0,revokeTokenTypes:b=["access_token","refresh_token"],revokeTokensOnSignout:S=!1,includeIdTokenInSilentSignout:v=!1,accessTokenExpiringNotificationTimeInSeconds:E=Z,userStore:k}=e;if(super(e),this.popup_redirect_uri=t,this.popup_post_logout_redirect_uri=r,this.popupWindowFeatures=n,this.popupWindowTarget=s,this.redirectMethod=i,this.redirectTarget=o,this.iframeNotifyParentOrigin=a,this.iframeScriptOrigin=c,this.silent_redirect_uri=u,this.silentRequestTimeoutInSeconds=d||l||10,this.automaticSilentRenew=h,this.validateSubOnSilentRenew=p,this.includeIdTokenInSilentRenew=f,this.monitorSession=g,this.monitorAnonymousSession=m,this.checkSessionIntervalInSeconds=_,this.stopCheckSessionOnError=y,this.query_status_response_type=w,this.revokeTokenTypes=b,this.revokeTokensOnSignout=S,this.includeIdTokenInSilentSignout=v,this.accessTokenExpiringNotificationTimeInSeconds=E,k)this.userStore=k;else{const e="undefined"!=typeof window?window.sessionStorage:new x;this.userStore=new C({store:e})}}},re=class e extends X{constructor({silentRequestTimeoutInSeconds:t=10}){super(),this._logger=new h("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 E("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 r=e.target;null==(t=r.parentNode)||t.removeChild(r),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)}},ne=class{constructor(e){this._settings=e,this._logger=new h("IFrameNavigator")}async prepare({silentRequestTimeoutInSeconds:e=this._settings.silentRequestTimeoutInSeconds}){return new re({silentRequestTimeoutInSeconds:e})}async callback(e){this._logger.create("callback"),re.notifyParent(e,this._settings.iframeNotifyParentOrigin)}},se=class extends X{constructor({popupWindowTarget:e=Y,popupWindowFeatures:t={},popupSignal:r}){super(),this._logger=new h("PopupWindow");const n=w.center({...Q,...t});this._window=window.open(void 0,e,w.serialize(n)),r&&r.addEventListener("abort",(()=>{var e;this._abort.raise(new Error(null!=(e=r.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 r=setInterval((()=>{this._window&&!this._window.closed||(this._logger.debug("Popup closed by user or isolated by redirect"),n(),this._disposeHandlers.delete(n))}),500),n=()=>clearInterval(r);return this._disposeHandlers.add(n),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 h("PopupNavigator")}async prepare({popupWindowFeatures:e=this._settings.popupWindowFeatures,popupWindowTarget:t=this._settings.popupWindowTarget,popupSignal:r}){return new se({popupWindowFeatures:e,popupWindowTarget:t,popupSignal:r})}async callback(e,{keepOpen:t=!1}){this._logger.create("callback"),se.notifyOpener(e,t)}},oe=class{constructor(e){this._settings=e,this._logger=new h("RedirectNavigator")}async prepare({redirectMethod:e=this._settings.redirectMethod,redirectTarget:t=this._settings.redirectTarget}){var r;this._logger.create("prepare");let n=window.self;"top"===t&&(n=null!=(r=window.top)?r:window.self);const s=n.location[e].bind(n.location);let i;return{navigate:async e=>{this._logger.create("navigate");const t=new Promise(((e,t)=>{i=t}));return s(e.url),await t},close:()=>{this._logger.create("close"),null==i||i(new Error("Redirect aborted")),n.stop()}}}async callback(){}},ae=class extends k{constructor(e){super({expiringNotificationTimeInSeconds:e.accessTokenExpiringNotificationTimeInSeconds}),this._logger=new h("UserManagerEvents"),this._userLoaded=new _("User loaded"),this._userUnloaded=new _("User unloaded"),this._silentRenewError=new _("Silent renew error"),this._userSignedIn=new _("User signed in"),this._userSignedOut=new _("User signed out"),this._userSessionChanged=new _("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()}},ce=class{constructor(e){this._userManager=e,this._logger=new h("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 E)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}},ue=class{constructor(e,t,r,n){this._logger=new h("UserManager"),this.settings=new te(e),this._client=new K(e),this._redirectNavigator=null!=t?t:new oe(this.settings),this._popupNavigator=null!=r?r:new ie(this.settings),this._iframeNavigator=null!=n?n:new ne(this.settings),this._events=new ae(this.settings),this._silentRenewService=new ce(this),this.settings.automaticSilentRenew&&this.startSilentRenew(),this._sessionMonitor=null,this.settings.monitorSession&&(this._sessionMonitor=new J(this))}get events(){return this._events}get metadataService(){return this._client.metadataService}async getUser(e=!1){const t=this._logger.create("getUser"),r=await this._loadUser();return r?(t.info("user loaded"),await this._events.load(r,e),r):(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:r,...n}=e;let s;(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(s=await this.generateDPoPJkt(this.settings.dpop));const i=await this._redirectNavigator.prepare({redirectMethod:r});await this._signinStart({request_type:"si:r",dpopJkt:s,...n},i)}async signinRedirectCallback(e=window.location.href){const t=this._logger.create("signinRedirectCallback"),r=await this._signinEnd(e);return r.profile&&r.profile.sub?t.info("success, signed in subject",r.profile.sub):t.info("no subject"),r}async signinResourceOwnerCredentials({username:e,password:t,skipUserInfo:r=!1}){const n=this._logger.create("signinResourceOwnerCredential"),s=await this._client.processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:r,extraTokenParams:this.settings.extraTokenParams});n.debug("got signin response");const i=await this._buildUser(s);return i.profile&&i.profile.sub?n.info("success, signed in subject",i.profile.sub):n.info("no subject"),i}async signinPopup(e={}){var t;const r=this._logger.create("signinPopup");let n;(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(n=await this.generateDPoPJkt(this.settings.dpop));const{popupWindowFeatures:s,popupWindowTarget:i,popupSignal:o,...a}=e,c=this.settings.popup_redirect_uri;c||r.throw(new Error("No popup_redirect_uri configured"));const l=await this._popupNavigator.prepare({popupWindowFeatures:s,popupWindowTarget:i,popupSignal:o}),u=await this._signin({request_type:"si:p",redirect_uri:c,display:"popup",dpopJkt:n,...a},l);return u&&(u.profile&&u.profile.sub?r.info("success, signed in subject",u.profile.sub):r.info("no subject")),u}async signinPopupCallback(e=window.location.href,t=!1){const r=this._logger.create("signinPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),r.info("success")}async signinSilent(e={}){var t,r;const n=this._logger.create("signinSilent"),{silentRequestTimeoutInSeconds:s,...i}=e;let o,a=await this._loadUser();if(null==a?void 0:a.refresh_token){n.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:s})}(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(o=await this.generateDPoPJkt(this.settings.dpop));const c=this.settings.silent_redirect_uri;let l;c||n.throw(new Error("No silent_redirect_uri configured")),a&&this.settings.validateSubOnSilentRenew&&(n.debug("subject prior to silent renew:",a.profile.sub),l=a.profile.sub);const u=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:s});return a=await this._signin({request_type:"si:s",redirect_uri:c,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?null==a?void 0:a.id_token:void 0,dpopJkt:o,...i},u,l),a&&((null==(r=a.profile)?void 0:r.sub)?n.info("success, signed in subject",a.profile.sub):n.info("no subject")),a}async _useRefreshToken(e){const t=await this._client.useRefreshToken({timeoutInSeconds:this.settings.silentRequestTimeoutInSeconds,...e}),r=new V({...e.state,...t});return await this.storeUser(r),await this._events.load(r),r}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:r}=await this._client.readSignoutResponseState(e);if(r)switch(r.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:r,...n}=e,s=this.settings.silent_redirect_uri;s||t.throw(new Error("No silent_redirect_uri configured"));const i=await this._loadUser(),o=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:r}),a=await this._signinStart({request_type:"si:s",redirect_uri:s,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,...n},o);try{const e={},r=await this._client.processSigninResponse(a.url,e);return t.debug("got signin response"),r.session_state&&r.profile.sub?(t.info("success for subject",r.profile.sub),{session_state:r.session_state,sub:r.profile.sub}):(t.info("success, user not authenticated"),null)}catch(c){if(this.settings.monitorAnonymousSession&&c instanceof v)switch(c.error){case"login_required":case"consent_required":case"interaction_required":case"account_selection_required":return t.info("success for anonymous user"),{session_state:c.session_state}}throw c}}async _signin(e,t,r){const n=await this._signinStart(e,t);return await this._signinEnd(n.url,r)}async _signinStart(e,t){const r=this._logger.create("_signinStart");try{const n=await this._client.createSigninRequest(e);return r.debug("got signin request"),await t.navigate({url:n.url,state:n.state.id,response_mode:n.state.response_mode,scriptOrigin:this.settings.iframeScriptOrigin})}catch(n){throw r.debug("error after preparing navigator, closing navigator window"),t.close(),n}}async _signinEnd(e,t){const r=this._logger.create("_signinEnd"),n=await this._client.processSigninResponse(e,{});r.debug("got signin response");return await this._buildUser(n,t)}async _buildUser(e,t){const r=this._logger.create("_buildUser"),n=new V(e);if(t){if(t!==n.profile.sub)throw r.debug("current user does not match user returned from signin. sub from signin:",n.profile.sub),new v({...e,error:"login_required"});r.debug("current user matches user returned from signin")}return await this.storeUser(n),r.debug("user stored"),await this._events.load(n),n}async signoutRedirect(e={}){const t=this._logger.create("signoutRedirect"),{redirectMethod:r,...n}=e,s=await this._redirectNavigator.prepare({redirectMethod:r});await this._signoutStart({request_type:"so:r",post_logout_redirect_uri:this.settings.post_logout_redirect_uri,...n},s),t.info("success")}async signoutRedirectCallback(e=window.location.href){const t=this._logger.create("signoutRedirectCallback"),r=await this._signoutEnd(e);return t.info("success"),r}async signoutPopup(e={}){const t=this._logger.create("signoutPopup"),{popupWindowFeatures:r,popupWindowTarget:n,popupSignal:s,...i}=e,o=this.settings.popup_post_logout_redirect_uri,a=await this._popupNavigator.prepare({popupWindowFeatures:r,popupWindowTarget:n,popupSignal:s});await this._signout({request_type:"so:p",post_logout_redirect_uri:o,state:null==o?void 0:{},...i},a),t.info("success")}async signoutPopupCallback(e=window.location.href,t=!1){const r=this._logger.create("signoutPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),r.info("success")}async _signout(e,t){const r=await this._signoutStart(e,t);return await this._signoutEnd(r.url)}async _signoutStart(e={},t){var r;const n=this._logger.create("_signoutStart");try{const s=await this._loadUser();n.debug("loaded current user from storage"),this.settings.revokeTokensOnSignout&&await this._revokeInternal(s);const i=e.id_token_hint||s&&s.id_token;i&&(n.debug("setting id_token_hint in signout request"),e.id_token_hint=i),await this.removeUser(),n.debug("user removed, creating signout request");const o=await this._client.createSignoutRequest(e);return n.debug("got signout request"),await t.navigate({url:o.url,state:null==(r=o.state)?void 0:r.id,scriptOrigin:this.settings.iframeScriptOrigin})}catch(s){throw n.debug("error after preparing navigator, closing navigator window"),t.close(),s}}async _signoutEnd(e){const t=this._logger.create("_signoutEnd"),r=await this._client.processSignoutResponse(e);return t.debug("got signout response"),r}async signoutSilent(e={}){var t;const r=this._logger.create("signoutSilent"),{silentRequestTimeoutInSeconds:n,...s}=e,i=this.settings.includeIdTokenInSilentSignout?null==(t=await this._loadUser())?void 0:t.id_token:void 0,o=this.settings.popup_post_logout_redirect_uri,a=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:n});await this._signout({request_type:"so:s",post_logout_redirect_uri:o,id_token_hint:i,...s},a),r.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 r=this._logger.create("_revokeInternal");if(!e)return;const n=t.filter((t=>"string"==typeof e[t]));if(n.length){for(const t of n)await this._client.revokeToken(e[t],t),r.info(`${t} revoked successfully`),"access_token"!==t&&(e[t]=null);await this.storeUser(e),r.debug("user stored"),await this._events.load(e)}else r.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 r=e.toStorageString();await this.settings.userStore.set(this._userStoreKey,r)}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,r,n){var s,i;const o=await(null==(i=null==(s=this.settings.dpop)?void 0:s.store)?void 0:i.get(this.settings.client_id));if(o)return await m.generateDPoPProof({url:e,accessToken:null==t?void 0:t.access_token,httpMethod:r,keyPair:o.keys,nonce:n})}async generateDPoPJkt(e){let t=await e.store.get(this.settings.client_id);if(!t){const r=await m.generateDPoPKeys();t=new $(r),await e.store.set(this.settings.client_id,t)}return await m.generateDPoPJkt(t.keys)}},de=s.createContext(void 0);de.displayName="AuthContext";var he={isLoading:!0,isAuthenticated:!1},pe=(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 r=t.error;return r.toString=()=>`${r.name}: ${r.message}`,{...e,isLoading:!1,error:r}}default:{const r=new TypeError(`unknown type ${t.type}`),n={name:r.name,message:r.message,innerError:r,stack:r.stack,source:"unknown",toString:()=>`${n.name}: ${n.message}`};return{...e,isLoading:!1,error:n}}}},fe=we("signinCallback","Sign-in failed"),ge=we("signoutCallback","Sign-out failed"),me=we("renewSilent","Renew silent failed");function _e(e,t){return{name:ye(e,"name",(()=>"Error")),message:ye(e,"message",(()=>t)),stack:ye(e,"stack",(()=>(new Error).stack)),innerError:e}}function we(e,t){return r=>({..._e(r,t),source:e})}function ye(e,t,r){if(e&&"object"==typeof e){const r=e[t];if("string"==typeof r)return r}return r()}var be=["clearStaleState","querySessionStatus","revokeTokens","startSilentRenew","stopSilentRenew"],Se=["signinPopup","signinSilent","signinRedirect","signinResourceOwnerCredentials","signoutPopup","signoutRedirect","signoutSilent"],ve=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.`)},Ee="undefined"==typeof window?null:ue,ke=e=>{const{children:t,onSigninCallback:r,skipSigninCallback:n,matchSignoutCallback:i,onSignoutCallback:o,onRemoveUser:a,userManager:c=null,...l}=e,[u]=s.useState((()=>null!=c?c:Ee?new Ee(l):{settings:l})),[d,h]=s.useReducer(pe,he),p=s.useMemo((()=>Object.assign({settings:u.settings,events:u.events},Object.fromEntries(be.map((e=>{var t,r;return[e,null!=(r=null==(t=u[e])?void 0:t.bind(u))?r:ve(e)]}))),Object.fromEntries(Se.map((e=>[e,u[e]?async t=>{h({type:"NAVIGATOR_INIT",method:e});try{return await u[e](t)}catch(r){return h({type:"ERROR",error:{..._e(r,`Unknown error while executing ${e}(...).`),source:e,args:t}}),null}finally{h({type:"NAVIGATOR_CLOSE"})}}:ve(e)]))))),[u]),f=s.useRef(!1);s.useEffect((()=>{u&&!f.current&&(f.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")))})()&&!n&&(e=await u.signinCallback(),r&&await r(e)),e=e||await u.getUser(),h({type:"INITIALISED",user:e})}catch(e){h({type:"ERROR",error:fe(e)})}try{if(i&&i(u.settings)){const e=await u.signoutCallback();o&&await o(e)}}catch(e){h({type:"ERROR",error:ge(e)})}})())}),[u,n,r,o,i]),s.useEffect((()=>{if(!u)return;const e=e=>{h({type:"USER_LOADED",user:e})};u.events.addUserLoaded(e);const t=()=>{h({type:"USER_UNLOADED"})};u.events.addUserUnloaded(t);const r=()=>{h({type:"USER_SIGNED_OUT"})};u.events.addUserSignedOut(r);const n=e=>{h({type:"ERROR",error:me(e)})};return u.events.addSilentRenewError(n),()=>{u.events.removeUserLoaded(e),u.events.removeUserUnloaded(t),u.events.removeUserSignedOut(r),u.events.removeSilentRenewError(n)}}),[u]);const g=s.useCallback((async()=>{await u.removeUser(),a&&await a()}),[u,a]),m=s.useMemo((()=>({...d,...p,removeUser:g})),[d,p,g]);return s.createElement(de.Provider,{value:m},t)},Re=()=>{const e=s.useContext(de);return e||console.warn("AuthProvider context is undefined, please verify you are calling useAuth() as child of a <AuthProvider> component."),e};function xe(e,t){return function(){return e.apply(t,arguments)}}const{toString:Te}=Object.prototype,{getPrototypeOf:Oe}=Object,{iterator:Ae,toStringTag:Ce}=Symbol,Ne=(e=>t=>{const r=Te.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),Pe=e=>(e=e.toLowerCase(),t=>Ne(t)===e),Ie=e=>t=>typeof t===e,{isArray:Ue}=Array,je=Ie("undefined");const Le=Pe("ArrayBuffer");const De=Ie("string"),Fe=Ie("function"),Me=Ie("number"),qe=e=>null!==e&&"object"==typeof e,Be=e=>{if("object"!==Ne(e))return!1;const t=Oe(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Ce in e||Ae in e)},He=Pe("Date"),ze=Pe("File"),We=Pe("Blob"),$e=Pe("FileList"),Ke=Pe("URLSearchParams"),[Je,Ve,Ge,Xe]=["ReadableStream","Request","Response","Headers"].map(Pe);function Qe(e,t,{allOwnKeys:r=!1}={}){if(null==e)return;let n,s;if("object"!=typeof e&&(e=[e]),Ue(e))for(n=0,s=e.length;n<s;n++)t.call(null,e[n],n,e);else{const s=r?Object.getOwnPropertyNames(e):Object.keys(e),i=s.length;let o;for(n=0;n<i;n++)o=s[n],t.call(null,e[o],o,e)}}function Ye(e,t){t=t.toLowerCase();const r=Object.keys(e);let n,s=r.length;for(;s-- >0;)if(n=r[s],t===n.toLowerCase())return n;return null}const Ze="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,et=e=>!je(e)&&e!==Ze;const tt=(e=>t=>e&&t instanceof e)("undefined"!=typeof Uint8Array&&Oe(Uint8Array)),rt=Pe("HTMLFormElement"),nt=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),st=Pe("RegExp"),it=(e,t)=>{const r=Object.getOwnPropertyDescriptors(e),n={};Qe(r,((r,s)=>{let i;!1!==(i=t(r,s,e))&&(n[s]=i||r)})),Object.defineProperties(e,n)};const ot=Pe("AsyncFunction"),at=(ct="function"==typeof setImmediate,lt=Fe(Ze.postMessage),ct?setImmediate:lt?(ut=`axios@${Math.random()}`,dt=[],Ze.addEventListener("message",(({source:e,data:t})=>{e===Ze&&t===ut&&dt.length&&dt.shift()()}),!1),e=>{dt.push(e),Ze.postMessage(ut,"*")}):e=>setTimeout(e));var ct,lt,ut,dt;const ht="undefined"!=typeof queueMicrotask?queueMicrotask.bind(Ze):"undefined"!=typeof process&&process.nextTick||at,pt={isArray:Ue,isArrayBuffer:Le,isBuffer:function(e){return null!==e&&!je(e)&&null!==e.constructor&&!je(e.constructor)&&Fe(e.constructor.isBuffer)&&e.constructor.isBuffer(e)},isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||Fe(e.append)&&("formdata"===(t=Ne(e))||"object"===t&&Fe(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&Le(e.buffer),t},isString:De,isNumber:Me,isBoolean:e=>!0===e||!1===e,isObject:qe,isPlainObject:Be,isReadableStream:Je,isRequest:Ve,isResponse:Ge,isHeaders:Xe,isUndefined:je,isDate:He,isFile:ze,isBlob:We,isRegExp:st,isFunction:Fe,isStream:e=>qe(e)&&Fe(e.pipe),isURLSearchParams:Ke,isTypedArray:tt,isFileList:$e,forEach:Qe,merge:function e(){const{caseless:t}=et(this)&&this||{},r={},n=(n,s)=>{const i=t&&Ye(r,s)||s;Be(r[i])&&Be(n)?r[i]=e(r[i],n):Be(n)?r[i]=e({},n):Ue(n)?r[i]=n.slice():r[i]=n};for(let s=0,i=arguments.length;s<i;s++)arguments[s]&&Qe(arguments[s],n);return r},extend:(e,t,r,{allOwnKeys:n}={})=>(Qe(t,((t,n)=>{r&&Fe(t)?e[n]=xe(t,r):e[n]=t}),{allOwnKeys:n}),e),trim:e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,r,n)=>{e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},toFlatObject:(e,t,r,n)=>{let s,i,o;const a={};if(t=t||{},null==e)return t;do{for(s=Object.getOwnPropertyNames(e),i=s.length;i-- >0;)o=s[i],n&&!n(o,e,t)||a[o]||(t[o]=e[o],a[o]=!0);e=!1!==r&&Oe(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},kindOf:Ne,kindOfTest:Pe,endsWith:(e,t,r)=>{e=String(e),(void 0===r||r>e.length)&&(r=e.length),r-=t.length;const n=e.indexOf(t,r);return-1!==n&&n===r},toArray:e=>{if(!e)return null;if(Ue(e))return e;let t=e.length;if(!Me(t))return null;const r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},forEachEntry:(e,t)=>{const r=(e&&e[Ae]).call(e);let n;for(;(n=r.next())&&!n.done;){const r=n.value;t.call(e,r[0],r[1])}},matchAll:(e,t)=>{let r;const n=[];for(;null!==(r=e.exec(t));)n.push(r);return n},isHTMLForm:rt,hasOwnProperty:nt,hasOwnProp:nt,reduceDescriptors:it,freezeMethods:e=>{it(e,((t,r)=>{if(Fe(e)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;const n=e[r];Fe(n)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")}))}))},toObjectSet:(e,t)=>{const r={},n=e=>{e.forEach((e=>{r[e]=!0}))};return Ue(e)?n(e):n(String(e).split(t)),r},toCamelCase:e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,(function(e,t,r){return t.toUpperCase()+r})),noop:()=>{},toFiniteNumber:(e,t)=>null!=e&&Number.isFinite(e=+e)?e:t,findKey:Ye,global:Ze,isContextDefined:et,isSpecCompliantForm:function(e){return!!(e&&Fe(e.append)&&"FormData"===e[Ce]&&e[Ae])},toJSONObject:e=>{const t=new Array(10),r=(e,n)=>{if(qe(e)){if(t.indexOf(e)>=0)return;if(!("toJSON"in e)){t[n]=e;const s=Ue(e)?[]:{};return Qe(e,((e,t)=>{const i=r(e,n+1);!je(i)&&(s[t]=i)})),t[n]=void 0,s}}return e};return r(e,0)},isAsyncFn:ot,isThenable:e=>e&&(qe(e)||Fe(e))&&Fe(e.then)&&Fe(e.catch),setImmediate:at,asap:ht,isIterable:e=>null!=e&&Fe(e[Ae])};function ft(e,t,r,n,s){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),n&&(this.request=n),s&&(this.response=s,this.status=s.status?s.status:null)}pt.inherits(ft,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:pt.toJSONObject(this.config),code:this.code,status:this.status}}});const gt=ft.prototype,mt={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach((e=>{mt[e]={value:e}})),Object.defineProperties(ft,mt),Object.defineProperty(gt,"isAxiosError",{value:!0}),ft.from=(e,t,r,n,s,i)=>{const o=Object.create(gt);return pt.toFlatObject(e,o,(function(e){return e!==Error.prototype}),(e=>"isAxiosError"!==e)),ft.call(o,e.message,t,r,n,s),o.cause=e,o.name=e.name,i&&Object.assign(o,i),o};function _t(e){return pt.isPlainObject(e)||pt.isArray(e)}function wt(e){return pt.endsWith(e,"[]")?e.slice(0,-2):e}function yt(e,t,r){return e?e.concat(t).map((function(e,t){return e=wt(e),!r&&t?"["+e+"]":e})).join(r?".":""):t}const bt=pt.toFlatObject(pt,{},null,(function(e){return/^is[A-Z]/.test(e)}));function St(e,t,r){if(!pt.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const n=(r=pt.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,(function(e,t){return!pt.isUndefined(t[e])}))).metaTokens,s=r.visitor||l,i=r.dots,o=r.indexes,a=(r.Blob||"undefined"!=typeof Blob&&Blob)&&pt.isSpecCompliantForm(t);if(!pt.isFunction(s))throw new TypeError("visitor must be a function");function c(e){if(null===e)return"";if(pt.isDate(e))return e.toISOString();if(pt.isBoolean(e))return e.toString();if(!a&&pt.isBlob(e))throw new ft("Blob is not supported. Use a Buffer instead.");return pt.isArrayBuffer(e)||pt.isTypedArray(e)?a&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function l(e,r,s){let a=e;if(e&&!s&&"object"==typeof e)if(pt.endsWith(r,"{}"))r=n?r:r.slice(0,-2),e=JSON.stringify(e);else if(pt.isArray(e)&&function(e){return pt.isArray(e)&&!e.some(_t)}(e)||(pt.isFileList(e)||pt.endsWith(r,"[]"))&&(a=pt.toArray(e)))return r=wt(r),a.forEach((function(e,n){!pt.isUndefined(e)&&null!==e&&t.append(!0===o?yt([r],n,i):null===o?r:r+"[]",c(e))})),!1;return!!_t(e)||(t.append(yt(s,r,i),c(e)),!1)}const u=[],d=Object.assign(bt,{defaultVisitor:l,convertValue:c,isVisitable:_t});if(!pt.isObject(e))throw new TypeError("data must be an object");return function e(r,n){if(!pt.isUndefined(r)){if(-1!==u.indexOf(r))throw Error("Circular reference detected in "+n.join("."));u.push(r),pt.forEach(r,(function(r,i){!0===(!(pt.isUndefined(r)||null===r)&&s.call(t,r,pt.isString(i)?i.trim():i,n,d))&&e(r,n?n.concat(i):[i])})),u.pop()}}(e),t}function vt(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,(function(e){return t[e]}))}function Et(e,t){this._pairs=[],e&&St(e,this,t)}const kt=Et.prototype;function Rt(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function xt(e,t,r){if(!t)return e;const n=r&&r.encode||Rt;pt.isFunction(r)&&(r={serialize:r});const s=r&&r.serialize;let i;if(i=s?s(t,r):pt.isURLSearchParams(t)?t.toString():new Et(t,r).toString(n),i){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+i}return e}kt.append=function(e,t){this._pairs.push([e,t])},kt.toString=function(e){const t=e?function(t){return e.call(this,t,vt)}:vt;return this._pairs.map((function(e){return t(e[0])+"="+t(e[1])}),"").join("&")};class Tt{constructor(){this.handlers=[]}use(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!r&&r.synchronous,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){pt.forEach(this.handlers,(function(t){null!==t&&e(t)}))}}const Ot={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},At={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:Et,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]},Ct="undefined"!=typeof window&&"undefined"!=typeof document,Nt="object"==typeof navigator&&navigator||void 0,Pt=Ct&&(!Nt||["ReactNative","NativeScript","NS"].indexOf(Nt.product)<0),It="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,Ut=Ct&&window.location.href||"http://localhost",jt={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Ct,hasStandardBrowserEnv:Pt,hasStandardBrowserWebWorkerEnv:It,navigator:Nt,origin:Ut},Symbol.toStringTag,{value:"Module"})),...At};function Lt(e){function t(e,r,n,s){let i=e[s++];if("__proto__"===i)return!0;const o=Number.isFinite(+i),a=s>=e.length;if(i=!i&&pt.isArray(n)?n.length:i,a)return pt.hasOwnProp(n,i)?n[i]=[n[i],r]:n[i]=r,!o;n[i]&&pt.isObject(n[i])||(n[i]=[]);return t(e,r,n[i],s)&&pt.isArray(n[i])&&(n[i]=function(e){const t={},r=Object.keys(e);let n;const s=r.length;let i;for(n=0;n<s;n++)i=r[n],t[i]=e[i];return t}(n[i])),!o}if(pt.isFormData(e)&&pt.isFunction(e.entries)){const r={};return pt.forEachEntry(e,((e,n)=>{t(function(e){return pt.matchAll(/\w+|\[(\w*)]/g,e).map((e=>"[]"===e[0]?"":e[1]||e[0]))}(e),n,r,0)})),r}return null}const Dt={transitional:Ot,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const r=t.getContentType()||"",n=r.indexOf("application/json")>-1,s=pt.isObject(e);s&&pt.isHTMLForm(e)&&(e=new FormData(e));if(pt.isFormData(e))return n?JSON.stringify(Lt(e)):e;if(pt.isArrayBuffer(e)||pt.isBuffer(e)||pt.isStream(e)||pt.isFile(e)||pt.isBlob(e)||pt.isReadableStream(e))return e;if(pt.isArrayBufferView(e))return e.buffer;if(pt.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let i;if(s){if(r.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return St(e,new jt.classes.URLSearchParams,Object.assign({visitor:function(e,t,r,n){return jt.isNode&&pt.isBuffer(e)?(this.append(t,e.toString("base64")),!1):n.defaultVisitor.apply(this,arguments)}},t))}(e,this.formSerializer).toString();if((i=pt.isFileList(e))||r.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return St(i?{"files[]":e}:e,t&&new t,this.formSerializer)}}return s||n?(t.setContentType("application/json",!1),function(e,t,r){if(pt.isString(e))try{return(t||JSON.parse)(e),pt.trim(e)}catch(en){if("SyntaxError"!==en.name)throw en}return(r||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||Dt.transitional,r=t&&t.forcedJSONParsing,n="json"===this.responseType;if(pt.isResponse(e)||pt.isReadableStream(e))return e;if(e&&pt.isString(e)&&(r&&!this.responseType||n)){const r=!(t&&t.silentJSONParsing)&&n;try{return JSON.parse(e)}catch(en){if(r){if("SyntaxError"===en.name)throw ft.from(en,ft.ERR_BAD_RESPONSE,this,null,this.response);throw en}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:jt.classes.FormData,Blob:jt.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};pt.forEach(["delete","get","head","post","put","patch"],(e=>{Dt.headers[e]={}}));const Ft=pt.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),Mt=Symbol("internals");function qt(e){return e&&String(e).trim().toLowerCase()}function Bt(e){return!1===e||null==e?e:pt.isArray(e)?e.map(Bt):String(e)}function Ht(e,t,r,n,s){return pt.isFunction(n)?n.call(this,t,r):(s&&(t=r),pt.isString(t)?pt.isString(n)?-1!==t.indexOf(n):pt.isRegExp(n)?n.test(t):void 0:void 0)}let zt=class{constructor(e){e&&this.set(e)}set(e,t,r){const n=this;function s(e,t,r){const s=qt(t);if(!s)throw new Error("header name must be a non-empty string");const i=pt.findKey(n,s);(!i||void 0===n[i]||!0===r||void 0===r&&!1!==n[i])&&(n[i||t]=Bt(e))}const i=(e,t)=>pt.forEach(e,((e,r)=>s(e,r,t)));if(pt.isPlainObject(e)||e instanceof this.constructor)i(e,t);else if(pt.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim()))i((e=>{const t={};let r,n,s;return e&&e.split("\n").forEach((function(e){s=e.indexOf(":"),r=e.substring(0,s).trim().toLowerCase(),n=e.substring(s+1).trim(),!r||t[r]&&Ft[r]||("set-cookie"===r?t[r]?t[r].push(n):t[r]=[n]:t[r]=t[r]?t[r]+", "+n:n)})),t})(e),t);else if(pt.isObject(e)&&pt.isIterable(e)){let r,n,s={};for(const t of e){if(!pt.isArray(t))throw TypeError("Object iterator must return a key-value pair");s[n=t[0]]=(r=s[n])?pt.isArray(r)?[...r,t[1]]:[r,t[1]]:t[1]}i(s,t)}else null!=e&&s(t,e,r);return this}get(e,t){if(e=qt(e)){const r=pt.findKey(this,e);if(r){const e=this[r];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=r.exec(e);)t[n[1]]=n[2];return t}(e);if(pt.isFunction(t))return t.call(this,e,r);if(pt.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=qt(e)){const r=pt.findKey(this,e);return!(!r||void 0===this[r]||t&&!Ht(0,this[r],r,t))}return!1}delete(e,t){const r=this;let n=!1;function s(e){if(e=qt(e)){const s=pt.findKey(r,e);!s||t&&!Ht(0,r[s],s,t)||(delete r[s],n=!0)}}return pt.isArray(e)?e.forEach(s):s(e),n}clear(e){const t=Object.keys(this);let r=t.length,n=!1;for(;r--;){const s=t[r];e&&!Ht(0,this[s],s,e,!0)||(delete this[s],n=!0)}return n}normalize(e){const t=this,r={};return pt.forEach(this,((n,s)=>{const i=pt.findKey(r,s);if(i)return t[i]=Bt(n),void delete t[s];const o=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,((e,t,r)=>t.toUpperCase()+r))}(s):String(s).trim();o!==s&&delete t[s],t[o]=Bt(n),r[o]=!0})),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return pt.forEach(this,((r,n)=>{null!=r&&!1!==r&&(t[n]=e&&pt.isArray(r)?r.join(", "):r)})),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map((([e,t])=>e+": "+t)).join("\n")}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const r=new this(e);return t.forEach((e=>r.set(e))),r}static accessor(e){const t=(this[Mt]=this[Mt]={accessors:{}}).accessors,r=this.prototype;function n(e){const n=qt(e);t[n]||(!function(e,t){const r=pt.toCamelCase(" "+t);["get","set","has"].forEach((n=>{Object.defineProperty(e,n+r,{value:function(e,r,s){return this[n].call(this,t,e,r,s)},configurable:!0})}))}(r,e),t[n]=!0)}return pt.isArray(e)?e.forEach(n):n(e),this}};function Wt(e,t){const r=this||Dt,n=t||r,s=zt.from(n.headers);let i=n.data;return pt.forEach(e,(function(e){i=e.call(r,i,s.normalize(),t?t.status:void 0)})),s.normalize(),i}function $t(e){return!(!e||!e.__CANCEL__)}function Kt(e,t,r){ft.call(this,null==e?"canceled":e,ft.ERR_CANCELED,t,r),this.name="CanceledError"}function Jt(e,t,r){const n=r.config.validateStatus;r.status&&n&&!n(r.status)?t(new ft("Request failed with status code "+r.status,[ft.ERR_BAD_REQUEST,ft.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):e(r)}zt.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),pt.reduceDescriptors(zt.prototype,(({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[r]=e}}})),pt.freezeMethods(zt),pt.inherits(Kt,ft,{__CANCEL__:!0});const Vt=(e,t,r=3)=>{let n=0;const s=function(e,t){e=e||10;const r=new Array(e),n=new Array(e);let s,i=0,o=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),l=n[o];s||(s=c),r[i]=a,n[i]=c;let u=o,d=0;for(;u!==i;)d+=r[u++],u%=e;if(i=(i+1)%e,i===o&&(o=(o+1)%e),c-s<t)return;const h=l&&c-l;return h?Math.round(1e3*d/h):void 0}}(50,250);return function(e,t){let r,n,s=0,i=1e3/t;const o=(t,i=Date.now())=>{s=i,r=null,n&&(clearTimeout(n),n=null),e.apply(null,t)};return[(...e)=>{const t=Date.now(),a=t-s;a>=i?o(e,t):(r=e,n||(n=setTimeout((()=>{n=null,o(r)}),i-a)))},()=>r&&o(r)]}((r=>{const i=r.loaded,o=r.lengthComputable?r.total:void 0,a=i-n,c=s(a);n=i;e({loaded:i,total:o,progress:o?i/o:void 0,bytes:a,rate:c||void 0,estimated:c&&o&&i<=o?(o-i)/c:void 0,event:r,lengthComputable:null!=o,[t?"download":"upload"]:!0})}),r)},Gt=(e,t)=>{const r=null!=e;return[n=>t[0]({lengthComputable:r,total:e,loaded:n}),t[1]]},Xt=e=>(...t)=>pt.asap((()=>e(...t))),Qt=jt.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,jt.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(jt.origin),jt.navigator&&/(msie|trident)/i.test(jt.navigator.userAgent)):()=>!0,Yt=jt.hasStandardBrowserEnv?{write(e,t,r,n,s,i){const o=[e+"="+encodeURIComponent(t)];pt.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),pt.isString(n)&&o.push("path="+n),pt.isString(s)&&o.push("domain="+s),!0===i&&o.push("secure"),document.cookie=o.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read:()=>null,remove(){}};function Zt(e,t,r){let n=!/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t);return e&&(n||0==r)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}const er=e=>e instanceof zt?{...e}:e;function tr(e,t){t=t||{};const r={};function n(e,t,r,n){return pt.isPlainObject(e)&&pt.isPlainObject(t)?pt.merge.call({caseless:n},e,t):pt.isPlainObject(t)?pt.merge({},t):pt.isArray(t)?t.slice():t}function s(e,t,r,s){return pt.isUndefined(t)?pt.isUndefined(e)?void 0:n(void 0,e,0,s):n(e,t,0,s)}function i(e,t){if(!pt.isUndefined(t))return n(void 0,t)}function o(e,t){return pt.isUndefined(t)?pt.isUndefined(e)?void 0:n(void 0,e):n(void 0,t)}function a(r,s,i){return i in t?n(r,s):i in e?n(void 0,r):void 0}const c={url:i,method:i,data:i,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:a,headers:(e,t,r)=>s(er(e),er(t),0,!0)};return pt.forEach(Object.keys(Object.assign({},e,t)),(function(n){const i=c[n]||s,o=i(e[n],t[n],n);pt.isUndefined(o)&&i!==a||(r[n]=o)})),r}const rr=e=>{const t=tr({},e);let r,{data:n,withXSRFToken:s,xsrfHeaderName:i,xsrfCookieName:o,headers:a,auth:c}=t;if(t.headers=a=zt.from(a),t.url=xt(Zt(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&a.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),pt.isFormData(n))if(jt.hasStandardBrowserEnv||jt.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if(!1!==(r=a.getContentType())){const[e,...t]=r?r.split(";").map((e=>e.trim())).filter(Boolean):[];a.setContentType([e||"multipart/form-data",...t].join("; "))}if(jt.hasStandardBrowserEnv&&(s&&pt.isFunction(s)&&(s=s(t)),s||!1!==s&&Qt(t.url))){const e=i&&o&&Yt.read(o);e&&a.set(i,e)}return t},nr="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise((function(t,r){const n=rr(e);let s=n.data;const i=zt.from(n.headers).normalize();let o,a,c,l,u,{responseType:d,onUploadProgress:h,onDownloadProgress:p}=n;function f(){l&&l(),u&&u(),n.cancelToken&&n.cancelToken.unsubscribe(o),n.signal&&n.signal.removeEventListener("abort",o)}let g=new XMLHttpRequest;function m(){if(!g)return;const n=zt.from("getAllResponseHeaders"in g&&g.getAllResponseHeaders());Jt((function(e){t(e),f()}),(function(e){r(e),f()}),{data:d&&"text"!==d&&"json"!==d?g.response:g.responseText,status:g.status,statusText:g.statusText,headers:n,config:e,request:g}),g=null}g.open(n.method.toUpperCase(),n.url,!0),g.timeout=n.timeout,"onloadend"in g?g.onloadend=m:g.onreadystatechange=function(){g&&4===g.readyState&&(0!==g.status||g.responseURL&&0===g.responseURL.indexOf("file:"))&&setTimeout(m)},g.onabort=function(){g&&(r(new ft("Request aborted",ft.ECONNABORTED,e,g)),g=null)},g.onerror=function(){r(new ft("Network Error",ft.ERR_NETWORK,e,g)),g=null},g.ontimeout=function(){let t=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded";const s=n.transitional||Ot;n.timeoutErrorMessage&&(t=n.timeoutErrorMessage),r(new ft(t,s.clarifyTimeoutError?ft.ETIMEDOUT:ft.ECONNABORTED,e,g)),g=null},void 0===s&&i.setContentType(null),"setRequestHeader"in g&&pt.forEach(i.toJSON(),(function(e,t){g.setRequestHeader(t,e)})),pt.isUndefined(n.withCredentials)||(g.withCredentials=!!n.withCredentials),d&&"json"!==d&&(g.responseType=n.responseType),p&&([c,u]=Vt(p,!0),g.addEventListener("progress",c)),h&&g.upload&&([a,l]=Vt(h),g.upload.addEventListener("progress",a),g.upload.addEventListener("loadend",l)),(n.cancelToken||n.signal)&&(o=t=>{g&&(r(!t||t.type?new Kt(null,e,g):t),g.abort(),g=null)},n.cancelToken&&n.cancelToken.subscribe(o),n.signal&&(n.signal.aborted?o():n.signal.addEventListener("abort",o)));const _=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(n.url);_&&-1===jt.protocols.indexOf(_)?r(new ft("Unsupported protocol "+_+":",ft.ERR_BAD_REQUEST,e)):g.send(s||null)}))},sr=(e,t)=>{const{length:r}=e=e?e.filter(Boolean):[];if(t||r){let r,n=new AbortController;const s=function(e){if(!r){r=!0,o();const t=e instanceof Error?e:this.reason;n.abort(t instanceof ft?t:new Kt(t instanceof Error?t.message:t))}};let i=t&&setTimeout((()=>{i=null,s(new ft(`timeout ${t} of ms exceeded`,ft.ETIMEDOUT))}),t);const o=()=>{e&&(i&&clearTimeout(i),i=null,e.forEach((e=>{e.unsubscribe?e.unsubscribe(s):e.removeEventListener("abort",s)})),e=null)};e.forEach((e=>e.addEventListener("abort",s)));const{signal:a}=n;return a.unsubscribe=()=>pt.asap(o),a}},ir=function*(e,t){let r=e.byteLength;if(r<t)return void(yield e);let n,s=0;for(;s<r;)n=s+t,yield e.slice(s,n),s=n},or=async function*(e){if(e[Symbol.asyncIterator])return void(yield*e);const t=e.getReader();try{for(;;){const{done:e,value:r}=await t.read();if(e)break;yield r}}finally{await t.cancel()}},ar=(e,t,r,n)=>{const s=async function*(e,t){for await(const r of or(e))yield*ir(r,t)}(e,t);let i,o=0,a=e=>{i||(i=!0,n&&n(e))};return new ReadableStream({async pull(e){try{const{done:t,value:n}=await s.next();if(t)return a(),void e.close();let i=n.byteLength;if(r){let e=o+=i;r(e)}e.enqueue(new Uint8Array(n))}catch(t){throw a(t),t}},cancel:e=>(a(e),s.return())},{highWaterMark:2})},cr="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,lr=cr&&"function"==typeof ReadableStream,ur=cr&&("function"==typeof TextEncoder?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),dr=(e,...t)=>{try{return!!e(...t)}catch(en){return!1}},hr=lr&&dr((()=>{let e=!1;const t=new Request(jt.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t})),pr=lr&&dr((()=>pt.isReadableStream(new Response("").body))),fr={stream:pr&&(e=>e.body)};var gr;cr&&(gr=new Response,["text","arrayBuffer","blob","formData","stream"].forEach((e=>{!fr[e]&&(fr[e]=pt.isFunction(gr[e])?t=>t[e]():(t,r)=>{throw new ft(`Response type '${e}' is not supported`,ft.ERR_NOT_SUPPORT,r)})})));const mr=async(e,t)=>{const r=pt.toFiniteNumber(e.getContentLength());return null==r?(async e=>{if(null==e)return 0;if(pt.isBlob(e))return e.size;if(pt.isSpecCompliantForm(e)){const t=new Request(jt.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return pt.isArrayBufferView(e)||pt.isArrayBuffer(e)?e.byteLength:(pt.isURLSearchParams(e)&&(e+=""),pt.isString(e)?(await ur(e)).byteLength:void 0)})(t):r},_r={http:null,xhr:nr,fetch:cr&&(async e=>{let{url:t,method:r,data:n,signal:s,cancelToken:i,timeout:o,onDownloadProgress:a,onUploadProgress:c,responseType:l,headers:u,withCredentials:d="same-origin",fetchOptions:h}=rr(e);l=l?(l+"").toLowerCase():"text";let p,f=sr([s,i&&i.toAbortSignal()],o);const g=f&&f.unsubscribe&&(()=>{f.unsubscribe()});let m;try{if(c&&hr&&"get"!==r&&"head"!==r&&0!==(m=await mr(u,n))){let e,r=new Request(t,{method:"POST",body:n,duplex:"half"});if(pt.isFormData(n)&&(e=r.headers.get("content-type"))&&u.setContentType(e),r.body){const[e,t]=Gt(m,Vt(Xt(c)));n=ar(r.body,65536,e,t)}}pt.isString(d)||(d=d?"include":"omit");const s="credentials"in Request.prototype;p=new Request(t,{...h,signal:f,method:r.toUpperCase(),headers:u.normalize().toJSON(),body:n,duplex:"half",credentials:s?d:void 0});let i=await fetch(p,h);const o=pr&&("stream"===l||"response"===l);if(pr&&(a||o&&g)){const e={};["status","statusText","headers"].forEach((t=>{e[t]=i[t]}));const t=pt.toFiniteNumber(i.headers.get("content-length")),[r,n]=a&&Gt(t,Vt(Xt(a),!0))||[];i=new Response(ar(i.body,65536,r,(()=>{n&&n(),g&&g()})),e)}l=l||"text";let _=await fr[pt.findKey(fr,l)||"text"](i,e);return!o&&g&&g(),await new Promise(((t,r)=>{Jt(t,r,{data:_,headers:zt.from(i.headers),status:i.status,statusText:i.statusText,config:e,request:p})}))}catch(_){if(g&&g(),_&&"TypeError"===_.name&&/Load failed|fetch/i.test(_.message))throw Object.assign(new ft("Network Error",ft.ERR_NETWORK,e,p),{cause:_.cause||_});throw ft.from(_,_&&_.code,e,p)}})};pt.forEach(_r,((e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(en){}Object.defineProperty(e,"adapterName",{value:t})}}));const wr=e=>`- ${e}`,yr=e=>pt.isFunction(e)||null===e||!1===e,br=e=>{e=pt.isArray(e)?e:[e];const{length:t}=e;let r,n;const s={};for(let i=0;i<t;i++){let t;if(r=e[i],n=r,!yr(r)&&(n=_r[(t=String(r)).toLowerCase()],void 0===n))throw new ft(`Unknown adapter '${t}'`);if(n)break;s[t||"#"+i]=n}if(!n){const e=Object.entries(s).map((([e,t])=>`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build")));throw new ft("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(wr).join("\n"):" "+wr(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return n};function Sr(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Kt(null,e)}function vr(e){Sr(e),e.headers=zt.from(e.headers),e.data=Wt.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return br(e.adapter||Dt.adapter)(e).then((function(t){return Sr(e),t.data=Wt.call(e,e.transformResponse,t),t.headers=zt.from(t.headers),t}),(function(t){return $t(t)||(Sr(e),t&&t.response&&(t.response.data=Wt.call(e,e.transformResponse,t.response),t.response.headers=zt.from(t.response.headers))),Promise.reject(t)}))}const Er="1.10.0",kr={};["object","boolean","number","function","string","symbol"].forEach(((e,t)=>{kr[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}}));const Rr={};kr.transitional=function(e,t,r){function n(e,t){return"[Axios v"+Er+"] Transitional option '"+e+"'"+t+(r?". "+r:"")}return(r,s,i)=>{if(!1===e)throw new ft(n(s," has been removed"+(t?" in "+t:"")),ft.ERR_DEPRECATED);return t&&!Rr[s]&&(Rr[s]=!0,console.warn(n(s," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,s,i)}},kr.spelling=function(e){return(t,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};const xr={assertOptions:function(e,t,r){if("object"!=typeof e)throw new ft("options must be an object",ft.ERR_BAD_OPTION_VALUE);const n=Object.keys(e);let s=n.length;for(;s-- >0;){const i=n[s],o=t[i];if(o){const t=e[i],r=void 0===t||o(t,i,e);if(!0!==r)throw new ft("option "+i+" must be "+r,ft.ERR_BAD_OPTION_VALUE)}else if(!0!==r)throw new ft("Unknown option "+i,ft.ERR_BAD_OPTION)}},validators:kr},Tr=xr.validators;let Or=class{constructor(e){this.defaults=e||{},this.interceptors={request:new Tt,response:new Tt}}async request(e,t){try{return await this._request(e,t)}catch(r){if(r instanceof Error){let e={};Error.captureStackTrace?Error.captureStackTrace(e):e=new Error;const t=e.stack?e.stack.replace(/^.+\n/,""):"";try{r.stack?t&&!String(r.stack).endsWith(t.replace(/^.+\n.+\n/,""))&&(r.stack+="\n"+t):r.stack=t}catch(en){}}throw r}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=tr(this.defaults,t);const{transitional:r,paramsSerializer:n,headers:s}=t;void 0!==r&&xr.assertOptions(r,{silentJSONParsing:Tr.transitional(Tr.boolean),forcedJSONParsing:Tr.transitional(Tr.boolean),clarifyTimeoutError:Tr.transitional(Tr.boolean)},!1),null!=n&&(pt.isFunction(n)?t.paramsSerializer={serialize:n}:xr.assertOptions(n,{encode:Tr.function,serialize:Tr.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),xr.assertOptions(t,{baseUrl:Tr.spelling("baseURL"),withXsrfToken:Tr.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let i=s&&pt.merge(s.common,s[t.method]);s&&pt.forEach(["delete","get","head","post","put","patch","common"],(e=>{delete s[e]})),t.headers=zt.concat(i,s);const o=[];let a=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(a=a&&e.synchronous,o.unshift(e.fulfilled,e.rejected))}));const c=[];let l;this.interceptors.response.forEach((function(e){c.push(e.fulfilled,e.rejected)}));let u,d=0;if(!a){const e=[vr.bind(this),void 0];for(e.unshift.apply(e,o),e.push.apply(e,c),u=e.length,l=Promise.resolve(t);d<u;)l=l.then(e[d++],e[d++]);return l}u=o.length;let h=t;for(d=0;d<u;){const e=o[d++],t=o[d++];try{h=e(h)}catch(p){t.call(this,p);break}}try{l=vr.call(this,h)}catch(p){return Promise.reject(p)}for(d=0,u=c.length;d<u;)l=l.then(c[d++],c[d++]);return l}getUri(e){return xt(Zt((e=tr(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}};pt.forEach(["delete","get","head","options"],(function(e){Or.prototype[e]=function(t,r){return this.request(tr(r||{},{method:e,url:t,data:(r||{}).data}))}})),pt.forEach(["post","put","patch"],(function(e){function t(t){return function(r,n,s){return this.request(tr(s||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:r,data:n}))}}Or.prototype[e]=t(),Or.prototype[e+"Form"]=t(!0)}));const Ar={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(Ar).forEach((([e,t])=>{Ar[t]=e}));const Cr=function e(t){const r=new Or(t),n=xe(Or.prototype.request,r);return pt.extend(n,Or.prototype,r,{allOwnKeys:!0}),pt.extend(n,r,null,{allOwnKeys:!0}),n.create=function(r){return e(tr(t,r))},n}(Dt);Cr.Axios=Or,Cr.CanceledError=Kt,Cr.CancelToken=class e{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new Promise((function(e){t=e}));const r=this;this.promise.then((e=>{if(!r._listeners)return;let t=r._listeners.length;for(;t-- >0;)r._listeners[t](e);r._listeners=null})),this.promise.then=e=>{let t;const n=new Promise((e=>{r.subscribe(e),t=e})).then(e);return n.cancel=function(){r.unsubscribe(t)},n},e((function(e,n,s){r.reason||(r.reason=new Kt(e,n,s),t(r.reason))}))}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let t;return{token:new e((function(e){t=e})),cancel:t}}},Cr.isCancel=$t,Cr.VERSION=Er,Cr.toFormData=St,Cr.AxiosError=ft,Cr.Cancel=Cr.CanceledError,Cr.all=function(e){return Promise.all(e)},Cr.spread=function(e){return function(t){return e.apply(null,t)}},Cr.isAxiosError=function(e){return pt.isObject(e)&&!0===e.isAxiosError},Cr.mergeConfig=tr,Cr.AxiosHeaders=zt,Cr.formToJSON=e=>Lt(pt.isHTMLForm(e)?new FormData(e):e),Cr.getAdapter=br,Cr.HttpStatusCode=Ar,Cr.default=Cr;const{Axios:Nr,AxiosError:Pr,CanceledError:Ir,isCancel:Ur,CancelToken:jr,VERSION:Lr,all:Dr,Cancel:Fr,isAxiosError:Mr,spread:qr,toFormData:Br,AxiosHeaders:Hr,HttpStatusCode:zr,formToJSON:Wr,getAdapter:$r,mergeConfig:Kr}=Cr;var Jr="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Vr(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Gr,Xr,Qr={exports:{}};
|
|
2
|
-
/*! Axios v1.10.0 Copyright (c) 2025 Matt Zabriskie and contributors */function Yr(){if(Xr)return Gr;function e(e,t){return function(){return e.apply(t,arguments)}}Xr=1;const{toString:t}=Object.prototype,{getPrototypeOf:r}=Object,{iterator:n,toStringTag:s}=Symbol,i=(e=>r=>{const n=t.call(r);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),o=e=>(e=e.toLowerCase(),t=>i(t)===e),a=e=>t=>typeof t===e,{isArray:c}=Array,l=a("undefined");const u=o("ArrayBuffer");const d=a("string"),h=a("function"),p=a("number"),f=e=>null!==e&&"object"==typeof e,g=e=>{if("object"!==i(e))return!1;const t=r(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||s in e||n in e)},m=o("Date"),_=o("File"),w=o("Blob"),y=o("FileList"),b=o("URLSearchParams"),[S,v,E,k]=["ReadableStream","Request","Response","Headers"].map(o);function R(e,t,{allOwnKeys:r=!1}={}){if(null==e)return;let n,s;if("object"!=typeof e&&(e=[e]),c(e))for(n=0,s=e.length;n<s;n++)t.call(null,e[n],n,e);else{const s=r?Object.getOwnPropertyNames(e):Object.keys(e),i=s.length;let o;for(n=0;n<i;n++)o=s[n],t.call(null,e[o],o,e)}}function x(e,t){t=t.toLowerCase();const r=Object.keys(e);let n,s=r.length;for(;s-- >0;)if(n=r[s],t===n.toLowerCase())return n;return null}const T="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:Jr,O=e=>!l(e)&&e!==T;const A=(e=>t=>e&&t instanceof e)("undefined"!=typeof Uint8Array&&r(Uint8Array)),C=o("HTMLFormElement"),N=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),P=o("RegExp"),I=(e,t)=>{const r=Object.getOwnPropertyDescriptors(e),n={};R(r,((r,s)=>{let i;!1!==(i=t(r,s,e))&&(n[s]=i||r)})),Object.defineProperties(e,n)};const U=o("AsyncFunction"),j=((e,t)=>e?setImmediate:t?((e,t)=>(T.addEventListener("message",(({source:r,data:n})=>{r===T&&n===e&&t.length&&t.shift()()}),!1),r=>{t.push(r),T.postMessage(e,"*")}))(`axios@${Math.random()}`,[]):e=>setTimeout(e))("function"==typeof setImmediate,h(T.postMessage)),L="undefined"!=typeof queueMicrotask?queueMicrotask.bind(T):"undefined"!=typeof process&&process.nextTick||j;var D={isArray:c,isArrayBuffer:u,isBuffer:function(e){return null!==e&&!l(e)&&null!==e.constructor&&!l(e.constructor)&&h(e.constructor.isBuffer)&&e.constructor.isBuffer(e)},isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||h(e.append)&&("formdata"===(t=i(e))||"object"===t&&h(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&u(e.buffer),t},isString:d,isNumber:p,isBoolean:e=>!0===e||!1===e,isObject:f,isPlainObject:g,isReadableStream:S,isRequest:v,isResponse:E,isHeaders:k,isUndefined:l,isDate:m,isFile:_,isBlob:w,isRegExp:P,isFunction:h,isStream:e=>f(e)&&h(e.pipe),isURLSearchParams:b,isTypedArray:A,isFileList:y,forEach:R,merge:function e(){const{caseless:t}=O(this)&&this||{},r={},n=(n,s)=>{const i=t&&x(r,s)||s;g(r[i])&&g(n)?r[i]=e(r[i],n):g(n)?r[i]=e({},n):c(n)?r[i]=n.slice():r[i]=n};for(let s=0,i=arguments.length;s<i;s++)arguments[s]&&R(arguments[s],n);return r},extend:(t,r,n,{allOwnKeys:s}={})=>(R(r,((r,s)=>{n&&h(r)?t[s]=e(r,n):t[s]=r}),{allOwnKeys:s}),t),trim:e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,r,n)=>{e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},toFlatObject:(e,t,n,s)=>{let i,o,a;const c={};if(t=t||{},null==e)return t;do{for(i=Object.getOwnPropertyNames(e),o=i.length;o-- >0;)a=i[o],s&&!s(a,e,t)||c[a]||(t[a]=e[a],c[a]=!0);e=!1!==n&&r(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},kindOf:i,kindOfTest:o,endsWith:(e,t,r)=>{e=String(e),(void 0===r||r>e.length)&&(r=e.length),r-=t.length;const n=e.indexOf(t,r);return-1!==n&&n===r},toArray:e=>{if(!e)return null;if(c(e))return e;let t=e.length;if(!p(t))return null;const r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},forEachEntry:(e,t)=>{const r=(e&&e[n]).call(e);let s;for(;(s=r.next())&&!s.done;){const r=s.value;t.call(e,r[0],r[1])}},matchAll:(e,t)=>{let r;const n=[];for(;null!==(r=e.exec(t));)n.push(r);return n},isHTMLForm:C,hasOwnProperty:N,hasOwnProp:N,reduceDescriptors:I,freezeMethods:e=>{I(e,((t,r)=>{if(h(e)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;const n=e[r];h(n)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")}))}))},toObjectSet:(e,t)=>{const r={},n=e=>{e.forEach((e=>{r[e]=!0}))};return c(e)?n(e):n(String(e).split(t)),r},toCamelCase:e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,(function(e,t,r){return t.toUpperCase()+r})),noop:()=>{},toFiniteNumber:(e,t)=>null!=e&&Number.isFinite(e=+e)?e:t,findKey:x,global:T,isContextDefined:O,isSpecCompliantForm:function(e){return!!(e&&h(e.append)&&"FormData"===e[s]&&e[n])},toJSONObject:e=>{const t=new Array(10),r=(e,n)=>{if(f(e)){if(t.indexOf(e)>=0)return;if(!("toJSON"in e)){t[n]=e;const s=c(e)?[]:{};return R(e,((e,t)=>{const i=r(e,n+1);!l(i)&&(s[t]=i)})),t[n]=void 0,s}}return e};return r(e,0)},isAsyncFn:U,isThenable:e=>e&&(f(e)||h(e))&&h(e.then)&&h(e.catch),setImmediate:j,asap:L,isIterable:e=>null!=e&&h(e[n])};function F(e,t,r,n,s){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),n&&(this.request=n),s&&(this.response=s,this.status=s.status?s.status:null)}D.inherits(F,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:D.toJSONObject(this.config),code:this.code,status:this.status}}});const M=F.prototype,q={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach((e=>{q[e]={value:e}})),Object.defineProperties(F,q),Object.defineProperty(M,"isAxiosError",{value:!0}),F.from=(e,t,r,n,s,i)=>{const o=Object.create(M);return D.toFlatObject(e,o,(function(e){return e!==Error.prototype}),(e=>"isAxiosError"!==e)),F.call(o,e.message,t,r,n,s),o.cause=e,o.name=e.name,i&&Object.assign(o,i),o};function B(e){return D.isPlainObject(e)||D.isArray(e)}function H(e){return D.endsWith(e,"[]")?e.slice(0,-2):e}function z(e,t,r){return e?e.concat(t).map((function(e,t){return e=H(e),!r&&t?"["+e+"]":e})).join(r?".":""):t}const W=D.toFlatObject(D,{},null,(function(e){return/^is[A-Z]/.test(e)}));function $(e,t,r){if(!D.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const n=(r=D.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,(function(e,t){return!D.isUndefined(t[e])}))).metaTokens,s=r.visitor||l,i=r.dots,o=r.indexes,a=(r.Blob||"undefined"!=typeof Blob&&Blob)&&D.isSpecCompliantForm(t);if(!D.isFunction(s))throw new TypeError("visitor must be a function");function c(e){if(null===e)return"";if(D.isDate(e))return e.toISOString();if(D.isBoolean(e))return e.toString();if(!a&&D.isBlob(e))throw new F("Blob is not supported. Use a Buffer instead.");return D.isArrayBuffer(e)||D.isTypedArray(e)?a&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function l(e,r,s){let a=e;if(e&&!s&&"object"==typeof e)if(D.endsWith(r,"{}"))r=n?r:r.slice(0,-2),e=JSON.stringify(e);else if(D.isArray(e)&&function(e){return D.isArray(e)&&!e.some(B)}(e)||(D.isFileList(e)||D.endsWith(r,"[]"))&&(a=D.toArray(e)))return r=H(r),a.forEach((function(e,n){!D.isUndefined(e)&&null!==e&&t.append(!0===o?z([r],n,i):null===o?r:r+"[]",c(e))})),!1;return!!B(e)||(t.append(z(s,r,i),c(e)),!1)}const u=[],d=Object.assign(W,{defaultVisitor:l,convertValue:c,isVisitable:B});if(!D.isObject(e))throw new TypeError("data must be an object");return function e(r,n){if(!D.isUndefined(r)){if(-1!==u.indexOf(r))throw Error("Circular reference detected in "+n.join("."));u.push(r),D.forEach(r,(function(r,i){!0===(!(D.isUndefined(r)||null===r)&&s.call(t,r,D.isString(i)?i.trim():i,n,d))&&e(r,n?n.concat(i):[i])})),u.pop()}}(e),t}function K(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,(function(e){return t[e]}))}function J(e,t){this._pairs=[],e&&$(e,this,t)}const V=J.prototype;function G(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function X(e,t,r){if(!t)return e;const n=r&&r.encode||G;D.isFunction(r)&&(r={serialize:r});const s=r&&r.serialize;let i;if(i=s?s(t,r):D.isURLSearchParams(t)?t.toString():new J(t,r).toString(n),i){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+i}return e}V.append=function(e,t){this._pairs.push([e,t])},V.toString=function(e){const t=e?function(t){return e.call(this,t,K)}:K;return this._pairs.map((function(e){return t(e[0])+"="+t(e[1])}),"").join("&")};var Q=class{constructor(){this.handlers=[]}use(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!r&&r.synchronous,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){D.forEach(this.handlers,(function(t){null!==t&&e(t)}))}},Y={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Z={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:J,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]};const ee="undefined"!=typeof window&&"undefined"!=typeof document,te="object"==typeof navigator&&navigator||void 0,re=ee&&(!te||["ReactNative","NativeScript","NS"].indexOf(te.product)<0),ne="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,se=ee&&window.location.href||"http://localhost";var ie={...Object.freeze({__proto__:null,hasBrowserEnv:ee,hasStandardBrowserWebWorkerEnv:ne,hasStandardBrowserEnv:re,navigator:te,origin:se}),...Z};function oe(e){function t(e,r,n,s){let i=e[s++];if("__proto__"===i)return!0;const o=Number.isFinite(+i),a=s>=e.length;if(i=!i&&D.isArray(n)?n.length:i,a)return D.hasOwnProp(n,i)?n[i]=[n[i],r]:n[i]=r,!o;n[i]&&D.isObject(n[i])||(n[i]=[]);return t(e,r,n[i],s)&&D.isArray(n[i])&&(n[i]=function(e){const t={},r=Object.keys(e);let n;const s=r.length;let i;for(n=0;n<s;n++)i=r[n],t[i]=e[i];return t}(n[i])),!o}if(D.isFormData(e)&&D.isFunction(e.entries)){const r={};return D.forEachEntry(e,((e,n)=>{t(function(e){return D.matchAll(/\w+|\[(\w*)]/g,e).map((e=>"[]"===e[0]?"":e[1]||e[0]))}(e),n,r,0)})),r}return null}const ae={transitional:Y,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const r=t.getContentType()||"",n=r.indexOf("application/json")>-1,s=D.isObject(e);s&&D.isHTMLForm(e)&&(e=new FormData(e));if(D.isFormData(e))return n?JSON.stringify(oe(e)):e;if(D.isArrayBuffer(e)||D.isBuffer(e)||D.isStream(e)||D.isFile(e)||D.isBlob(e)||D.isReadableStream(e))return e;if(D.isArrayBufferView(e))return e.buffer;if(D.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let i;if(s){if(r.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return $(e,new ie.classes.URLSearchParams,Object.assign({visitor:function(e,t,r,n){return ie.isNode&&D.isBuffer(e)?(this.append(t,e.toString("base64")),!1):n.defaultVisitor.apply(this,arguments)}},t))}(e,this.formSerializer).toString();if((i=D.isFileList(e))||r.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return $(i?{"files[]":e}:e,t&&new t,this.formSerializer)}}return s||n?(t.setContentType("application/json",!1),function(e,t,r){if(D.isString(e))try{return(t||JSON.parse)(e),D.trim(e)}catch(en){if("SyntaxError"!==en.name)throw en}return(r||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||ae.transitional,r=t&&t.forcedJSONParsing,n="json"===this.responseType;if(D.isResponse(e)||D.isReadableStream(e))return e;if(e&&D.isString(e)&&(r&&!this.responseType||n)){const r=!(t&&t.silentJSONParsing)&&n;try{return JSON.parse(e)}catch(en){if(r){if("SyntaxError"===en.name)throw F.from(en,F.ERR_BAD_RESPONSE,this,null,this.response);throw en}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:ie.classes.FormData,Blob:ie.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};D.forEach(["delete","get","head","post","put","patch"],(e=>{ae.headers[e]={}}));var ce=ae;const le=D.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]);const ue=Symbol("internals");function de(e){return e&&String(e).trim().toLowerCase()}function he(e){return!1===e||null==e?e:D.isArray(e)?e.map(he):String(e)}function pe(e,t,r,n,s){return D.isFunction(n)?n.call(this,t,r):(s&&(t=r),D.isString(t)?D.isString(n)?-1!==t.indexOf(n):D.isRegExp(n)?n.test(t):void 0:void 0)}class fe{constructor(e){e&&this.set(e)}set(e,t,r){const n=this;function s(e,t,r){const s=de(t);if(!s)throw new Error("header name must be a non-empty string");const i=D.findKey(n,s);(!i||void 0===n[i]||!0===r||void 0===r&&!1!==n[i])&&(n[i||t]=he(e))}const i=(e,t)=>D.forEach(e,((e,r)=>s(e,r,t)));if(D.isPlainObject(e)||e instanceof this.constructor)i(e,t);else if(D.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim()))i((e=>{const t={};let r,n,s;return e&&e.split("\n").forEach((function(e){s=e.indexOf(":"),r=e.substring(0,s).trim().toLowerCase(),n=e.substring(s+1).trim(),!r||t[r]&&le[r]||("set-cookie"===r?t[r]?t[r].push(n):t[r]=[n]:t[r]=t[r]?t[r]+", "+n:n)})),t})(e),t);else if(D.isObject(e)&&D.isIterable(e)){let r,n,s={};for(const t of e){if(!D.isArray(t))throw TypeError("Object iterator must return a key-value pair");s[n=t[0]]=(r=s[n])?D.isArray(r)?[...r,t[1]]:[r,t[1]]:t[1]}i(s,t)}else null!=e&&s(t,e,r);return this}get(e,t){if(e=de(e)){const r=D.findKey(this,e);if(r){const e=this[r];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=r.exec(e);)t[n[1]]=n[2];return t}(e);if(D.isFunction(t))return t.call(this,e,r);if(D.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=de(e)){const r=D.findKey(this,e);return!(!r||void 0===this[r]||t&&!pe(0,this[r],r,t))}return!1}delete(e,t){const r=this;let n=!1;function s(e){if(e=de(e)){const s=D.findKey(r,e);!s||t&&!pe(0,r[s],s,t)||(delete r[s],n=!0)}}return D.isArray(e)?e.forEach(s):s(e),n}clear(e){const t=Object.keys(this);let r=t.length,n=!1;for(;r--;){const s=t[r];e&&!pe(0,this[s],s,e,!0)||(delete this[s],n=!0)}return n}normalize(e){const t=this,r={};return D.forEach(this,((n,s)=>{const i=D.findKey(r,s);if(i)return t[i]=he(n),void delete t[s];const o=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,((e,t,r)=>t.toUpperCase()+r))}(s):String(s).trim();o!==s&&delete t[s],t[o]=he(n),r[o]=!0})),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return D.forEach(this,((r,n)=>{null!=r&&!1!==r&&(t[n]=e&&D.isArray(r)?r.join(", "):r)})),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map((([e,t])=>e+": "+t)).join("\n")}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const r=new this(e);return t.forEach((e=>r.set(e))),r}static accessor(e){const t=(this[ue]=this[ue]={accessors:{}}).accessors,r=this.prototype;function n(e){const n=de(e);t[n]||(!function(e,t){const r=D.toCamelCase(" "+t);["get","set","has"].forEach((n=>{Object.defineProperty(e,n+r,{value:function(e,r,s){return this[n].call(this,t,e,r,s)},configurable:!0})}))}(r,e),t[n]=!0)}return D.isArray(e)?e.forEach(n):n(e),this}}fe.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),D.reduceDescriptors(fe.prototype,(({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[r]=e}}})),D.freezeMethods(fe);var ge=fe;function me(e,t){const r=this||ce,n=t||r,s=ge.from(n.headers);let i=n.data;return D.forEach(e,(function(e){i=e.call(r,i,s.normalize(),t?t.status:void 0)})),s.normalize(),i}function _e(e){return!(!e||!e.__CANCEL__)}function we(e,t,r){F.call(this,null==e?"canceled":e,F.ERR_CANCELED,t,r),this.name="CanceledError"}function ye(e,t,r){const n=r.config.validateStatus;r.status&&n&&!n(r.status)?t(new F("Request failed with status code "+r.status,[F.ERR_BAD_REQUEST,F.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):e(r)}D.inherits(we,F,{__CANCEL__:!0});const be=(e,t,r=3)=>{let n=0;const s=function(e,t){e=e||10;const r=new Array(e),n=new Array(e);let s,i=0,o=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),l=n[o];s||(s=c),r[i]=a,n[i]=c;let u=o,d=0;for(;u!==i;)d+=r[u++],u%=e;if(i=(i+1)%e,i===o&&(o=(o+1)%e),c-s<t)return;const h=l&&c-l;return h?Math.round(1e3*d/h):void 0}}(50,250);return function(e,t){let r,n,s=0,i=1e3/t;const o=(t,i=Date.now())=>{s=i,r=null,n&&(clearTimeout(n),n=null),e.apply(null,t)};return[(...e)=>{const t=Date.now(),a=t-s;a>=i?o(e,t):(r=e,n||(n=setTimeout((()=>{n=null,o(r)}),i-a)))},()=>r&&o(r)]}((r=>{const i=r.loaded,o=r.lengthComputable?r.total:void 0,a=i-n,c=s(a);n=i;e({loaded:i,total:o,progress:o?i/o:void 0,bytes:a,rate:c||void 0,estimated:c&&o&&i<=o?(o-i)/c:void 0,event:r,lengthComputable:null!=o,[t?"download":"upload"]:!0})}),r)},Se=(e,t)=>{const r=null!=e;return[n=>t[0]({lengthComputable:r,total:e,loaded:n}),t[1]]},ve=e=>(...t)=>D.asap((()=>e(...t)));var Ee=ie.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,ie.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(ie.origin),ie.navigator&&/(msie|trident)/i.test(ie.navigator.userAgent)):()=>!0,ke=ie.hasStandardBrowserEnv?{write(e,t,r,n,s,i){const o=[e+"="+encodeURIComponent(t)];D.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),D.isString(n)&&o.push("path="+n),D.isString(s)&&o.push("domain="+s),!0===i&&o.push("secure"),document.cookie=o.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read:()=>null,remove(){}};function Re(e,t,r){let n=!/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t);return e&&(n||0==r)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}const xe=e=>e instanceof ge?{...e}:e;function Te(e,t){t=t||{};const r={};function n(e,t,r,n){return D.isPlainObject(e)&&D.isPlainObject(t)?D.merge.call({caseless:n},e,t):D.isPlainObject(t)?D.merge({},t):D.isArray(t)?t.slice():t}function s(e,t,r,s){return D.isUndefined(t)?D.isUndefined(e)?void 0:n(void 0,e,0,s):n(e,t,0,s)}function i(e,t){if(!D.isUndefined(t))return n(void 0,t)}function o(e,t){return D.isUndefined(t)?D.isUndefined(e)?void 0:n(void 0,e):n(void 0,t)}function a(r,s,i){return i in t?n(r,s):i in e?n(void 0,r):void 0}const c={url:i,method:i,data:i,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:a,headers:(e,t,r)=>s(xe(e),xe(t),0,!0)};return D.forEach(Object.keys(Object.assign({},e,t)),(function(n){const i=c[n]||s,o=i(e[n],t[n],n);D.isUndefined(o)&&i!==a||(r[n]=o)})),r}var Oe=e=>{const t=Te({},e);let r,{data:n,withXSRFToken:s,xsrfHeaderName:i,xsrfCookieName:o,headers:a,auth:c}=t;if(t.headers=a=ge.from(a),t.url=X(Re(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&a.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),D.isFormData(n))if(ie.hasStandardBrowserEnv||ie.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if(!1!==(r=a.getContentType())){const[e,...t]=r?r.split(";").map((e=>e.trim())).filter(Boolean):[];a.setContentType([e||"multipart/form-data",...t].join("; "))}if(ie.hasStandardBrowserEnv&&(s&&D.isFunction(s)&&(s=s(t)),s||!1!==s&&Ee(t.url))){const e=i&&o&&ke.read(o);e&&a.set(i,e)}return t};var Ae="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise((function(t,r){const n=Oe(e);let s=n.data;const i=ge.from(n.headers).normalize();let o,a,c,l,u,{responseType:d,onUploadProgress:h,onDownloadProgress:p}=n;function f(){l&&l(),u&&u(),n.cancelToken&&n.cancelToken.unsubscribe(o),n.signal&&n.signal.removeEventListener("abort",o)}let g=new XMLHttpRequest;function m(){if(!g)return;const n=ge.from("getAllResponseHeaders"in g&&g.getAllResponseHeaders());ye((function(e){t(e),f()}),(function(e){r(e),f()}),{data:d&&"text"!==d&&"json"!==d?g.response:g.responseText,status:g.status,statusText:g.statusText,headers:n,config:e,request:g}),g=null}g.open(n.method.toUpperCase(),n.url,!0),g.timeout=n.timeout,"onloadend"in g?g.onloadend=m:g.onreadystatechange=function(){g&&4===g.readyState&&(0!==g.status||g.responseURL&&0===g.responseURL.indexOf("file:"))&&setTimeout(m)},g.onabort=function(){g&&(r(new F("Request aborted",F.ECONNABORTED,e,g)),g=null)},g.onerror=function(){r(new F("Network Error",F.ERR_NETWORK,e,g)),g=null},g.ontimeout=function(){let t=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded";const s=n.transitional||Y;n.timeoutErrorMessage&&(t=n.timeoutErrorMessage),r(new F(t,s.clarifyTimeoutError?F.ETIMEDOUT:F.ECONNABORTED,e,g)),g=null},void 0===s&&i.setContentType(null),"setRequestHeader"in g&&D.forEach(i.toJSON(),(function(e,t){g.setRequestHeader(t,e)})),D.isUndefined(n.withCredentials)||(g.withCredentials=!!n.withCredentials),d&&"json"!==d&&(g.responseType=n.responseType),p&&([c,u]=be(p,!0),g.addEventListener("progress",c)),h&&g.upload&&([a,l]=be(h),g.upload.addEventListener("progress",a),g.upload.addEventListener("loadend",l)),(n.cancelToken||n.signal)&&(o=t=>{g&&(r(!t||t.type?new we(null,e,g):t),g.abort(),g=null)},n.cancelToken&&n.cancelToken.subscribe(o),n.signal&&(n.signal.aborted?o():n.signal.addEventListener("abort",o)));const _=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(n.url);_&&-1===ie.protocols.indexOf(_)?r(new F("Unsupported protocol "+_+":",F.ERR_BAD_REQUEST,e)):g.send(s||null)}))};var Ce=(e,t)=>{const{length:r}=e=e?e.filter(Boolean):[];if(t||r){let r,n=new AbortController;const s=function(e){if(!r){r=!0,o();const t=e instanceof Error?e:this.reason;n.abort(t instanceof F?t:new we(t instanceof Error?t.message:t))}};let i=t&&setTimeout((()=>{i=null,s(new F(`timeout ${t} of ms exceeded`,F.ETIMEDOUT))}),t);const o=()=>{e&&(i&&clearTimeout(i),i=null,e.forEach((e=>{e.unsubscribe?e.unsubscribe(s):e.removeEventListener("abort",s)})),e=null)};e.forEach((e=>e.addEventListener("abort",s)));const{signal:a}=n;return a.unsubscribe=()=>D.asap(o),a}};const Ne=function*(e,t){let r=e.byteLength;if(r<t)return void(yield e);let n,s=0;for(;s<r;)n=s+t,yield e.slice(s,n),s=n},Pe=async function*(e){if(e[Symbol.asyncIterator])return void(yield*e);const t=e.getReader();try{for(;;){const{done:e,value:r}=await t.read();if(e)break;yield r}}finally{await t.cancel()}},Ie=(e,t,r,n)=>{const s=async function*(e,t){for await(const r of Pe(e))yield*Ne(r,t)}(e,t);let i,o=0,a=e=>{i||(i=!0,n&&n(e))};return new ReadableStream({async pull(e){try{const{done:t,value:n}=await s.next();if(t)return a(),void e.close();let i=n.byteLength;if(r){let e=o+=i;r(e)}e.enqueue(new Uint8Array(n))}catch(t){throw a(t),t}},cancel:e=>(a(e),s.return())},{highWaterMark:2})},Ue="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,je=Ue&&"function"==typeof ReadableStream,Le=Ue&&("function"==typeof TextEncoder?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),De=(e,...t)=>{try{return!!e(...t)}catch(en){return!1}},Fe=je&&De((()=>{let e=!1;const t=new Request(ie.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t})),Me=je&&De((()=>D.isReadableStream(new Response("").body))),qe={stream:Me&&(e=>e.body)};Ue&&(e=>{["text","arrayBuffer","blob","formData","stream"].forEach((t=>{!qe[t]&&(qe[t]=D.isFunction(e[t])?e=>e[t]():(e,r)=>{throw new F(`Response type '${t}' is not supported`,F.ERR_NOT_SUPPORT,r)})}))})(new Response);const Be=async(e,t)=>{const r=D.toFiniteNumber(e.getContentLength());return null==r?(async e=>{if(null==e)return 0;if(D.isBlob(e))return e.size;if(D.isSpecCompliantForm(e)){const t=new Request(ie.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return D.isArrayBufferView(e)||D.isArrayBuffer(e)?e.byteLength:(D.isURLSearchParams(e)&&(e+=""),D.isString(e)?(await Le(e)).byteLength:void 0)})(t):r};const He={http:null,xhr:Ae,fetch:Ue&&(async e=>{let{url:t,method:r,data:n,signal:s,cancelToken:i,timeout:o,onDownloadProgress:a,onUploadProgress:c,responseType:l,headers:u,withCredentials:d="same-origin",fetchOptions:h}=Oe(e);l=l?(l+"").toLowerCase():"text";let p,f=Ce([s,i&&i.toAbortSignal()],o);const g=f&&f.unsubscribe&&(()=>{f.unsubscribe()});let m;try{if(c&&Fe&&"get"!==r&&"head"!==r&&0!==(m=await Be(u,n))){let e,r=new Request(t,{method:"POST",body:n,duplex:"half"});if(D.isFormData(n)&&(e=r.headers.get("content-type"))&&u.setContentType(e),r.body){const[e,t]=Se(m,be(ve(c)));n=Ie(r.body,65536,e,t)}}D.isString(d)||(d=d?"include":"omit");const s="credentials"in Request.prototype;p=new Request(t,{...h,signal:f,method:r.toUpperCase(),headers:u.normalize().toJSON(),body:n,duplex:"half",credentials:s?d:void 0});let i=await fetch(p,h);const o=Me&&("stream"===l||"response"===l);if(Me&&(a||o&&g)){const e={};["status","statusText","headers"].forEach((t=>{e[t]=i[t]}));const t=D.toFiniteNumber(i.headers.get("content-length")),[r,n]=a&&Se(t,be(ve(a),!0))||[];i=new Response(Ie(i.body,65536,r,(()=>{n&&n(),g&&g()})),e)}l=l||"text";let _=await qe[D.findKey(qe,l)||"text"](i,e);return!o&&g&&g(),await new Promise(((t,r)=>{ye(t,r,{data:_,headers:ge.from(i.headers),status:i.status,statusText:i.statusText,config:e,request:p})}))}catch(_){if(g&&g(),_&&"TypeError"===_.name&&/Load failed|fetch/i.test(_.message))throw Object.assign(new F("Network Error",F.ERR_NETWORK,e,p),{cause:_.cause||_});throw F.from(_,_&&_.code,e,p)}})};D.forEach(He,((e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(en){}Object.defineProperty(e,"adapterName",{value:t})}}));const ze=e=>`- ${e}`,We=e=>D.isFunction(e)||null===e||!1===e;var $e=e=>{e=D.isArray(e)?e:[e];const{length:t}=e;let r,n;const s={};for(let i=0;i<t;i++){let t;if(r=e[i],n=r,!We(r)&&(n=He[(t=String(r)).toLowerCase()],void 0===n))throw new F(`Unknown adapter '${t}'`);if(n)break;s[t||"#"+i]=n}if(!n){const e=Object.entries(s).map((([e,t])=>`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build")));throw new F("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(ze).join("\n"):" "+ze(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return n};function Ke(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new we(null,e)}function Je(e){Ke(e),e.headers=ge.from(e.headers),e.data=me.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return $e(e.adapter||ce.adapter)(e).then((function(t){return Ke(e),t.data=me.call(e,e.transformResponse,t),t.headers=ge.from(t.headers),t}),(function(t){return _e(t)||(Ke(e),t&&t.response&&(t.response.data=me.call(e,e.transformResponse,t.response),t.response.headers=ge.from(t.response.headers))),Promise.reject(t)}))}const Ve="1.10.0",Ge={};["object","boolean","number","function","string","symbol"].forEach(((e,t)=>{Ge[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}}));const Xe={};Ge.transitional=function(e,t,r){function n(e,t){return"[Axios v"+Ve+"] Transitional option '"+e+"'"+t+(r?". "+r:"")}return(r,s,i)=>{if(!1===e)throw new F(n(s," has been removed"+(t?" in "+t:"")),F.ERR_DEPRECATED);return t&&!Xe[s]&&(Xe[s]=!0,console.warn(n(s," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,s,i)}},Ge.spelling=function(e){return(t,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};var Qe={assertOptions:function(e,t,r){if("object"!=typeof e)throw new F("options must be an object",F.ERR_BAD_OPTION_VALUE);const n=Object.keys(e);let s=n.length;for(;s-- >0;){const i=n[s],o=t[i];if(o){const t=e[i],r=void 0===t||o(t,i,e);if(!0!==r)throw new F("option "+i+" must be "+r,F.ERR_BAD_OPTION_VALUE)}else if(!0!==r)throw new F("Unknown option "+i,F.ERR_BAD_OPTION)}},validators:Ge};const Ye=Qe.validators;class Ze{constructor(e){this.defaults=e||{},this.interceptors={request:new Q,response:new Q}}async request(e,t){try{return await this._request(e,t)}catch(r){if(r instanceof Error){let e={};Error.captureStackTrace?Error.captureStackTrace(e):e=new Error;const t=e.stack?e.stack.replace(/^.+\n/,""):"";try{r.stack?t&&!String(r.stack).endsWith(t.replace(/^.+\n.+\n/,""))&&(r.stack+="\n"+t):r.stack=t}catch(en){}}throw r}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=Te(this.defaults,t);const{transitional:r,paramsSerializer:n,headers:s}=t;void 0!==r&&Qe.assertOptions(r,{silentJSONParsing:Ye.transitional(Ye.boolean),forcedJSONParsing:Ye.transitional(Ye.boolean),clarifyTimeoutError:Ye.transitional(Ye.boolean)},!1),null!=n&&(D.isFunction(n)?t.paramsSerializer={serialize:n}:Qe.assertOptions(n,{encode:Ye.function,serialize:Ye.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),Qe.assertOptions(t,{baseUrl:Ye.spelling("baseURL"),withXsrfToken:Ye.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let i=s&&D.merge(s.common,s[t.method]);s&&D.forEach(["delete","get","head","post","put","patch","common"],(e=>{delete s[e]})),t.headers=ge.concat(i,s);const o=[];let a=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(a=a&&e.synchronous,o.unshift(e.fulfilled,e.rejected))}));const c=[];let l;this.interceptors.response.forEach((function(e){c.push(e.fulfilled,e.rejected)}));let u,d=0;if(!a){const e=[Je.bind(this),void 0];for(e.unshift.apply(e,o),e.push.apply(e,c),u=e.length,l=Promise.resolve(t);d<u;)l=l.then(e[d++],e[d++]);return l}u=o.length;let h=t;for(d=0;d<u;){const e=o[d++],t=o[d++];try{h=e(h)}catch(p){t.call(this,p);break}}try{l=Je.call(this,h)}catch(p){return Promise.reject(p)}for(d=0,u=c.length;d<u;)l=l.then(c[d++],c[d++]);return l}getUri(e){return X(Re((e=Te(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}}D.forEach(["delete","get","head","options"],(function(e){Ze.prototype[e]=function(t,r){return this.request(Te(r||{},{method:e,url:t,data:(r||{}).data}))}})),D.forEach(["post","put","patch"],(function(e){function t(t){return function(r,n,s){return this.request(Te(s||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:r,data:n}))}}Ze.prototype[e]=t(),Ze.prototype[e+"Form"]=t(!0)}));var et=Ze;class tt{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new Promise((function(e){t=e}));const r=this;this.promise.then((e=>{if(!r._listeners)return;let t=r._listeners.length;for(;t-- >0;)r._listeners[t](e);r._listeners=null})),this.promise.then=e=>{let t;const n=new Promise((e=>{r.subscribe(e),t=e})).then(e);return n.cancel=function(){r.unsubscribe(t)},n},e((function(e,n,s){r.reason||(r.reason=new we(e,n,s),t(r.reason))}))}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let e;return{token:new tt((function(t){e=t})),cancel:e}}}var rt=tt;const nt={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(nt).forEach((([e,t])=>{nt[t]=e}));var st=nt;const it=function t(r){const n=new et(r),s=e(et.prototype.request,n);return D.extend(s,et.prototype,n,{allOwnKeys:!0}),D.extend(s,n,null,{allOwnKeys:!0}),s.create=function(e){return t(Te(r,e))},s}(ce);return it.Axios=et,it.CanceledError=we,it.CancelToken=rt,it.isCancel=_e,it.VERSION=Ve,it.toFormData=$,it.AxiosError=F,it.Cancel=it.CanceledError,it.all=function(e){return Promise.all(e)},it.spread=function(e){return function(t){return e.apply(null,t)}},it.isAxiosError=function(e){return D.isObject(e)&&!0===e.isAxiosError},it.mergeConfig=Te,it.AxiosHeaders=ge,it.formToJSON=e=>oe(D.isHTMLForm(e)?new FormData(e):e),it.getAdapter=$e,it.HttpStatusCode=st,it.default=it,Gr=it}var Zr,en;const tn=Vr(Zr?Qr.exports:(Zr=1,Qr.exports=(en=Yr(),function(){var e={593:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0}),t.resendFailedRequest=t.getRetryInstance=t.unsetCache=t.createRequestQueueInterceptor=t.createRefreshCall=t.shouldInterceptError=t.mergeOptions=t.defaultOptions=void 0;const n=r(300);t.defaultOptions={statusCodes:[401],pauseInstanceWhileRefreshing:!1},t.mergeOptions=function(e,t){return Object.assign(Object.assign(Object.assign({},e),{pauseInstanceWhileRefreshing:t.skipWhileRefreshing}),t)},t.shouldInterceptError=function(e,t,r,n){var s,i;return!(!e||(null===(s=e.config)||void 0===s?void 0:s.skipAuthRefresh)||!(t.interceptNetworkError&&!e.response&&0===e.request.status||e.response&&((null==t?void 0:t.shouldRefresh)?t.shouldRefresh(e):null===(i=t.statusCodes)||void 0===i?void 0:i.includes(parseInt(e.response.status))))||(e.response||(e.response={config:e.config}),t.pauseInstanceWhileRefreshing&&n.skipInstances.includes(r)))},t.createRefreshCall=function(e,t,r){return r.refreshCall||(r.refreshCall=t(e),"function"==typeof r.refreshCall.then)?r.refreshCall:(console.warn("axios-auth-refresh requires `refreshTokenCall` to return a promise."),Promise.reject())},t.createRequestQueueInterceptor=function(e,t,r){return void 0===t.requestQueueInterceptorId&&(t.requestQueueInterceptorId=e.interceptors.request.use((e=>t.refreshCall.catch((()=>{throw new n.default.Cancel("Request call failed")})).then((()=>r.onRetry?r.onRetry(e):e))))),t.requestQueueInterceptorId},t.unsetCache=function(e,t){e.interceptors.request.eject(t.requestQueueInterceptorId),t.requestQueueInterceptorId=void 0,t.refreshCall=void 0,t.skipInstances=t.skipInstances.filter((t=>t!==e))},t.getRetryInstance=function(e,t){return t.retryInstance||e},t.resendFailedRequest=function(e,t){return e.config.skipAuthRefresh=!0,t(e.response.config)}},300:function(e){e.exports=en}},t={};function r(n){var s=t[n];if(void 0!==s)return s.exports;var i=t[n]={exports:{}};return e[n](i,i.exports,r),i.exports}var n={};return function(){var e=n;Object.defineProperty(e,"__esModule",{value:!0});const t=r(593);e.default=function(e,r,n={}){if("function"!=typeof r)throw new Error("axios-auth-refresh requires `refreshAuthCall` to be a function that returns a promise.");const s={skipInstances:[],refreshCall:void 0,requestQueueInterceptorId:void 0};return e.interceptors.response.use((e=>e),(i=>{if(n=(0,t.mergeOptions)(t.defaultOptions,n),!(0,t.shouldInterceptError)(i,n,e,s))return Promise.reject(i);n.pauseInstanceWhileRefreshing&&s.skipInstances.push(e);const o=(0,t.createRefreshCall)(i,r,s);return(0,t.createRequestQueueInterceptor)(e,s,n),o.catch((e=>Promise.reject(e))).then((()=>(0,t.resendFailedRequest)(i,(0,t.getRetryInstance)(e,n)))).finally((()=>(0,t.unsetCache)(e,s)))}))}}(),n}())));var rn=class{constructor(e){this.apiKey=e}async getAccessToken(){return this.apiKey}async refreshToken(){return Promise.resolve()}},nn=class{constructor(e){r(this,"getTokenFn"),r(this,"refreshTokenFn"),r(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)}},sn={baseUrl:"undefined"!=typeof process&&(null==(e=process.env)?void 0:e.ECHO_BASE_URL)||"https://echo.merit.systems"};var on=class e extends Error{constructor(t,n,s){super(n),r(this,"code"),r(this,"details"),r(this,"statusCode"),r(this,"endpoint"),r(this,"originalError"),this.name="EchoError",this.code=t,void 0!==(null==s?void 0:s.details)&&(this.details=s.details),void 0!==(null==s?void 0:s.statusCode)&&(this.statusCode=s.statusCode),void 0!==(null==s?void 0:s.endpoint)&&(this.endpoint=s.endpoint),void 0!==(null==s?void 0:s.originalError)&&(this.originalError=s.originalError),Error.captureStackTrace&&Error.captureStackTrace(this,e)}},an=class extends on{constructor(e,t,r,n,s){const i={};void 0!==n&&(i.details=n),void 0!==r&&(i.statusCode=r),void 0!==s&&(i.endpoint=s),super(e,t,i),this.name="EchoApiError"}},cn=class extends on{constructor(e,t,r){const n={originalError:t};void 0!==r&&(n.endpoint=r),super("NETWORK_ERROR",e,n),this.name="EchoNetworkError"}},ln=class extends on{constructor(e,t,n){const s={};void 0!==n&&(s.endpoint=n),super("TIMEOUT_ERROR",e,s),r(this,"timeout"),this.name="EchoTimeoutError",this.timeout=t}},un="UNAUTHORIZED",dn="TOKEN_EXPIRED",hn="INVALID_TOKEN",pn="BAD_REQUEST",fn="NOT_FOUND",gn="RATE_LIMITED",mn="INSUFFICIENT_BALANCE",_n="VALIDATION_ERROR",wn="NETWORK_ERROR",yn="TIMEOUT_ERROR",bn="SERVER_ERROR",Sn="SERVICE_UNAVAILABLE";function vn(e,t,r){if(e&&"object"==typeof e&&"isAxiosError"in e){const n=e;if("ECONNABORTED"===n.code)return new ln("Request timeout"+(t?` while ${t}`:""),3e4,r);if(!n.response)return new cn("Network error"+(t?` while ${t}`:""),n,r);const s=n.response.status,i=n.response.data;let o,a;const c=(null==i?void 0:i.error)||(null==i?void 0:i.message);switch(s){case 401:o=un,a=c||"Authentication required. Please sign in again.";break;case 403:o=hn,a=c||"Access denied. Your session may have expired.";break;case 404:o=fn,a=c||"Resource not found";break;case 429:o=gn,a=c||"Too many requests. Please try again later.";break;case 400:o=pn,a=c||"Invalid request";break;case 402:o=mn,a=c||"Insufficient balance. Please add credits to continue.";break;case 422:o=_n,a=c||"Validation failed";break;case 503:o=Sn,a=c||"Service temporarily unavailable. Please try again.";break;default:o=bn,a=c||"An unexpected error occurred"}return new an(o,t?`Failed to ${t}: ${a}`:a,s,(null==i?void 0:i.details)||(null==i?void 0:i.error_description),r)}return e instanceof Error?new cn(e.message||"Unknown error"+(t?` while ${t}`:""),e,r):"string"==typeof e?new an(bn,e,void 0,void 0,r):new an(bn,"Unknown error"+(t?` while ${t}`:""),void 0,String(e),r)}function En(e){switch(e.code){case un:case dn:case hn:return"Please sign in to continue";case mn:return"Insufficient balance. Please add credits to your account.";case gn:return"Too many requests. Please wait a moment and try again.";case wn:return"Connection failed. Please check your internet connection.";case yn:return"Request timed out. Please try again.";case Sn:return"Service is temporarily unavailable. Please try again later.";case fn:return e.message||"The requested resource was not found.";case _n:return e.message||"Please check your input and try again.";default:return e.message||"An unexpected error occurred. Please try again."}}var kn=class{constructor(e){this.http=e}async handleRequest(e,t,r){try{return(await e()).data}catch(n){throw vn(n,t,r)}}handleError(e,t,r){throw vn(e,t,r)}},Rn=class extends kn{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}`}},xn=class extends kn{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")}},Tn=class extends kn{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 this.handleError(e,"listing supported models")}}async getSupportedModelsByProvider(){try{return(await this.getSupportedModels()).models_by_provider}catch(e){throw this.handleError(e,"getting models by provider")}}},On=class extends kn{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,r){const n={amount:e,description:t||"Echo Credits"};r&&(n.successUrl=r);try{return(await this.createPaymentLink(n)).paymentLink.url}catch(s){throw this.handleError(s,"getting payment URL")}}},An=class extends kn{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 r={echoAppId:e,code:t};return this.handleRequest((()=>this.http.post("/api/v1/user/referral",r)),"registering referral code","/api/v1/user/referral")}},Cn=class{constructor(e){var t;if(r(this,"http"),r(this,"config"),r(this,"tokenProvider"),r(this,"balance"),r(this,"payments"),r(this,"apps"),r(this,"users"),r(this,"models"),this.config=(t=e,{...sn,...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 rn(e)}this.http=Cr.create({baseURL:this.config.baseUrl,timeout:3e4}),this.http.interceptors.request.use((async e=>{const t=await this.tokenProvider.getAccessToken();return t&&(e.headers.Authorization=`Bearer ${t}`),e}));tn(this.http,(async e=>{try{await this.tokenProvider.refreshToken();const t=await this.tokenProvider.getAccessToken();return t&&(e.response.config.headers.Authorization=`Bearer ${t}`),Promise.resolve()}catch(t){return this.tokenProvider.onRefreshError&&this.tokenProvider.onRefreshError(t),Promise.reject(t)}}),{statusCodes:[401],pauseInstanceWhileRefreshing:!0}),this.balance=new xn(this.http),this.payments=new On(this.http),this.apps=new Rn(this.http,this.config.baseUrl),this.users=new An(this.http),this.models=new Tn(this.http)}};function Nn({apiUrl:e}){var t;const r=Re(),[n,i]=s.useState(null);return s.useEffect((()=>{var t;if(!(null==(t=r.user)?void 0:t.access_token))return void i(null);const n=new nn({getTokenFn:()=>{var e;return Promise.resolve((null==(e=r.user)?void 0:e.access_token)||null)},refreshTokenFn:async()=>{await r.signinSilent()},onRefreshErrorFn:e=>{console.error("Token refresh failed:",e),r.signoutSilent()}}),s=new Cn({baseUrl:e,tokenProvider:n});return i(s),()=>{i(null)}}),[e,null==(t=r.user)?void 0:t.access_token,r.signinSilent,r.signoutSilent]),n}const Pn=s.createContext(null);function In({config:e,children:t}){var r,i,o;const a=Re(),c=a.user,l=c?function(e){return{id:e.profile.sub||"",email:e.profile.email||"",name:e.profile.name||e.profile.preferred_username||"",picture:e.profile.picture||""}}(c):null,u=e.apiUrl||"https://echo.merit.systems",d=(null==(r=a.user)?void 0:r.access_token)||null,h=Nn({apiUrl:u}),{balance:p,freeTierBalance:f,refreshBalance:g,error:m,isLoading:_}=function(e,t){const[r,n]=s.useState(null),[i,o]=s.useState(null),[a,c]=s.useState(null),[l,u]=s.useState(!1),d=s.useCallback((async()=>{if(!e)throw new Error("Not authenticated");u(!0);try{const[r,s]=await Promise.all([e.balance.getBalance(),e.balance.getFreeBalance(t)]);n(r),o(s),c(null)}catch(r){const e=vn(r,"refreshing balance"),t=En(e);throw c(t),e}finally{u(!1)}}),[e,t]);return s.useEffect((()=>{e&&t?d().catch((e=>{console.error("Error loading initial balance:",e)})):(n(null),o(null),c(null))}),[e,t,d]),{balance:r,freeTierBalance:i,error:a,isLoading:l,refreshBalance:d}}(h,e.appId),{createPaymentLink:w,error:y,isLoading:b}=function(e){const[t,r]=s.useState(null),[n,i]=s.useState(!1);return{createPaymentLink:s.useCallback((async(t,n,s)=>{if(!e)throw new Error("Not authenticated");i(!0);try{const i=await e.payments.createPaymentLink({amount:t,description:n||"Echo Credits",successUrl:s||window.location.origin});return r(null),i.paymentLink.url}catch(o){const e=vn(o,"creating payment link"),t=En(e);throw r(t),e}finally{i(!1)}}),[e]),error:t,isLoading:n}}(h),S=s.useCallback((async()=>{try{await a.removeUser()}catch(e){console.error("Error during auth cleanup:",e)}}),[a.removeUser]),v=s.useCallback((async()=>{var e;return(null==(e=a.user)?void 0:e.access_token)||null}),[null==(i=a.user)?void 0:i.access_token]),E=(null==(o=a.error)?void 0:o.message)||m||y||null,k=a.isLoading||_||b,R={user:l||null,rawUser:c,balance:p,freeTierBalance:f,isAuthenticated:a.isAuthenticated,isLoading:k,error:E,token:d,echoClient:h,signIn:a.signinRedirect,signOut:S,refreshBalance:g,createPaymentLink:w,getToken:v,clearAuth:S};return n.jsx(Pn.Provider,{value:R,children:t})}function Un(){const e=s.useContext(Pn);if(!e)throw new Error("useEcho must be used within an EchoProvider");return e}
|
|
3
|
-
/*! @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:jn,setPrototypeOf:Ln,isFrozen:Dn,getPrototypeOf:Fn,getOwnPropertyDescriptor:Mn}=Object;let{freeze:qn,seal:Bn,create:Hn}=Object,{apply:zn,construct:Wn}="undefined"!=typeof Reflect&&Reflect;qn||(qn=function(e){return e}),Bn||(Bn=function(e){return e}),zn||(zn=function(e,t,r){return e.apply(t,r)}),Wn||(Wn=function(e,t){return new e(...t)});const $n=os(Array.prototype.forEach),Kn=os(Array.prototype.lastIndexOf),Jn=os(Array.prototype.pop),Vn=os(Array.prototype.push),Gn=os(Array.prototype.splice),Xn=os(String.prototype.toLowerCase),Qn=os(String.prototype.toString),Yn=os(String.prototype.match),Zn=os(String.prototype.replace),es=os(String.prototype.indexOf),ts=os(String.prototype.trim),rs=os(Object.prototype.hasOwnProperty),ns=os(RegExp.prototype.test),ss=(is=TypeError,function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return Wn(is,t)});var is;function os(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var r=arguments.length,n=new Array(r>1?r-1:0),s=1;s<r;s++)n[s-1]=arguments[s];return zn(e,t,n)}}function as(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Xn;Ln&&Ln(e,null);let n=t.length;for(;n--;){let s=t[n];if("string"==typeof s){const e=r(s);e!==s&&(Dn(t)||(t[n]=e),s=e)}e[s]=!0}return e}function cs(e){for(let t=0;t<e.length;t++){rs(e,t)||(e[t]=null)}return e}function ls(e){const t=Hn(null);for(const[r,n]of jn(e)){rs(e,r)&&(Array.isArray(n)?t[r]=cs(n):n&&"object"==typeof n&&n.constructor===Object?t[r]=ls(n):t[r]=n)}return t}function us(e,t){for(;null!==e;){const r=Mn(e,t);if(r){if(r.get)return os(r.get);if("function"==typeof r.value)return os(r.value)}e=Fn(e)}return function(){return null}}const ds=qn(["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"]),hs=qn(["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"]),ps=qn(["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"]),fs=qn(["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"]),gs=qn(["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"]),ms=qn(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),_s=qn(["#text"]),ws=qn(["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"]),ys=qn(["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"]),bs=qn(["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"]),Ss=qn(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),vs=Bn(/\{\{[\w\W]*|[\w\W]*\}\}/gm),Es=Bn(/<%[\w\W]*|[\w\W]*%>/gm),ks=Bn(/\$\{[\w\W]*/gm),Rs=Bn(/^data-[\-\w.\u00B7-\uFFFF]+$/),xs=Bn(/^aria-[\-\w]+$/),Ts=Bn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Os=Bn(/^(?:\w+script|data):/i),As=Bn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Cs=Bn(/^html$/i),Ns=Bn(/^[a-z][.\w]*(-[.\w]+)+$/i);var Ps=Object.freeze({__proto__:null,ARIA_ATTR:xs,ATTR_WHITESPACE:As,CUSTOM_ELEMENT:Ns,DATA_ATTR:Rs,DOCTYPE_NAME:Cs,ERB_EXPR:Es,IS_ALLOWED_URI:Ts,IS_SCRIPT_OR_DATA:Os,MUSTACHE_EXPR:vs,TMPLIT_EXPR:ks});const Is=1,Us=3,js=7,Ls=8,Ds=9;var Fs=function e(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"undefined"==typeof window?null:window;const r=t=>e(t);if(r.version="3.2.6",r.removed=[],!t||!t.document||t.document.nodeType!==Ds||!t.Element)return r.isSupported=!1,r;let{document:n}=t;const s=n,i=s.currentScript,{DocumentFragment:o,HTMLTemplateElement:a,Node:c,Element:l,NodeFilter:u,NamedNodeMap:d=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:h,DOMParser:p,trustedTypes:f}=t,g=l.prototype,m=us(g,"cloneNode"),_=us(g,"remove"),w=us(g,"nextSibling"),y=us(g,"childNodes"),b=us(g,"parentNode");if("function"==typeof a){const e=n.createElement("template");e.content&&e.content.ownerDocument&&(n=e.content.ownerDocument)}let S,v="";const{implementation:E,createNodeIterator:k,createDocumentFragment:R,getElementsByTagName:x}=n,{importNode:T}=s;let O={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]};r.isSupported="function"==typeof jn&&"function"==typeof b&&E&&void 0!==E.createHTMLDocument;const{MUSTACHE_EXPR:A,ERB_EXPR:C,TMPLIT_EXPR:N,DATA_ATTR:P,ARIA_ATTR:I,IS_SCRIPT_OR_DATA:U,ATTR_WHITESPACE:j,CUSTOM_ELEMENT:L}=Ps;let{IS_ALLOWED_URI:D}=Ps,F=null;const M=as({},[...ds,...hs,...ps,...gs,..._s]);let q=null;const B=as({},[...ws,...ys,...bs,...Ss]);let H=Object.seal(Hn(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}})),z=null,W=null,$=!0,K=!0,J=!1,V=!0,G=!1,X=!0,Q=!1,Y=!1,Z=!1,ee=!1,te=!1,re=!1,ne=!0,se=!1,ie=!0,oe=!1,ae={},ce=null;const le=as({},["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 ue=null;const de=as({},["audio","video","img","source","image","track"]);let he=null;const pe=as({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),fe="http://www.w3.org/1998/Math/MathML",ge="http://www.w3.org/2000/svg",me="http://www.w3.org/1999/xhtml";let _e=me,we=!1,ye=null;const be=as({},[fe,ge,me],Qn);let Se=as({},["mi","mo","mn","ms","mtext"]),ve=as({},["annotation-xml"]);const Ee=as({},["title","style","font","a","script"]);let ke=null;const Re=["application/xhtml+xml","text/html"];let xe=null,Te=null;const Oe=n.createElement("form"),Ae=function(e){return e instanceof RegExp||e instanceof Function},Ce=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!Te||Te!==e){if(e&&"object"==typeof e||(e={}),e=ls(e),ke=-1===Re.indexOf(e.PARSER_MEDIA_TYPE)?"text/html":e.PARSER_MEDIA_TYPE,xe="application/xhtml+xml"===ke?Qn:Xn,F=rs(e,"ALLOWED_TAGS")?as({},e.ALLOWED_TAGS,xe):M,q=rs(e,"ALLOWED_ATTR")?as({},e.ALLOWED_ATTR,xe):B,ye=rs(e,"ALLOWED_NAMESPACES")?as({},e.ALLOWED_NAMESPACES,Qn):be,he=rs(e,"ADD_URI_SAFE_ATTR")?as(ls(pe),e.ADD_URI_SAFE_ATTR,xe):pe,ue=rs(e,"ADD_DATA_URI_TAGS")?as(ls(de),e.ADD_DATA_URI_TAGS,xe):de,ce=rs(e,"FORBID_CONTENTS")?as({},e.FORBID_CONTENTS,xe):le,z=rs(e,"FORBID_TAGS")?as({},e.FORBID_TAGS,xe):ls({}),W=rs(e,"FORBID_ATTR")?as({},e.FORBID_ATTR,xe):ls({}),ae=!!rs(e,"USE_PROFILES")&&e.USE_PROFILES,$=!1!==e.ALLOW_ARIA_ATTR,K=!1!==e.ALLOW_DATA_ATTR,J=e.ALLOW_UNKNOWN_PROTOCOLS||!1,V=!1!==e.ALLOW_SELF_CLOSE_IN_ATTR,G=e.SAFE_FOR_TEMPLATES||!1,X=!1!==e.SAFE_FOR_XML,Q=e.WHOLE_DOCUMENT||!1,ee=e.RETURN_DOM||!1,te=e.RETURN_DOM_FRAGMENT||!1,re=e.RETURN_TRUSTED_TYPE||!1,Z=e.FORCE_BODY||!1,ne=!1!==e.SANITIZE_DOM,se=e.SANITIZE_NAMED_PROPS||!1,ie=!1!==e.KEEP_CONTENT,oe=e.IN_PLACE||!1,D=e.ALLOWED_URI_REGEXP||Ts,_e=e.NAMESPACE||me,Se=e.MATHML_TEXT_INTEGRATION_POINTS||Se,ve=e.HTML_INTEGRATION_POINTS||ve,H=e.CUSTOM_ELEMENT_HANDLING||{},e.CUSTOM_ELEMENT_HANDLING&&Ae(e.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(H.tagNameCheck=e.CUSTOM_ELEMENT_HANDLING.tagNameCheck),e.CUSTOM_ELEMENT_HANDLING&&Ae(e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(H.attributeNameCheck=e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),e.CUSTOM_ELEMENT_HANDLING&&"boolean"==typeof e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements&&(H.allowCustomizedBuiltInElements=e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),G&&(K=!1),te&&(ee=!0),ae&&(F=as({},_s),q=[],!0===ae.html&&(as(F,ds),as(q,ws)),!0===ae.svg&&(as(F,hs),as(q,ys),as(q,Ss)),!0===ae.svgFilters&&(as(F,ps),as(q,ys),as(q,Ss)),!0===ae.mathMl&&(as(F,gs),as(q,bs),as(q,Ss))),e.ADD_TAGS&&(F===M&&(F=ls(F)),as(F,e.ADD_TAGS,xe)),e.ADD_ATTR&&(q===B&&(q=ls(q)),as(q,e.ADD_ATTR,xe)),e.ADD_URI_SAFE_ATTR&&as(he,e.ADD_URI_SAFE_ATTR,xe),e.FORBID_CONTENTS&&(ce===le&&(ce=ls(ce)),as(ce,e.FORBID_CONTENTS,xe)),ie&&(F["#text"]=!0),Q&&as(F,["html","head","body"]),F.table&&(as(F,["tbody"]),delete z.tbody),e.TRUSTED_TYPES_POLICY){if("function"!=typeof e.TRUSTED_TYPES_POLICY.createHTML)throw ss('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw ss('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');S=e.TRUSTED_TYPES_POLICY,v=S.createHTML("")}else void 0===S&&(S=function(e,t){if("object"!=typeof e||"function"!=typeof e.createPolicy)return null;let r=null;const n="data-tt-policy-suffix";t&&t.hasAttribute(n)&&(r=t.getAttribute(n));const s="dompurify"+(r?"#"+r:"");try{return e.createPolicy(s,{createHTML:e=>e,createScriptURL:e=>e})}catch(i){return console.warn("TrustedTypes policy "+s+" could not be created."),null}}(f,i)),null!==S&&"string"==typeof v&&(v=S.createHTML(""));qn&&qn(e),Te=e}},Ne=as({},[...hs,...ps,...fs]),Pe=as({},[...gs,...ms]),Ie=function(e){Vn(r.removed,{element:e});try{b(e).removeChild(e)}catch(t){_(e)}},Ue=function(e,t){try{Vn(r.removed,{attribute:t.getAttributeNode(e),from:t})}catch(n){Vn(r.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e)if(ee||te)try{Ie(t)}catch(n){}else try{t.setAttribute(e,"")}catch(n){}},je=function(e){let t=null,r=null;if(Z)e="<remove></remove>"+e;else{const t=Yn(e,/^[\r\n\t ]+/);r=t&&t[0]}"application/xhtml+xml"===ke&&_e===me&&(e='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+e+"</body></html>");const s=S?S.createHTML(e):e;if(_e===me)try{t=(new p).parseFromString(s,ke)}catch(o){}if(!t||!t.documentElement){t=E.createDocument(_e,"template",null);try{t.documentElement.innerHTML=we?v:s}catch(o){}}const i=t.body||t.documentElement;return e&&r&&i.insertBefore(n.createTextNode(r),i.childNodes[0]||null),_e===me?x.call(t,Q?"html":"body")[0]:Q?t.documentElement:i},Le=function(e){return k.call(e.ownerDocument||e,e,u.SHOW_ELEMENT|u.SHOW_COMMENT|u.SHOW_TEXT|u.SHOW_PROCESSING_INSTRUCTION|u.SHOW_CDATA_SECTION,null)},De=function(e){return e instanceof h&&("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)},Fe=function(e){return"function"==typeof c&&e instanceof c};function Me(e,t,n){$n(e,(e=>{e.call(r,t,n,Te)}))}const qe=function(e){let t=null;if(Me(O.beforeSanitizeElements,e,null),De(e))return Ie(e),!0;const n=xe(e.nodeName);if(Me(O.uponSanitizeElement,e,{tagName:n,allowedTags:F}),X&&e.hasChildNodes()&&!Fe(e.firstElementChild)&&ns(/<[/\w!]/g,e.innerHTML)&&ns(/<[/\w!]/g,e.textContent))return Ie(e),!0;if(e.nodeType===js)return Ie(e),!0;if(X&&e.nodeType===Ls&&ns(/<[/\w]/g,e.data))return Ie(e),!0;if(!F[n]||z[n]){if(!z[n]&&He(n)){if(H.tagNameCheck instanceof RegExp&&ns(H.tagNameCheck,n))return!1;if(H.tagNameCheck instanceof Function&&H.tagNameCheck(n))return!1}if(ie&&!ce[n]){const t=b(e)||e.parentNode,r=y(e)||e.childNodes;if(r&&t){for(let n=r.length-1;n>=0;--n){const s=m(r[n],!0);s.__removalCount=(e.__removalCount||0)+1,t.insertBefore(s,w(e))}}}return Ie(e),!0}return e instanceof l&&!function(e){let t=b(e);t&&t.tagName||(t={namespaceURI:_e,tagName:"template"});const r=Xn(e.tagName),n=Xn(t.tagName);return!!ye[e.namespaceURI]&&(e.namespaceURI===ge?t.namespaceURI===me?"svg"===r:t.namespaceURI===fe?"svg"===r&&("annotation-xml"===n||Se[n]):Boolean(Ne[r]):e.namespaceURI===fe?t.namespaceURI===me?"math"===r:t.namespaceURI===ge?"math"===r&&ve[n]:Boolean(Pe[r]):e.namespaceURI===me?!(t.namespaceURI===ge&&!ve[n])&&!(t.namespaceURI===fe&&!Se[n])&&!Pe[r]&&(Ee[r]||!Ne[r]):!("application/xhtml+xml"!==ke||!ye[e.namespaceURI]))}(e)?(Ie(e),!0):"noscript"!==n&&"noembed"!==n&&"noframes"!==n||!ns(/<\/no(script|embed|frames)/i,e.innerHTML)?(G&&e.nodeType===Us&&(t=e.textContent,$n([A,C,N],(e=>{t=Zn(t,e," ")})),e.textContent!==t&&(Vn(r.removed,{element:e.cloneNode()}),e.textContent=t)),Me(O.afterSanitizeElements,e,null),!1):(Ie(e),!0)},Be=function(e,t,r){if(ne&&("id"===t||"name"===t)&&(r in n||r in Oe))return!1;if(K&&!W[t]&&ns(P,t));else if($&&ns(I,t));else if(!q[t]||W[t]){if(!(He(e)&&(H.tagNameCheck instanceof RegExp&&ns(H.tagNameCheck,e)||H.tagNameCheck instanceof Function&&H.tagNameCheck(e))&&(H.attributeNameCheck instanceof RegExp&&ns(H.attributeNameCheck,t)||H.attributeNameCheck instanceof Function&&H.attributeNameCheck(t))||"is"===t&&H.allowCustomizedBuiltInElements&&(H.tagNameCheck instanceof RegExp&&ns(H.tagNameCheck,r)||H.tagNameCheck instanceof Function&&H.tagNameCheck(r))))return!1}else if(he[t]);else if(ns(D,Zn(r,j,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==es(r,"data:")||!ue[e]){if(J&&!ns(U,Zn(r,j,"")));else if(r)return!1}else;return!0},He=function(e){return"annotation-xml"!==e&&Yn(e,L)},ze=function(e){Me(O.beforeSanitizeAttributes,e,null);const{attributes:t}=e;if(!t||De(e))return;const n={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:q,forceKeepAttr:void 0};let s=t.length;for(;s--;){const o=t[s],{name:a,namespaceURI:c,value:l}=o,u=xe(a),d=l;let h="value"===a?d:ts(d);if(n.attrName=u,n.attrValue=h,n.keepAttr=!0,n.forceKeepAttr=void 0,Me(O.uponSanitizeAttribute,e,n),h=n.attrValue,!se||"id"!==u&&"name"!==u||(Ue(a,e),h="user-content-"+h),X&&ns(/((--!?|])>)|<\/(style|title)/i,h)){Ue(a,e);continue}if(n.forceKeepAttr)continue;if(!n.keepAttr){Ue(a,e);continue}if(!V&&ns(/\/>/i,h)){Ue(a,e);continue}G&&$n([A,C,N],(e=>{h=Zn(h,e," ")}));const p=xe(e.nodeName);if(Be(p,u,h)){if(S&&"object"==typeof f&&"function"==typeof f.getAttributeType)if(c);else switch(f.getAttributeType(p,u)){case"TrustedHTML":h=S.createHTML(h);break;case"TrustedScriptURL":h=S.createScriptURL(h)}if(h!==d)try{c?e.setAttributeNS(c,a,h):e.setAttribute(a,h),De(e)?Ie(e):Jn(r.removed)}catch(i){Ue(a,e)}}else Ue(a,e)}Me(O.afterSanitizeAttributes,e,null)},We=function e(t){let r=null;const n=Le(t);for(Me(O.beforeSanitizeShadowDOM,t,null);r=n.nextNode();)Me(O.uponSanitizeShadowNode,r,null),qe(r),ze(r),r.content instanceof o&&e(r.content);Me(O.afterSanitizeShadowDOM,t,null)};return r.sanitize=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=null,i=null,a=null,l=null;if(we=!e,we&&(e="\x3c!--\x3e"),"string"!=typeof e&&!Fe(e)){if("function"!=typeof e.toString)throw ss("toString is not a function");if("string"!=typeof(e=e.toString()))throw ss("dirty is not a string, aborting")}if(!r.isSupported)return e;if(Y||Ce(t),r.removed=[],"string"==typeof e&&(oe=!1),oe){if(e.nodeName){const t=xe(e.nodeName);if(!F[t]||z[t])throw ss("root node is forbidden and cannot be sanitized in-place")}}else if(e instanceof c)n=je("\x3c!----\x3e"),i=n.ownerDocument.importNode(e,!0),i.nodeType===Is&&"BODY"===i.nodeName||"HTML"===i.nodeName?n=i:n.appendChild(i);else{if(!ee&&!G&&!Q&&-1===e.indexOf("<"))return S&&re?S.createHTML(e):e;if(n=je(e),!n)return ee?null:re?v:""}n&&Z&&Ie(n.firstChild);const u=Le(oe?e:n);for(;a=u.nextNode();)qe(a),ze(a),a.content instanceof o&&We(a.content);if(oe)return e;if(ee){if(te)for(l=R.call(n.ownerDocument);n.firstChild;)l.appendChild(n.firstChild);else l=n;return(q.shadowroot||q.shadowrootmode)&&(l=T.call(s,l,!0)),l}let d=Q?n.outerHTML:n.innerHTML;return Q&&F["!doctype"]&&n.ownerDocument&&n.ownerDocument.doctype&&n.ownerDocument.doctype.name&&ns(Cs,n.ownerDocument.doctype.name)&&(d="<!DOCTYPE "+n.ownerDocument.doctype.name+">\n"+d),G&&$n([A,C,N],(e=>{d=Zn(d,e," ")})),S&&re?S.createHTML(d):d},r.setConfig=function(){Ce(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),Y=!0},r.clearConfig=function(){Te=null,Y=!1},r.isValidAttribute=function(e,t,r){Te||Ce({});const n=xe(e),s=xe(t);return Be(n,s,r)},r.addHook=function(e,t){"function"==typeof t&&Vn(O[e],t)},r.removeHook=function(e,t){if(void 0!==t){const r=Kn(O[e],t);return-1===r?void 0:Gn(O[e],r,1)[0]}return Jn(O[e])},r.removeHooks=function(e){O[e]=[]},r.removeAllHooks=function(){O={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},r}();const Ms=(()=>{if("undefined"!=typeof window)return Fs;try{const{JSDOM:e}=require("jsdom"),{window:t}=new e("");return Fs(t)}catch{return{sanitize:e=>String(e||"").replace(/<[^>]*>/g,"")}}})();function qs(e){if(!e)return"";const t=String(e);try{let e=Ms.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 Bs(e,t={}){const{onComplete:r,onCancel:n,onError:s}=t,i=function(e){if(!e)return"";const t=qs(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==s||s(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 s=()=>{try{if(e.closed)return null==r||r(),void t();setTimeout(s,1e3)}catch{null==r||r(),t()}};s(),setTimeout((()=>{e.close(),null==n||n(),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==r||r(),window.removeEventListener("focus",t),e())};window.addEventListener("focus",t),setTimeout((()=>{window.removeEventListener("focus",t),sessionStorage.removeItem("echo_payment_flow"),null==n||n(),e()}),18e5)}))):(null==n||n(),Promise.resolve())}catch(o){const e=o instanceof Error?o:new Error("Payment flow failed");throw null==s||s(e),e}}const Hs=({className:e="",width:t=16,height:r=16,variant:s="light"})=>{const i="dark"===s?"#DFE2D9":"#232323";return n.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:r,"aria-label":"Echo Logo",children:[n.jsx("defs",{children:n.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 `})}),n.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"}),n.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"}),n.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"}),n.jsxs("g",{children:[n.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"}),n.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"}),n.jsx("rect",{className:"cls-4",x:"111.88",y:"3.94",width:"2.27",height:"63.28"}),n.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)"}),n.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)"}),n.jsx("rect",{className:"cls-4",x:"111.88",y:"130.5",width:"2.27",height:"126.56"}),n.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)"}),n.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 zs=({onAddCredits:e,onCancel:t,isProcessing:r})=>{const[i,o]=s.useState(""),a=s.useRef(null);s.useEffect((()=>{a.current&&a.current.focus()}),[]);const c=""!==i&&Number(i)>0;return n.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:"8px"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[n.jsx("span",{style:{fontSize:"14px",color:"#6b7280",fontFamily:"HelveticaNowDisplay, sans-serif"},children:"$"}),n.jsx("input",{ref:a,type:"number",placeholder:"0.00",value:i,onChange:e=>o(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"})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[n.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"}),n.jsx("button",{onClick:()=>{const t=Number(i);t>0&&e(t)},disabled:r||!c,style:{padding:"8px 16px",backgroundColor:r||!c?"#9ca3af":"#dc2626",color:"white",border:"none",borderRadius:"6px",fontSize:"14px",fontWeight:"500",cursor:r||!c?"not-allowed":"pointer",fontFamily:"HelveticaNowDisplay, sans-serif"},onMouseEnter:e=>{!r&&c&&(e.currentTarget.style.backgroundColor="#b91c1c")},onMouseLeave:e=>{!r&&c&&(e.currentTarget.style.backgroundColor="#dc2626")},children:r?"Processing...":"Add Credits"})]})]})};exports.EchoProvider=function({config:e,children:t}){const[r,i]=s.useState(!1);if(s.useEffect((()=>{i(!0)}),[]),!r)return null;const o=e.apiUrl||"https://echo.merit.systems",a={userManager:"undefined"!=typeof window&&window.__echoUserManager||new ue({authority:o,client_id:e.appId,redirect_uri:e.redirectUri||window.location.origin,scope:e.scope||"llm:invoke offline_access",silentRequestTimeoutInSeconds:10,silent_redirect_uri:e.redirectUri||window.location.origin,includeIdTokenInSilentRenew:!1,validateSubOnSilentRenew:!0,loadUserInfo:!0,metadata:{authorization_endpoint:`${o}/api/oauth/authorize`,token_endpoint:`${o}/api/oauth/token`,userinfo_endpoint:`${o}/api/oauth/userinfo`,issuer:o,jwks_uri:`${o}/.well-known/jwks.json`,end_session_endpoint:`${o}/api/oauth/logout`},userStore:new C({store:window.localStorage})}),onSigninCallback:()=>{window.location.search.includes("code=")&&window.history.replaceState({},document.title,window.location.pathname)}};return n.jsx(ke,{...a,children:n.jsx(In,{config:e,children:t})})},exports.EchoSignIn=function({onSuccess:e,onError:t,className:r="",children:i}){const{signIn:o,isAuthenticated:a,isLoading:c,user:l,error:u}=Un(),[d,h]=s.useState(!1);s.useEffect((()=>{a&&l&&e&&e(l)}),[a,l,e]),s.useEffect((()=>{u&&t&&t(new Error(u))}),[u,t]);const p=async()=>{try{await o()}catch(e){t&&t(e instanceof Error?e:new Error("Sign in failed"))}};return a?n.jsx("div",{className:`echo-signin-success ${r}`,children:n.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:[n.jsx(Hs,{width:16,height:16,variant:"light"}),n.jsxs("span",{children:["Signed in as ",qs((null==l?void 0:l.name)||(null==l?void 0:l.email))]})]})}):n.jsx("div",{className:`echo-signin ${r}`,children:i?n.jsx("div",{onClick:p,style:{cursor:"pointer"},children:i}):n.jsxs("button",{onClick:p,disabled:c,className:"echo-signin-button",style:{display:"flex",alignItems:"center",gap:"8px",padding:"12px 20px",backgroundColor:c?"#f3f4f6":d?"#f1f5f9":"#ffffff",color:c?"#9ca3af":"#09090b",border:"1px solid #e2e8f0",borderRadius:"8px",cursor:c?"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:()=>h(!0),onMouseLeave:()=>h(!1),children:[n.jsx(Hs,{width:16,height:16,variant:"light"}),n.jsx("span",{children:c?"Signing in...":"Sign in"})]})})},exports.EchoTokenPurchase=function({onPurchaseComplete:e,onError:t,className:r="",children:i}){const{createPaymentLink:o,isAuthenticated:a,balance:c,freeTierBalance:l,refreshBalance:u}=Un(),[d,h]=s.useState(!1),[p,f]=s.useState(null),[g,m]=s.useState(!1),[_,w]=s.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==c?void 0:c.balance)||0)},S=async r=>{if(!a){const e=new Error("Please sign in to purchase tokens");return f(e.message),void(t&&t(e))}try{h(!0),f(null);const n=await o(r);await Bs(n,{onComplete:async()=>{try{await u(),m(!1),w(!1),e&&c&&e(c)}catch(r){const e=r instanceof Error?r:new Error("Failed to refresh balance");f(e.message),t&&t(e)}finally{h(!1)}},onCancel:()=>{h(!1)},onError:e=>{f(e.message),t&&t(e),h(!1)}})}catch(n){const e=n instanceof Error?n:new Error("Failed to create payment link");f(e.message),t&&t(e),h(!1)}},v=()=>{m(!1),w(!1),f(null)};if(!a)return n.jsx("div",{className:`echo-token-purchase ${r}`,children:n.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 E=()=>{const[e,t]=s.useState(!1);return n.jsxs("button",{onClick:()=>m(!0),className:`echo-token-purchase-compact ${r}`,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:[n.jsx(Hs,{width:16,height:16,variant:"light"}),n.jsx("span",{children:y(b())}),n.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:[n.jsx("path",{d:"M7 7h10v10"}),n.jsx("path",{d:"M7 17 17 7"})]})]})},k=()=>n.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&&v()},children:n.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:[n.jsx("div",{style:{padding:"16px 16px 0 16px",marginBottom:"12px"},children:n.jsx("h2",{style:{fontSize:"18px",fontWeight:"500",color:"#111827",margin:0,fontFamily:"HelveticaNowDisplay, sans-serif"},children:"Credits"})}),n.jsxs("div",{style:{padding:"0 16px",marginBottom:"16px"},children:[n.jsx("p",{style:{fontSize:"14px",color:"#6b7280",margin:"0 0 4px 0",fontFamily:"HelveticaNowDisplay, sans-serif"},children:"Total Available"}),n.jsx("p",{style:{fontSize:"28px",fontWeight:"700",color:"#111827",margin:"0 0 12px 0",fontFamily:"HelveticaNowDisplay, sans-serif"},children:y(b())}),n.jsxs("div",{style:{marginBottom:"8px"},children:[l&&b()>0&&n.jsxs("div",{style:{marginBottom:"8px"},children:[n.jsxs("div",{style:{fontSize:"12px",color:"#6b7280",fontFamily:"HelveticaNowDisplay, sans-serif",display:"flex",alignItems:"center",gap:"6px",marginBottom:"4px"},children:[n.jsx("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:"#3b82f6"}}),n.jsxs("span",{children:[y(l.userSpendInfo.amountLeft<0?0:l.userSpendInfo.amountLeft)," ","Free Tier",l.userSpendInfo&&l.userSpendInfo.spendLimit&&n.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&&n.jsx("div",{style:{width:"100%",height:"4px",backgroundColor:"#e5e7eb",borderRadius:"2px",overflow:"hidden",marginBottom:"4px",border:"1px solid #d1d5db"},children:n.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"}})})]}),c&&c.balance>0&&n.jsxs("div",{style:{fontSize:"12px",color:"#6b7280",fontFamily:"HelveticaNowDisplay, sans-serif"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",marginBottom:"4px"},children:[n.jsx("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:"#dc2626"}}),n.jsxs("span",{children:[y(c.balance)," Paid Credits",c.totalSpent&&n.jsxs("span",{style:{color:"#9ca3af",marginLeft:"8px"},children:["(",y(c.totalSpent)," /"," ",y(c.totalPaid)," spent)"]})]})]}),c.totalPaid>0&&n.jsx("div",{style:{width:"100%",height:"4px",backgroundColor:"#e5e7eb",borderRadius:"2px",overflow:"hidden",border:"1px solid #d1d5db"},children:n.jsx("div",{style:{width:`${Math.max(0,Math.min(100,c.balance/c.totalPaid*100))}%`,height:"100%",backgroundColor:"#dc2626"}})})]})]})]}),n.jsxs("div",{style:{padding:"0 16px 16px 16px",borderTop:"1px solid #f3f4f6",paddingTop:"16px"},children:[n.jsx("p",{style:{fontSize:"14px",color:"#6b7280",margin:"0 0 12px 0",fontFamily:"HelveticaNowDisplay, sans-serif"},children:"Add Credits"}),_?n.jsx(zs,{onAddCredits:S,onCancel:()=>w(!1),isProcessing:d}):n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[n.jsx("button",{onClick:()=>S(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"}),n.jsx("button",{onClick:()=>w(!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"})]})]}),p&&n.jsx("div",{style:{margin:"0 16px 12px 16px",padding:"8px 12px",backgroundColor:"#fee2e2",color:"#dc2626",borderRadius:"6px",fontSize:"14px",fontFamily:"HelveticaNowDisplay, sans-serif"},children:p}),n.jsx("div",{style:{padding:"12px 16px",display:"flex",justifyContent:"flex-end",borderTop:"1px solid #f3f4f6"},children:n.jsx("button",{onClick:v,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 n.jsxs(n.Fragment,{children:[i?n.jsx("div",{onClick:()=>m(!0),style:{cursor:"pointer"},children:i}):n.jsx(E,{}),g&&n.jsx(k,{})]})},exports.Logo=Hs,exports.useEcho=Un,exports.useEchoClient=Nn,exports.useEchoOpenAI=function(e={}){const{baseURL:t="https://echo.router.merit.systems",enabled:r=!0}=e,{token:n,isAuthenticated:i}=Un(),[o,a]=s.useState(void 0),[c,l]=s.useState(null),[u,d]=s.useState(!1),h=s.useRef(null);return s.useEffect((()=>{if(h.current&&h.current.abort(),!r||!n||!i)return a(void 0),l(null),void d(!1);return(async()=>{const e=new AbortController;h.current=e,d(!0),l(null);try{if(e.signal.aborted)return;const{default:r}=await import("openai");if(e.signal.aborted)return;const s=new r({apiKey:n,baseURL:t,dangerouslyAllowBrowser:!0});e.signal.aborted||a(s)}catch(r){if(!e.signal.aborted){const e=r instanceof Error?r.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:",r),a(void 0)}}finally{e.signal.aborted||d(!1)}})(),()=>{h.current&&h.current.abort()}}),[n,i,t,r]),{openai:o,isReady:void 0!==o&&!u,error:c,isLoading:u}};
|
|
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,l,u,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||{});(u=d||(d={})).reset=function(){a=3,l=c},u.setLevel=function(e){if(!(0<=e&&e<=4))throw new Error("Invalid log level");a=e},u.setLogger=function(e){l=e};var p=class e{constructor(e){this._name=e}debug(...t){a>=4&&l.debug(e._format(this._name,this._method),...t)}info(...t){a>=3&&l.info(e._format(this._name,this._method),...t)}warn(...t){a>=2&&l.warn(e._format(this._name,this._method),...t)}error(...t){a>=1&&l.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&&l.debug(e._format(t),...n)}static info(t,...n){a>=3&&l.info(e._format(t),...n)}static warn(t,...n){a>=2&&l.warn(e._format(t),...n)}static error(t,...n){a>=1&&l.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 l={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),l.ath=a),o&&(l.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,l,i.privateKey)}catch(u){throw u instanceof TypeError?new Error(`Error exporting dpop public key: ${u.message}`):u}}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(u){throw i.error("Network Error"),u}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 l;try{l=await s.json()}catch(u){if(i.error("Error parsing JSON response",u),s.ok)throw u;throw new Error(`${s.statusText} (${s.status})`)}if(!s.ok){if(i.error("Error from server:",l),l.error)throw new k(l);throw new Error(`${s.statusText} (${s.status}): ${JSON.stringify(l)}`)}return l}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 l;void 0!==n&&(a.Authorization="Basic "+n),this._appendExtraHeaders(a);try{s.debug("url:",e),l=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",l.status);const u=l.headers.get("Content-Type");if(u&&!this._contentTypes.find((e=>u.startsWith(e))))throw new Error(`Invalid response Content-Type: ${null!=u?u:"undefined"}, from URL: ${e}`);const c=await l.text();let d={};if(c)try{d=JSON.parse(c)}catch(p){if(s.error("Error parsing JSON response",p),l.ok)throw p;throw new Error(`${l.statusText} (${l.status})`)}if(!l.ok){if(s.error("Error from server:",d),l.headers.has("dpop-nonce")){const e=l.headers.get("dpop-nonce");throw new E(e,`${JSON.stringify(d)}`)}if(d.error)throw new k(d,t);throw new Error(`${l.statusText} (${l.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:l="openid",redirect_uri:u,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:R={},dpop:U,omitScopeWhenRequesting:P=!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=l,this.redirect_uri=u,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=P,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=R,this.dpop=U,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}},R=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 l;switch(this._settings.client_authentication){case"client_secret_basic":if(null==r)throw s.throw(new Error("A client_secret is required")),null;l=f.generateBasicAuth(n,r);break;case"client_secret_post":a.append("client_id",n),r&&a.append("client_secret",r)}const u=await this._metadataService.getTokenEndpoint(!1);s.debug("got token endpoint");const c=await this._jsonService.postForm(u,{body:a,basicAuth:l,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 l=await this._metadataService.getTokenEndpoint(!1);o.debug("got token endpoint");const u=await this._jsonService.postForm(l,{body:s,basicAuth:a,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials});return o.debug("got response"),u}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 l;switch(this._settings.client_authentication){case"client_secret_basic":if(null==n)throw s.throw(new Error("A client_secret is required")),null;l=f.generateBasicAuth(t,n);break;case"client_secret_post":a.append("client_id",t),n&&a.append("client_secret",n)}const u=await this._metadataService.getTokenEndpoint(!1);s.debug("got token endpoint");const c=await this._jsonService.postForm(u,{body:a,basicAuth:l,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")}},U=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 R(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}},P=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],l=await t.get(n);let u=!1;if(l)try{const t=await e.fromStorageString(l);r.debug("got item from key:",n,t.created),t.created<=i&&(u=!0)}catch(s){r.error("Error parsing state for key:",n,s),u=!0}else r.debug("no item in storage for key:",n),u=!0;u&&(r.debug("removed item for key:",n),t.remove(n))}}},j=class e extends P{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:l,request_type:u,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:u,url_state:p,code_verifier:!v,client_id:r,authority:n,redirect_uri:i,response_mode:l,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:l,...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 l=new URL(e);if(n&&l.searchParams.append("id_token_hint",n),s&&l.searchParams.append("client_id",s),r&&(l.searchParams.append("post_logout_redirect_uri",r),t||a)){this.state=new P({data:t,request_type:o,url_state:a});let e=this.state.id;a&&(e=`${e}${w}${a}`),l.searchParams.append("state",e)}for(const[u,c]of Object.entries({...i}))null!=c&&l.searchParams.append(u,c.toString());this.url=l.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}},B=class{constructor(e,t){this.keys=e,this.nonce=t}},J=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 U(this.settings,this.metadataService,this._claimsService),this._tokenClient=new R(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:l,response_type:u=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"!==u)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:u,scope:c,state_data:e,url_state:l,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 B(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 l,u;if(void 0===this.settings.refreshTokenAllowedScope)l=e.scope;else{const t=this.settings.refreshTokenAllowedScope.split(" ");l=((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{u=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:l,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),u=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:l,redirect_uri:t,resource:n,timeoutInSeconds:r,extraHeaders:i,...o})}const c=new M(new URLSearchParams);return Object.assign(c,u),a.debug("validating response",c),await this._validator.validateRefreshResponse(c,{...e,scope:l}),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"),l=await this.metadataService.getEndSessionEndpoint();if(!l)throw a.throw(new Error("No end session endpoint")),null;a.debug("Received end session endpoint",l),n||!o||t||(n=this.settings.client_id);const u=new L({url:l,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=u.state;return c&&(a.debug("Signout request has state to persist"),await this.settings.stateStore.set(c.id,c.toStorageString())),u}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 P.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"),P.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:l=e.iframeScriptOrigin,requestTimeoutInSeconds:u,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=l,this.silent_redirect_uri=c,this.silentRequestTimeoutInSeconds=d||u||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()}},le=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)}},ue=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 J(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 le(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,l=this.settings.popup_redirect_uri;l||n.throw(new Error("No popup_redirect_uri configured"));const u=await this._popupNavigator.prepare({popupWindowFeatures:i,popupWindowTarget:o,popupSignal:s}),c=await this._signin({request_type:"si:p",redirect_uri:l,display:"popup",dpopJkt:r,...a},u);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 ue(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 l=this.settings.silent_redirect_uri;let u;l||r.throw(new Error("No silent_redirect_uri configured")),a&&this.settings.validateSubOnSilentRenew&&(r.debug("subject prior to silent renew:",a.profile.sub),u=a.profile.sub);const c=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:i});return a=await this._signin({request_type:"si:s",redirect_uri:l,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?null==a?void 0:a.id_token:void 0,dpopJkt:s,...o},c,u),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(l){if(this.settings.monitorAnonymousSession&&l instanceof k)switch(l.error){case"login_required":case"consent_required":case"interaction_required":case"account_selection_required":return t.info("success for anonymous user"),{session_state:l.session_state}}throw l}}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 B(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:l=null,...u}=e,[c]=i.useState((()=>null!=l?l:Ie?new Ie(u):{settings:u})),[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",Re=`vercel.ai.error.${Ae}`,Ue=Symbol.for(Re),Pe=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:l}){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=l}static isInstance(e){return Ce.hasMarker(e,Re)}};Ne=Ue;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}`,Be=Symbol.for(We),Je=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=Be;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 lt,ut="AI_LoadAPIKeyError",ct=`vercel.ai.error.${ut}`,dt=Symbol.for(ct),pt=class extends Ce{constructor({message:e}){super({name:ut,message:e}),this[lt]=!0}static isInstance(e){return Ce.hasMarker(e,ct)}};lt=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 Rt 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 Ut(e){}function Pt(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=Ut,onError:n=Ut,onRetry:r=Ut,onComment:i}=e;let o,s="",a=!0,l="",u="";function c(e){if(""===e)return l.length>0&&t({id:o,event:u||void 0,data:l.endsWith("\n")?l.slice(0,-1):l}),o=void 0,l="",void(u="");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":u=t;break;case"data":l=`${l}${t}\n`;break;case"id":o=t.includes("\0")?void 0:t;break;case"retry":/^\d+$/.test(t)?r(parseInt(t,10)):n(new Rt(`Invalid \`retry\` value: "${t}"`,{type:"invalid-retry",value:t,line:i}));break;default:n(new Rt(`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,l="",u="",s=""}}}class jt extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let r;super({start(i){r=Pt({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 Bt(e,t){return"bigint"==typeof t?t.toString():t}function Jt(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=Jt((()=>{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 ln=new Set(["string","number","symbol"]),un=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,l;const u={...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==(l=n.localeError)?void 0:l.call(n,e))??"Invalid input";u.message=c}return delete u.inst,delete u.continue,(null==t?void 0:t.reportInput)||delete u.input,u}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:Jt,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:Bt,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:un,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:ln,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,Bt,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},An=Dt("$ZodError",Cn),Rn=Dt("$ZodError",Cn,{Parent:Error});function Un(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 Pn(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,l=0;for(;l<e.length;){const t=e[l],r=l===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)),l++}}};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(Rn),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(Rn),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(Rn),Bn=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}},Jn=Bn(Rn),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])$/,lr=/^(([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})$/,ur=/^((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:ur,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:lr,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})}})),Rr=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})}})),Ur=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})}})),Pr=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})}})),Br=Dt("$ZodCheckLowerCase",((e,t)=>{t.pattern??(t.pattern=Er),Fr.init(e,t)})),Jr=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 Jn(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)})),li=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})}}})),ui=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=lr),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=ur),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}})),Ri=Dt("$ZodNumber",((e,t)=>{Pr.init(e,t),Ai.init(e,t)})),Ui=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}})),Pi=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),Pi.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 Bi(e,t,n){e.issues.length&&t.issues.push(...In(n,e.issues)),t.value[n]=e.value}const Ji=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=>Bi(t,n,e)))):Bi(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=Jt((()=>{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 l;e._zod.parse=(u,c)=>{l??(l=n.value);const d=u.value;if(!i(d))return u.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),u;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)),u=r(u,c);else{u.value={};const e=l.shape;for(const t of l.keys){const n=e[t]._zod.run({value:d[t],issues:[]},c);n instanceof Promise?p.push(n.then((e=>Hi(e,u,t,d)))):Hi(n,u,t,d)}}if(!a)return p.length?Promise.all(p).then((()=>u)):u;const m=[],h=l.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,u,e,d)))):Hi(t,u,e,d)}return m.length&&u.issues.push({code:"unrecognized_keys",keys:m,input:d,inst:e}),p.length?Promise.all(p).then((()=>u)):u}}));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=Jt((()=>{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 l=-1;for(const e of n){if(l++,l>=s.length&&l>=r)continue;const t=e._zod.run({value:s[l],issues:[]},o);t instanceof Promise?a.push(t.then((e=>no(e,i,l)))):no(t,i,l)}if(t.rest){const e=s.slice(n.length);for(const n of e){l++;const e=t.rest._zod.run({value:n,issues:[]},o);e instanceof Promise?a.push(e.then((e=>no(e,i,l)))):no(e,i,l)}}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 l=t.valueType._zod.run({value:i[s],issues:[]},r);l instanceof Promise?o.push(l.then((e=>{e.issues.length&&n.issues.push(...In(s,e.issues)),n.value[a.value]=e.value}))):(l.issues.length&&n.issues.push(...In(s,l.issues)),n.value[a.value]=l.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 l=t.keyType._zod.run({value:s,issues:[]},r),u=t.valueType._zod.run({value:a,issues:[]},r);l instanceof Promise||u instanceof Promise?o.push(Promise.all([l,u]).then((([t,o])=>{oo(t,o,n,s,i,e,r)}))):oo(l,u,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&&(ln.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&&(ln.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 lo=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=>ln.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}})),uo=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&&!un.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 Ro=()=>{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 Uo=()=>{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 Po(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=Po(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=Po(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 Bo=()=>{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 Jo=()=>{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 ls=()=>{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 us=()=>{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:Ro()}},az:function(){return{localeError:Uo()}},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:Bo()}},fi:function(){return{localeError:Jo()}},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:us()}},ps:function(){return{localeError:ls()}},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 Rs(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...pn(t)})}function Us(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...pn(t)})}function Ps(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 Bs(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...pn(t)})}function Js(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 la(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...pn(t)})}function ua(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 Rr({check:"greater_than",...pn(t),value:e,inclusive:!1})}function Ca(e,t){return new Rr({check:"greater_than",...pn(t),value:e,inclusive:!0})}function Aa(e){return Na(0,e)}function Ra(e){return Ta(0,e)}function Ua(e){return Oa(0,e)}function Pa(e){return Ca(0,e)}function ja(e,t){return new Ur({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 Br({check:"string_format",format:"lowercase",...pn(e)})}function Ba(e){return new Jr({check:"string_format",format:"uppercase",...pn(e)})}function Ja(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 el(){return Ya((e=>e.toLowerCase()))}function tl(){return Ya((e=>e.toUpperCase()))}function nl(e,t,n){return new e({type:"array",element:t,...pn(n)})}function rl(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 il(e,t){return new e({type:"file",...pn(t)})}function ol(e,t,n){const r=pn(n);r.abort??(r.abort=!0);return new e({type:"custom",check:"custom",fn:t,...r})}function sl(e,t,n){return new e({type:"custom",check:"custom",fn:t,...pn(n)})}function al(e){const t=ll((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 ll(e,t){const n=new Nr({check:"custom",...pn(t)});return n._zod.check=e,n}function ul(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,l=e.Boolean??Ui,u=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 u({type:"string",error:n.error}),out:c,error:n.error});return new a({type:"pipe",in:d,out:new l({type:"boolean",error:n.error}),error:n.error})}function cl(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 dl{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 pl(e){return new dl({type:"function",input:Array.isArray(null==e?void 0:e.input)?rl(to,null==e?void 0:e.input):(null==e?void 0:e.input)??nl(Ji,ka(Zi)),output:(null==e?void 0:e.output)??ka(Zi)})}class ml{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:""},l=this.seen.get(e);if(l){l.count++;return t.schemaPath.includes(e)&&(l.cycle=t.path),l.schema}const u={schema:{},count:1,cycle:void 0,path:t.path};this.seen.set(e,u);const c=null==(r=(n=e._zod).toJSONSchema)?void 0:r.call(n);if(c)u.schema=c;else{const n={...t,schemaPath:[...t.schemaPath,e],path:t.path},r=e._zod.parent;if(r)u.ref=r,this.process(r,n),this.seen.get(r).isParent=!0;else{const t=u.schema;switch(s.type){case"string":{const n=t;n.type="string";const{minimum:r,maximum:i,format:o,patterns:s,contentEncoding:l}=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),l&&(n.contentEncoding=l),s&&s.size>0){const e=[...s];1===e.length?n.pattern=e[0].source:e.length>1&&(u.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:l}=e._zod.bag;"string"==typeof o&&o.includes("int")?n.type="integer":n.type="number","number"==typeof l&&("draft-4"===this.target?(n.minimum=l,n.exclusiveMinimum=!0):n.exclusiveMinimum=l),"number"==typeof r&&(n.minimum=r,"number"==typeof l&&"draft-4"!==this.target&&(l>=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),u.ref=s.innerType;break;case"success":t.type="boolean";break;case"default":this.process(s.innerType,n),u.ref=s.innerType,t.default=JSON.parse(JSON.stringify(s.defaultValue));break;case"prefault":this.process(s.innerType,n),u.ref=s.innerType,"input"===this.io&&(t._prefault=JSON.parse(JSON.stringify(s.defaultValue)));break;case"catch":{let e;this.process(s.innerType,n),u.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),u.ref=e;break}case"readonly":this.process(s.innerType,n),u.ref=s.innerType,t.readOnly=!0;break;case"lazy":{const t=e._zod.innerType;this.process(t,n),u.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(u.schema,d),"input"===this.io&&gl(e)&&(delete u.schema.examples,delete u.schema.default),"input"===this.io&&u.schema._prefault&&((o=u.schema).default??(o.default=u.schema._prefault)),delete u.schema._prefault;return this.seen.get(e).schema}emit(e,t){var n,r,i,o,s,a;const l={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},u=this.seen.get(e);if(!u)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(l.external){const r=null==(t=l.external.registry.get(e[0]))?void 0:t.id,i=l.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]===u)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"===l.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(l.external){const t=null==(r=l.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"===l.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=l.external)?void 0:o.uri){const t=null==(s=l.external.registry.get(e))?void 0:s.id;if(!t)throw new Error("Schema is missing an `id` property");m.$id=l.external.uri(t)}Object.assign(m,u.def);const h=(null==(a=l.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)}l.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 hl(e,t){if(e instanceof Es){const n=new ml(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 ml(t);return n.process(e),n.emit(e,t)}function gl(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 gl(r.element,n);case"object":for(const e in r.shape)if(gl(r.shape[e],n))return!0;return!1;case"union":for(const e of r.options)if(gl(e,n))return!0;return!1;case"intersection":return gl(r.left,n)||gl(r.right,n);case"tuple":for(const e of r.items)if(gl(e,n))return!0;return!(!r.rest||!gl(r.rest,n));case"record":case"map":return gl(r.keyType,n)||gl(r.valueType,n);case"set":return gl(r.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":case"default":case"prefault":return gl(r.innerType,n);case"lazy":return gl(r.getter(),n);case"transform":return!0;case"pipe":return gl(r.in,n)||gl(r.out,n)}throw new Error(`Unknown schema type: ${r.type}`)}const fl=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"})),vl=Object.freeze(Object.defineProperty({__proto__:null,$ZodAny:Li,$ZodArray:Ji,$ZodAsyncError:Lt,$ZodBase64:Si,$ZodBase64URL:Ei,$ZodBigInt:Pi,$ZodBigIntFormat:ji,$ZodBoolean:Ui,$ZodCIDRv4:ki,$ZodCIDRv6:xi,$ZodCUID:di,$ZodCUID2:pi,$ZodCatch:ko,$ZodCheck:Nr,$ZodCheckBigIntFormat:jr,$ZodCheckEndsWith:Kr,$ZodCheckGreaterThan:Rr,$ZodCheckIncludes:Hr,$ZodCheckLengthEquals:qr,$ZodCheckLessThan:Ar,$ZodCheckLowerCase:Br,$ZodCheckMaxLength:Lr,$ZodCheckMaxSize:zr,$ZodCheckMimeType:Xr,$ZodCheckMinLength:Zr,$ZodCheckMinSize:Dr,$ZodCheckMultipleOf:Ur,$ZodCheckNumberFormat:Pr,$ZodCheckOverwrite:Qr,$ZodCheckProperty:Yr,$ZodCheckRegex:Wr,$ZodCheckSizeEquals:Mr,$ZodCheckStartsWith:Vr,$ZodCheckStringFormat:Fr,$ZodCheckUpperCase:Jr,$ZodCustom:Co,$ZodCustomStringFormat:Ci,$ZodDate:Wi,$ZodDefault:fo,$ZodDiscriminatedUnion:Yi,$ZodE164:Ti,$ZodEmail:ai,$ZodEmoji:ui,$ZodEnum:lo,$ZodError:An,$ZodFile:co,$ZodFunction:dl,$ZodGUID:oi,$ZodIPv4:bi,$ZodIPv6:wi,$ZodISODate:vi,$ZodISODateTime:fi,$ZodISODuration:_i,$ZodISOTime:yi,$ZodIntersection:Xi,$ZodJWT:Ni,$ZodKSUID:gi,$ZodLazy:No,$ZodLiteral:uo,$ZodMap:io,$ZodNaN:xo,$ZodNanoID:ci,$ZodNever:qi,$ZodNonOptional:_o,$ZodNull:Mi,$ZodNullable:go,$ZodNumber:Ai,$ZodNumberFormat:Ri,$ZodObject:Vi,$ZodOptional:ho,$ZodPipe:Io,$ZodPrefault:yo,$ZodPromise:Oo,$ZodReadonly:$o,$ZodRealError:Rn,$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:li,$ZodUUID:si,$ZodUndefined:Di,$ZodUnion:Gi,$ZodUnknown:Zi,$ZodVoid:Fi,$ZodXID:hi,$brand:Mt,$constructor:Dt,$input:$s,$output:Ss,Doc:ei,JSONSchema:fl,JSONSchemaGenerator:ml,NEVER:zt,TimePrecision:ea,_any:wa,_array:nl,_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:ll,_cidrv4:Vs,_cidrv6:Ks,_coercedBigint:ga,_coercedBoolean:ma,_coercedDate:$a,_coercedNumber:sa,_coercedString:Cs,_cuid:Zs,_cuid2:qs,_custom:ol,_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:il,_float32:la,_float64:ua,_gt:Na,_gte:Ca,_guid:Rs,_includes:Ja,_int:aa,_int32:ca,_int64:fa,_intersection:function(e,t,n){return new e({type:"intersection",left:t,right:n})},_ipv4:Js,_ipv6:Hs,_isoDate:na,_isoDateTime:ta,_isoDuration:ia,_isoTime:ra,_jwt:Qs,_ksuid:Bs,_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:Ra,_never:xa,_nonnegative:Pa,_nonoptional:function(e,t,n){return new e({type:"nonoptional",innerType:t,...pn(n)})},_nonpositive:Ua,_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:sl,_regex:Fa,_safeParse:Fn,_safeParseAsync:Bn,_set:function(e,t,n){return new e({type:"set",valueType:t,...pn(n)})},_size:Ma,_startsWith:Ha,_string:Ns,_stringFormat:cl,_stringbool:ul,_success:function(e,t){return new e({type:"success",innerType:t})},_superRefine:al,_symbol:ya,_templateLiteral:function(e,t,n){return new e({type:"template_literal",parts:t,...pn(n)})},_toLowerCase:el,_toUpperCase:tl,_transform:function(e,t){return new e({type:"transform",transform:t})},_trim:Qa,_tuple:rl,_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:Ba,_url:Ds,_uuid:Us,_uuidv4:Ps,_uuidv6:js,_uuidv7:zs,_void:Ia,_xid:Ws,clone:dn,config:qt,flattenError:Un,formatError:Pn,function:pl,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:Jn,toDotPath:zn,toJSONSchema:hl,treeifyError:jn,util:Nn,version:ti},Symbol.toStringTag,{value:"Module"})),yl=Dt("ZodISODateTime",((e,t)=>{fi.init(e,t),Dl.init(e,t)}));function _l(e){return ta(yl,e)}const bl=Dt("ZodISODate",((e,t)=>{vi.init(e,t),Dl.init(e,t)}));function wl(e){return na(bl,e)}const kl=Dt("ZodISOTime",((e,t)=>{yi.init(e,t),Dl.init(e,t)}));function xl(e){return ra(kl,e)}const Il=Dt("ZodISODuration",((e,t)=>{_i.init(e,t),Dl.init(e,t)}));function Sl(e){return ia(Il,e)}const $l=Object.freeze(Object.defineProperty({__proto__:null,ZodISODate:bl,ZodISODateTime:yl,ZodISODuration:Il,ZodISOTime:kl,date:wl,datetime:_l,duration:Sl,time:xl},Symbol.toStringTag,{value:"Module"})),El=(e,t)=>{An.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>Pn(e,t)},flatten:{value:t=>Un(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Bt,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Bt,2)}},isEmpty:{get:()=>0===e.issues.length}})},Tl=Dt("ZodError",El),Ol=Dt("ZodError",El,{Parent:Error}),Nl=Mn(Ol),Cl=Zn(Ol),Al=Fn(Ol),Rl=Bn(Ol),Ul=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)=>Nl(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Al(e,t,n),e.parseAsync=async(t,n)=>Cl(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Rl(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=()=>Xu(e),e.nullable=()=>ec(e),e.nullish=()=>Xu(ec(e)),e.nonoptional=t=>sc(e,t),e.array=()=>Eu(e),e.or=t=>Ru([e,t]),e.and=t=>zu(e,t),e.transform=t=>pc(e,Gu(t)),e.default=t=>nc(e,t),e.prefault=t=>ic(e,t),e.catch=t=>uc(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))),Pl=Dt("_ZodString",((e,t)=>{ri.init(e,t),Ul.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(Ja(...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(Ba(t)),e.trim=()=>e.check(Qa()),e.normalize=(...t)=>e.check(Xa(...t)),e.toLowerCase=()=>e.check(el()),e.toUpperCase=()=>e.check(tl())})),jl=Dt("ZodString",((e,t)=>{ri.init(e,t),Pl.init(e,t),e.email=t=>e.check(As(Ml,t)),e.url=t=>e.check(Ds(ql,t)),e.jwt=t=>e.check(Qs(iu,t)),e.emoji=t=>e.check(Ms(Fl,t)),e.guid=t=>e.check(Rs(Ll,t)),e.uuid=t=>e.check(Us(Zl,t)),e.uuidv4=t=>e.check(Ps(Zl,t)),e.uuidv6=t=>e.check(js(Zl,t)),e.uuidv7=t=>e.check(zs(Zl,t)),e.nanoid=t=>e.check(Ls(Wl,t)),e.guid=t=>e.check(Rs(Ll,t)),e.cuid=t=>e.check(Zs(Bl,t)),e.cuid2=t=>e.check(qs(Jl,t)),e.ulid=t=>e.check(Fs(Hl,t)),e.base64=t=>e.check(Gs(eu,t)),e.base64url=t=>e.check(Ys(nu,t)),e.xid=t=>e.check(Ws(Vl,t)),e.ksuid=t=>e.check(Bs(Kl,t)),e.ipv4=t=>e.check(Js(Gl,t)),e.ipv6=t=>e.check(Hs(Yl,t)),e.cidrv4=t=>e.check(Vs(Xl,t)),e.cidrv6=t=>e.check(Ks(Ql,t)),e.e164=t=>e.check(Xs(ru,t)),e.datetime=t=>e.check(_l(t)),e.date=t=>e.check(wl(t)),e.time=t=>e.check(xl(t)),e.duration=t=>e.check(Sl(t))}));function zl(e){return Ns(jl,e)}const Dl=Dt("ZodStringFormat",((e,t)=>{ii.init(e,t),Pl.init(e,t)})),Ml=Dt("ZodEmail",((e,t)=>{ai.init(e,t),Dl.init(e,t)}));const Ll=Dt("ZodGUID",((e,t)=>{oi.init(e,t),Dl.init(e,t)}));const Zl=Dt("ZodUUID",((e,t)=>{si.init(e,t),Dl.init(e,t)}));const ql=Dt("ZodURL",((e,t)=>{li.init(e,t),Dl.init(e,t)}));const Fl=Dt("ZodEmoji",((e,t)=>{ui.init(e,t),Dl.init(e,t)}));const Wl=Dt("ZodNanoID",((e,t)=>{ci.init(e,t),Dl.init(e,t)}));const Bl=Dt("ZodCUID",((e,t)=>{di.init(e,t),Dl.init(e,t)}));const Jl=Dt("ZodCUID2",((e,t)=>{pi.init(e,t),Dl.init(e,t)}));const Hl=Dt("ZodULID",((e,t)=>{mi.init(e,t),Dl.init(e,t)}));const Vl=Dt("ZodXID",((e,t)=>{hi.init(e,t),Dl.init(e,t)}));const Kl=Dt("ZodKSUID",((e,t)=>{gi.init(e,t),Dl.init(e,t)}));const Gl=Dt("ZodIPv4",((e,t)=>{bi.init(e,t),Dl.init(e,t)}));const Yl=Dt("ZodIPv6",((e,t)=>{wi.init(e,t),Dl.init(e,t)}));const Xl=Dt("ZodCIDRv4",((e,t)=>{ki.init(e,t),Dl.init(e,t)}));const Ql=Dt("ZodCIDRv6",((e,t)=>{xi.init(e,t),Dl.init(e,t)}));const eu=Dt("ZodBase64",((e,t)=>{Si.init(e,t),Dl.init(e,t)}));function tu(e){return Gs(eu,e)}const nu=Dt("ZodBase64URL",((e,t)=>{Ei.init(e,t),Dl.init(e,t)}));const ru=Dt("ZodE164",((e,t)=>{Ti.init(e,t),Dl.init(e,t)}));const iu=Dt("ZodJWT",((e,t)=>{Ni.init(e,t),Dl.init(e,t)}));const ou=Dt("ZodCustomStringFormat",((e,t)=>{Ci.init(e,t),Dl.init(e,t)}));const su=Dt("ZodNumber",((e,t)=>{Ai.init(e,t),Ul.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(uu(t)),e.safe=t=>e.check(uu(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 au(e){return oa(su,e)}const lu=Dt("ZodNumberFormat",((e,t)=>{Ri.init(e,t),su.init(e,t)}));function uu(e){return aa(lu,e)}const cu=Dt("ZodBoolean",((e,t)=>{Ui.init(e,t),Ul.init(e,t)}));function du(e){return pa(cu,e)}const pu=Dt("ZodBigInt",((e,t)=>{Pi.init(e,t),Ul.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 mu=Dt("ZodBigIntFormat",((e,t)=>{ji.init(e,t),pu.init(e,t)}));const hu=Dt("ZodSymbol",((e,t)=>{zi.init(e,t),Ul.init(e,t)}));const gu=Dt("ZodUndefined",((e,t)=>{Di.init(e,t),Ul.init(e,t)}));const fu=Dt("ZodNull",((e,t)=>{Mi.init(e,t),Ul.init(e,t)}));function vu(e){return ba(fu,e)}const yu=Dt("ZodAny",((e,t)=>{Li.init(e,t),Ul.init(e,t)}));function _u(){return wa(yu)}const bu=Dt("ZodUnknown",((e,t)=>{Zi.init(e,t),Ul.init(e,t)}));function wu(){return ka(bu)}const ku=Dt("ZodNever",((e,t)=>{qi.init(e,t),Ul.init(e,t)}));function xu(e){return xa(ku,e)}const Iu=Dt("ZodVoid",((e,t)=>{Fi.init(e,t),Ul.init(e,t)}));const Su=Dt("ZodDate",((e,t)=>{Wi.init(e,t),Ul.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 $u=Dt("ZodArray",((e,t)=>{Ji.init(e,t),Ul.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 Eu(e,t){return nl($u,e,t)}const Tu=Dt("ZodObject",((e,t)=>{Vi.init(e,t),Ul.init(e,t),Yt(e,"shape",(()=>t.shape)),e.keyof=()=>Bu(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:wu()}),e.loose=()=>e.clone({...e._zod.def,catchall:wu()}),e.strict=()=>e.clone({...e._zod.def,catchall:xu()}),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(Yu,e,t[0]),e.required=(...t)=>kn(oc,e,t[0])}));function Ou(e,t){const n={type:"object",get shape(){return Qt(this,"shape",e?Xt(e):{}),this.shape},...pn(t)};return new Tu(n)}function Nu(e,t){return new Tu({type:"object",get shape(){return Qt(this,"shape",Xt(e)),this.shape},catchall:xu(),...pn(t)})}function Cu(e,t){return new Tu({type:"object",get shape(){return Qt(this,"shape",Xt(e)),this.shape},catchall:wu(),...pn(t)})}const Au=Dt("ZodUnion",((e,t)=>{Gi.init(e,t),Ul.init(e,t),e.options=t.options}));function Ru(e,t){return new Au({type:"union",options:e,...pn(t)})}const Uu=Dt("ZodDiscriminatedUnion",((e,t)=>{Au.init(e,t),Yi.init(e,t)}));function Pu(e,t,n){return new Uu({type:"union",options:t,discriminator:e,...pn(n)})}const ju=Dt("ZodIntersection",((e,t)=>{Xi.init(e,t),Ul.init(e,t)}));function zu(e,t){return new ju({type:"intersection",left:e,right:t})}const Du=Dt("ZodTuple",((e,t)=>{to.init(e,t),Ul.init(e,t),e.rest=t=>e.clone({...e._zod.def,rest:t})}));function Mu(e,t,n){const r=t instanceof ni;return new Du({type:"tuple",items:e,rest:r?t:null,...pn(r?n:t)})}const Lu=Dt("ZodRecord",((e,t)=>{ro.init(e,t),Ul.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType}));function Zu(e,t,n){return new Lu({type:"record",keyType:e,valueType:t,...pn(n)})}const qu=Dt("ZodMap",((e,t)=>{io.init(e,t),Ul.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType}));const Fu=Dt("ZodSet",((e,t)=>{so.init(e,t),Ul.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 Wu=Dt("ZodEnum",((e,t)=>{lo.init(e,t),Ul.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 Wu({...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 Wu({...t,checks:[],...pn(r),entries:i})}}));function Bu(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map((e=>[e,e]))):e;return new Wu({type:"enum",entries:n,...pn(t)})}const Ju=Dt("ZodLiteral",((e,t)=>{uo.init(e,t),Ul.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 Hu(e,t){return new Ju({type:"literal",values:Array.isArray(e)?e:[e],...pn(t)})}const Vu=Dt("ZodFile",((e,t)=>{co.init(e,t),Ul.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 Ku=Dt("ZodTransform",((e,t)=>{po.init(e,t),Ul.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 Gu(e){return new Ku({type:"transform",transform:e})}const Yu=Dt("ZodOptional",((e,t)=>{ho.init(e,t),Ul.init(e,t),e.unwrap=()=>e._zod.def.innerType}));function Xu(e){return new Yu({type:"optional",innerType:e})}const Qu=Dt("ZodNullable",((e,t)=>{go.init(e,t),Ul.init(e,t),e.unwrap=()=>e._zod.def.innerType}));function ec(e){return new Qu({type:"nullable",innerType:e})}const tc=Dt("ZodDefault",((e,t)=>{fo.init(e,t),Ul.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),Ul.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),Ul.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),Ul.init(e,t),e.unwrap=()=>e._zod.def.innerType}));const lc=Dt("ZodCatch",((e,t)=>{ko.init(e,t),Ul.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap}));function uc(e,t){return new lc({type:"catch",innerType:e,catchValue:"function"==typeof t?t:()=>t})}const cc=Dt("ZodNaN",((e,t)=>{xo.init(e,t),Ul.init(e,t)}));const dc=Dt("ZodPipe",((e,t)=>{Io.init(e,t),Ul.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),Ul.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),Ul.init(e,t)}));const fc=Dt("ZodLazy",((e,t)=>{No.init(e,t),Ul.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),Ul.init(e,t),e.unwrap=()=>e._zod.def.innerType}));const _c=Dt("ZodCustom",((e,t)=>{Co.init(e,t),Ul.init(e,t)}));function bc(e,t){return ol(_c,e??(()=>!0),t)}function wc(e,t={}){return sl(_c,e,t)}function kc(e){return al(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(su,e)}Ic||(Ic={});const $c=Object.freeze(Object.defineProperty({__proto__:null,bigint:function(e){return ga(pu,e)},boolean:function(e){return ma(cu,e)},date:function(e){return $a(Su,e)},number:Sc,string:function(e){return Cs(jl,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:yu,ZodArray:$u,ZodBase64:eu,ZodBase64URL:nu,ZodBigInt:pu,ZodBigIntFormat:mu,ZodBoolean:cu,ZodCIDRv4:Xl,ZodCIDRv6:Ql,ZodCUID:Bl,ZodCUID2:Jl,ZodCatch:lc,ZodCustom:_c,ZodCustomStringFormat:ou,ZodDate:Su,ZodDefault:tc,ZodDiscriminatedUnion:Uu,ZodE164:ru,ZodEmail:Ml,ZodEmoji:Fl,ZodEnum:Wu,ZodError:Tl,ZodFile:Vu,get ZodFirstPartyTypeKind(){return Ic},ZodGUID:Ll,ZodIPv4:Gl,ZodIPv6:Yl,ZodISODate:bl,ZodISODateTime:yl,ZodISODuration:Il,ZodISOTime:kl,ZodIntersection:ju,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:iu,ZodKSUID:Kl,ZodLazy:fc,ZodLiteral:Ju,ZodMap:qu,ZodNaN:cc,ZodNanoID:Wl,ZodNever:ku,ZodNonOptional:oc,ZodNull:fu,ZodNullable:Qu,ZodNumber:su,ZodNumberFormat:lu,ZodObject:Tu,ZodOptional:Yu,ZodPipe:dc,ZodPrefault:rc,ZodPromise:yc,ZodReadonly:mc,ZodRealError:Ol,ZodRecord:Lu,ZodSet:Fu,ZodString:jl,ZodStringFormat:Dl,ZodSuccess:ac,ZodSymbol:hu,ZodTemplateLiteral:gc,ZodTransform:Ku,ZodTuple:Du,ZodType:Ul,ZodULID:Hl,ZodURL:ql,ZodUUID:Zl,ZodUndefined:gu,ZodUnion:Au,ZodUnknown:bu,ZodVoid:Iu,ZodXID:Vl,_ZodString:Pl,_default:nc,any:_u,array:Eu,base64:tu,base64url:function(e){return Ys(nu,e)},bigint:function(e){return ha(pu,e)},boolean:du,catch:uc,check:function(e){const t=new Nr({check:"custom"});return t._zod.check=e,t},cidrv4:function(e){return Vs(Xl,e)},cidrv6:function(e){return Ks(Ql,e)},clone:dn,coerce:$c,config:qt,core:vl,cuid:function(e){return Zs(Bl,e)},cuid2:function(e){return qs(Jl,e)},custom:bc,date:function(e){return Sa(Su,e)},discriminatedUnion:Pu,e164:function(e){return Xs(ru,e)},email:function(e){return As(Ml,e)},emoji:function(e){return Ms(Fl,e)},endsWith:Va,enum:Bu,file:function(e){return il(Vu,e)},flattenError:Un,float32:function(e){return la(lu,e)},float64:function(e){return ua(lu,e)},formatError:Pn,function:pl,getErrorMap:function(){return qt().customError},globalRegistry:Os,gt:Na,gte:Ca,guid:function(e){return Rs(Ll,e)},hostname:function(e){return cl(ou,"hostname",mr,e)},includes:Ja,instanceof:xc,int:uu,int32:function(e){return ca(lu,e)},int64:function(e){return fa(mu,e)},intersection:zu,ipv4:function(e){return Js(Gl,e)},ipv6:function(e){return Hs(Yl,e)},iso:$l,json:function(e){const t=vc((()=>Ru([zl(e),au(),du(),vu(),Eu(t),Zu(zl(),t)])));return t},jwt:function(e){return Qs(iu,e)},keyof:function(e){const t=e._zod.def.shape;return Bu(Object.keys(t))},ksuid:function(e){return Bs(Kl,e)},lazy:vc,length:qa,literal:Hu,locales:Is,looseObject:Cu,lowercase:Wa,lt:Ta,lte:Oa,map:function(e,t,n){return new qu({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(Wl,e)},nativeEnum:function(e,t){return new Wu({type:"enum",entries:e,...pn(t)})},negative:Ra,never:xu,nonnegative:Pa,nonoptional:sc,nonpositive:Ua,normalize:Xa,null:vu,nullable:ec,nullish:function(e){return Xu(ec(e))},number:au,object:Ou,optional:Xu,overwrite:Ya,parse:Nl,parseAsync:Cl,partialRecord:function(e,t,n){const r=dn(e);return r._zod.values=void 0,new Lu({type:"record",keyType:r,valueType:t,...pn(n)})},pipe:pc,positive:Aa,prefault:ic,preprocess:function(e,t){return pc(Gu(e),t)},prettifyError:Dn,promise:function(e){return new yc({type:"promise",innerType:e})},property:Ka,readonly:hc,record:Zu,refine:wc,regex:Fa,regexes:Or,registry:Ts,safeParse:Al,safeParseAsync:Rl,set:function(e,t){return new Fu({type:"set",valueType:e,...pn(t)})},setErrorMap:function(e){qt({customError:e})},size:Ma,startsWith:Ha,strictObject:Nu,string:zl,stringFormat:function(e,t,n={}){return cl(ou,e,t,n)},stringbool:(...e)=>ul({Pipe:dc,Boolean:cu,String:jl,Transform:Ku},...e),success:function(e){return new ac({type:"success",innerType:e})},superRefine:kc,symbol:function(e){return ya(hu,e)},templateLiteral:function(e,t){return new gc({type:"template_literal",parts:e,...pn(t)})},toJSONSchema:hl,toLowerCase:el,toUpperCase:tl,transform:Gu,treeifyError:jn,trim:Qa,tuple:Mu,uint32:function(e){return da(lu,e)},uint64:function(e){return va(mu,e)},ulid:function(e){return Fs(Hl,e)},undefined:function(e){return _a(gu,e)},union:Ru,unknown:wu,uppercase:Ba,url:function(e){return Ds(ql,e)},uuid:function(e){return Us(Zl,e)},uuidv4:function(e){return Ps(Zl,e)},uuidv6:function(e){return js(Zl,e)},uuidv7:function(e){return zs(Zl,e)},void:function(e){return Ia(Iu,e)},xid:function(e){return Ws(Vl,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 Rc=(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 Uc(e){if("openAi"!==e.target)return{};const t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:"relative"===e.$refStrategy?Rc(t,e.currentPath):t.join("/")}}function Pc(e,t){return ld(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])$/,Bc=/^(([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])$/,Jc=/^([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,Bc,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,Jc,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="",l=!1,u=!1,c=!1;for(let d=0;d<s.length;d++)if(l)a+=s[d],l=!1;else{if(r)if(u){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+=u?`${s[d]}\r\n`:`[${s[d]}\r\n]`:(a+=s[d],"\\"===s[d]?l=!0:u&&"]"===s[d]?u=!1:u||"["!==s[d]||(u=!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]:ld(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",r]})??Uc(t)})),{}),additionalProperties:t.rejectedAdditionalProperties};const l={type:"object",additionalProperties:ld(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if("openApi3"===t.target)return l;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{...l,propertyNames:r}}if((null==(o=e.keyType)?void 0:o._def.typeName)===Ic.ZodEnum)return{...l,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}=Pc(e.keyType._def,t);return{...l,propertyNames:r}}return l}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)=>ld(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 l=ld(e._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});void 0!==l&&(r.properties[a]=l,s||i.push(a))}i.length&&(r.required=i);const s=function(e,t){if("ZodNever"!==e.catchall._def.typeName)return ld(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:Uc(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=ld(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=[ld(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),ld(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)=>ld(e._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]}))).reduce(((e,t)=>void 0===t?e:[...e,t]),[]),additionalItems:ld(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map(((e,n)=>ld(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=ld(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const n=ld(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 ld(e.innerType._def,t);const r=ld(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Uc(t)},r]}:Uc(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:[ld(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Uc(t),ld(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Uc(t)],minItems:2,maxItems:2}}}(e,n);case Ic.ZodSet:return function(e,t){const n={type:"array",uniqueItems:!0,items:ld(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 ld(e.type._def,t)}(e,n);case Ic.ZodNaN:case Ic.ZodNever:return function(e){return"openAi"===e.target?void 0:{not:Uc({...e,currentPath:[...e.currentPath,"not"]})}}(n);case Ic.ZodEffects:return function(e,t){return"input"===t.effectStrategy?ld(e.schema._def,t):Uc(t)}(e,n);case Ic.ZodAny:return Uc(n);case Ic.ZodUnknown:return function(e){return Uc(e)}(n);case Ic.ZodDefault:return function(e,t){return{...ld(e.innerType._def,t),default:e.defaultValue()}}(e,n);case Ic.ZodBranded:return Pc(e,n);case Ic.ZodReadonly:case Ic.ZodCatch:return((e,t)=>ld(e.innerType._def,t))(e,n);case Ic.ZodPipeline:return((e,t)=>{if("input"===t.pipeStrategy)return ld(e.in._def,t);if("output"===t.pipeStrategy)return ld(e.out._def,t);const n=ld(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]});return{allOf:[n,ld(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 ld(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=ud(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?ld(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 ud=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Rc(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`),Uc(t)):"seen"===t.$refStrategy?Uc(t):void 0}},cd=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n);function dd(...e){return e.reduce(((e,t)=>({...e,...null!=t?t:{}})),{})}function pd(e){return Object.fromEntries([...e.headers])}var md=({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 Je({argument:"separator",message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`},hd=md();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*:/,_d=/"constructor"\s*:/;function bd(e){const t=JSON.parse(e);return null===t||"object"!=typeof t||!1===yd.test(e)&&!1===_d.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 bd(e)}finally{Error.stackTraceLimit=t}}var kd=Symbol.for("vercel.ai.validator");function xd(e){return function(e){return"object"==typeof e&&null!==e&&kd in e&&!0===e[kd]&&"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})}},{[kd]:!0,validate:n});var t,n}async function Id({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}async function Sd({value:e,schema:t}){const n=xd(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=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 $d({text:e,schema:t}))}}))}async function Od({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 Je({argument:"providerOptions",message:`invalid ${e} provider options`,cause:r.error});return r.value}var Nd=()=>globalThis.fetch,Cd=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:o,fetch:s})=>Ad({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:o,fetch:s}),Ad=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:i,abortSignal:o,fetch:s=Nd()})=>{try{const u=await s(e,{method:"POST",headers:(a=t,Object.fromEntries(Object.entries(a).filter((([e,t])=>null!=t)))),body:n.content,signal:o}),c=pd(u);if(!u.ok){let t;try{t=await i({response:u,url:e,requestBodyValues:n.values})}catch(l){if(gd(l)||Pe.isInstance(l))throw l;throw new Pe({message:"Failed to process error response",cause:l,statusCode:u.status,url:e,responseHeaders:c,requestBodyValues:n.values})}throw t.value}try{return await r({response:u,url:e,requestBodyValues:n.values})}catch(l){if(l instanceof Error&&(gd(l)||Pe.isInstance(l)))throw l;throw new Pe({message:"Failed to process successful response",cause:l,statusCode:u.status,url:e,responseHeaders:c,requestBodyValues:n.values})}}catch(l){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 Pe({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}({error:l,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:l,...u})=>({type:"provider-defined",id:e,name:t,args:u,inputSchema:n,outputSchema:i,execute:r,toModelOutput:o,onInputStart:s,onInputDelta:a,onInputAvailable:l})}function Ud({id:e,name:t,inputSchema:n,outputSchema:r}){return({execute:i,toModelOutput:o,onInputStart:s,onInputDelta:a,onInputAvailable:l,...u})=>({type:"provider-defined",id:e,name:t,args:u,inputSchema:n,outputSchema:r,execute:i,toModelOutput:o,onInputStart:s,onInputDelta:a,onInputAvailable:l})}async function Pd(e){return"function"==typeof e&&(e=e()),Promise.resolve(e)}var jd=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:i,requestBodyValues:o})=>{const s=await r.text(),a=pd(r);if(""===s.trim())return{responseHeaders:a,value:new Pe({message:r.statusText,url:i,requestBodyValues:o,statusCode:r.status,responseHeaders:a,responseBody:s,isRetryable:null==n?void 0:n(r)})};try{const l=await async function({text:e,schema:t}){try{const n=wd(e);return null==t?n:Id({value:n,schema:t})}catch(n){if(at.isInstance(n)||Tt.isInstance(n))throw n;throw new at({text:e,cause:n})}}({text:s,schema:e});return{responseHeaders:a,value:new Pe({message:t(l),url:i,requestBodyValues:o,statusCode:r.status,responseHeaders:a,responseBody:s,data:l,isRetryable:null==n?void 0:n(r,l)})}}catch(l){return{responseHeaders:a,value:new Pe({message:r.statusText,url:i,requestBodyValues:o,statusCode:r.status,responseHeaders:a,responseBody:s,isRetryable:null==n?void 0:n(r)})}}},zd=e=>async({response:t})=>{const n=pd(t);if(null==t.body)throw new Le({});return{responseHeaders:n,value:Td({stream:t.body,schema:e})}},Dd=e=>async({response:t,url:n,requestBodyValues:r})=>{const i=await t.text(),o=await $d({text:i,schema:e}),s=pd(t);if(!o.success)throw new Pe({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 Md(e,t){const n=null!=void 0&&undefined;return qd(((e,t)=>{const n=Nc(t);let r="object"==typeof t&&t.definitions?Object.entries(t.definitions).reduce(((e,[t,r])=>({...e,[t]:ld(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??Uc(n)})),{}):void 0;const i="string"==typeof t?t:"title"===(null==t?void 0:t.nameStrategy)||null==t?void 0:t.name,o=ld(e._def,void 0===i?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??Uc(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})(e,{$refStrategy:n?"root":"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}}})}function Ld(e,t){return function(e){return"_zod"in e}(e)?function(e){return qd(hl(e,{target:"draft-7",io:"output",reused:"inline"}),{validate:async t=>{const n=await Rl(e,t);return n.success?{success:!0,value:n.data}:{success:!1,error:n.error}}})}(e):Md(e)}var Zd=Symbol.for("vercel.ai.schema");function qd(e,{validate:t}={}){return{[Zd]:!0,_type:void 0,[kd]:!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:Bd}=globalThis;function Jd(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=Bd(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=Ou({error:Ou({message:zl(),type:zl().nullish(),param:_u().nullish(),code:Ru([zl(),au()]).nullish()})}),Gd=jd({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=Ou({logitBias:Zu(Sc(),au()).optional(),logprobs:Ru([du(),au()]).optional(),parallelToolCalls:du().optional(),user:zl().optional(),reasoningEffort:Bu(["minimal","low","medium","high"]).optional(),maxCompletionTokens:au().optional(),store:du().optional(),metadata:Zu(zl().max(64),zl().max(512)).optional(),prediction:Zu(zl(),_u()).optional(),structuredOutputs:du().optional(),serviceTier:Bu(["auto","flex","priority"]).optional(),strictJsonSchema:du().optional(),textVerbosity:Bu(["low","medium","high"]).optional(),promptCacheKey:zl().optional(),safetyIdentifier:zl().optional()}),ep=Ou({key:zl(),type:Bu(["eq","ne","gt","gte","lt","lte"]),value:Ru([zl(),au(),du()])}),tp=Ou({type:Bu(["and","or"]),filters:Eu(Ru([ep,vc((()=>tp))]))}),np=Ru([ep,tp]),rp=Ou({vectorStoreIds:Eu(zl()).optional(),maxNumResults:au().optional(),ranking:Ou({ranker:Bu(["auto","default-2024-08-21"]).optional()}).optional(),filters:np.optional()}),ip=Rd({id:"openai.file_search",name:"file_search",inputSchema:Ou({query:zl()})}),op=Ou({searchContextSize:Bu(["low","medium","high"]).optional(),userLocation:Ou({type:Hu("approximate"),country:zl().optional(),city:zl().optional(),region:zl().optional(),timezone:zl().optional()}).optional()}),sp=Rd({id:"openai.web_search_preview",name:"web_search_preview",inputSchema:Ou({})});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:l,seed:u,tools:c,toolChoice:d,providerOptions:p}){var m,h,g,f;const v=[],y=null!=(m=await Od({provider:"openai",providerOptions:p,schema:Qd}))?m:{},_=null==(h=y.structuredOutputs)||h;null!=i&&v.push({type:"unsupported-setting",setting:"topK"}),"json"!==(null==l?void 0:l.type)||null==l.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==l?void 0:l.type)?_&&null!=l.schema?{type:"json_schema",json_schema:{schema:l.schema,strict:k,name:null!=(f=l.name)?f:"response",description:l.description}}:{type:"json_object"}:void 0,stop:a,seed:u,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,l,u,c,d,p,m,h;const{args:g,warnings:f}=await this.getArgs(e),{responseHeaders:v,value:y,rawValue:_}=await Cd({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:dd(this.config.headers(),e.headers),body:g,failedResponseHandler:Gd,successfulResponseHandler:Dd(up),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:hd(),toolName:$.function.name,input:$.function.arguments});for(const $ of null!=(r=b.message.annotations)?r:[])w.push({type:"source",sourceType:"url",id:hd(),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!=(l=null==(a=y.usage)?void 0:a.prompt_tokens)?l:void 0,outputTokens:null!=(c=null==(u=y.usage)?void 0:u.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 Cd({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:dd(this.config.headers(),e.headers),body:r,failedResponseHandler:Gd,successfulResponseHandler:zd(cp),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=[];let a="unknown";const l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let u=!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 R=t.value;if("error"in R)return a="error",void n.enqueue({type:"error",error:R.error});u&&(u=!1,n.enqueue({type:"response-metadata",...Yd(R)})),null!=R.usage&&(l.inputTokens=null!=(r=R.usage.prompt_tokens)?r:void 0,l.outputTokens=null!=(i=R.usage.completion_tokens)?i:void 0,l.totalTokens=null!=(o=R.usage.total_tokens)?o:void 0,l.reasoningTokens=null!=(m=null==(p=R.usage.completion_tokens_details)?void 0:p.reasoning_tokens)?m:void 0,l.cachedInputTokens=null!=(g=null==(h=R.usage.prompt_tokens_details)?void 0:h.cached_tokens)?g:void 0,null!=(null==(f=R.usage.completion_tokens_details)?void 0:f.accepted_prediction_tokens)&&(d.openai.acceptedPredictionTokens=null==(v=R.usage.completion_tokens_details)?void 0:v.accepted_prediction_tokens),null!=(null==(y=R.usage.completion_tokens_details)?void 0:y.rejected_prediction_tokens)&&(d.openai.rejectedPredictionTokens=null==(_=R.usage.completion_tokens_details)?void 0:_.rejected_prediction_tokens));const U=R.choices[0];if(null!=(null==U?void 0:U.finish_reason)&&(a=Xd(U.finish_reason)),null!=(null==(b=null==U?void 0:U.logprobs)?void 0:b.content)&&(d.openai.logprobs=U.logprobs.content),null==(null==U?void 0:U.delta))return;const P=U.delta;if(null!=P.content&&(c||(n.enqueue({type:"text-start",id:"0"}),c=!0),n.enqueue({type:"text-delta",id:"0",delta:P.content})),null!=P.tool_calls)for(const e of P.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}),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!=(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)&&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!=P.annotations)for(const e of P.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:l,...null!=d?{providerMetadata:d}:{}})}})),request:{body:r},response:{headers:i}}}},lp=Ou({prompt_tokens:au().nullish(),completion_tokens:au().nullish(),total_tokens:au().nullish(),prompt_tokens_details:Ou({cached_tokens:au().nullish()}).nullish(),completion_tokens_details:Ou({reasoning_tokens:au().nullish(),accepted_prediction_tokens:au().nullish(),rejected_prediction_tokens:au().nullish()}).nullish()}).nullish(),up=Ou({id:zl().nullish(),created:au().nullish(),model:zl().nullish(),choices:Eu(Ou({message:Ou({role:Hu("assistant").nullish(),content:zl().nullish(),tool_calls:Eu(Ou({id:zl().nullish(),type:Hu("function"),function:Ou({name:zl(),arguments:zl()})})).nullish(),annotations:Eu(Ou({type:Hu("url_citation"),start_index:au(),end_index:au(),url:zl(),title:zl()})).nullish()}),index:au(),logprobs:Ou({content:Eu(Ou({token:zl(),logprob:au(),top_logprobs:Eu(Ou({token:zl(),logprob:au()}))})).nullish()}).nullish(),finish_reason:zl().nullish()})),usage:lp}),cp=Ru([Ou({id:zl().nullish(),created:au().nullish(),model:zl().nullish(),choices:Eu(Ou({delta:Ou({role:Bu(["assistant"]).nullish(),content:zl().nullish(),tool_calls:Eu(Ou({index:au(),id:zl().nullish(),type:Hu("function").nullish(),function:Ou({name:zl().nullish(),arguments:zl().nullish()})})).nullish(),annotations:Eu(Ou({type:Hu("url_citation"),start_index:au(),end_index:au(),url:zl(),title:zl()})).nullish()}).nullish(),logprobs:Ou({content:Eu(Ou({token:zl(),logprob:au(),top_logprobs:Eu(Ou({token:zl(),logprob:au()}))})).nullish()}).nullish(),finish_reason:zl().nullish(),index:au()})),usage:lp}),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=Ou({echo:du().optional(),logitBias:Zu(zl(),au()).optional(),suffix:zl().optional(),user:zl().optional(),logprobs:Ru([du(),au()]).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:l,tools:u,toolChoice:c,seed:d,providerOptions:p}){const m=[],h={...await Od({provider:"openai",providerOptions:p,schema:fp}),...await Od({provider:this.providerOptionsName,providerOptions:p,schema:fp})};null!=i&&m.push({type:"unsupported-setting",setting:"topK"}),(null==u?void 0:u.length)&&m.push({type:"unsupported-setting",setting:"tools"}),null!=c&&m.push({type:"unsupported-setting",setting:"toolChoice"}),null!=l&&"text"!==l.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:l}=await Cd({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:dd(this.config.headers(),e.headers),body:i,failedResponseHandler:Gd,successfulResponseHandler:Dd(_p),abortSignal:e.abortSignal,fetch:this.config.fetch}),u=a.choices[0],c={openai:{}};return null!=u.logprobs&&(c.openai.logprobs=u.logprobs),{content:[{type:"text",text:u.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(u.finish_reason),request:{body:i},response:{...hp(a),headers:s,body:l},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 Cd({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:dd(this.config.headers(),e.headers),body:r,failedResponseHandler:Gd,successfulResponseHandler:zd(bp),abortSignal:e.abortSignal,fetch:this.config.fetch});let s="unknown";const a={openai:{}},l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let u=!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});u&&(u=!1,n.enqueue({type:"response-metadata",...hp(r)}),n.enqueue({type:"text-start",id:"0"})),null!=r.usage&&(l.inputTokens=r.usage.prompt_tokens,l.outputTokens=r.usage.completion_tokens,l.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){u||e.enqueue({type:"text-end",id:"0"}),e.enqueue({type:"finish",finishReason:s,providerMetadata:a,usage:l})}})),request:{body:r},response:{headers:i}}}},yp=Ou({prompt_tokens:au(),completion_tokens:au(),total_tokens:au()}),_p=Ou({id:zl().nullish(),created:au().nullish(),model:zl().nullish(),choices:Eu(Ou({text:zl(),finish_reason:zl(),logprobs:Ou({tokens:Eu(zl()),token_logprobs:Eu(au()),top_logprobs:Eu(Zu(zl(),au())).nullish()}).nullish()})),usage:yp.nullish()}),bp=Ru([Ou({id:zl().nullish(),created:au().nullish(),model:zl().nullish(),choices:Eu(Ou({text:zl(),finish_reason:zl().nullish(),index:au(),logprobs:Ou({tokens:Eu(zl()),token_logprobs:Eu(au()),top_logprobs:Eu(Zu(zl(),au())).nullish()}).nullish()})),usage:yp.nullish()}),Kd]),wp=Ou({dimensions:au().optional(),user:zl().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 Od({provider:"openai",providerOptions:r,schema:wp}))?i:{},{responseHeaders:s,value:a,rawValue:l}=await Cd({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:dd(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:"float",dimensions:o.dimensions,user:o.user},failedResponseHandler:Gd,successfulResponseHandler:Dd(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:l}}}},xp=Ou({data:Eu(Ou({embedding:Eu(au())})),usage:Ou({prompt_tokens:au()}).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 l,u,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==(u=null==(l=this.config._internal)?void 0:l.currentDate)?void 0:u.call(l))?c:new Date,{value:h,responseHeaders:g}=await Cd({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:dd(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:Dd(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=Ou({data:Eu(Ou({b64_json:zl(),revised_prompt:zl().optional()}))}),Tp=Ou({container:Ru([zl(),Ou({fileIds:Eu(zl()).optional()})]).optional()}),Op={codeInterpreter:Rd({id:"openai.code_interpreter",name:"code_interpreter",inputSchema:Ou({})}),fileSearch:ip,webSearchPreview:sp};function Np(e,t){return!!t&&t.some((t=>e.startsWith(t)))}var Cp=Ou({itemId:zl().nullish(),reasoningEncryptedContent:zl().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 Rp=Eu(Ou({token:zl(),logprob:au(),top_logprobs:Eu(Ou({token:zl(),logprob:au()}))})),Up=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({maxOutputTokens:e,temperature:t,stopSequences:n,topP:r,topK:i,presencePenalty:o,frequencyPenalty:s,seed:a,prompt:l,providerOptions:u,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,l;const u=[],c=[];for(const{role:d,content:p}of e)switch(d){case"system":switch(t){case"system":u.push({role:"system",content:p});break;case"developer":u.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":u.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){if(e.data instanceof URL)throw new At({functionality:"PDF file parts with URLs"});return{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":u.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;u.push({type:"function_call",call_id:t.toolCallId,name:t.toolName,arguments:JSON.stringify(t.input),id:null!=(l=null==(a=null==(s=t.providerOptions)?void 0:s.openai)?void 0:a.itemId)?l: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 Od({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},u.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)}u.push({type:"function_call_output",call_id:e.toolCallId,output:n})}break;default:throw new Error(`Unsupported role: ${d}`)}return{messages:u,warnings:c}}({prompt:l,systemMessageMode:f.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes});g.push(...y);const _=await Od({provider:"openai",providerOptions:u,schema:Zp}),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,l,u,c,d,p,m,h,g,f,v;const{args:y,warnings:_}=await this.getArgs(e),b=this.config.url({path:"/responses",modelId:this.modelId}),{responseHeaders:w,value:k,rawValue:x}=await Cd({url:b,headers:dd(this.config.headers(),e.headers),body:y,failedResponseHandler:Gd,successfulResponseHandler:Dd(Ou({id:zl(),created_at:au(),error:Ou({code:zl(),message:zl()}).nullish(),model:zl(),output:Eu(Pu("type",[Ou({type:Hu("message"),role:Hu("assistant"),id:zl(),content:Eu(Ou({type:Hu("output_text"),text:zl(),logprobs:Rp.nullish(),annotations:Eu(Pu("type",[Ou({type:Hu("url_citation"),start_index:au(),end_index:au(),url:zl(),title:zl()}),Ou({type:Hu("file_citation"),start_index:au(),end_index:au(),file_id:zl(),quote:zl()})]))}))}),Ou({type:Hu("function_call"),call_id:zl(),name:zl(),arguments:zl(),id:zl()}),Ou({type:Hu("web_search_call"),id:zl(),status:zl().optional(),action:Ou({type:Hu("search"),query:zl().optional()}).nullish()}),Ou({type:Hu("computer_call"),id:zl(),status:zl().optional()}),Ou({type:Hu("file_search_call"),id:zl(),status:zl().optional(),queries:Eu(zl()).nullish(),results:Eu(Ou({attributes:Ou({file_id:zl(),filename:zl(),score:au(),text:zl()})})).nullish()}),Ou({type:Hu("reasoning"),id:zl(),encrypted_content:zl().nullish(),summary:Eu(Ou({type:Hu("summary_text"),text:zl()}))})])),incomplete_details:Ou({reason:zl()}).nullable(),usage:Pp})),abortSignal:e.abortSignal,fetch:this.config.fetch});if(k.error)throw new Pe({message:k.error.message,url:b,requestBodyValues:y,statusCode:400,responseHeaders:w,responseBody:x,isRetryable:!1});const I=[],S=[];for(const E of k.output)switch(E.type){case"reasoning":0===E.summary.length&&E.summary.push({type:"summary_text",text:""});for(const e of E.summary)I.push({type:"reasoning",text:e.text,providerMetadata:{openai:{itemId:E.id,reasoningEncryptedContent:null!=(t=E.encrypted_content)?t:null}}});break;case"message":for(const t of E.content){(null==(r=null==(n=e.providerOptions)?void 0:n.openai)?void 0:r.logprobs)&&t.logprobs&&S.push(t.logprobs),I.push({type:"text",text:t.text,providerMetadata:{openai:{itemId:E.id}}});for(const e of t.annotations)"url_citation"===e.type?I.push({type:"source",sourceType:"url",id:null!=(s=null==(o=(i=this.config).generateId)?void 0:o.call(i))?s:hd(),url:e.url,title:e.title}):"file_citation"===e.type&&I.push({type:"source",sourceType:"document",id:null!=(u=null==(l=(a=this.config).generateId)?void 0:l.call(a))?u:hd(),mediaType:"text/plain",title:e.quote,filename:e.file_id})}break;case"function_call":I.push({type:"tool-call",toolCallId:E.call_id,toolName:E.name,input:E.arguments,providerMetadata:{openai:{itemId:E.id}}});break;case"web_search_call":I.push({type:"tool-call",toolCallId:E.id,toolName:"web_search_preview",input:null!=(d=null==(c=E.action)?void 0:c.query)?d:"",providerExecuted:!0}),I.push({type:"tool-result",toolCallId:E.id,toolName:"web_search_preview",result:{status:E.status||"completed",...(null==(p=E.action)?void 0:p.query)&&{query:E.action.query}},providerExecuted:!0});break;case"computer_call":I.push({type:"tool-call",toolCallId:E.id,toolName:"computer_use",input:"",providerExecuted:!0}),I.push({type:"tool-result",toolCallId:E.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:E.status||"completed"},providerExecuted:!0});break;case"file_search_call":I.push({type:"tool-call",toolCallId:E.id,toolName:"file_search",input:"",providerExecuted:!0}),I.push({type:"tool-result",toolCallId:E.id,toolName:"file_search",result:{type:"file_search_tool_result",status:E.status||"completed",...E.queries&&{queries:E.queries},...E.results&&{results:E.results}},providerExecuted:!0})}const $={openai:{responseId:k.id}};return S.length>0&&($.openai.logprobs=S),{content:I,finishReason:Ap({finishReason:null==(m=k.incomplete_details)?void 0:m.reason,hasToolCalls:I.some((e=>"tool-call"===e.type))}),usage:{inputTokens:k.usage.input_tokens,outputTokens:k.usage.output_tokens,totalTokens:k.usage.input_tokens+k.usage.output_tokens,reasoningTokens:null!=(g=null==(h=k.usage.output_tokens_details)?void 0:h.reasoning_tokens)?g:void 0,cachedInputTokens:null!=(v=null==(f=k.usage.input_tokens_details)?void 0:f.cached_tokens)?v:void 0},request:{body:y},response:{id:k.id,timestamp:new Date(1e3*k.created_at),modelId:k.model,headers:w,body:x},providerMetadata:$,warnings:_}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),{responseHeaders:r,value:i}=await Cd({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:dd(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:Gd,successfulResponseHandler:zd(Dp),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=this;let s="unknown";const a={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=[];let u=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,$,E,T,O;if(e.includeRawChunks&&n.enqueue({type:"raw",rawValue:t.rawValue}),!t.success)return s="error",void n.enqueue({type:"error",error:t.error});const N=t.value;if(Lp(N))"function_call"===N.item.type?(c[N.output_index]={toolName:N.item.name,toolCallId:N.item.call_id},n.enqueue({type:"tool-input-start",id:N.item.call_id,toolName:N.item.name})):"web_search_call"===N.item.type?(c[N.output_index]={toolName:"web_search_preview",toolCallId:N.item.id},n.enqueue({type:"tool-input-start",id:N.item.id,toolName:"web_search_preview"})):"computer_call"===N.item.type?(c[N.output_index]={toolName:"computer_use",toolCallId:N.item.id},n.enqueue({type:"tool-input-start",id:N.item.id,toolName:"computer_use"})):"file_search_call"===N.item.type?(c[N.output_index]={toolName:"file_search",toolCallId:N.item.id},n.enqueue({type:"tool-input-start",id:N.item.id,toolName:"file_search"})):"message"===N.item.type?n.enqueue({type:"text-start",id:N.item.id,providerMetadata:{openai:{itemId:N.item.id}}}):function(e){return Lp(e)&&"reasoning"===e.item.type}(N)&&(p[N.item.id]={encryptedContent:N.item.encrypted_content,summaryParts:[0]},n.enqueue({type:"reasoning-start",id:`${N.item.id}:0`,providerMetadata:{openai:{itemId:N.item.id,reasoningEncryptedContent:null!=(r=N.item.encrypted_content)?r:null}}}));else if(Mp(N)){if("function_call"===N.item.type)c[N.output_index]=void 0,d=!0,n.enqueue({type:"tool-input-end",id:N.item.call_id}),n.enqueue({type:"tool-call",toolCallId:N.item.call_id,toolName:N.item.name,input:N.item.arguments,providerMetadata:{openai:{itemId:N.item.id}}});else if("web_search_call"===N.item.type)c[N.output_index]=void 0,d=!0,n.enqueue({type:"tool-input-end",id:N.item.id}),n.enqueue({type:"tool-call",toolCallId:N.item.id,toolName:"web_search_preview",input:null!=(m=null==(i=N.item.action)?void 0:i.query)?m:"",providerExecuted:!0}),n.enqueue({type:"tool-result",toolCallId:N.item.id,toolName:"web_search_preview",result:{type:"web_search_tool_result",status:N.item.status||"completed",...(null==(h=N.item.action)?void 0:h.query)&&{query:N.item.action.query}},providerExecuted:!0});else if("computer_call"===N.item.type)c[N.output_index]=void 0,d=!0,n.enqueue({type:"tool-input-end",id:N.item.id}),n.enqueue({type:"tool-call",toolCallId:N.item.id,toolName:"computer_use",input:"",providerExecuted:!0}),n.enqueue({type:"tool-result",toolCallId:N.item.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:N.item.status||"completed"},providerExecuted:!0});else if("file_search_call"===N.item.type)c[N.output_index]=void 0,d=!0,n.enqueue({type:"tool-input-end",id:N.item.id}),n.enqueue({type:"tool-call",toolCallId:N.item.id,toolName:"file_search",input:"",providerExecuted:!0}),n.enqueue({type:"tool-result",toolCallId:N.item.id,toolName:"file_search",result:{type:"file_search_tool_result",status:N.item.status||"completed",...N.item.queries&&{queries:N.item.queries},...N.item.results&&{results:N.item.results}},providerExecuted:!0});else if("message"===N.item.type)n.enqueue({type:"text-end",id:N.item.id});else if(function(e){return Mp(e)&&"reasoning"===e.item.type}(N)){const e=p[N.item.id];for(const t of e.summaryParts)n.enqueue({type:"reasoning-end",id:`${N.item.id}:${t}`,providerMetadata:{openai:{itemId:N.item.id,reasoningEncryptedContent:null!=(g=N.item.encrypted_content)?g:null}}});delete p[N.item.id]}}else if(function(e){return"response.function_call_arguments.delta"===e.type}(N)){const e=c[N.output_index];null!=e&&n.enqueue({type:"tool-input-delta",id:e.toolCallId,delta:N.delta})}else!function(e){return"response.created"===e.type}(N)?!function(e){return"response.output_text.delta"===e.type}(N)?!function(e){return"response.reasoning_summary_part.added"===e.type}(N)?!function(e){return"response.reasoning_summary_text.delta"===e.type}(N)?!function(e){return"response.completed"===e.type||"response.incomplete"===e.type}(N)?!function(e){return"response.output_text.annotation.added"===e.type}(N)?function(e){return"error"===e.type}(N)&&n.enqueue({type:"error",error:N}):"url_citation"===N.annotation.type?n.enqueue({type:"source",sourceType:"url",id:null!=($=null==(S=(I=o.config).generateId)?void 0:S.call(I))?$:hd(),url:N.annotation.url,title:N.annotation.title}):"file_citation"===N.annotation.type&&n.enqueue({type:"source",sourceType:"document",id:null!=(O=null==(T=(E=o.config).generateId)?void 0:T.call(E))?O:hd(),mediaType:"text/plain",title:N.annotation.quote,filename:N.annotation.file_id}):(s=Ap({finishReason:null==(_=N.response.incomplete_details)?void 0:_.reason,hasToolCalls:d}),a.inputTokens=N.response.usage.input_tokens,a.outputTokens=N.response.usage.output_tokens,a.totalTokens=N.response.usage.input_tokens+N.response.usage.output_tokens,a.reasoningTokens=null!=(w=null==(b=N.response.usage.output_tokens_details)?void 0:b.reasoning_tokens)?w:void 0,a.cachedInputTokens=null!=(x=null==(k=N.response.usage.input_tokens_details)?void 0:k.cached_tokens)?x:void 0):n.enqueue({type:"reasoning-delta",id:`${N.item_id}:${N.summary_index}`,delta:N.delta,providerMetadata:{openai:{itemId:N.item_id}}}):N.summary_index>0&&(null==(f=p[N.item_id])||f.summaryParts.push(N.summary_index),n.enqueue({type:"reasoning-start",id:`${N.item_id}:${N.summary_index}`,providerMetadata:{openai:{itemId:N.item_id,reasoningEncryptedContent:null!=(y=null==(v=p[N.item_id])?void 0:v.encryptedContent)?y:null}}})):(n.enqueue({type:"text-delta",id:N.item_id,delta:N.delta}),N.logprobs&&l.push(N.logprobs)):(u=N.response.id,n.enqueue({type:"response-metadata",id:N.response.id,timestamp:new Date(1e3*N.response.created_at),modelId:N.response.model}))},flush(e){const t={openai:{responseId:u}};l.length>0&&(t.openai.logprobs=l),e.enqueue({type:"finish",finishReason:s,usage:a,providerMetadata:t})}})),request:{body:t},response:{headers:r}}}},Pp=Ou({input_tokens:au(),input_tokens_details:Ou({cached_tokens:au().nullish()}).nullish(),output_tokens:au(),output_tokens_details:Ou({reasoning_tokens:au().nullish()}).nullish()}),jp=Ou({type:Hu("response.output_text.delta"),item_id:zl(),delta:zl(),logprobs:Rp.nullish()}),zp=Ou({type:Hu("error"),code:zl(),message:zl(),param:zl().nullish(),sequence_number:au()}),Dp=Ru([jp,Ou({type:Bu(["response.completed","response.incomplete"]),response:Ou({incomplete_details:Ou({reason:zl()}).nullish(),usage:Pp})}),Ou({type:Hu("response.created"),response:Ou({id:zl(),created_at:au(),model:zl()})}),Ou({type:Hu("response.output_item.added"),output_index:au(),item:Pu("type",[Ou({type:Hu("message"),id:zl()}),Ou({type:Hu("reasoning"),id:zl(),encrypted_content:zl().nullish()}),Ou({type:Hu("function_call"),id:zl(),call_id:zl(),name:zl(),arguments:zl()}),Ou({type:Hu("web_search_call"),id:zl(),status:zl(),action:Ou({type:Hu("search"),query:zl().optional()}).nullish()}),Ou({type:Hu("computer_call"),id:zl(),status:zl()}),Ou({type:Hu("file_search_call"),id:zl(),status:zl(),queries:Eu(zl()).nullish(),results:Eu(Ou({attributes:Ou({file_id:zl(),filename:zl(),score:au(),text:zl()})})).optional()})])}),Ou({type:Hu("response.output_item.done"),output_index:au(),item:Pu("type",[Ou({type:Hu("message"),id:zl()}),Ou({type:Hu("reasoning"),id:zl(),encrypted_content:zl().nullish()}),Ou({type:Hu("function_call"),id:zl(),call_id:zl(),name:zl(),arguments:zl(),status:Hu("completed")}),Ou({type:Hu("web_search_call"),id:zl(),status:Hu("completed"),action:Ou({type:Hu("search"),query:zl().optional()}).nullish()}),Ou({type:Hu("computer_call"),id:zl(),status:Hu("completed")}),Ou({type:Hu("file_search_call"),id:zl(),status:Hu("completed"),queries:Eu(zl()).nullish(),results:Eu(Ou({attributes:Ou({file_id:zl(),filename:zl(),score:au(),text:zl()})})).nullish()})])}),Ou({type:Hu("response.function_call_arguments.delta"),item_id:zl(),output_index:au(),delta:zl()}),Ou({type:Hu("response.output_text.annotation.added"),annotation:Pu("type",[Ou({type:Hu("url_citation"),url:zl(),title:zl()}),Ou({type:Hu("file_citation"),file_id:zl(),quote:zl()})])}),Ou({type:Hu("response.reasoning_summary_part.added"),item_id:zl(),summary_index:au()}),Ou({type:Hu("response.reasoning_summary_text.delta"),item_id:zl(),summary_index:au(),delta:zl()}),zp,Ou({type:zl()}).loose()]);function Mp(e){return"response.output_item.done"===e.type}function Lp(e){return"response.output_item.added"===e.type}var Zp=Ou({metadata:_u().nullish(),parallelToolCalls:du().nullish(),previousResponseId:zl().nullish(),store:du().nullish(),user:zl().nullish(),reasoningEffort:zl().nullish(),strictJsonSchema:du().nullish(),instructions:zl().nullish(),reasoningSummary:zl().nullish(),serviceTier:Bu(["auto","flex","priority"]).nullish(),include:Eu(Bu(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),textVerbosity:Bu(["low","medium","high"]).nullish(),promptCacheKey:zl().nullish(),safetyIdentifier:zl().nullish(),logprobs:Ru([du(),au().min(1).max(20)]).optional()}),qp=Ou({instructions:zl().nullish(),speed:au().min(.25).max(4).default(1).nullish()}),Fp=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=[],l=await Od({provider:"openai",providerOptions:s,schema:qp}),u={model:this.modelId,input:e,voice:t,response_format:"mp3",speed:r,instructions:i};if(n&&(["mp3","opus","aac","flac","wav","pcm"].includes(n)?u.response_format=n:a.push({type:"unsupported-setting",setting:"outputFormat",details:`Unsupported output format: ${n}. Using mp3 instead.`})),l){const e={};for(const t in e){const n=e[t];void 0!==n&&(u[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:u,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:l,rawValue:u}=await Cd({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:dd(this.config.headers(),e.headers),body:o,failedResponseHandler:Gd,successfulResponseHandler:async({response:e,url:t,requestBodyValues:n})=>{const r=pd(e);if(!e.body)throw new Pe({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 Pe({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:l,body:u}}}},Wp=Ou({include:Eu(zl()).optional(),language:zl().optional(),prompt:zl().optional(),temperature:au().min(0).max(1).default(0).optional(),timestampGranularities:Eu(Bu(["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"},Jp=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 Od({provider:"openai",providerOptions:n,schema:Wp}),i=new FormData,o=e instanceof Uint8Array?new Blob([e]):new Blob([Jd(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,l;const u=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})=>Ad({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:dd(this.config.headers(),e.headers),formData:c,failedResponseHandler:Gd,successfulResponseHandler:Dd(Hp),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!=(l=p.duration)?l:void 0,warnings:d,response:{timestamp:u,modelId:this.modelId,headers:m,body:h}}}},Hp=Ou({text:zl(),language:zl().nullish(),duration:au().nullish(),words:Eu(Ou({word:zl(),start:au(),end:au()})).nullish(),segments:Eu(Ou({id:au(),seek:au(),start:au(),end:au(),text:zl(),tokens:Eu(au()),temperature:au(),avg_logprob:au(),compression_ratio:au(),no_speech_prob:au()})).nullish()});function Vp(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 ${vd({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}),l=t=>new Jp(t,{provider:`${i}.transcription`,url:({path:e})=>`${r}${e}`,headers:o,fetch:e.fetch}),u=t=>new Fp(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=l,p.transcriptionModel=l,p.speech=u,p.speechModel=u,p.tools=Op,p}var Kp=Vp(),Gp=jd({errorSchema:Ou({type:Hu("error"),error:Ou({type:zl(),message:zl()})}),errorToMessage:e=>e.error.message}),Yp=Ou({citations:Ou({enabled:du()}).optional(),title:zl().optional(),context:zl().optional()}),Xp=Ou({sendReasoning:du().optional(),thinking:Ou({type:Ru([Hu("enabled"),Hu("disabled")]),budgetTokens:au().optional()}).optional(),disableParallelToolUse:du().optional()});function Qp(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 em=Ou({maxUses:au().optional(),allowedDomains:Eu(zl()).optional(),blockedDomains:Eu(zl()).optional(),userLocation:Ou({type:Hu("approximate"),city:zl().optional(),region:zl().optional(),country:zl().optional(),timezone:zl().optional()}).optional()}),tm=Eu(Ou({url:zl(),title:zl(),pageAge:zl().nullable(),encryptedContent:zl(),type:zl()})),nm=Ud({id:"anthropic.web_search_20250305",name:"web_search",inputSchema:Ou({query:zl()}),outputSchema:tm});function rm(e){return"object"==typeof e&&null!==e&&"type"in e&&"web_search_20250305"===e.type}var im=Ou({type:Hu("code_execution_result"),stdout:zl(),stderr:zl(),return_code:au()}),om=Ud({id:"anthropic.code_execution_20250522",name:"code_execution",inputSchema:Ou({code:zl()}),outputSchema:im});function sm(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 am({prompt:e,sendReasoning:t,warnings:n}){var r,i,o,s,a;const l=new Set,u=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 Od({provider:"anthropic",providerOptions:e,schema:Yp});return null!=(n=null==(t=null==r?void 0:r.citations)?void 0:t.enabled)&&n}async function m(e){const t=await Od({provider:"anthropic",providerOptions:e,schema:Yp});return{title:null==t?void 0:t.title,context:null==t?void 0:t.context}}for(let h=0;h<u.length;h++){const e=u[h],g=h===u.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:Qp(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],u=e===a.length-1,c=null!=(r=Qp(s.providerOptions))?r:u?Qp(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){l.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:sm(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=Qp(r.providerOptions))?s:i?Qp(n.providerOptions):void 0,l=r.output;let u;switch(l.type){case"content":u=l.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":u=l.value;break;default:u=JSON.stringify(l.value)}t.push({type:"tool_result",tool_use_id:r.toolCallId,content:u,is_error:"error-text"===l.type||"error-json"===l.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:l}=o;for(let e=0;e<l.length;e++){const i=l[e],u=e===l.length-1,c=null!=(a=Qp(i.providerOptions))?a:u?Qp(o.providerOptions):void 0;switch(i.type){case"text":r.push({type:"text",text:g&&s&&u?i.text.trim():i.text,cache_control:c});break;case"reasoning":if(t){const e=await Od({provider:"anthropic",providerOptions:i.providerOptions,schema:gm});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=tm.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=im.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:l}}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 um={webSearchResult:Ou({type:Hu("web_search_result_location"),cited_text:zl(),url:zl(),title:zl(),encrypted_index:zl()}),pageLocation:Ou({type:Hu("page_location"),cited_text:zl(),document_index:au(),document_title:zl().nullable(),start_page_number:au(),end_page_number:au()}),charLocation:Ou({type:Hu("char_location"),cited_text:zl(),document_index:au(),document_title:zl().nullable(),start_char_index:au(),end_char_index:au()})},cm=Pu("type",[um.webSearchResult,um.pageLocation,um.charLocation]);function dm(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)}}Pu("type",[um.pageLocation,um.charLocation]);var pm=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:i,frequencyPenalty:o,presencePenalty:s,stopSequences:a,responseFormat:l,seed:u,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!=u&&f.push({type:"unsupported-setting",setting:"seed"}),"json"===(null==l?void 0:l.type)&&(null==l.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==l?void 0:l.type)&&null!=l.schema?{type:"function",name:"json",description:"Respond with a JSON object.",inputSchema:l.schema}:void 0,y=await Od({provider:"anthropic",providerOptions:p,schema:Xp}),{prompt:_,betas:b}=await am({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(rm(a))o.push(a);else switch(a.type){case"function":const e=Qp(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=em.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 dd(await Pd(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:l,usesJsonResponseTool:u}=await this.getArgs(e),c=this.extractCitationDocuments(e.prompt),{responseHeaders:d,value:p,rawValue:m}=await Cd({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:l,headers:e.headers}),body:this.transformRequestBody(s),failedResponseHandler:Gp,successfulResponseHandler:Dd(mm),abortSignal:e.abortSignal,fetch:this.config.fetch}),h=[];for(const g of p.content)switch(g.type){case"text":if(!u&&(h.push({type:"text",text:g.text}),g.citations))for(const e of g.citations)dm(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(u?{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:u}),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:l}=await Cd({url:this.buildRequestUrl(!0),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(s),failedResponseHandler:Gp,successfulResponseHandler:zd(hm),abortSignal:e.abortSignal,fetch:this.config.fetch});let u="unknown";const c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},d={};let p,m;const h=this.generateId;return{stream:l.pipeThrough(new TransformStream({start(e){e.enqueue({type:"stream-start",warnings:n})},transform(t,n){var r,s,a,l,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 dm(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!=(l=y.message.id)?l: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(u=lm({finishReason:y.delta.stop_reason,isJsonResponseFromTool:i}));case"message_stop":return void n.enqueue({type:"finish",finishReason:u,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}}}},mm=Ou({type:Hu("message"),id:zl().nullish(),model:zl().nullish(),content:Eu(Pu("type",[Ou({type:Hu("text"),text:zl(),citations:Eu(cm).optional()}),Ou({type:Hu("thinking"),thinking:zl(),signature:zl()}),Ou({type:Hu("redacted_thinking"),data:zl()}),Ou({type:Hu("tool_use"),id:zl(),name:zl(),input:wu()}),Ou({type:Hu("server_tool_use"),id:zl(),name:zl(),input:Zu(zl(),wu()).nullish()}),Ou({type:Hu("web_search_tool_result"),tool_use_id:zl(),content:Ru([Eu(Ou({type:Hu("web_search_result"),url:zl(),title:zl(),encrypted_content:zl(),page_age:zl().nullish()})),Ou({type:Hu("web_search_tool_result_error"),error_code:zl()})])}),Ou({type:Hu("code_execution_tool_result"),tool_use_id:zl(),content:Ru([Ou({type:Hu("code_execution_result"),stdout:zl(),stderr:zl(),return_code:au()}),Ou({type:Hu("code_execution_tool_result_error"),error_code:zl()})])})])),stop_reason:zl().nullish(),usage:Cu({input_tokens:au(),output_tokens:au(),cache_creation_input_tokens:au().nullish(),cache_read_input_tokens:au().nullish()})}),hm=Pu("type",[Ou({type:Hu("message_start"),message:Ou({id:zl().nullish(),model:zl().nullish(),usage:Cu({input_tokens:au(),output_tokens:au(),cache_creation_input_tokens:au().nullish(),cache_read_input_tokens:au().nullish()})})}),Ou({type:Hu("content_block_start"),index:au(),content_block:Pu("type",[Ou({type:Hu("text"),text:zl()}),Ou({type:Hu("thinking"),thinking:zl()}),Ou({type:Hu("tool_use"),id:zl(),name:zl()}),Ou({type:Hu("redacted_thinking"),data:zl()}),Ou({type:Hu("server_tool_use"),id:zl(),name:zl(),input:Zu(zl(),wu()).nullish()}),Ou({type:Hu("web_search_tool_result"),tool_use_id:zl(),content:Ru([Eu(Ou({type:Hu("web_search_result"),url:zl(),title:zl(),encrypted_content:zl(),page_age:zl().nullish()})),Ou({type:Hu("web_search_tool_result_error"),error_code:zl()})])}),Ou({type:Hu("code_execution_tool_result"),tool_use_id:zl(),content:Ru([Ou({type:Hu("code_execution_result"),stdout:zl(),stderr:zl(),return_code:au()}),Ou({type:Hu("code_execution_tool_result_error"),error_code:zl()})])})])}),Ou({type:Hu("content_block_delta"),index:au(),delta:Pu("type",[Ou({type:Hu("input_json_delta"),partial_json:zl()}),Ou({type:Hu("text_delta"),text:zl()}),Ou({type:Hu("thinking_delta"),thinking:zl()}),Ou({type:Hu("signature_delta"),signature:zl()}),Ou({type:Hu("citations_delta"),citation:cm})])}),Ou({type:Hu("content_block_stop"),index:au()}),Ou({type:Hu("error"),error:Ou({type:zl(),message:zl()})}),Ou({type:Hu("message_delta"),delta:Ou({stop_reason:zl().nullish()}),usage:Ou({output_tokens:au()})}),Ou({type:Hu("message_stop")}),Ou({type:Hu("ping")})]),gm=Ou({signature:zl().optional(),redactedData:zl().optional()}),fm=Rd({id:"anthropic.bash_20241022",name:"bash",inputSchema:Ec.object({command:Ec.string(),restart:Ec.boolean().optional()})}),vm=Rd({id:"anthropic.bash_20250124",name:"bash",inputSchema:Ec.object({command:Ec.string(),restart:Ec.boolean().optional()})}),ym=Rd({id:"anthropic.computer_20241022",name:"computer",inputSchema:Ou({action:Bu(["key","type","mouse_move","left_click","left_click_drag","right_click","middle_click","double_click","screenshot","cursor_position"]),coordinate:Eu(au().int()).optional(),text:zl().optional()})}),_m=Rd({id:"anthropic.computer_20250124",name:"computer",inputSchema:Ou({action:Bu(["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:Mu([au().int(),au().int()]).optional(),duration:au().optional(),scroll_amount:au().optional(),scroll_direction:Bu(["up","down","left","right"]).optional(),start_coordinate:Mu([au().int(),au().int()]).optional(),text:zl().optional()})}),bm={bash_20241022:fm,bash_20250124:vm,textEditor_20241022:Rd({id:"anthropic.text_editor_20241022",name:"str_replace_editor",inputSchema:Ou({command:Bu(["view","create","str_replace","insert","undo_edit"]),path:zl(),file_text:zl().optional(),insert_line:au().int().optional(),new_str:zl().optional(),old_str:zl().optional(),view_range:Eu(au().int()).optional()})}),textEditor_20250124:Rd({id:"anthropic.text_editor_20250124",name:"str_replace_editor",inputSchema:Ou({command:Bu(["view","create","str_replace","insert","undo_edit"]),path:zl(),file_text:zl().optional(),insert_line:au().int().optional(),new_str:zl().optional(),old_str:zl().optional(),view_range:Eu(au().int()).optional()})}),textEditor_20250429:Rd({id:"anthropic.text_editor_20250429",name:"str_replace_based_edit_tool",inputSchema:Ou({command:Bu(["view","create","str_replace","insert"]),path:zl(),file_text:zl().optional(),insert_line:au().int().optional(),new_str:zl().optional(),old_str:zl().optional(),view_range:Eu(au().int()).optional()})}),computer_20241022:ym,computer_20250124:_m,webSearch_20250305:(e={})=>nm(e),codeExecution_20250522:(e={})=>om(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}),i=t=>{var i;return new pm(t,{provider:"anthropic.messages",baseURL:n,headers:r,fetch:e.fetch,generateId:null!=(i=e.generateId)?i:hd,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=bm,o}var km=wm(),xm=jd({errorSchema:Ou({error:Ou({code:au().nullable(),message:zl(),status:zl()})}),errorToMessage:e=>e.error.message}),Im=Ou({outputDimensionality:au().optional(),taskType:Bu(["SEMANTIC_SIMILARITY","CLASSIFICATION","CLUSTERING","RETRIEVAL_DOCUMENT","RETRIEVAL_QUERY","QUESTION_ANSWERING","FACT_VERIFICATION","CODE_RETRIEVAL_QUERY"]).optional()}),Sm=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 Od({provider:"google",providerOptions:r,schema:Im});if(e.length>this.maxEmbeddingsPerCall)throw new kt({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const o=dd(await Pd(this.config.headers),t);if(1===e.length){const{responseHeaders:t,value:r,rawValue:s}=await Cd({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:xm,successfulResponseHandler:Dd(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:l}=await Cd({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:xm,successfulResponseHandler:Dd($m),abortSignal:n,fetch:this.config.fetch});return{embeddings:a.embeddings.map((e=>e.values)),usage:void 0,response:{headers:s,body:l}}}},$m=Ou({embeddings:Eu(Ou({values:Eu(au())}))}),Em=Ou({embedding:Ou({values:Eu(au())})});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:i,items:o,allOf:s,anyOf:a,oneOf:l,format:u,const:c,minLength:d,enum:p}=e,m={};if(n&&(m.description=n),r&&(m.required=r),u&&(m.format=u),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]=Tm(n),e)),{})),o&&(m.items=Array.isArray(o)?o.map(Tm):Tm(o)),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 l&&(m.oneOf=l.map(Tm)),void 0!==d&&(m.minLength=d),m}function Om(e){return e.includes("/")?e:`models/${e}`}var Nm=Ou({responseModalities:Eu(Bu(["TEXT","IMAGE"])).optional(),thinkingConfig:Ou({thinkingBudget:au().optional(),includeThoughts:du().optional()}).optional(),cachedContent:zl().optional(),structuredOutputs:du().optional(),safetySettings:Eu(Ou({category:Bu(["HARM_CATEGORY_UNSPECIFIED","HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_SEXUALLY_EXPLICIT","HARM_CATEGORY_CIVIC_INTEGRITY"]),threshold:Bu(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"])})).optional(),threshold:Bu(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"]).optional(),audioTimestamp:du().optional(),labels:Zu(zl(),zl()).optional()});function Cm({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 Am=Ou({web:Ou({uri:zl(),title:zl()}).nullish(),retrievedContext:Ou({uri:zl(),title:zl()}).nullish()}),Rm=Ou({webSearchQueries:Eu(zl()).nullish(),retrievalQueries:Eu(zl()).nullish(),searchEntryPoint:Ou({renderedContent:zl()}).nullish(),groundingChunks:Eu(Am).nullish(),groundingSupports:Eu(Ou({segment:Ou({startIndex:au().nullish(),endIndex:au().nullish(),text:zl().nullish()}),segment_text:zl().nullish(),groundingChunkIndices:Eu(au()).nullish(),supportChunkIndices:Eu(au()).nullish(),confidenceScores:Eu(au()).nullish(),confidenceScore:Eu(au()).nullish()})).nullish(),retrievalMetadata:Ru([Ou({webDynamicRetrievalScore:au()}),Ou({})]).nullish()}),Um=Rd({id:"google.google_search",name:"google_search",inputSchema:Ou({mode:Bu(["MODE_DYNAMIC","MODE_UNSPECIFIED"]).default("MODE_UNSPECIFIED"),dynamicThreshold:au().default(1)})}),Pm=Ou({retrievedUrl:zl(),urlRetrievalStatus:zl()}),jm=Ou({urlMetadata:Eu(Pm)}),zm=Rd({id:"google.url_context",name:"url_context",inputSchema:Ou({})}),Dm=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:i,frequencyPenalty:o,presencePenalty:s,stopSequences:a,responseFormat:l,seed:u,tools:c,toolChoice:d,providerOptions:p}){var m,h;const g=[],f=await Od({provider:"google",providerOptions:p,schema:Nm});!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:l}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:l});break;case"user":{o=!1;const e=[];for(const t of l)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:l.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:l.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)),l=e.some((e=>"provider-defined"===e.type));if(a&&l&&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."}),l){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 u=[];for(const d of e)"function"===d.type?u.push({name:d.name,description:null!=(r=d.description)?r:"",parameters:Tm(d.inputSchema)}):i.push({type:"unsupported-tool",tool:d});if(null==t)return{tools:{functionDeclarations:u},toolConfig:void 0,toolWarnings:i};const c=t.type;switch(c){case"auto":return{tools:{functionDeclarations:u},toolConfig:{functionCallingConfig:{mode:"AUTO"}},toolWarnings:i};case"none":return{tools:{functionDeclarations:u},toolConfig:{functionCallingConfig:{mode:"NONE"}},toolWarnings:i};case"required":return{tools:{functionDeclarations:u},toolConfig:{functionCallingConfig:{mode:"ANY"}},toolWarnings:i};case"tool":return{tools:{functionDeclarations:u},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:u,responseMimeType:"json"===(null==l?void 0:l.type)?"application/json":void 0,responseSchema:"json"!==(null==l?void 0:l.type)||null==l.schema||null!=(h=null==f?void 0:f.structuredOutputs)&&!h?void 0:Tm(l.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,l,u,c,d,p;const{args:m,warnings:h}=await this.getArgs(e),g=JSON.stringify(m),f=dd(await Pd(this.config.headers),e.headers),{responseHeaders:v,value:y,rawValue:_}=await Cd({url:`${this.config.baseURL}/${Om(this.modelId)}:generateContent`,headers:f,body:m,failedResponseHandler:xm,successfulResponseHandler:Dd(Fm),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=Mm({groundingMetadata:b.groundingMetadata,generateId:this.config.generateId}))?i:[];for(const $ of S)w.push($);return{content:w,finishReason:Cm({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!=(l=null==x?void 0:x.thoughtsTokenCount)?l:void 0,cachedInputTokens:null!=(u=null==x?void 0:x.cachedContentTokenCount)?u: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=dd(await Pd(this.config.headers),e.headers),{responseHeaders:o,value:s}=await Cd({url:`${this.config.baseURL}/${Om(this.modelId)}:streamGenerateContent?alt=sse`,headers:i,body:t,failedResponseHandler:xm,successfulResponseHandler:zd(Wm),abortSignal:e.abortSignal,fetch:this.config.fetch});let a="unknown";const l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let u;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&&(l.inputTokens=null!=(r=S.promptTokenCount)?r:void 0,l.outputTokens=null!=(i=S.candidatesTokenCount)?i:void 0,l.totalTokens=null!=(o=S.totalTokenCount)?o:void 0,l.reasoningTokens=null!=(s=S.thoughtsTokenCount)?s:void 0,l.cachedInputTokens=null!=(v=S.cachedContentTokenCount)?v:void 0);const $=null==(y=I.candidates)?void 0:y[0];if(null==$)return;const E=$.content,T=Mm({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=Cm({finishReason:$.finishReason,hasToolCalls:d}),u={google:{groundingMetadata:null!=(w=$.groundingMetadata)?w:null,urlContextMetadata:null!=(k=$.urlContextMetadata)?k:null,safetyRatings:null!=(x=$.safetyRatings)?x:null}},null!=S&&(u.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:l,providerMetadata:u})}})),response:{headers:o},request:{body:r}}}};function Mm({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 Lm=Ou({parts:Eu(Ru([Ou({functionCall:Ou({name:zl(),args:wu()}),thoughtSignature:zl().nullish()}),Ou({inlineData:Ou({mimeType:zl(),data:zl()})}),Ou({executableCode:Ou({language:zl(),code:zl()}).nullish(),codeExecutionResult:Ou({outcome:zl(),output:zl()}).nullish(),text:zl().nullish(),thought:du().nullish(),thoughtSignature:zl().nullish()})])).nullish()}),Zm=Ou({category:zl().nullish(),probability:zl().nullish(),probabilityScore:au().nullish(),severity:zl().nullish(),severityScore:au().nullish(),blocked:du().nullish()}),qm=Ou({cachedContentTokenCount:au().nullish(),thoughtsTokenCount:au().nullish(),promptTokenCount:au().nullish(),candidatesTokenCount:au().nullish(),totalTokenCount:au().nullish()}),Fm=Ou({candidates:Eu(Ou({content:Lm.nullish().or(Ou({}).strict()),finishReason:zl().nullish(),safetyRatings:Eu(Zm).nullish(),groundingMetadata:Rm.nullish(),urlContextMetadata:jm.nullish()})),usageMetadata:qm.nullish()}),Wm=Ou({candidates:Eu(Ou({content:Lm.nullish(),finishReason:zl().nullish(),safetyRatings:Eu(Zm).nullish(),groundingMetadata:Rm.nullish(),urlContextMetadata:jm.nullish()})).nullish(),usageMetadata:qm.nullish()}),Bm={googleSearch:Um,urlContext:zm,codeExecution:Ud({id:"google.code_execution",name:"code_execution",inputSchema:Ou({language:zl().describe("The programming language of the code."),code:zl().describe("The code to be executed.")}),outputSchema:Ou({outcome:zl().describe('The outcome of the execution (e.g., "OUTCOME_OK").'),output:zl().describe("The output from the code execution.")})})},Jm=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:l,providerOptions:u,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!=l&&p.push({type:"unsupported-setting",setting:"seed",details:"This model does not support the `seed` option through this provider."});const m=await Od({provider:"google",providerOptions:u,schema:Vm}),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 Cd({url:`${this.config.baseURL}/models/${this.modelId}:predict`,headers:dd(await Pd(this.config.headers),c),body:f,failedResponseHandler:xm,successfulResponseHandler:Dd(Hm),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}}}},Hm=Ou({predictions:Eu(Ou({bytesBase64Encoded:zl()})).default([])}),Vm=Ou({personGeneration:Bu(["dont_allow","allow_adult","allow_all"]).nullish(),aspectRatio:Bu(["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}),i=t=>{var i;return new Dm(t,{provider:"google.generative-ai",baseURL:n,headers:r,generateId:null!=(i=e.generateId)?i: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})},o=t=>new Sm(t,{provider:"google.generative-ai",baseURL:n,headers:r,fetch:e.fetch}),s=(t,i={})=>new Jm(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 Gm=Km(),Ym=class{constructor(e){this.apiKey=e}async getAccessToken(){return this.apiKey}async refreshToken(){return Promise.resolve()}},Xm=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)}},Qm={baseUrl:"undefined"!=typeof process&&(null==(e=process.env)?void 0:e.ECHO_BASE_URL)||"https://echo.merit.systems"};var eh="https://echo.router.merit.systems",th=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"})}},nh=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 rh(e,t,n){if("TypeError"===e.name)return new nh("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 nh(`HTTP_${e}`,`${i}${t?` while ${t}`:""}`,n?{statusCode:e,endpoint:n}:{statusCode:e})}return new nh("UNKNOWN_ERROR",`${e.message}${t?` while ${t}`:""}`,n?{endpoint:n}:void 0)}var ih=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 rh(r,t,n);throw new nh("UNKNOWN_ERROR","Unknown error occurred",n?{endpoint:n}:void 0)}}},oh=class extends ih{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}`}},sh=class extends ih{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")}},ah=class extends ih{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 ih{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}}},uh=class extends ih{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")}},ch=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,{...Qm,...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 Ym(e)}this.http=new th(this.config.baseUrl,this.tokenProvider),this.balance=new sh(this.http),this.payments=new lh(this.http),this.apps=new oh(this.http,this.config.baseUrl),this.users=new uh(this.http),this.models=new ah(this.http)}};function dh({appId:e,baseRouterUrl:t=eh},n){const r=async()=>{const r=await n(e);return Vp({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 ph({appId:e,baseRouterUrl:t=eh},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:km.tools})}function mh({appId:e,baseRouterUrl:t=eh},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:Gm.tools})}function hh({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 Xm({getTokenFn:()=>{var e;return Promise.resolve((null==(e=r.user)?void 0:e.access_token)||null)},refreshTokenFn:async()=>{await r.signinSilent()},onRefreshErrorFn:e=>{console.error("Token refresh failed:",e),r.signoutSilent()}}),n=new ch({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 gh=i.createContext(null),fh=i.createContext(null);function vh({config:e,children:t}){var n,o,s;const a=$e(),l=a.user,u=l?function(e){return{id:e.profile.sub||"",email:e.profile.email||"",name:e.profile.name||e.profile.preferred_username||"",picture:e.profile.picture||""}}(l):null,c=e.apiUrl||"https://echo.merit.systems",d=(null==(n=a.user)?void 0:n.access_token)||null,p=hh({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,l]=i.useState(null),[u,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),l(null)}catch(n){const e=rh(n instanceof Error?n:new Error(String(n)),"refreshing balance");throw l(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),l(null))}),[e,t,d]),{balance:n,freeTierBalance:o,error:a,isLoading:u,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=rh(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:u||null,rawUser:l,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})),[u,l,m,h,a.isAuthenticated,$,x,d,p,a.signinRedirect,w,g,y,k,e]),T=i.useMemo((()=>({isRefreshing:S})),[S]);return r.jsx(gh.Provider,{value:E,children:r.jsx(fh.Provider,{value:T,children:t})})}function yh(){const e=i.useContext(gh);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:_h,setPrototypeOf:bh,isFrozen:wh,getPrototypeOf:kh,getOwnPropertyDescriptor:xh}=Object;let{freeze:Ih,seal:Sh,create:$h}=Object,{apply:Eh,construct:Th}="undefined"!=typeof Reflect&&Reflect;Ih||(Ih=function(e){return e}),Sh||(Sh=function(e){return e}),Eh||(Eh=function(e,t,n){return e.apply(t,n)}),Th||(Th=function(e,t){return new e(...t)});const Oh=Wh(Array.prototype.forEach),Nh=Wh(Array.prototype.lastIndexOf),Ch=Wh(Array.prototype.pop),Ah=Wh(Array.prototype.push),Rh=Wh(Array.prototype.splice),Uh=Wh(String.prototype.toLowerCase),Ph=Wh(String.prototype.toString),jh=Wh(String.prototype.match),zh=Wh(String.prototype.replace),Dh=Wh(String.prototype.indexOf),Mh=Wh(String.prototype.trim),Lh=Wh(Object.prototype.hasOwnProperty),Zh=Wh(RegExp.prototype.test),qh=(Fh=TypeError,function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return Th(Fh,t)});var Fh;function Wh(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 Eh(e,t,r)}}function Bh(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Uh;bh&&bh(e,null);let r=t.length;for(;r--;){let i=t[r];if("string"==typeof i){const e=n(i);e!==i&&(wh(t)||(t[r]=e),i=e)}e[i]=!0}return e}function Jh(e){for(let t=0;t<e.length;t++){Lh(e,t)||(e[t]=null)}return e}function Hh(e){const t=$h(null);for(const[n,r]of _h(e)){Lh(e,n)&&(Array.isArray(r)?t[n]=Jh(r):r&&"object"==typeof r&&r.constructor===Object?t[n]=Hh(r):t[n]=r)}return t}function Vh(e,t){for(;null!==e;){const n=xh(e,t);if(n){if(n.get)return Wh(n.get);if("function"==typeof n.value)return Wh(n.value)}e=kh(e)}return function(){return null}}const Kh=Ih(["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"]),Gh=Ih(["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"]),Yh=Ih(["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"]),Xh=Ih(["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"]),Qh=Ih(["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"]),eg=Ih(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),tg=Ih(["#text"]),ng=Ih(["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"]),rg=Ih(["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"]),ig=Ih(["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"]),og=Ih(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),sg=Sh(/\{\{[\w\W]*|[\w\W]*\}\}/gm),ag=Sh(/<%[\w\W]*|[\w\W]*%>/gm),lg=Sh(/\$\{[\w\W]*/gm),ug=Sh(/^data-[\-\w.\u00B7-\uFFFF]+$/),cg=Sh(/^aria-[\-\w]+$/),dg=Sh(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),pg=Sh(/^(?:\w+script|data):/i),mg=Sh(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),hg=Sh(/^html$/i),gg=Sh(/^[a-z][.\w]*(-[.\w]+)+$/i);var fg=Object.freeze({__proto__:null,ARIA_ATTR:cg,ATTR_WHITESPACE:mg,CUSTOM_ELEMENT:gg,DATA_ATTR:ug,DOCTYPE_NAME:hg,ERB_EXPR:ag,IS_ALLOWED_URI:dg,IS_SCRIPT_OR_DATA:pg,MUSTACHE_EXPR:sg,TMPLIT_EXPR:lg});const vg=1,yg=3,_g=7,bg=8,wg=9;var kg=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!==wg||!t.Element)return n.isSupported=!1,n;let{document:r}=t;const i=r,o=i.currentScript,{DocumentFragment:s,HTMLTemplateElement:a,Node:l,Element:u,NodeFilter:c,NamedNodeMap:d=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:p,DOMParser:m,trustedTypes:h}=t,g=u.prototype,f=Vh(g,"cloneNode"),v=Vh(g,"remove"),y=Vh(g,"nextSibling"),_=Vh(g,"childNodes"),b=Vh(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 _h&&"function"==typeof b&&x&&void 0!==x.createHTMLDocument;const{MUSTACHE_EXPR:O,ERB_EXPR:N,TMPLIT_EXPR:C,DATA_ATTR:A,ARIA_ATTR:R,IS_SCRIPT_OR_DATA:U,ATTR_WHITESPACE:P,CUSTOM_ELEMENT:j}=fg;let{IS_ALLOWED_URI:z}=fg,D=null;const M=Bh({},[...Kh,...Gh,...Yh,...Qh,...tg]);let L=null;const Z=Bh({},[...ng,...rg,...ig,...og]);let q=Object.seal($h(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,B=!0,J=!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={},le=null;const ue=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],Ph);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=Hh(e),Ie=-1===Se.indexOf(e.PARSER_MEDIA_TYPE)?"text/html":e.PARSER_MEDIA_TYPE,$e="application/xhtml+xml"===Ie?Ph:Uh,D=Lh(e,"ALLOWED_TAGS")?Bh({},e.ALLOWED_TAGS,$e):M,L=Lh(e,"ALLOWED_ATTR")?Bh({},e.ALLOWED_ATTR,$e):Z,_e=Lh(e,"ALLOWED_NAMESPACES")?Bh({},e.ALLOWED_NAMESPACES,Ph):be,pe=Lh(e,"ADD_URI_SAFE_ATTR")?Bh(Hh(me),e.ADD_URI_SAFE_ATTR,$e):me,ce=Lh(e,"ADD_DATA_URI_TAGS")?Bh(Hh(de),e.ADD_DATA_URI_TAGS,$e):de,le=Lh(e,"FORBID_CONTENTS")?Bh({},e.FORBID_CONTENTS,$e):ue,F=Lh(e,"FORBID_TAGS")?Bh({},e.FORBID_TAGS,$e):Hh({}),W=Lh(e,"FORBID_ATTR")?Bh({},e.FORBID_ATTR,$e):Hh({}),ae=!!Lh(e,"USE_PROFILES")&&e.USE_PROFILES,B=!1!==e.ALLOW_ARIA_ATTR,J=!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||dg,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&&(J=!1),te&&(ee=!0),ae&&(D=Bh({},tg),L=[],!0===ae.html&&(Bh(D,Kh),Bh(L,ng)),!0===ae.svg&&(Bh(D,Gh),Bh(L,rg),Bh(L,og)),!0===ae.svgFilters&&(Bh(D,Yh),Bh(L,rg),Bh(L,og)),!0===ae.mathMl&&(Bh(D,Qh),Bh(L,ig),Bh(L,og))),e.ADD_TAGS&&(D===M&&(D=Hh(D)),Bh(D,e.ADD_TAGS,$e)),e.ADD_ATTR&&(L===Z&&(L=Hh(L)),Bh(L,e.ADD_ATTR,$e)),e.ADD_URI_SAFE_ATTR&&Bh(pe,e.ADD_URI_SAFE_ATTR,$e),e.FORBID_CONTENTS&&(le===ue&&(le=Hh(le)),Bh(le,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 qh('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw qh('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(""));Ih&&Ih(e),Ee=e}},Ce=Bh({},[...Gh,...Yh,...Xh]),Ae=Bh({},[...Qh,...eg]),Re=function(e){Ah(n.removed,{element:e});try{b(e).removeChild(e)}catch(t){v(e)}},Ue=function(e,t){try{Ah(n.removed,{attribute:t.getAttributeNode(e),from:t})}catch(r){Ah(n.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e)if(ee||te)try{Re(t)}catch(r){}else try{t.setAttribute(e,"")}catch(r){}},Pe=function(e){let t=null,n=null;if(Q)e="<remove></remove>"+e;else{const t=jh(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 l&&e instanceof l};function Me(e,t,r){Oh(e,(e=>{e.call(n,t,r,Ee)}))}const Le=function(e){let t=null;if(Me(T.beforeSanitizeElements,e,null),ze(e))return Re(e),!0;const r=$e(e.nodeName);if(Me(T.uponSanitizeElement,e,{tagName:r,allowedTags:D}),G&&e.hasChildNodes()&&!De(e.firstElementChild)&&Zh(/<[/\w!]/g,e.innerHTML)&&Zh(/<[/\w!]/g,e.textContent))return Re(e),!0;if(e.nodeType===_g)return Re(e),!0;if(G&&e.nodeType===bg&&Zh(/<[/\w]/g,e.data))return Re(e),!0;if(!D[r]||F[r]){if(!F[r]&&qe(r)){if(q.tagNameCheck instanceof RegExp&&Zh(q.tagNameCheck,r))return!1;if(q.tagNameCheck instanceof Function&&q.tagNameCheck(r))return!1}if(oe&&!le[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 Re(e),!0}return e instanceof u&&!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)?(Re(e),!0):"noscript"!==r&&"noembed"!==r&&"noframes"!==r||!Zh(/<\/no(script|embed|frames)/i,e.innerHTML)?(K&&e.nodeType===yg&&(t=e.textContent,Oh([O,N,C],(e=>{t=zh(t,e," ")})),e.textContent!==t&&(Ah(n.removed,{element:e.cloneNode()}),e.textContent=t)),Me(T.afterSanitizeElements,e,null),!1):(Re(e),!0)},Ze=function(e,t,n){if(re&&("id"===t||"name"===t)&&(n in r||n in Te))return!1;if(J&&!W[t]&&Zh(A,t));else if(B&&Zh(R,t));else if(!L[t]||W[t]){if(!(qe(e)&&(q.tagNameCheck instanceof RegExp&&Zh(q.tagNameCheck,e)||q.tagNameCheck instanceof Function&&q.tagNameCheck(e))&&(q.attributeNameCheck instanceof RegExp&&Zh(q.attributeNameCheck,t)||q.attributeNameCheck instanceof Function&&q.attributeNameCheck(t))||"is"===t&&q.allowCustomizedBuiltInElements&&(q.tagNameCheck instanceof RegExp&&Zh(q.tagNameCheck,n)||q.tagNameCheck instanceof Function&&q.tagNameCheck(n))))return!1}else if(pe[t]);else if(Zh(z,zh(n,P,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==Dh(n,"data:")||!ce[e]){if(H&&!Zh(U,zh(n,P,"")));else if(n)return!1}else;return!0},qe=function(e){return"annotation-xml"!==e&&jh(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:l,value:u}=s,c=$e(a),d=u;let p="value"===a?d:Mh(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||(Ue(a,e),p="user-content-"+p),G&&Zh(/((--!?|])>)|<\/(style|title)/i,p)){Ue(a,e);continue}if(r.forceKeepAttr)continue;if(!r.keepAttr){Ue(a,e);continue}if(!V&&Zh(/\/>/i,p)){Ue(a,e);continue}K&&Oh([O,N,C],(e=>{p=zh(p,e," ")}));const m=$e(e.nodeName);if(Ze(m,c,p)){if(w&&"object"==typeof h&&"function"==typeof h.getAttributeType)if(l);else switch(h.getAttributeType(m,c)){case"TrustedHTML":p=w.createHTML(p);break;case"TrustedScriptURL":p=w.createScriptURL(p)}if(p!==d)try{l?e.setAttributeNS(l,a,p):e.setAttribute(a,p),ze(e)?Re(e):Ch(n.removed)}catch(o){Ue(a,e)}}else Ue(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,u=null;if(ye=!e,ye&&(e="\x3c!--\x3e"),"string"!=typeof e&&!De(e)){if("function"!=typeof e.toString)throw qh("toString is not a function");if("string"!=typeof(e=e.toString()))throw qh("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 qh("root node is forbidden and cannot be sanitized in-place")}}else if(e instanceof l)r=Pe("\x3c!----\x3e"),o=r.ownerDocument.importNode(e,!0),o.nodeType===vg&&"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=Pe(e),!r)return ee?null:ne?k:""}r&&Q&&Re(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(u=S.call(r.ownerDocument);r.firstChild;)u.appendChild(r.firstChild);else u=r;return(L.shadowroot||L.shadowrootmode)&&(u=E.call(i,u,!0)),u}let d=Y?r.outerHTML:r.innerHTML;return Y&&D["!doctype"]&&r.ownerDocument&&r.ownerDocument.doctype&&r.ownerDocument.doctype.name&&Zh(hg,r.ownerDocument.doctype.name)&&(d="<!DOCTYPE "+r.ownerDocument.doctype.name+">\n"+d),K&&Oh([O,N,C],(e=>{d=zh(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&&Ah(T[e],t)},n.removeHook=function(e,t){if(void 0!==t){const n=Nh(T[e],t);return-1===n?void 0:Rh(T[e],n,1)[0]}return Ch(T[e])},n.removeHooks=function(e){T[e]=[]},n.removeAllHooks=function(){T={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},n}();const xg=(()=>{if("undefined"!=typeof window)return kg;try{const{JSDOM:e}=require("jsdom"),{window:t}=new e("");return kg(t)}catch{return{sanitize:e=>String(e||"").replace(/<[^>]*>/g,"")}}})();function Ig(e){if(!e)return"";const t=String(e);try{let e=xg.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 Sg(e,t={}){const{onComplete:n,onCancel:r,onError:i}=t,o=function(e){if(!e)return"";const t=Ig(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 $g=({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 Eg=({onAddCredits:e,onCancel:t,isProcessing:n})=>{const[o,s]=i.useState(""),a=i.useRef(null);i.useEffect((()=>{a.current&&a.current.focus()}),[]);const l=""!==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||!l,style:{padding:"8px 16px",backgroundColor:n||!l?"#9ca3af":"#dc2626",color:"white",border:"none",borderRadius:"6px",fontSize:"14px",fontWeight:"500",cursor:n||!l?"not-allowed":"pointer",fontFamily:"HelveticaNowDisplay, sans-serif"},onMouseEnter:e=>{!n&&l&&(e.currentTarget.style.backgroundColor="#b91c1c")},onMouseLeave:e=>{!n&&l&&(e.currentTarget.style.backgroundColor="#dc2626")},children:n?"Processing...":"Add Credits"})]})]})};const Tg=i.createContext(null);var Og,Ng=Object.defineProperty,Cg="AI_NoObjectGeneratedError",Ag=`vercel.ai.error.${Cg}`,Rg=Symbol.for(Ag),Ug=class extends Ce{constructor({message:e="No object generated.",cause:t,text:n,response:r,usage:i,finishReason:o}){super({name:Cg,message:e,cause:t}),this[Og]=!0,this.text=n,this.response=r,this.usage=i,this.finishReason=o}static isInstance(e){return Ce.hasMarker(e,Ag)}};Og=Rg;var Pg=Ru([zl(),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"})]),jg=vc((()=>Ru([vu(),zl(),au(),du(),Zu(zl(),jg),Eu(jg)]))),zg=Zu(zl(),Zu(zl(),jg)),Dg=Ou({type:Hu("text"),text:zl(),providerOptions:zg.optional()}),Mg=Ou({type:Hu("image"),image:Ru([Pg,xc(URL)]),mediaType:zl().optional(),providerOptions:zg.optional()}),Lg=Ou({type:Hu("file"),data:Ru([Pg,xc(URL)]),filename:zl().optional(),mediaType:zl(),providerOptions:zg.optional()}),Zg=Ou({type:Hu("reasoning"),text:zl(),providerOptions:zg.optional()}),qg=Ou({type:Hu("tool-call"),toolCallId:zl(),toolName:zl(),input:wu(),providerOptions:zg.optional(),providerExecuted:du().optional()}),Fg=Pu("type",[Ou({type:Hu("text"),value:zl()}),Ou({type:Hu("json"),value:jg}),Ou({type:Hu("error-text"),value:zl()}),Ou({type:Hu("error-json"),value:jg}),Ou({type:Hu("content"),value:Eu(Ru([Ou({type:Hu("text"),text:zl()}),Ou({type:Hu("media"),data:zl(),mediaType:zl()})]))})]),Wg=Ou({type:Hu("tool-result"),toolCallId:zl(),toolName:zl(),output:Fg,providerOptions:zg.optional()}),Bg=Ou({role:Hu("system"),content:zl(),providerOptions:zg.optional()}),Jg=Ou({role:Hu("user"),content:Ru([zl(),Eu(Ru([Dg,Mg,Lg]))]),providerOptions:zg.optional()}),Hg=Ou({role:Hu("assistant"),content:Ru([zl(),Eu(Ru([Dg,Lg,Zg,qg,Wg]))]),providerOptions:zg.optional()});Ru([Bg,Jg,Hg,Ou({role:Hu("tool"),content:Eu(Wg),providerOptions:zg.optional()})]),md({prefix:"aitxt",size:24}),TransformStream;var Vg=Ru([Nu({type:Hu("text-start"),id:zl(),providerMetadata:zg.optional()}),Nu({type:Hu("text-delta"),id:zl(),delta:zl(),providerMetadata:zg.optional()}),Nu({type:Hu("text-end"),id:zl(),providerMetadata:zg.optional()}),Nu({type:Hu("error"),errorText:zl()}),Nu({type:Hu("tool-input-start"),toolCallId:zl(),toolName:zl(),providerExecuted:du().optional(),dynamic:du().optional()}),Nu({type:Hu("tool-input-delta"),toolCallId:zl(),inputTextDelta:zl()}),Nu({type:Hu("tool-input-available"),toolCallId:zl(),toolName:zl(),input:wu(),providerExecuted:du().optional(),providerMetadata:zg.optional(),dynamic:du().optional()}),Nu({type:Hu("tool-input-error"),toolCallId:zl(),toolName:zl(),input:wu(),providerExecuted:du().optional(),providerMetadata:zg.optional(),dynamic:du().optional(),errorText:zl()}),Nu({type:Hu("tool-output-available"),toolCallId:zl(),output:wu(),providerExecuted:du().optional(),dynamic:du().optional(),preliminary:du().optional()}),Nu({type:Hu("tool-output-error"),toolCallId:zl(),errorText:zl(),providerExecuted:du().optional(),dynamic:du().optional()}),Nu({type:Hu("reasoning"),text:zl(),providerMetadata:zg.optional()}),Nu({type:Hu("reasoning-start"),id:zl(),providerMetadata:zg.optional()}),Nu({type:Hu("reasoning-delta"),id:zl(),delta:zl(),providerMetadata:zg.optional()}),Nu({type:Hu("reasoning-end"),id:zl(),providerMetadata:zg.optional()}),Nu({type:Hu("reasoning-part-finish")}),Nu({type:Hu("source-url"),sourceId:zl(),url:zl(),title:zl().optional(),providerMetadata:zg.optional()}),Nu({type:Hu("source-document"),sourceId:zl(),mediaType:zl(),title:zl(),filename:zl().optional(),providerMetadata:zg.optional()}),Nu({type:Hu("file"),url:zl(),mediaType:zl(),providerMetadata:zg.optional()}),Nu({type:zl().startsWith("data-"),id:zl().optional(),data:wu(),transient:du().optional()}),Nu({type:Hu("start-step")}),Nu({type:Hu("finish-step")}),Nu({type:Hu("start"),messageId:zl().optional(),messageMetadata:wu().optional()}),Nu({type:Hu("finish"),messageMetadata:wu().optional()}),Nu({type:Hu("abort")}),Nu({type:Hu("message-metadata"),messageMetadata:wu()})]);function Kg(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?Kg(o,i):i}return n}function Gg(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 l=0;l<e.length;l++){const a=e[l];switch(t[t.length-1]){case"ROOT":i(a,l,"FINISH");break;case"INSIDE_OBJECT_START":switch(a){case'"':t.pop(),t.push("INSIDE_OBJECT_KEY");break;case"}":n=l,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,l,"INSIDE_OBJECT_AFTER_VALUE");break;case"INSIDE_OBJECT_AFTER_VALUE":o(a,l);break;case"INSIDE_STRING":switch(a){case'"':t.pop(),n=l;break;case"\\":t.push("INSIDE_STRING_ESCAPE");break;default:n=l}break;case"INSIDE_ARRAY_START":if("]"===a)n=l,t.pop();else n=l,i(a,l,"INSIDE_ARRAY_AFTER_VALUE");break;case"INSIDE_ARRAY_AFTER_VALUE":switch(a){case",":t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break;case"]":n=l,t.pop();break;default:n=l}break;case"INSIDE_ARRAY_AFTER_COMMA":i(a,l,"INSIDE_ARRAY_AFTER_VALUE");break;case"INSIDE_STRING_ESCAPE":t.pop(),n=l;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=l;break;case"e":case"E":case"-":case".":break;case",":t.pop(),"INSIDE_ARRAY_AFTER_VALUE"===t[t.length-1]&&s(a,l),"INSIDE_OBJECT_AFTER_VALUE"===t[t.length-1]&&o(a,l);break;case"}":t.pop(),"INSIDE_OBJECT_AFTER_VALUE"===t[t.length-1]&&o(a,l);break;case"]":t.pop(),"INSIDE_ARRAY_AFTER_VALUE"===t[t.length-1]&&s(a,l);break;default:t.pop()}break;case"INSIDE_LITERAL":{const i=e.substring(r,l+1);"false".startsWith(i)||"true".startsWith(i)||"null".startsWith(i)?n=l:(t.pop(),"INSIDE_OBJECT_AFTER_VALUE"===t[t.length-1]?o(a,l):"INSIDE_ARRAY_AFTER_VALUE"===t[t.length-1]&&s(a,l));break}}}let a=e.slice(0,n+1);for(let l=t.length-1;l>=0;l--){switch(t[l]){case"INSIDE_STRING":a+='"';break;case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":a+="}";break;case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":a+="]";break;case"INSIDE_LITERAL":{const 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 Yg(e){if(void 0===e)return{value:void 0,state:"undefined-input"};let t=await $d({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await $d({text:Gg(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function Xg(e){return e.type.startsWith("tool-")}function Qg(e){return e.type.split("-").slice(1).join("-")}function ef({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 tf({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:l})=>{var u,c,d,p;function m(e){const t=r.message.parts.filter(Xg).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=>Xg(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?Kg(r.message.metadata,e):e;null!=t&&await Id({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),l();break}case"text-delta":{const t=r.activeTextParts[e.id];t.text+=e.delta,t.providerMetadata=null!=(u=e.providerMetadata)?u:t.providerMetadata,l();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],l();break}case"reasoning-start":{const t={type:"reasoning",text:"",providerMetadata:e.providerMetadata,state:"streaming"};r.activeReasoningParts[e.id]=t,r.message.parts.push(t),l();break}case"reasoning-delta":{const t=r.activeReasoningParts[e.id];t.text+=e.delta,t.providerMetadata=null!=(d=e.providerMetadata)?d:t.providerMetadata,l();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],l();break}case"file":r.message.parts.push({type:"file",mediaType:e.mediaType,url:e.url}),l();break;case"source-url":r.message.parts.push({type:"source-url",sourceId:e.sourceId,url:e.url,title:e.title,providerMetadata:e.providerMetadata}),l();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}),l();break;case"tool-input-start":{const t=r.message.parts.filter(Xg);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}),l();break}case"tool-input-delta":{const t=r.partialToolCalls[e.toolCallId];t.text+=e.inputTextDelta;const{value:n}=await Yg(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}),l();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}),l(),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}),l();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:Qg(t),state:"output-available",input:t.input,output:e.output,providerExecuted:e.providerExecuted,preliminary:e.preliminary})}l();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:Qg(t),state:"output-error",input:t.input,rawInput:t.rawInput,errorText:e.errorText})}l();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||l();break;case"finish":case"message-metadata":await v(e.messageMetadata),null!=e.messageMetadata&&l();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 Id({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),l()}}a.enqueue(e)}))}}))}md({prefix:"aitxt",size:24}),md({prefix:"aiobj",size:24});var nf=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()}))}};md({prefix:"aiobj",size:24});((e,t)=>{for(var n in t)Ng(e,n,{get:t[n],enumerable:!0})})({},{object:()=>of,text:()=>rf});var rf=()=>({type:"text",responseFormat:{type:"text"},parsePartial:async({text:e})=>({partial:e}),parseOutput:async({text:e})=>e}),of=({schema:e})=>{const t=Fd(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:e}){const t=await Yg(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 $d({text:e});if(!r.success)throw new Ug({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 Ug({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}}},sf=Cu({name:zl(),version:zl()}),af=Cu({_meta:Xu(Ou({}).loose())}),lf=af,uf=Ou({method:zl(),params:Xu(af)}),cf=Cu({experimental:Xu(Ou({}).loose()),logging:Xu(Ou({}).loose()),prompts:Xu(Cu({listChanged:Xu(du())})),resources:Xu(Cu({subscribe:Xu(du()),listChanged:Xu(du())})),tools:Xu(Cu({listChanged:Xu(du())}))});lf.extend({protocolVersion:zl(),capabilities:cf,serverInfo:sf,instructions:Xu(zl())});var df=lf.extend({nextCursor:Xu(zl())}),pf=Ou({name:zl(),description:Xu(zl()),inputSchema:Ou({type:Hu("object"),properties:Xu(Ou({}).loose())}).loose()}).loose();df.extend({tools:Eu(pf)});var mf=Ou({type:Hu("text"),text:zl()}).loose(),hf=Ou({type:Hu("image"),data:tu(),mimeType:zl()}).loose(),gf=Ou({uri:zl(),mimeType:Xu(zl())}).loose(),ff=gf.extend({text:zl()}),vf=gf.extend({blob:tu()}),yf=Ou({type:Hu("resource"),resource:Ru([ff,vf])}).loose();lf.extend({content:Eu(Ru([mf,hf,yf])),isError:du().default(!1).optional()}).or(lf.extend({toolResult:wu()}));var _f="2.0",bf=Ou({jsonrpc:Hu(_f),id:Ru([zl(),au().int()])}).merge(uf).strict(),wf=Ou({jsonrpc:Hu(_f),id:Ru([zl(),au().int()]),result:lf}).strict(),kf=Ou({jsonrpc:Hu(_f),id:Ru([zl(),au().int()]),error:Ou({code:au().int(),message:zl(),data:Xu(wu())})}).strict();Ru([bf,Ou({jsonrpc:Hu(_f)}).merge(Ou({method:zl(),params:Xu(af)})).strict(),wf,kf]);var xf,If,Sf=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 Pd(this.body),l=await Pd(this.headers),u=await Pd(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:{...l,...t.headers},credentials:u,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:{...l,...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:u,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 Pd(this.body),a=await Pd(this.headers),l=await Pd(this.credentials),u=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:l,requestMetadata:e.metadata})),c=null!=(n=null==u?void 0:u.api)?n:`${this.api}/${e.chatId}/stream`,d=void 0!==(null==u?void 0:u.headers)?u.headers:{...a,...e.headers},p=null!=(r=null==u?void 0:u.credentials)?r:l,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)}},$f=class extends Sf{constructor(e={}){super(e)}processResponseStream(e){return Td({stream:e,schema:Vg}).pipeThrough(new TransformStream({async transform(e,t){if(!e.success)throw e.error;t.enqueue(e.value)}}))}},Ef=class{constructor({generateId:e=hd,id:t=e(),transport:n=new $f,messageMetadataSchema:r,dataPartSchemas:i,state:o,onError:s,onToolCall:a,onFinish:l,onData:u,sendAutomaticallyWhen:c}){this.activeResponse=void 0,this.jobExecutor=new nf,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=>Xg(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=>Xg(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=l,this.onData=u,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 l=this.lastMessage;try{const s={state:ef({lastMessage:this.state.snapshot(l),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 u=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:tf({stream:a,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:u,onError:e=>{throw e}}),onError:e=>{throw e}}),null==(o=this.onFinish)||o.call(this,{message:s.state.message}),this.setStatus({status:"ready"})}catch(u){if("AbortError"===u.name)return this.setStatus({status:"ready"}),null;this.onError&&u instanceof Error&&this.onError(u),this.setStatus({status:"error",error:u})}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})}},Tf=Ou({type:Hu("text"),text:zl(),state:Bu(["streaming","done"]).optional(),providerMetadata:zg.optional()}),Of=Ou({type:Hu("reasoning"),text:zl(),state:Bu(["streaming","done"]).optional(),providerMetadata:zg.optional()}),Nf=Ou({type:Hu("source-url"),sourceId:zl(),url:zl(),title:zl().optional(),providerMetadata:zg.optional()}),Cf=Ou({type:Hu("source-document"),sourceId:zl(),mediaType:zl(),title:zl(),filename:zl().optional(),providerMetadata:zg.optional()}),Af=Ou({type:Hu("file"),mediaType:zl(),filename:zl().optional(),url:zl(),providerMetadata:zg.optional()}),Rf=Ou({type:Hu("step-start")}),Uf=Ou({type:zl().startsWith("data-"),id:zl().optional(),data:wu()}),Pf=[Ou({type:Hu("dynamic-tool"),toolName:zl(),toolCallId:zl(),state:Hu("input-streaming"),input:wu().optional(),output:xu().optional(),errorText:xu().optional()}),Ou({type:Hu("dynamic-tool"),toolName:zl(),toolCallId:zl(),state:Hu("input-available"),input:wu(),output:xu().optional(),errorText:xu().optional(),callProviderMetadata:zg.optional()}),Ou({type:Hu("dynamic-tool"),toolName:zl(),toolCallId:zl(),state:Hu("output-available"),input:wu(),output:wu(),errorText:xu().optional(),callProviderMetadata:zg.optional(),preliminary:du().optional()}),Ou({type:Hu("dynamic-tool"),toolName:zl(),toolCallId:zl(),state:Hu("output-error"),input:wu(),output:xu().optional(),errorText:zl(),callProviderMetadata:zg.optional()})],jf=[Ou({type:zl().startsWith("tool-"),toolCallId:zl(),state:Hu("input-streaming"),input:wu().optional(),output:xu().optional(),errorText:xu().optional()}),Ou({type:zl().startsWith("tool-"),toolCallId:zl(),state:Hu("input-available"),input:wu(),output:xu().optional(),errorText:xu().optional(),callProviderMetadata:zg.optional()}),Ou({type:zl().startsWith("tool-"),toolCallId:zl(),state:Hu("output-available"),input:wu(),output:wu(),errorText:xu().optional(),callProviderMetadata:zg.optional(),preliminary:du().optional()}),Ou({type:zl().startsWith("tool-"),toolCallId:zl(),state:Hu("output-error"),input:wu(),output:xu().optional(),errorText:zl(),callProviderMetadata:zg.optional()})];function zf(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Df(){if(If)return xf;return If=1,xf=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)}}}Ou({id:zl(),role:Bu(["system","user","assistant"]),metadata:wu().optional(),parts:Eu(Ru([Tf,Of,Nf,Cf,Af,Rf,Uf,...Pf,...jf]))});const Mf=zf(Df());var Lf,Zf,qf,Ff,Wf,Bf,Jf,Hf,Vf,Kf=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},Gf=(e,t,n)=>(Kf(e,t,"read from private field"),n?n.call(e):t.get(e)),Yf=(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)},Xf=(e,t,n,r)=>(Kf(e,t,"write to private field"),t.set(e,n),n);var Qf,ev=class{constructor(e=[]){Yf(this,Lf,void 0),Yf(this,Zf,"ready"),Yf(this,qf,void 0),Yf(this,Ff,new Set),Yf(this,Wf,new Set),Yf(this,Bf,new Set),this.pushMessage=e=>{Xf(this,Lf,Gf(this,Lf).concat(e)),Gf(this,Jf).call(this)},this.popMessage=()=>{Xf(this,Lf,Gf(this,Lf).slice(0,-1)),Gf(this,Jf).call(this)},this.replaceMessage=(e,t)=>{Xf(this,Lf,[...Gf(this,Lf).slice(0,e),this.snapshot(t),...Gf(this,Lf).slice(e+1)]),Gf(this,Jf).call(this)},this.snapshot=e=>structuredClone(e),this["~registerMessagesCallback"]=(e,t)=>{const n=t?(r=e,null!=(i=t)?Mf(r,i):r):e;var r,i;return Gf(this,Ff).add(n),()=>{Gf(this,Ff).delete(n)}},this["~registerStatusCallback"]=e=>(Gf(this,Wf).add(e),()=>{Gf(this,Wf).delete(e)}),this["~registerErrorCallback"]=e=>(Gf(this,Bf).add(e),()=>{Gf(this,Bf).delete(e)}),Yf(this,Jf,(()=>{Gf(this,Ff).forEach((e=>e()))})),Yf(this,Hf,(()=>{Gf(this,Wf).forEach((e=>e()))})),Yf(this,Vf,(()=>{Gf(this,Bf).forEach((e=>e()))})),Xf(this,Lf,e)}get status(){return Gf(this,Zf)}set status(e){Xf(this,Zf,e),Gf(this,Hf).call(this)}get error(){return Gf(this,qf)}set error(e){Xf(this,qf,e),Gf(this,Vf).call(this)}get messages(){return Gf(this,Lf)}set messages(e){Xf(this,Lf,[...e]),Gf(this,Jf).call(this)}};Lf=new WeakMap,Zf=new WeakMap,qf=new WeakMap,Ff=new WeakMap,Wf=new WeakMap,Bf=new WeakMap,Jf=new WeakMap,Hf=new WeakMap,Vf=new WeakMap;var tv=class extends Ef{constructor({messages:e,...t}){const n=new ev(e);super({...t,state:n}),Yf(this,Qf,void 0),this["~registerMessagesCallback"]=(e,t)=>Gf(this,Qf)["~registerMessagesCallback"](e,t),this["~registerStatusCallback"]=e=>Gf(this,Qf)["~registerStatusCallback"](e),this["~registerErrorCallback"]=e=>Gf(this,Qf)["~registerErrorCallback"](e),Xf(this,Qf,n)}};Qf=new WeakMap;var nv,rv=Object.defineProperty,iv="AI_NoObjectGeneratedError",ov=`vercel.ai.error.${iv}`,sv=Symbol.for(ov),av=class extends Ce{constructor({message:e="No object generated.",cause:t,text:n,response:r,usage:i,finishReason:o}){super({name:iv,message:e,cause:t}),this[nv]=!0,this.text=n,this.response=r,this.usage=i,this.finishReason=o}static isInstance(e){return Ce.hasMarker(e,ov)}};nv=sv;var lv,uv="AI_MessageConversionError",cv=`vercel.ai.error.${uv}`,dv=Symbol.for(cv),pv=class extends Ce{constructor({originalMessage:e,message:t}){super({name:uv,message:t}),this[lv]=!0,this.originalMessage=e}static isInstance(e){return Ce.hasMarker(e,cv)}};lv=dv;var mv=Ru([zl(),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"})]),hv=vc((()=>Ru([vu(),zl(),au(),du(),Zu(zl(),hv),Eu(hv)]))),gv=Zu(zl(),Zu(zl(),hv)),fv=Ou({type:Hu("text"),text:zl(),providerOptions:gv.optional()}),vv=Ou({type:Hu("image"),image:Ru([mv,xc(URL)]),mediaType:zl().optional(),providerOptions:gv.optional()}),yv=Ou({type:Hu("file"),data:Ru([mv,xc(URL)]),filename:zl().optional(),mediaType:zl(),providerOptions:gv.optional()}),_v=Ou({type:Hu("reasoning"),text:zl(),providerOptions:gv.optional()}),bv=Ou({type:Hu("tool-call"),toolCallId:zl(),toolName:zl(),input:wu(),providerOptions:gv.optional(),providerExecuted:du().optional()}),wv=Pu("type",[Ou({type:Hu("text"),value:zl()}),Ou({type:Hu("json"),value:hv}),Ou({type:Hu("error-text"),value:zl()}),Ou({type:Hu("error-json"),value:hv}),Ou({type:Hu("content"),value:Eu(Ru([Ou({type:Hu("text"),text:zl()}),Ou({type:Hu("media"),data:zl(),mediaType:zl()})]))})]),kv=Ou({type:Hu("tool-result"),toolCallId:zl(),toolName:zl(),output:wv,providerOptions:gv.optional()}),xv=Ou({role:Hu("system"),content:zl(),providerOptions:gv.optional()}),Iv=Ou({role:Hu("user"),content:Ru([zl(),Eu(Ru([fv,vv,yv]))]),providerOptions:gv.optional()}),Sv=Ou({role:Hu("assistant"),content:Ru([zl(),Eu(Ru([fv,yv,_v,bv,kv]))]),providerOptions:gv.optional()});function $v({output:e,tool:t,errorMode:n}){return"text"===n?{type:"error-text",value:Ze(e)}:"json"===n?{type:"error-json",value:Ev(e)}:(null==t?void 0:t.toModelOutput)?t.toModelOutput(e):"string"==typeof e?{type:"text",value:e}:{type:"json",value:Ev(e)}}function Ev(e){return void 0===e?null:e}function Tv(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 l=0;l<e.length;l++){const a=e[l];switch(t[t.length-1]){case"ROOT":i(a,l,"FINISH");break;case"INSIDE_OBJECT_START":switch(a){case'"':t.pop(),t.push("INSIDE_OBJECT_KEY");break;case"}":n=l,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,l,"INSIDE_OBJECT_AFTER_VALUE");break;case"INSIDE_OBJECT_AFTER_VALUE":o(a,l);break;case"INSIDE_STRING":switch(a){case'"':t.pop(),n=l;break;case"\\":t.push("INSIDE_STRING_ESCAPE");break;default:n=l}break;case"INSIDE_ARRAY_START":if("]"===a)n=l,t.pop();else n=l,i(a,l,"INSIDE_ARRAY_AFTER_VALUE");break;case"INSIDE_ARRAY_AFTER_VALUE":switch(a){case",":t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break;case"]":n=l,t.pop();break;default:n=l}break;case"INSIDE_ARRAY_AFTER_COMMA":i(a,l,"INSIDE_ARRAY_AFTER_VALUE");break;case"INSIDE_STRING_ESCAPE":t.pop(),n=l;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=l;break;case"e":case"E":case"-":case".":break;case",":t.pop(),"INSIDE_ARRAY_AFTER_VALUE"===t[t.length-1]&&s(a,l),"INSIDE_OBJECT_AFTER_VALUE"===t[t.length-1]&&o(a,l);break;case"}":t.pop(),"INSIDE_OBJECT_AFTER_VALUE"===t[t.length-1]&&o(a,l);break;case"]":t.pop(),"INSIDE_ARRAY_AFTER_VALUE"===t[t.length-1]&&s(a,l);break;default:t.pop()}break;case"INSIDE_LITERAL":{const i=e.substring(r,l+1);"false".startsWith(i)||"true".startsWith(i)||"null".startsWith(i)?n=l:(t.pop(),"INSIDE_OBJECT_AFTER_VALUE"===t[t.length-1]?o(a,l):"INSIDE_ARRAY_AFTER_VALUE"===t[t.length-1]&&s(a,l));break}}}let a=e.slice(0,n+1);for(let l=t.length-1;l>=0;l--){switch(t[l]){case"INSIDE_STRING":a+='"';break;case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":a+="}";break;case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":a+="]";break;case"INSIDE_LITERAL":{const 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 Ov(e){return e.type.startsWith("tool-")}function Nv(e){return e.type.split("-").slice(1).join("-")}Ru([xv,Iv,Sv,Ou({role:Hu("tool"),content:Eu(kv),providerOptions:gv.optional()})]),md({prefix:"aitxt",size:24}),TransformStream,Ru([Nu({type:Hu("text-start"),id:zl(),providerMetadata:gv.optional()}),Nu({type:Hu("text-delta"),id:zl(),delta:zl(),providerMetadata:gv.optional()}),Nu({type:Hu("text-end"),id:zl(),providerMetadata:gv.optional()}),Nu({type:Hu("error"),errorText:zl()}),Nu({type:Hu("tool-input-start"),toolCallId:zl(),toolName:zl(),providerExecuted:du().optional(),dynamic:du().optional()}),Nu({type:Hu("tool-input-delta"),toolCallId:zl(),inputTextDelta:zl()}),Nu({type:Hu("tool-input-available"),toolCallId:zl(),toolName:zl(),input:wu(),providerExecuted:du().optional(),providerMetadata:gv.optional(),dynamic:du().optional()}),Nu({type:Hu("tool-input-error"),toolCallId:zl(),toolName:zl(),input:wu(),providerExecuted:du().optional(),providerMetadata:gv.optional(),dynamic:du().optional(),errorText:zl()}),Nu({type:Hu("tool-output-available"),toolCallId:zl(),output:wu(),providerExecuted:du().optional(),dynamic:du().optional(),preliminary:du().optional()}),Nu({type:Hu("tool-output-error"),toolCallId:zl(),errorText:zl(),providerExecuted:du().optional(),dynamic:du().optional()}),Nu({type:Hu("reasoning"),text:zl(),providerMetadata:gv.optional()}),Nu({type:Hu("reasoning-start"),id:zl(),providerMetadata:gv.optional()}),Nu({type:Hu("reasoning-delta"),id:zl(),delta:zl(),providerMetadata:gv.optional()}),Nu({type:Hu("reasoning-end"),id:zl(),providerMetadata:gv.optional()}),Nu({type:Hu("reasoning-part-finish")}),Nu({type:Hu("source-url"),sourceId:zl(),url:zl(),title:zl().optional(),providerMetadata:gv.optional()}),Nu({type:Hu("source-document"),sourceId:zl(),mediaType:zl(),title:zl(),filename:zl().optional(),providerMetadata:gv.optional()}),Nu({type:Hu("file"),url:zl(),mediaType:zl(),providerMetadata:gv.optional()}),Nu({type:zl().startsWith("data-"),id:zl().optional(),data:wu(),transient:du().optional()}),Nu({type:Hu("start-step")}),Nu({type:Hu("finish-step")}),Nu({type:Hu("start"),messageId:zl().optional(),messageMetadata:wu().optional()}),Nu({type:Hu("finish"),messageMetadata:wu().optional()}),Nu({type:Hu("abort")}),Nu({type:Hu("message-metadata"),messageMetadata:wu()})]),md({prefix:"aitxt",size:24}),md({prefix:"aiobj",size:24}),md({prefix:"aiobj",size:24});((e,t)=>{for(var n in t)rv(e,n,{get:t[n],enumerable:!0})})({},{object:()=>Av,text:()=>Cv});var Cv=()=>({type:"text",responseFormat:{type:"text"},parsePartial:async({text:e})=>({partial:e}),parseOutput:async({text:e})=>e}),Av=({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 $d({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await $d({text:Tv(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 $d({text:e});if(!r.success)throw new av({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 av({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}}},Rv=Cu({name:zl(),version:zl()}),Uv=Cu({_meta:Xu(Ou({}).loose())}),Pv=Uv,jv=Ou({method:zl(),params:Xu(Uv)}),zv=Cu({experimental:Xu(Ou({}).loose()),logging:Xu(Ou({}).loose()),prompts:Xu(Cu({listChanged:Xu(du())})),resources:Xu(Cu({subscribe:Xu(du()),listChanged:Xu(du())})),tools:Xu(Cu({listChanged:Xu(du())}))});Pv.extend({protocolVersion:zl(),capabilities:zv,serverInfo:Rv,instructions:Xu(zl())});var Dv=Pv.extend({nextCursor:Xu(zl())}),Mv=Ou({name:zl(),description:Xu(zl()),inputSchema:Ou({type:Hu("object"),properties:Xu(Ou({}).loose())}).loose()}).loose();Dv.extend({tools:Eu(Mv)});var Lv=Ou({type:Hu("text"),text:zl()}).loose(),Zv=Ou({type:Hu("image"),data:tu(),mimeType:zl()}).loose(),qv=Ou({uri:zl(),mimeType:Xu(zl())}).loose(),Fv=qv.extend({text:zl()}),Wv=qv.extend({blob:tu()}),Bv=Ou({type:Hu("resource"),resource:Ru([Fv,Wv])}).loose();Pv.extend({content:Eu(Ru([Lv,Zv,Bv])),isError:du().default(!1).optional()}).or(Pv.extend({toolResult:wu()}));var Jv="2.0",Hv=Ou({jsonrpc:Hu(Jv),id:Ru([zl(),au().int()])}).merge(jv).strict(),Vv=Ou({jsonrpc:Hu(Jv),id:Ru([zl(),au().int()]),result:Pv}).strict(),Kv=Ou({jsonrpc:Hu(Jv),id:Ru([zl(),au().int()]),error:Ou({code:au().int(),message:zl(),data:Xu(wu())})}).strict();Ru([Hv,Ou({jsonrpc:Hu(Jv)}).merge(Ou({method:zl(),params:Xu(Uv)})).strict(),Vv,Kv]);var Gv=Ou({type:Hu("text"),text:zl(),state:Bu(["streaming","done"]).optional(),providerMetadata:gv.optional()}),Yv=Ou({type:Hu("reasoning"),text:zl(),state:Bu(["streaming","done"]).optional(),providerMetadata:gv.optional()}),Xv=Ou({type:Hu("source-url"),sourceId:zl(),url:zl(),title:zl().optional(),providerMetadata:gv.optional()}),Qv=Ou({type:Hu("source-document"),sourceId:zl(),mediaType:zl(),title:zl(),filename:zl().optional(),providerMetadata:gv.optional()}),ey=Ou({type:Hu("file"),mediaType:zl(),filename:zl().optional(),url:zl(),providerMetadata:gv.optional()}),ty=Ou({type:Hu("step-start")}),ny=Ou({type:zl().startsWith("data-"),id:zl().optional(),data:wu()}),ry=[Ou({type:Hu("dynamic-tool"),toolName:zl(),toolCallId:zl(),state:Hu("input-streaming"),input:wu().optional(),output:xu().optional(),errorText:xu().optional()}),Ou({type:Hu("dynamic-tool"),toolName:zl(),toolCallId:zl(),state:Hu("input-available"),input:wu(),output:xu().optional(),errorText:xu().optional(),callProviderMetadata:gv.optional()}),Ou({type:Hu("dynamic-tool"),toolName:zl(),toolCallId:zl(),state:Hu("output-available"),input:wu(),output:wu(),errorText:xu().optional(),callProviderMetadata:gv.optional(),preliminary:du().optional()}),Ou({type:Hu("dynamic-tool"),toolName:zl(),toolCallId:zl(),state:Hu("output-error"),input:wu(),output:xu().optional(),errorText:zl(),callProviderMetadata:gv.optional()})],iy=[Ou({type:zl().startsWith("tool-"),toolCallId:zl(),state:Hu("input-streaming"),input:wu().optional(),output:xu().optional(),errorText:xu().optional()}),Ou({type:zl().startsWith("tool-"),toolCallId:zl(),state:Hu("input-available"),input:wu(),output:xu().optional(),errorText:xu().optional(),callProviderMetadata:gv.optional()}),Ou({type:zl().startsWith("tool-"),toolCallId:zl(),state:Hu("output-available"),input:wu(),output:wu(),errorText:xu().optional(),callProviderMetadata:gv.optional(),preliminary:du().optional()}),Ou({type:zl().startsWith("tool-"),toolCallId:zl(),state:Hu("output-error"),input:wu(),output:xu().optional(),errorText:zl(),callProviderMetadata:gv.optional()})];function oy(){const e=function(){const e=i.useContext(Tg);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=>!Ov(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 pv({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(!Ov(n))throw new Error(`Unsupported part: ${n}`);{const i=Nv(n);if("input-streaming"===n.state)throw new pv({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:$v({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=>Ov(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:Nv(e);return{type:"tool-result",toolCallId:e.toolCallId,toolName:r,output:$v({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 pv({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||Ov(t)?i.push(t):"step-start"===t.type&&e();e();break}break;default:{const e=r.role;throw new pv({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}}Ou({id:zl(),role:Bu(["system","user","assistant"]),metadata:wu().optional(),parts:Eu(Ru([Gv,Yv,Xv,Qv,ey,ty,ny,...ry,...iy]))}),exports.EchoChatProvider=function({chatFn:e,children:t}){return r.jsx(Tg.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,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(vh,{config:e,children:t})})},exports.EchoSignIn=function({onSuccess:e,onError:t,className:n="",children:o}){const{signIn:s,isLoading:a,user:l,error:u}=yh(),[c,d]=i.useState(!1);i.useEffect((()=>{l&&e&&e(l)}),[l,e]),i.useEffect((()=>{u&&t&&t(new Error(u))}),[u,t]);const p=async()=>{try{await s()}catch(e){t&&t(e instanceof Error?e:new Error("Sign in failed"))}};return l?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($g,{width:16,height:16,variant:"light"}),r.jsxs("span",{children:["Signed in as ",Ig((null==l?void 0:l.name)||(null==l?void 0:l.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($g,{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:l,freeTierBalance:u,refreshBalance:c}=yh(),[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==u?void 0:u.userSpendInfo)?void 0:e.amountLeft)||0)<0?0:(null==(t=null==u?void 0:u.userSpendInfo)?void 0:t.amountLeft)||0)+((null==l?void 0:l.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 Sg(r,{onComplete:async()=>{try{await c(),f(!1),y(!1),e&&l&&e(l)}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($g,{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:[u&&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:[_(u.userSpendInfo.amountLeft<0?0:u.userSpendInfo.amountLeft)," ","Free Tier",u.userSpendInfo&&u.userSpendInfo.spendLimit&&r.jsxs("span",{style:{color:"#9ca3af",marginLeft:"8px"},children:["(",_(u.userSpendInfo.amountSpent>u.userSpendInfo.spendLimit?u.userSpendInfo.spendLimit:u.userSpendInfo.amountSpent)," ","of"," ",_(u.userSpendInfo.spendLimit)," ","spent)"]})]})]}),u.userSpendInfo&&u.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,u.userSpendInfo.amountLeft)/(u.userSpendInfo.spendLimit||1)*100))}%`,height:"100%",backgroundColor:"#3b82f6"}})})]}),l&&l.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:[_(l.balance)," Paid Credits",l.totalSpent&&r.jsxs("span",{style:{color:"#9ca3af",marginLeft:"8px"},children:["(",_(l.totalSpent)," /"," ",_(l.totalPaid)," spent)"]})]})]}),l.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,l.balance/l.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(Eg,{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=$g,exports.useChat=function(){return function({experimental_throttle:e,resume:t=!1,...n}={}){const r=i.useRef("chat"in n?n.chat:new tv(n));("chat"in n&&n.chat!==r.current||"id"in n&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new tv(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)),l=i.useSyncExternalStore(r.current["~registerStatusCallback"],(()=>r.current.status),(()=>r.current.status)),u=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:u,resumeStream:r.current.resumeStream,status:l,addToolResult:r.current.addToolResult}}({transport:oy()})},exports.useEcho=yh,exports.useEchoClient=hh,exports.useEchoModelProviders=()=>{const{token:e,config:t}=yh();return i.useMemo((()=>{const n={appId:t.appId,baseRouterUrl:t.baseRouterUrl},r=async()=>e;return{openai:dh(n,r),anthropic:ph(n,r),google:mh(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}=yh(),[s,a]=i.useState(void 0),[l,u]=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),u(null),void d(!1);return(async()=>{const e=new AbortController;p.current=e,d(!0),u(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")?u("OpenAI package not found. Please install it with: pnpm add openai"):u(`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:l,isLoading:c}};
|
|
4
3
|
//# sourceMappingURL=index.cjs.map
|