@barndoor-ai/sdk 1.0.2 → 1.2.0

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/index.esm.js CHANGED
@@ -1,13 +1,13 @@
1
- import e from"os";import t,{dirname as r,join as o}from"path";import n from"fs/promises";import{jwtVerify as s,createRemoteJWKSet as a}from"jose";import i from"crypto";import c from"http";import u,{fileURLToPath as l}from"url";import{spawn as d}from"child_process";import h from"readline";import p from"pkce-challenge";import{readFileSync as f}from"fs";class m extends Error{constructor(e){super(e),this.name="BarndoorError"}}class y extends m{constructor(e,t=null){super(e),this.name="AuthenticationError",this.errorCode=t}}class g extends y{constructor(e,t=null){let r=e;r+=t?` ${t}`:" Run 'barndoor-login' to authenticate.",super(r),this.name="TokenError",this.helpText=t}}class v extends g{}class _ extends g{}class w extends m{constructor(e,t){let r;const o=t.toString().toLowerCase();r=o.includes("timeout")?`Connection to ${e} timed out. Please check your internet connection and try again.`:o.includes("connection refused")?`Could not connect to ${e}. The service may be unavailable.`:o.includes("name resolution")||o.includes("getaddrinfo")?`Could not resolve hostname for ${e}. Please check the URL and your DNS settings.`:`Failed to connect to ${e}. Please check your internet connection.`,super(r),this.url=e,this.originalError=t}}class $ extends m{constructor(e,t,r=null){super($._createUserFriendlyMessage(e,t,r)),this.name="HTTPError",this.statusCode=e,this.responseBody=r}static _createUserFriendlyMessage(e,t,r){const o=`Request failed (HTTP ${e})`;return 400===e?`${o}: Invalid request. Please check your input parameters.`:401===e?`${o}: Authentication failed. Please check your token or re-authenticate.`:403===e?`${o}: Access denied. You don't have permission for this operation.`:404===e?`${o}: Resource not found. Please check the server ID or URL.`:429===e?`${o}: Rate limit exceeded. Please wait before making more requests.`:e>=500&&e<600?`${o}: Server error. Please try again later or contact support.`:`${o}: ${t}`}}class b extends m{constructor(e,t=null){let r=`Server '${e}' not found`;r+=t?`. Available servers: ${t.join(", ")}`:". Use listServers() to see available servers.",super(r),this.serverIdentifier=e,this.availableServers=t}}let k=class extends y{};class E extends m{}class S extends m{}class P{constructor(e=30,t=10){this.read=1e3*e,this.connect=1e3*t}}class T{constructor(e=new P,t=3){this.timeoutConfig=e,this.maxRetries=t,this.closed=!1}async request(e,t,r={}){if(this.closed)throw new Error("HTTP client has been closed");const{headers:o={},json:n,params:s,...a}=r,i=this._buildUrl(t,s),c={method:e.toUpperCase(),headers:{"Content-Type":"application/json","User-Agent":"barndoor-js-sdk/0.1.0",...o},...a};let u;n&&(c.body=JSON.stringify(n));for(let t=0;t<=this.maxRetries;t++){const r=new AbortController,o=this.timeoutConfig.connect+this.timeoutConfig.read,n=setTimeout(()=>r.abort(),o),s={...c,signal:r.signal};try{const e=await globalThis.fetch(i,s);if(clearTimeout(n),!e.ok){let t="";try{const r=e;"function"==typeof r.text?t=await r.text():"function"==typeof r.json&&(t=JSON.stringify(await r.json()))}catch{}throw new $(e.status,e.statusText,t)}let t="";const r=e,o=r&&r.headers;let a;return o&&("function"==typeof o.get?t=o.get("content-type")||o.get("Content-Type")||"":"object"==typeof o&&(t=o["content-type"]||o["Content-Type"]||"")),a=t.includes("application/json")||!t&&"function"==typeof r.json?await e.json():t.includes("text/")||!t&&"function"==typeof r.text?await e.text():"function"==typeof r.arrayBuffer?await e.arrayBuffer():e,a}catch(r){if(clearTimeout(n),r instanceof Error&&"AbortError"===r.name){const e=this.timeoutConfig.connect+this.timeoutConfig.read;u=new S(`Request to ${i} timed out after ${e}ms`)}else if(r instanceof $){if(r.statusCode>=400&&r.statusCode<500)throw r;if(!(r.statusCode>=500&&r.statusCode<600))throw r;{const t=e.toUpperCase();if(!("GET"===t||"HEAD"===t||"OPTIONS"===t))throw r;u=r}}else u=r instanceof Error&&"TypeError"===r.name&&r.message.includes("fetch")?new w(i,r):r instanceof Error?r:new Error(String(r));if(t===this.maxRetries)break;const o=Math.min(1e3*Math.pow(2,t),1e4);await this._sleep(o)}}throw u||(u=new Error(`Request to ${i} failed after ${this.maxRetries+1} attempts with no specific error`)),u}_buildUrl(e,t){if(!t||0===Object.keys(t).length)return e;const r=new URL(e);return Object.entries(t).forEach(([e,t])=>{null!=t&&r.searchParams.append(e,String(t))}),r.toString()}_sleep(e){return new Promise(t=>setTimeout(t,e))}async close(){this.closed=!0}async aclose(){await this.close()}}class I{constructor(e){if(this.id=e.id,this.name=e.name,this.slug=e.slug,this.provider=e.provider??null,this.connection_status=e.connection_status,!(this.id&&this.name&&this.slug&&this.connection_status))throw new Error("ServerSummary missing required fields")}static fromApiResponse(e){return new I(e)}}class x extends I{constructor(e){super(e),this.url=e.url??null}static fromApiResponse(e){return new x(e)}}class N{constructor(e){if(this.agent_token=e.agent_token,this.expires_in=e.expires_in,!this.agent_token||"number"!=typeof this.expires_in)throw new Error("AgentToken missing required fields")}static fromApiResponse(e){return new N(e)}}const C={production:{issuer:"https://auth.barndoor.ai/realms/barndoor",audience:"https://barndoor.ai/",baseUrl:"https://{org_slug}.platform.barndoor.ai"},uat:{issuer:"https://auth.barndooruat.com/realms/barndoor",audience:"https://barndoor.ai/",baseUrl:"https://{org_slug}.trial.barndooruat.com"},dev:{issuer:"https://auth.barndoordev.com/realms/barndoor",audience:"https://barndoor.ai/",baseUrl:"https://{org_slug}.platform.barndoordev.com"},"enterprise-production":{issuer:"https://auth.barndoor.ai",audience:"https://barndoor.ai/",baseUrl:"https://{org_slug}.mcp.barndoor.ai"},"enterprise-uat":{issuer:"https://auth.barndooruat.com",audience:"https://barndoor.ai/",baseUrl:"https://{org_slug}.mcp.barndooruat.com"},"enterprise-dev":{issuer:"https://auth.barndoordev.com",audience:"https://barndoor.ai/",baseUrl:"https://{org_slug}.mcp.barndoordev.com"},localdev:{issuer:"http://localhost:8080/realms/barndoor",audience:"https://barndoor.ai/",baseUrl:"http://localhost:8000"}},j="undefined"!=typeof window&&void 0!==window.document,R="undefined"==typeof window&&"undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node;function O(e,t=""){return R?process.env[e]??t:j&&window.ENV?window.ENV[e]??t:t}class z{constructor(e={}){const t=e.environment??(O("MODE")||O("BARNDOOR_ENV")||"production");this.environment={production:"production",prod:"production",uat:"uat",dev:"dev",development:"dev","enterprise-production":"enterprise-production","enterprise-prod":"enterprise-production","enterprise-uat":"enterprise-uat","enterprise-dev":"enterprise-dev",enterprise:"enterprise-production",localdev:"localdev",local:"localdev"}[t.toLowerCase()]??"production";const r=C[this.environment]??C.production,o=O("AUTH_URL"),n=e.authDomain??O("AUTH_DOMAIN");e.authIssuer?this.authIssuer=e.authIssuer:this.authIssuer=o||(n?n.startsWith("http")?n:`https://${n}`:r.issuer),this.clientId=e.clientId??(O("AGENT_CLIENT_ID")||O("AUTH_CLIENT_ID")||""),this.clientSecret=e.clientSecret??(O("AGENT_CLIENT_SECRET")||O("AUTH_CLIENT_SECRET")||""),this.apiAudience=e.apiAudience??(O("API_AUDIENCE")||r.audience),this.promptForLogin=e.promptForLogin??!1,this.skipLoginLocal=e.skipLoginLocal??!1,this.baseUrl=e.baseUrl??(O("BARNDOOR_API")||O("BARNDOOR_URL")||r.baseUrl)}get authDomain(){let e=this.authIssuer;return e.startsWith("https://")?e=e.slice(8):e.startsWith("http://")&&(e=e.slice(7)),e}static getStaticConfig(){return new z}static getDynamicConfig(e,t={}){const{requireOrganization:r=!0,fallbackOrganizationId:o}=t,n=new z,s=A(e);if(s.hasOrganization){const e=String(s.organizationId??"").trim().toLowerCase();if(!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(e))throw new E("Invalid organization subdomain format from token");return n.baseUrl=n.baseUrl.replace("{org_slug}",e),n}if(o)return n.baseUrl=n.baseUrl.replace("{org_slug}",o),n;if(r){const e=s.error||"No organization information found in token";throw new E(`Failed to extract organization ID from token: ${e}. This token may be for a personal account or may be missing organization claims. Consider using getStaticConfig() for organization-independent operations or provide a fallbackOrganizationId in the options.`)}return n}validate(){if(!this.authIssuer||""===this.authIssuer.trim())throw new E("authIssuer is required");if(!this.apiAudience||""===this.apiAudience.trim())throw new E("apiAudience is required");if(!this.baseUrl||""===this.baseUrl.trim())throw new E("baseUrl is required")}}function A(e){try{const t=e.split(".");if(3!==t.length)return{hasOrganization:!1,error:"Invalid JWT format - expected 3 parts separated by dots"};let r,o;try{r=JSON.parse(function(e){if("undefined"!=typeof globalThis&&globalThis.atob)return globalThis.atob(e);if("undefined"!=typeof Buffer)return Buffer.from(e,"base64").toString("utf-8");throw new Error("No base64 decode function available")}(t[1].replace(/-/g,"+").replace(/_/g,"/")))}catch(e){return{hasOrganization:!1,error:"Failed to parse JWT payload - token may be corrupted"}}if(r.user&&"object"==typeof r.user&&(o=r.user.organization_name??r.user.organization_slug),!o){const e=r["https://barndoor.ai/organization_slug"],t=r.organization_slug,n=r.organization_name,s=r.org_slug;o=("string"==typeof n?n:void 0)??("string"==typeof e?e:void 0)??("string"==typeof t?t:void 0)??("string"==typeof s?s:void 0)}return o&&"string"==typeof o&&""!==o.trim()?{organizationId:o.trim(),hasOrganization:!0}:{hasOrganization:!1,error:"No organization information found in token. This token may be for a personal account or may be missing organization claims."}}catch(e){return{hasOrganization:!1,error:`Failed to decode JWT token: ${e instanceof Error?e.message:String(e)}`}}}function M(){return z.getStaticConfig()}function D(e,t){return z.getDynamicConfig(e,t)}function U(e){return A(e)}function q(e){return A(e).hasOrganization}let V={debug:(e,...t)=>{"undefined"!=typeof console&&console.debug&&console.debug(e,...t)},info:(e,...t)=>{"undefined"!=typeof console&&console.info&&console.info(e,...t)},warn:(e,...t)=>{"undefined"!=typeof console&&console.warn&&console.warn(e,...t)},error:(e,...t)=>{"undefined"!=typeof console&&console.error&&console.error(e,...t)}};function F(e){V=e}function L(){return V}function H(e){return{debug:(t,...r)=>{V.debug(`[${e}] ${t}`,...r)},info:(t,...r)=>{V.info(`[${e}] ${t}`,...r)},warn:(t,...r)=>{V.warn(`[${e}] ${t}`,...r)},error:(t,...r)=>{V.error(`[${e}] ${t}`,...r)}}}function K(e,...t){V.debug(e,...t)}function Z(e,...t){V.info(e,...t)}function G(e,...t){V.warn(e,...t)}function B(e,...t){V.error(e,...t)}const J=H("token"),W=new Map;async function Q(e){if(W.has(e))return W.get(e);const t=e.replace(/\/$/,""),r=`${t}/.well-known/openid-configuration`;try{const t=new AbortController,o=setTimeout(()=>t.abort(),5e3);try{const o=await fetch(r,{signal:t.signal});if(!o.ok)throw new Error(`HTTP ${o.status}`);const n=await o.json();return W.set(e,n),J.debug(`OIDC discovery successful for ${e}`),n}finally{clearTimeout(o)}}catch(r){return J.warn(`OIDC discovery failed for ${e}:`,r),t.includes("/realms/")?{issuer:t,token_endpoint:`${t}/protocol/openid-connect/token`,authorization_endpoint:`${t}/protocol/openid-connect/auth`,userinfo_endpoint:`${t}/protocol/openid-connect/userinfo`,jwks_uri:`${t}/protocol/openid-connect/certs`}:{issuer:t,token_endpoint:`${t}/oauth/token`,authorization_endpoint:`${t}/authorize`,userinfo_endpoint:`${t}/userinfo`,jwks_uri:`${t}/.well-known/jwks.json`}}}function Y(){W.clear()}function X(e){console.warn("setTokenLogger is deprecated. Use setLogger from the main logging module instead.")}function ee(e){try{const t=e.split(".");if(3!==t.length)return null;const r=JSON.parse(function(e){const t=e.replace(/-/g,"+").replace(/_/g,"/");if(R)return Buffer.from(t,"base64").toString("utf8");if("undefined"!=typeof globalThis&&globalThis.atob)return globalThis.atob(t);throw new Error("No base64 decode function available")}(t[1]));return r}catch(e){return null}}function te(e,t){return"undefined"!=typeof AbortSignal&&"timeout"in AbortSignal?e:Promise.race([e,new Promise((e,r)=>{setTimeout(()=>r(new Error("Request timeout")),t)})])}var re;!function(e){e.VALID="valid",e.EXPIRED="expired",e.INVALID="invalid"}(re||(re={}));const oe=new Map;class ne{constructor(e){this.lockAcquired=!1,this.lockFile=`${e}.lock`}async acquire(e=5e3){if(!R)return;const t=Date.now();for(;Date.now()-t<e;)try{return await n.writeFile(this.lockFile,process.pid.toString(),{flag:"wx"}),void(this.lockAcquired=!0)}catch(e){if(!e||"object"!=typeof e||!("code"in e)||"EEXIST"!==e.code)throw new g(`Failed to acquire file lock: ${e}`);try{const e=await n.readFile(this.lockFile,"utf8"),t=parseInt(e.trim(),10);try{process.kill(t,0),await new Promise(e=>setTimeout(e,100));continue}catch(e){if(e&&"object"==typeof e&&"code"in e){const t=e;if("EPERM"===t.code){await new Promise(e=>setTimeout(e,100));continue}if("ESRCH"===t.code){await n.unlink(this.lockFile).catch(()=>{});continue}}await n.unlink(this.lockFile).catch(()=>{});continue}}catch{await n.unlink(this.lockFile).catch(()=>{});continue}}throw new g("Failed to acquire file lock: timeout")}async release(){if(R&&this.lockAcquired)try{await n.unlink(this.lockFile),this.lockAcquired=!1}catch(e){console.debug("Failed to release file lock:",e)}}}class se{}class ae extends se{constructor(){super(),this.storageKey="barndoor_token"}async loadToken(){try{const e=localStorage.getItem(this.storageKey);return e?JSON.parse(e):null}catch(e){return J.warn("Failed to load token from localStorage:",e),null}}async saveToken(e){try{localStorage.setItem(this.storageKey,JSON.stringify(e))}catch(e){const t=e instanceof Error?e.message:String(e);throw new g(`Failed to save token: ${t}`)}}async clearToken(){try{localStorage.removeItem(this.storageKey)}catch(e){J.warn("Failed to clear token from localStorage:",e)}}}class ie extends se{constructor(){super(),this.tokenFile=this._getTokenFilePath()}_getTokenFilePath(){if(R)return t.join(e.homedir(),".barndoor","token.json");throw new Error("NodeTokenStorage can only be used in Node.js environment")}async loadToken(){if(!R)throw new Error("NodeTokenStorage can only be used in Node.js environment");const e=new ne(this.tokenFile);try{await e.acquire();const t=await n.readFile(this.tokenFile,"utf8");return JSON.parse(t)}catch(e){return e&&"object"==typeof e&&"code"in e&&"ENOENT"===e.code||J.warn("Failed to load token from file:",e),null}finally{await e.release()}}async saveToken(e){if(!R)throw new Error("NodeTokenStorage can only be used in Node.js environment");const r=new ne(this.tokenFile);try{await r.acquire(),await n.mkdir(t.dirname(this.tokenFile),{recursive:!0}),await n.writeFile(this.tokenFile,JSON.stringify(e,null,2)),await n.chmod(this.tokenFile,384),J.debug("Token saved to storage")}catch(e){const t=e instanceof Error?e.message:String(e);throw new g(`Failed to save token: ${t}`)}finally{await r.release()}}async clearToken(){if(!R)throw new Error("NodeTokenStorage can only be used in Node.js environment");try{await n.unlink(this.tokenFile)}catch(e){e&&"object"==typeof e&&"code"in e&&"ENOENT"!==e.code&&J.warn("Failed to clear token file:",e)}}}function ce(){if(j)return new ae;if(R)return new ie;throw new Error("Unsupported environment for token storage")}async function ue(e,t,r){try{const o=await async function(e){if(oe.has(e))return oe.get(e);try{const t=(await Q(e)).jwks_uri;if(!t)throw J.debug(`No jwks_uri in OIDC config for ${e}`),new Error("No jwks_uri available");const r=a(new URL(t));return oe.set(e,r),r}catch(t){throw J.debug(`Failed to get JWKS for ${e}:`,t),t}}(t),n=`${t.replace(/\/$/,"")}/`;return await s(e,o,{issuer:n,audience:r}),J.debug("Token verified locally using JWKS"),re.VALID}catch(e){return e&&"object"==typeof e&&"code"in e&&"ERR_JWT_EXPIRED"===e.code?(J.debug("Token expired (verified locally)"),re.EXPIRED):(J.debug("JWT verification failed:",e),re.INVALID)}}class le{constructor(){this._locked=!1,this._waitQueue=[]}async acquire(){return new Promise(e=>{this._locked?this._waitQueue.push(e):(this._locked=!0,e())})}release(){if(this._waitQueue.length>0){const e=this._waitQueue.shift();e&&e()}else this._locked=!1}async withLock(e){await this.acquire();try{return await e()}finally{this.release()}}}class de{constructor(e){this._refreshMutex=new le,this.storage=ce()}async getValidToken(){return this._refreshMutex.withLock(async()=>{const e=await this.storage.loadToken();if(!e)throw new g("No token found. Please authenticate.");try{if(this._shouldRefreshToken(e)&&e.refresh_token){J.debug("Proactively refreshing token before expiration");const t=await this._refreshToken(e),r={...e,...t};return await this.storage.saveToken(r),r.access_token}const t=await this._validateOrRefresh(e);return await this.storage.saveToken(t),t.access_token}catch(e){throw J.error("Token validation/refresh failed:",e),new v("Token expired and refresh failed. Please re-authenticate.")}})}_shouldRefreshToken(e){const t=ee(e.access_token);if(!t?.exp)return!0;const r=Math.floor(Date.now()/1e3);return t.exp-r<300}async _validateOrRefresh(e){const t=e.access_token,r=M(),o=await ue(t,r.authIssuer,r.apiAudience);if(o===re.VALID)return J.debug("Token validated locally"),e;if(o===re.INVALID&&(J.debug("Local validation failed, trying remote"),await this._isTokenValidRemote(t)))return J.debug("Token validated remotely"),e;if(J.info("Token invalid or expired, attempting refresh"),e.refresh_token){const t=await this._refreshToken(e);return{...e,...t}}throw new v("Token expired and no refresh token available")}async _isTokenValidRemote(e){try{const t=M(),r=(await Q(t.authIssuer)).userinfo_endpoint,o=fetch(r,{headers:{Authorization:`Bearer ${e}`},..."undefined"!=typeof AbortSignal&&"timeout"in AbortSignal?{signal:AbortSignal.timeout(5e3)}:{}});return(await te(o,5e3)).ok}catch(e){return J.debug("Remote token validation failed:",e),!1}}async _refreshToken(e){const t=e.refresh_token;if(!t)throw new g("No refresh token available");const r=M();if(j&&r.clientSecret)throw new g("Refresh flow requires a confidential client; run interactive login again.");const o=(await Q(r.authIssuer)).token_endpoint,n=new URLSearchParams({grant_type:"refresh_token",client_id:r.clientId,refresh_token:t});r.clientSecret&&!j&&n.set("client_secret",r.clientSecret);try{const e=fetch(o,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString(),..."undefined"!=typeof AbortSignal&&"timeout"in AbortSignal?{signal:AbortSignal.timeout(15e3)}:{}}),t=await te(e,15e3);if(400===t.status){let e="Invalid refresh token";try{e=(await t.json()).error_description||e}catch{}throw J.warn(`Refresh token invalid: ${e}`),new v(`Refresh token expired or invalid: ${e}`)}if(429===t.status)throw J.warn("Rate limited during token refresh"),new g("Rate limited during token refresh. Please try again later.");if(t.status>=500)throw J.warn(`Auth server error during refresh: ${t.status}`),new g(`Auth server temporarily unavailable (HTTP ${t.status})`);if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);return await t.json()}catch(e){if(e instanceof g||e instanceof v)throw e;if(e&&"object"==typeof e&&"name"in e){if("TimeoutError"===e.name||"AbortError"===e.name)throw J.warn("Timeout during token refresh"),new g("Token refresh timed out. Please check your connection.");if("TypeError"===e.name&&"message"in e&&"string"==typeof e.message&&e.message.includes("fetch"))throw J.warn(`Network error during token refresh: ${e.message}`),new g("Network error during token refresh. Please check your connection.")}J.error("Unexpected error during token refresh:",e);const t=e instanceof Error?e.message:String(e);throw new g(`Token refresh failed: ${t}`)}}}async function he(){try{const e=ce(),t=await e.loadToken();return t?.access_token??null}catch(e){return null}}async function pe(e){const t=ce();let r;r="string"==typeof e?{access_token:e}:e,await t.saveToken(r)}async function fe(){const e=ce();await e.clearToken()}async function me(e){try{const e=ce(),t=await e.loadToken();if(!t?.access_token)return!1;const r=M(),o=(await Q(r.authIssuer)).userinfo_endpoint,n=fetch(o,{headers:{Authorization:`Bearer ${t.access_token}`},..."undefined"!=typeof AbortSignal&&"timeout"in AbortSignal?{signal:AbortSignal.timeout(1e4)}:{}});return(await te(n,1e4)).ok}catch(e){return!1}}async function ye(e){try{const t=new de(e||"");return await t.getValidToken(),!0}catch(e){return J.warn("Token validation/refresh failed:",e),!1}}async function ge(e,t){try{const t=M(),r=await ue(e,t.authIssuer,t.apiAudience);if(r===re.VALID)return{valid:!0};if(r===re.INVALID)try{const r=(await Q(t.authIssuer)).userinfo_endpoint,o=fetch(r,{headers:{Authorization:`Bearer ${e}`},..."undefined"!=typeof AbortSignal&&"timeout"in AbortSignal?{signal:AbortSignal.timeout(5e3)}:{}});return{valid:(await te(o,5e3)).ok}}catch(e){return J.warn("Remote token validation failed:",e),{valid:!1}}return{valid:!1}}catch(e){return J.warn("Token validation failed:",e),{valid:!1}}}class ve{constructor(){this._codeVerifier=null,this._currentState=null,this._logger=H("pkce")}async buildAuthorizationUrl({domain:e,clientId:t,redirectUri:r,audience:o,scope:n="openid profile email",issuer:s}){this._codeVerifier=_e(32);const a=we(await async function(e){const t=(new TextEncoder).encode(e);if(j&&window.crypto&&window.crypto.subtle){const e=await window.crypto.subtle.digest("SHA-256",t);return new Uint8Array(e)}if(R){const t=i.createHash("sha256").update(e).digest();return new Uint8Array(t)}throw new Error("SHA256 not available in this environment")}(this._codeVerifier));this._currentState=_e(16);const c=new URLSearchParams({response_type:"code",client_id:t,redirect_uri:r,scope:n,audience:o,state:this._currentState,code_challenge:a,code_challenge_method:"S256"});let u;if(s){u=(await Q(s)).authorization_endpoint}else{if(!e)throw new k("Either issuer or domain must be provided");u=`https://${e}/authorize`}return`${u}?${c.toString()}`}async exchangeCodeForToken({domain:e,clientId:t,code:r,redirectUri:o,clientSecret:n,issuer:s}){const a=new URLSearchParams({grant_type:"authorization_code",client_id:t,code:r,redirect_uri:o});if(n&&a.set("client_secret",n),this._codeVerifier&&a.set("code_verifier",this._codeVerifier),!n&&!this._codeVerifier)throw new k("Either client_secret or PKCE verifier must be provided");let i;if(s){i=(await Q(s)).token_endpoint}else{if(!e)throw new k("Either issuer or domain must be provided");i=`https://${e}/oauth/token`}try{const e=await fetch(i,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:a.toString()});if(!e.ok){const t=await e.json().catch(()=>({}));throw this._logger.error("Token endpoint response:",t),new k(`Token exchange failed: ${t.error??t.error_description??e.statusText}`)}const t=await e.json();return this.clearState(),t}catch(e){if(e instanceof k)throw e;const t=e instanceof Error?e.message:String(e);throw new k(`Token exchange failed: ${t}`)}}validateState(e){return Boolean(this._currentState&&e===this._currentState)}clearState(){this._codeVerifier=null,this._currentState=null}getState(){return this._codeVerifier&&this._currentState?{codeVerifier:this._codeVerifier,codeChallenge:"",state:this._currentState,timestamp:Date.now()}:null}}function _e(e){const t=new Uint8Array(e);if(j&&window.crypto&&window.crypto.getRandomValues)window.crypto.getRandomValues(t);else{if(!R)throw new Error("Secure random generator not available for PKCE.");i.randomFillSync(t)}return we(t)}function we(e){const t=function(e){if("undefined"!=typeof globalThis&&globalThis.btoa)return globalThis.btoa(String.fromCharCode(...e));if("undefined"!=typeof Buffer)return Buffer.from(e).toString("base64");throw new Error("No base64 encode function available")}(e);return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function $e(e=52765){if(!R)throw new Error("Local callback server is only available in Node.js environment");const t=H("pkce"),r="undefined"!=typeof process&&process.env&&process.env.BARNDOOR_REDIRECT_HOST||"127.0.0.1",o=r.startsWith("http")?`${r}:${e}/cb`:`http://${r}:${e}/cb`,n=new Promise((r,n)=>{const s=c.createServer((e,o)=>{t.debug(`Callback server received request: ${e.method} ${e.url}`);const a=u.parse(e.url??"",!0);if(t.debug(`Parsed URL - pathname: ${a.pathname}, query:`,a.query),"/cb"===a.pathname){const{code:i,state:c,error:u,error_description:l}=a.query;t.debug(`Callback params - code: ${!!i}, state: ${!!c}, error: ${u}`),o.writeHead(200,{"Content-Type":"text/html"}),u?(t.error(`OAuth error: ${u} - ${l}`),o.end("\n <html>\n <body>\n <h1>Authentication Failed</h1>\n <p>Error: Authentication error occurred.</p>\n <p>Description: Please return to the application for details.</p>\n <p>You can close this window.</p>\n </body>\n </html>\n "),s.close(),n(new k(`OAuth error: ${u} - ${l}`))):i?(t.info("OAuth callback received successfully, closing server"),o.end("\n <html>\n <body>\n <h1>Authentication Successful</h1>\n <p>You can close this window and return to your application.</p>\n <script>\n console.log('Authentication callback received. You can close this window.');\n setTimeout(() => window.close(), 1000);\n <\/script>\n </body>\n </html>\n "),s.close(),r([i,c])):(t.warn("No authorization code received in callback"),t.warn(`Full URL: ${e.url}`),t.warn("Query params:",a.query),o.end(`\n <html>\n <body>\n <h1>Authentication Failed</h1>\n <p>No authorization code received.</p>\n <p>Full URL: ${e.url}</p>\n <p>You can close this window.</p>\n </body>\n </html>\n `),s.close(),n(new k("No authorization code received")))}else t.debug(`404 for path: ${a.pathname}`),o.writeHead(404,{"Content-Type":"text/plain"}),o.end("Not found")});s.listen(e,"0.0.0.0",()=>{console.log(`OAuth callback server listening on ${o}`)}),s.on("error",e=>{n(new k(`Failed to start callback server: ${e.message}`))}),s.on("connection",e=>{t.debug(`New connection from ${e.remoteAddress}:${e.remotePort}`)})});return[o,n]}class be{constructor(e,t={}){this._logger=H("client");const{token:r,timeout:o=30,maxRetries:n=3}=t;this.base=this._validateUrl(e,"API base URL").replace(/\/$/,"");const s=Object.prototype.hasOwnProperty.call(t,"token");if(this._token=s?this._validateToken(r):null,"number"!=typeof o||o<=0)throw new E("timeout must be a positive number");if(!Number.isInteger(n)||n<0)throw new E("maxRetries must be a non-negative integer");const a=new P(o,o/3);this._http=new T(a,n),this._tokenValidated=!1,this._closed=!1,this._logger.info(`Initialized BarndoorSDK for ${this.base}`)}get token(){if(!this._token)throw new Error("No token available. Call authenticate() first or provide token in constructor.");return this._token}async authenticate(e){this._token=this._validateToken(e),this._tokenValidated=!1,await this.ensureValidToken(),this._logger.info("Authentication successful")}_validateUrl(e,t){if(!e||"string"!=typeof e)throw new E(`${t} must be a non-empty string`);try{return new URL(e),e}catch(e){throw new E(`${t} must be a valid URL`)}}_validateToken(e){if(!e||"string"!=typeof e)throw new g("Token must be a non-empty string");if(3!==e.split(".").length)throw new g("Token must be a valid JWT");return e}_ensureNotClosed(){if(this._closed)throw new Error("SDK has been closed. Create a new instance or use as context manager.")}async _req(e,t,r={}){this._ensureNotClosed(),await this.ensureValidToken();const o=r.headers??{};o.Authorization=`Bearer ${this.token}`;const n=`${this.base}${t}`;return await this._http.request(e,n,{...r,headers:o})}async validateCachedToken(){if(!this.token)return!1;try{const e=M(),t=(await Q(e.authIssuer)).userinfo_endpoint,r=new AbortController,o=setTimeout(()=>r.abort(),1e4);try{const e=(await fetch(t,{headers:{Authorization:`Bearer ${this.token}`},signal:r.signal})).ok;return e&&(this._tokenValidated=!0),e}finally{clearTimeout(o)}}catch(e){return!1}}async ensureValidToken(){if(!this._token)throw new Error("No token available. Call authenticate() first or provide token in constructor.");if(this._tokenValidated)return;const e=(R?process.env.BARNDOOR_ENV:"")??"";if(["test","ci"].includes(e.toLowerCase()))return void(this._tokenValidated=!0);if(!await this.validateCachedToken())throw new g("Token validation failed. Please re-authenticate.");this._tokenValidated=!0}async listServers(){this._logger.debug("Fetching server list");try{const e=[];let t=1;for(;null!==t;){const r=1===t?"/api/servers":`/api/servers?page=${t}`,o=await this._req("GET",r),n=o.data.map(e=>I.fromApiResponse(e));e.push(...n),t=o.pagination.next_page}return this._logger.info(`Retrieved ${e.length} servers total`),e}catch(e){throw this._logger.error("Failed to list servers:",e),e}}async getServer(e){const t=this._validateServerId(e);this._logger.info(`Fetching server details for ${t}`);const r=this._isUuid(t)?`/api/servers/${t}`:`/api/servers/by-slug/${t}`,o=await this._req("GET",r);return x.fromApiResponse(o)}async initiateConnection(e,t){const r=this._validateServerId(e);let o;t&&(o=this._validateUrl(t,"Return URL")),this._logger.info(`Initiating connection for server ${r}`);const n=o?{return_url:o}:void 0;try{const e=this._isUuid(r)?`/api/servers/${r}/connect`:`/api/servers/by-slug/${r}/connect`;return await this._req("POST",e,{params:n,json:{}})}catch(e){if(e instanceof $&&500===e.statusCode&&e.responseBody?.includes("OAuth server configuration not found"))throw new Error("Server is missing OAuth configuration. Ask an admin to configure credentials before initiating a connection.");throw e}}async getConnectionStatus(e){const t=this._validateServerId(e);this._logger.info(`Checking connection status for server ${t}`);const r=this._isUuid(t)?`/api/servers/${t}/connection`:`/api/servers/by-slug/${t}/connection`;return(await this._req("GET",r)).status}async disconnectServer(e){const t=this._validateServerId(e);this._logger.info(`Disconnecting from server ${t}`);try{const e=this._isUuid(t)?`/api/servers/${t}/connection`:`/api/servers/by-slug/${t}/connection`;await this._req("DELETE",e),this._logger.info(`Successfully disconnected from server ${t}`)}catch(e){if(e instanceof $&&404===e.statusCode)throw new Error(`Connection not found for server ${t}. Server may not be connected.`);throw e}}_validateServerId(e){if(!e||"string"!=typeof e)throw new Error("Server ID must be a non-empty string");if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)&&!/^[a-z0-9-]+$/.test(e))throw new Error("Server ID must be a valid UUID or slug (lowercase letters, numbers, and hyphens only)");return e}_isUuid(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}async close(){this._closed||(await this._http.close(),this._closed=!0)}async aclose(){await this.close()}async ensureServerConnected(t,r={}){const{pollSeconds:o=60}=r;if(!R)throw new Error("ensureServerConnected requires Node.js environment for browser opening");let n;try{n=await this.getServer(t)}catch(e){if(e instanceof $&&404===e.statusCode)throw new b(t);throw e}if("connected"===n.connection_status)return;const s=n.slug||t,a=(await this.initiateConnection(s)).auth_url;if(!a)throw new Error("Registry did not return auth_url");const i=e.platform();let c;try{c=new URL(a)}catch{throw new Error("Invalid auth_url returned by server")}if("https:"!==c.protocol&&("http:"!==c.protocol||"localhost"!==c.hostname&&"127.0.0.1"!==c.hostname))throw new Error("Auth URL must use HTTPS (http allowed only for localhost)");try{"darwin"===i?d("open",[a],{detached:!0,stdio:"ignore"}).unref():"win32"===i?d("powershell",["-NoProfile","Start-Process",a],{detached:!0,stdio:"ignore"}).unref():d("xdg-open",[a],{detached:!0,stdio:"ignore"}).unref()}catch(e){this._logger.warn("Failed to open browser",e)}for(let e=0;e<o;e++){if("connected"===await this.getConnectionStatus(s))return;await new Promise(e=>setTimeout(e,1e3))}throw new Error("OAuth connection was not completed in time")}}const ke=Object.freeze({status:"aborted"});function Ee(e,t,r){function o(r,o){var n;Object.defineProperty(r,"_zod",{value:r._zod??{},enumerable:!1}),(n=r._zod).traits??(n.traits=new Set),r._zod.traits.add(e),t(r,o);for(const e in a.prototype)e in r||Object.defineProperty(r,e,{value:a.prototype[e].bind(r)});r._zod.constr=a,r._zod.def=o}const n=r?.Parent??Object;class s extends n{}function a(e){var t;const n=r?.Parent?new s:this;o(n,e),(t=n._zod).deferred??(t.deferred=[]);for(const e of n._zod.deferred)e();return n}return Object.defineProperty(s,"name",{value:e}),Object.defineProperty(a,"init",{value:o}),Object.defineProperty(a,Symbol.hasInstance,{value:t=>!!(r?.Parent&&t instanceof r.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(a,"name",{value:e}),a}class Se extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const Pe={};function Te(e){return e&&Object.assign(Pe,e),Pe}function Ie(e,t){return"bigint"==typeof t?t.toString():t}function xe(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Ne(e){return null==e}function Ce(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function je(e,t,r){Object.defineProperty(e,t,{get(){{const o=r();return e[t]=o,o}},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function Re(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Oe(e){return JSON.stringify(e)}const ze=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function Ae(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const Me=xe(()=>{if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function De(e){if(!1===Ae(e))return!1;const t=e.constructor;if(void 0===t)return!0;const r=t.prototype;return!1!==Ae(r)&&!1!==Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")}const Ue=new Set(["string","number","symbol"]);function qe(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ve(e,t,r){const o=new e._zod.constr(t??e._zod.def);return t&&!r?.parent||(o._zod.parent=e),o}function Fe(e){const t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==t?.message){if(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}const Le={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function He(e,t=0){for(let r=t;r<e.issues.length;r++)if(!0!==e.issues[r]?.continue)return!0;return!1}function Ke(e,t){return t.map(t=>{var r;return(r=t).path??(r.path=[]),t.path.unshift(e),t})}function Ze(e){return"string"==typeof e?e:e?.message}function Ge(e,t,r){const o={...e,path:e.path??[]};if(!e.message){const n=Ze(e.inst?._zod.def?.error?.(e))??Ze(t?.error?.(e))??Ze(r.customError?.(e))??Ze(r.localeError?.(e))??"Invalid input";o.message=n}return delete o.inst,delete o.continue,t?.reportInput||delete o.input,o}function Be(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function Je(...e){const[t,r,o]=e;return"string"==typeof t?{message:t,code:"custom",input:r,inst:o}:{...t}}const We=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get:()=>JSON.stringify(t,Ie,2),enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Qe=Ee("$ZodError",We),Ye=Ee("$ZodError",We,{Parent:Error});const Xe=e=>(t,r,o,n)=>{const s=o?Object.assign(o,{async:!1}):{async:!1},a=t._zod.run({value:r,issues:[]},s);if(a instanceof Promise)throw new Se;if(a.issues.length){const t=new(n?.Err??e)(a.issues.map(e=>Ge(e,s,Te())));throw ze(t,n?.callee),t}return a.value},et=e=>async(t,r,o,n)=>{const s=o?Object.assign(o,{async:!0}):{async:!0};let a=t._zod.run({value:r,issues:[]},s);if(a instanceof Promise&&(a=await a),a.issues.length){const t=new(n?.Err??e)(a.issues.map(e=>Ge(e,s,Te())));throw ze(t,n?.callee),t}return a.value},tt=e=>(t,r,o)=>{const n=o?{...o,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},n);if(s instanceof Promise)throw new Se;return s.issues.length?{success:!1,error:new(e??Qe)(s.issues.map(e=>Ge(e,n,Te())))}:{success:!0,data:s.value}},rt=tt(Ye),ot=e=>async(t,r,o)=>{const n=o?Object.assign(o,{async:!0}):{async:!0};let s=t._zod.run({value:r,issues:[]},n);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(e=>Ge(e,n,Te())))}:{success:!0,data:s.value}},nt=ot(Ye),st=/^[cC][^\s-]{8,}$/,at=/^[0-9a-z]+$/,it=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,ct=/^[0-9a-vA-V]{20}$/,ut=/^[A-Za-z0-9]{27}$/,lt=/^[a-zA-Z0-9_-]{21}$/,dt=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,ht=/^([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})$/,pt=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)$/,ft=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;const mt=/^(?:(?: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])$/,yt=/^(([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})$/,gt=/^((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])$/,vt=/^(([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])$/,_t=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,wt=/^[A-Za-z0-9_-]*$/,$t=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,bt=/^\+(?:[0-9]){6,14}[0-9]$/,kt="(?:(?:\\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])))",Et=new RegExp(`^${kt}$`);function St(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+)?)?`}const Pt=/^\d+$/,Tt=/^-?\d+(?:\.\d+)?/i,It=/true|false/i,xt=/null/i,Nt=/^[^A-Z]*$/,Ct=/^[^a-z]*$/,jt=Ee("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Rt={number:"number",bigint:"bigint",object:"date"},Ot=Ee("$ZodCheckLessThan",(e,t)=>{jt.init(e,t);const r=Rt[typeof t.value];e._zod.onattach.push(e=>{const r=e._zod.bag,o=(t.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<o&&(t.inclusive?r.maximum=t.value:r.exclusiveMaximum=t.value)}),e._zod.check=o=>{(t.inclusive?o.value<=t.value:o.value<t.value)||o.issues.push({origin:r,code:"too_big",maximum:t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),zt=Ee("$ZodCheckGreaterThan",(e,t)=>{jt.init(e,t);const r=Rt[typeof t.value];e._zod.onattach.push(e=>{const r=e._zod.bag,o=(t.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>o&&(t.inclusive?r.minimum=t.value:r.exclusiveMinimum=t.value)}),e._zod.check=o=>{(t.inclusive?o.value>=t.value:o.value>t.value)||o.issues.push({origin:r,code:"too_small",minimum:t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),At=Ee("$ZodCheckMultipleOf",(e,t)=>{jt.init(e,t),e._zod.onattach.push(e=>{var r;(r=e._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof r.value?r.value%t.value===BigInt(0):0===function(e,t){const r=(e.toString().split(".")[1]||"").length,o=(t.toString().split(".")[1]||"").length,n=r>o?r:o;return Number.parseInt(e.toFixed(n).replace(".",""))%Number.parseInt(t.toFixed(n).replace(".",""))/10**n}(r.value,t.value))||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),Mt=Ee("$ZodCheckNumberFormat",(e,t)=>{jt.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),o=r?"int":"number",[n,s]=Le[t.format];e._zod.onattach.push(e=>{const o=e._zod.bag;o.format=t.format,o.minimum=n,o.maximum=s,r&&(o.pattern=Pt)}),e._zod.check=a=>{const i=a.value;if(r){if(!Number.isInteger(i))return void a.issues.push({expected:o,format:t.format,code:"invalid_type",input:i,inst:e});if(!Number.isSafeInteger(i))return void(i>0?a.issues.push({input:i,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,continue:!t.abort}):a.issues.push({input:i,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,continue:!t.abort}))}i<n&&a.issues.push({origin:"number",input:i,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort}),i>s&&a.issues.push({origin:"number",input:i,code:"too_big",maximum:s,inst:e})}}),Dt=Ee("$ZodCheckMaxLength",(e,t)=>{var r;jt.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!Ne(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const r=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<r&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{const o=r.value;if(o.length<=t.maximum)return;const n=Be(o);r.issues.push({origin:n,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Ut=Ee("$ZodCheckMinLength",(e,t)=>{var r;jt.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!Ne(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const r=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>r&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const o=r.value;if(o.length>=t.minimum)return;const n=Be(o);r.issues.push({origin:n,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),qt=Ee("$ZodCheckLengthEquals",(e,t)=>{var r;jt.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!Ne(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const r=e._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=r=>{const o=r.value,n=o.length;if(n===t.length)return;const s=Be(o),a=n>t.length;r.issues.push({origin:s,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),Vt=Ee("$ZodCheckStringFormat",(e,t)=>{var r,o;jt.init(e,t),e._zod.onattach.push(e=>{const r=e._zod.bag;r.format=t.format,t.pattern&&(r.patterns??(r.patterns=new Set),r.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(o=e._zod).check??(o.check=()=>{})}),Ft=Ee("$ZodCheckRegex",(e,t)=>{Vt.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Lt=Ee("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Nt),Vt.init(e,t)}),Ht=Ee("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Ct),Vt.init(e,t)}),Kt=Ee("$ZodCheckIncludes",(e,t)=>{jt.init(e,t);const r=qe(t.includes),o=new RegExp("number"==typeof t.position?`^.{${t.position}}${r}`:r);t.pattern=o,e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(o)}),e._zod.check=r=>{r.value.includes(t.includes,t.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),Zt=Ee("$ZodCheckStartsWith",(e,t)=>{jt.init(e,t);const r=new RegExp(`^${qe(t.prefix)}.*`);t.pattern??(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=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),Gt=Ee("$ZodCheckEndsWith",(e,t)=>{jt.init(e,t);const r=new RegExp(`.*${qe(t.suffix)}$`);t.pattern??(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=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),Bt=Ee("$ZodCheckOverwrite",(e,t)=>{jt.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class Jt{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),r=Math.min(...t.map(e=>e.length-e.trimStart().length)),o=t.map(e=>e.slice(r)).map(e=>" ".repeat(2*this.indent)+e);for(const e of o)this.content.push(e)}compile(){const e=Function,t=this?.args;return new e(...t,[...(this?.content??[""]).map(e=>` ${e}`)].join("\n"))}}const Wt={major:4,minor:0,patch:0},Qt=Ee("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Wt;const o=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&o.unshift(e);for(const t of o)for(const r of t._zod.onattach)r(e);if(0===o.length)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const t=(e,t,r)=>{let o,n=He(e);for(const s of t){if(s._zod.def.when){if(!s._zod.def.when(e))continue}else if(n)continue;const t=e.issues.length,a=s._zod.check(e);if(a instanceof Promise&&!1===r?.async)throw new Se;if(o||a instanceof Promise)o=(o??Promise.resolve()).then(async()=>{await a;e.issues.length!==t&&(n||(n=He(e,t)))});else{if(e.issues.length===t)continue;n||(n=He(e,t))}}return o?o.then(()=>e):e};e._zod.run=(r,n)=>{const s=e._zod.parse(r,n);if(s instanceof Promise){if(!1===n.async)throw new Se;return s.then(e=>t(e,o,n))}return t(s,o,n)}}e["~standard"]={validate:t=>{try{const r=rt(e,t);return r.success?{value:r.data}:{issues:r.error?.issues}}catch(r){return nt(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}}),Yt=Ee("$ZodString",(e,t)=>{var r;Qt.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??(r=e._zod.bag,new RegExp(`^${r?`[\\s\\S]{${r?.minimum??0},${r?.maximum??""}}`:"[\\s\\S]*"}$`)),e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=String(r.value)}catch(o){}return"string"==typeof r.value||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),Xt=Ee("$ZodStringFormat",(e,t)=>{Vt.init(e,t),Yt.init(e,t)}),er=Ee("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=ht),Xt.init(e,t)}),tr=Ee("$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=pt(e))}else t.pattern??(t.pattern=pt());Xt.init(e,t)}),rr=Ee("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=ft),Xt.init(e,t)}),or=Ee("$ZodURL",(e,t)=>{Xt.init(e,t),e._zod.check=r=>{try{const o=r.value,n=new URL(o),s=n.href;return t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(n.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:$t.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),void(!o.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s)}catch(o){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),nr=Ee("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Xt.init(e,t)}),sr=Ee("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=lt),Xt.init(e,t)}),ar=Ee("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=st),Xt.init(e,t)}),ir=Ee("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=at),Xt.init(e,t)}),cr=Ee("$ZodULID",(e,t)=>{t.pattern??(t.pattern=it),Xt.init(e,t)}),ur=Ee("$ZodXID",(e,t)=>{t.pattern??(t.pattern=ct),Xt.init(e,t)}),lr=Ee("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=ut),Xt.init(e,t)}),dr=Ee("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=function(e){const t=St({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-]\\d{2}:\\d{2})");const o=`${t}(?:${r.join("|")})`;return new RegExp(`^${kt}T(?:${o})$`)}(t)),Xt.init(e,t)}),hr=Ee("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Et),Xt.init(e,t)}),pr=Ee("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=new RegExp(`^${St(t)}$`)),Xt.init(e,t)}),fr=Ee("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=dt),Xt.init(e,t)}),mr=Ee("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=mt),Xt.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.format="ipv4"})}),yr=Ee("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=yt),Xt.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.format="ipv6"}),e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),gr=Ee("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=gt),Xt.init(e,t)}),vr=Ee("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=vt),Xt.init(e,t),e._zod.check=r=>{const[o,n]=r.value.split("/");try{if(!n)throw new Error;const e=Number(n);if(`${e}`!==n)throw new Error;if(e<0||e>128)throw new Error;new URL(`http://[${o}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function _r(e){if(""===e)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const wr=Ee("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=_t),Xt.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{_r(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});const $r=Ee("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=wt),Xt.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{(function(e){if(!wt.test(e))return!1;const t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return _r(t.padEnd(4*Math.ceil(t.length/4),"="))})(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),br=Ee("$ZodE164",(e,t)=>{t.pattern??(t.pattern=bt),Xt.init(e,t)});const kr=Ee("$ZodJWT",(e,t)=>{Xt.init(e,t),e._zod.check=r=>{(function(e,t=null){try{const r=e.split(".");if(3!==r.length)return!1;const[o]=r;if(!o)return!1;const n=JSON.parse(atob(o));return!("typ"in n&&"JWT"!==n?.typ||!n.alg||t&&(!("alg"in n)||n.alg!==t))}catch{return!1}})(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),Er=Ee("$ZodNumber",(e,t)=>{Qt.init(e,t),e._zod.pattern=e._zod.bag.pattern??Tt,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=Number(r.value)}catch(e){}const n=r.value;if("number"==typeof n&&!Number.isNaN(n)&&Number.isFinite(n))return r;const s="number"==typeof n?Number.isNaN(n)?"NaN":Number.isFinite(n)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:n,inst:e,...s?{received:s}:{}}),r}}),Sr=Ee("$ZodNumber",(e,t)=>{Mt.init(e,t),Er.init(e,t)}),Pr=Ee("$ZodBoolean",(e,t)=>{Qt.init(e,t),e._zod.pattern=It,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=Boolean(r.value)}catch(e){}const n=r.value;return"boolean"==typeof n||r.issues.push({expected:"boolean",code:"invalid_type",input:n,inst:e}),r}}),Tr=Ee("$ZodNull",(e,t)=>{Qt.init(e,t),e._zod.pattern=xt,e._zod.values=new Set([null]),e._zod.parse=(t,r)=>{const o=t.value;return null===o||t.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),t}}),Ir=Ee("$ZodAny",(e,t)=>{Qt.init(e,t),e._zod.parse=e=>e}),xr=Ee("$ZodUnknown",(e,t)=>{Qt.init(e,t),e._zod.parse=e=>e}),Nr=Ee("$ZodNever",(e,t)=>{Qt.init(e,t),e._zod.parse=(t,r)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function Cr(e,t,r){e.issues.length&&t.issues.push(...Ke(r,e.issues)),t.value[r]=e.value}const jr=Ee("$ZodArray",(e,t)=>{Qt.init(e,t),e._zod.parse=(r,o)=>{const n=r.value;if(!Array.isArray(n))return r.issues.push({expected:"array",code:"invalid_type",input:n,inst:e}),r;r.value=Array(n.length);const s=[];for(let e=0;e<n.length;e++){const a=n[e],i=t.element._zod.run({value:a,issues:[]},o);i instanceof Promise?s.push(i.then(t=>Cr(t,r,e))):Cr(i,r,e)}return s.length?Promise.all(s).then(()=>r):r}});function Rr(e,t,r){e.issues.length&&t.issues.push(...Ke(r,e.issues)),t.value[r]=e.value}function Or(e,t,r,o){e.issues.length?void 0===o[r]?t.value[r]=r in o?void 0:e.value:t.issues.push(...Ke(r,e.issues)):void 0===e.value?r in o&&(t.value[r]=void 0):t.value[r]=e.value}const zr=Ee("$ZodObject",(e,t)=>{Qt.init(e,t);const r=xe(()=>{const e=Object.keys(t.shape);for(const r of e)if(!(t.shape[r]instanceof Qt))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const r=(o=t.shape,Object.keys(o).filter(e=>"optional"===o[e]._zod.optin&&"optional"===o[e]._zod.optout));var o;return{shape:t.shape,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(r)}});je(e._zod,"propValues",()=>{const e=t.shape,r={};for(const t in e){const o=e[t]._zod;if(o.values){r[t]??(r[t]=new Set);for(const e of o.values)r[t].add(e)}}return r});let o;const n=Ae,s=!Pe.jitless,a=s&&Me.value,i=t.catchall;let c;e._zod.parse=(u,l)=>{c??(c=r.value);const d=u.value;if(!n(d))return u.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),u;const h=[];if(s&&a&&!1===l?.async&&!0!==l.jitless)o||(o=(e=>{const t=new Jt(["shape","payload","ctx"]),o=r.value,n=e=>{const t=Oe(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");const s=Object.create(null);let a=0;for(const e of o.keys)s[e]="key_"+a++;t.write("const newResult = {}");for(const e of o.keys)if(o.optionalKeys.has(e)){const r=s[e];t.write(`const ${r} = ${n(e)};`);const o=Oe(e);t.write(`\n if (${r}.issues.length) {\n if (input[${o}] === undefined) {\n if (${o} in input) {\n newResult[${o}] = undefined;\n }\n } else {\n payload.issues = payload.issues.concat(\n ${r}.issues.map((iss) => ({\n ...iss,\n path: iss.path ? [${o}, ...iss.path] : [${o}],\n }))\n );\n }\n } else if (${r}.value === undefined) {\n if (${o} in input) newResult[${o}] = undefined;\n } else {\n newResult[${o}] = ${r}.value;\n }\n `)}else{const r=s[e];t.write(`const ${r} = ${n(e)};`),t.write(`\n if (${r}.issues.length) payload.issues = payload.issues.concat(${r}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${Oe(e)}, ...iss.path] : [${Oe(e)}]\n })));`),t.write(`newResult[${Oe(e)}] = ${r}.value`)}t.write("payload.value = newResult;"),t.write("return payload;");const i=t.compile();return(t,r)=>i(e,t,r)})(t.shape)),u=o(u,l);else{u.value={};const e=c.shape;for(const t of c.keys){const r=e[t],o=r._zod.run({value:d[t],issues:[]},l),n="optional"===r._zod.optin&&"optional"===r._zod.optout;o instanceof Promise?h.push(o.then(e=>n?Or(e,u,t,d):Rr(e,u,t))):n?Or(o,u,t,d):Rr(o,u,t)}}if(!i)return h.length?Promise.all(h).then(()=>u):u;const p=[],f=c.keySet,m=i._zod,y=m.def.type;for(const e of Object.keys(d)){if(f.has(e))continue;if("never"===y){p.push(e);continue}const t=m.run({value:d[e],issues:[]},l);t instanceof Promise?h.push(t.then(t=>Rr(t,u,e))):Rr(t,u,e)}return p.length&&u.issues.push({code:"unrecognized_keys",keys:p,input:d,inst:e}),h.length?Promise.all(h).then(()=>u):u}});function Ar(e,t,r,o){for(const r of e)if(0===r.issues.length)return t.value=r.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(e=>e.issues.map(e=>Ge(e,o,Te())))}),t}const Mr=Ee("$ZodUnion",(e,t)=>{Qt.init(e,t),je(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),je(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),je(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),je(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=>Ce(e.source)).join("|")})$`)}}),e._zod.parse=(r,o)=>{let n=!1;const s=[];for(const e of t.options){const t=e._zod.run({value:r.value,issues:[]},o);if(t instanceof Promise)s.push(t),n=!0;else{if(0===t.issues.length)return t;s.push(t)}}return n?Promise.all(s).then(t=>Ar(t,r,e,o)):Ar(s,r,e,o)}}),Dr=Ee("$ZodDiscriminatedUnion",(e,t)=>{Mr.init(e,t);const r=e._zod.parse;je(e._zod,"propValues",()=>{const e={};for(const r of t.options){const o=r._zod.propValues;if(!o||0===Object.keys(o).length)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(const[t,r]of Object.entries(o)){e[t]||(e[t]=new Set);for(const o of r)e[t].add(o)}}return e});const o=xe(()=>{const e=t.options,r=new Map;for(const o of e){const e=o._zod.propValues[t.discriminator];if(!e||0===e.size)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(o)}"`);for(const t of e){if(r.has(t))throw new Error(`Duplicate discriminator value "${String(t)}"`);r.set(t,o)}}return r});e._zod.parse=(n,s)=>{const a=n.value;if(!Ae(a))return n.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),n;const i=o.value.get(a?.[t.discriminator]);return i?i._zod.run(n,s):t.unionFallback?r(n,s):(n.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:a,path:[t.discriminator],inst:e}),n)}}),Ur=Ee("$ZodIntersection",(e,t)=>{Qt.init(e,t),e._zod.parse=(e,r)=>{const o=e.value,n=t.left._zod.run({value:o,issues:[]},r),s=t.right._zod.run({value:o,issues:[]},r);return n instanceof Promise||s instanceof Promise?Promise.all([n,s]).then(([t,r])=>Vr(e,t,r)):Vr(e,n,s)}});function qr(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(De(e)&&De(t)){const r=Object.keys(t),o=Object.keys(e).filter(e=>-1!==r.indexOf(e)),n={...e,...t};for(const r of o){const o=qr(e[r],t[r]);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n[r]=o.data}return{valid:!0,data:n}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let o=0;o<e.length;o++){const n=qr(e[o],t[o]);if(!n.valid)return{valid:!1,mergeErrorPath:[o,...n.mergeErrorPath]};r.push(n.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Vr(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),He(e))return e;const o=qr(t.value,r.value);if(!o.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}const Fr=Ee("$ZodRecord",(e,t)=>{Qt.init(e,t),e._zod.parse=(r,o)=>{const n=r.value;if(!De(n))return r.issues.push({expected:"record",code:"invalid_type",input:n,inst:e}),r;const s=[];if(t.keyType._zod.values){const a=t.keyType._zod.values;r.value={};for(const e of a)if("string"==typeof e||"number"==typeof e||"symbol"==typeof e){const a=t.valueType._zod.run({value:n[e],issues:[]},o);a instanceof Promise?s.push(a.then(t=>{t.issues.length&&r.issues.push(...Ke(e,t.issues)),r.value[e]=t.value})):(a.issues.length&&r.issues.push(...Ke(e,a.issues)),r.value[e]=a.value)}let i;for(const e in n)a.has(e)||(i=i??[],i.push(e));i&&i.length>0&&r.issues.push({code:"unrecognized_keys",input:n,inst:e,keys:i})}else{r.value={};for(const a of Reflect.ownKeys(n)){if("__proto__"===a)continue;const i=t.keyType._zod.run({value:a,issues:[]},o);if(i instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(i.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:i.issues.map(e=>Ge(e,o,Te())),input:a,path:[a],inst:e}),r.value[i.value]=i.value;continue}const c=t.valueType._zod.run({value:n[a],issues:[]},o);c instanceof Promise?s.push(c.then(e=>{e.issues.length&&r.issues.push(...Ke(a,e.issues)),r.value[i.value]=e.value})):(c.issues.length&&r.issues.push(...Ke(a,c.issues)),r.value[i.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),Lr=Ee("$ZodEnum",(e,t)=>{Qt.init(e,t);const r=function(e){const t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,r])=>-1===t.indexOf(+e)).map(([e,t])=>t)}(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(e=>Ue.has(typeof e)).map(e=>"string"==typeof e?qe(e):e.toString()).join("|")})$`),e._zod.parse=(t,o)=>{const n=t.value;return e._zod.values.has(n)||t.issues.push({code:"invalid_value",values:r,input:n,inst:e}),t}}),Hr=Ee("$ZodLiteral",(e,t)=>{Qt.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(e=>"string"==typeof e?qe(e):e?e.toString():String(e)).join("|")})$`),e._zod.parse=(r,o)=>{const n=r.value;return e._zod.values.has(n)||r.issues.push({code:"invalid_value",values:t.values,input:n,inst:e}),r}}),Kr=Ee("$ZodTransform",(e,t)=>{Qt.init(e,t),e._zod.parse=(e,r)=>{const o=t.transform(e.value,e);if(r.async){return(o instanceof Promise?o:Promise.resolve(o)).then(t=>(e.value=t,e))}if(o instanceof Promise)throw new Se;return e.value=o,e}}),Zr=Ee("$ZodOptional",(e,t)=>{Qt.init(e,t),e._zod.optin="optional",e._zod.optout="optional",je(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),je(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${Ce(e.source)})?$`):void 0}),e._zod.parse=(e,r)=>"optional"===t.innerType._zod.optin?t.innerType._zod.run(e,r):void 0===e.value?e:t.innerType._zod.run(e,r)}),Gr=Ee("$ZodNullable",(e,t)=>{Qt.init(e,t),je(e._zod,"optin",()=>t.innerType._zod.optin),je(e._zod,"optout",()=>t.innerType._zod.optout),je(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${Ce(e.source)}|null)$`):void 0}),je(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,r)=>null===e.value?e:t.innerType._zod.run(e,r)}),Br=Ee("$ZodDefault",(e,t)=>{Qt.init(e,t),e._zod.optin="optional",je(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>{if(void 0===e.value)return e.value=t.defaultValue,e;const o=t.innerType._zod.run(e,r);return o instanceof Promise?o.then(e=>Jr(e,t)):Jr(o,t)}});function Jr(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}const Wr=Ee("$ZodPrefault",(e,t)=>{Qt.init(e,t),e._zod.optin="optional",je(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>(void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,r))}),Qr=Ee("$ZodNonOptional",(e,t)=>{Qt.init(e,t),je(e._zod,"values",()=>{const e=t.innerType._zod.values;return e?new Set([...e].filter(e=>void 0!==e)):void 0}),e._zod.parse=(r,o)=>{const n=t.innerType._zod.run(r,o);return n instanceof Promise?n.then(t=>Yr(t,e)):Yr(n,e)}});function Yr(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 Xr=Ee("$ZodCatch",(e,t)=>{Qt.init(e,t),e._zod.optin="optional",je(e._zod,"optout",()=>t.innerType._zod.optout),je(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>{const o=t.innerType._zod.run(e,r);return o instanceof Promise?o.then(o=>(e.value=o.value,o.issues.length&&(e.value=t.catchValue({...e,error:{issues:o.issues.map(e=>Ge(e,r,Te()))},input:e.value}),e.issues=[]),e)):(e.value=o.value,o.issues.length&&(e.value=t.catchValue({...e,error:{issues:o.issues.map(e=>Ge(e,r,Te()))},input:e.value}),e.issues=[]),e)}}),eo=Ee("$ZodPipe",(e,t)=>{Qt.init(e,t),je(e._zod,"values",()=>t.in._zod.values),je(e._zod,"optin",()=>t.in._zod.optin),je(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(e,r)=>{const o=t.in._zod.run(e,r);return o instanceof Promise?o.then(e=>to(e,t,r)):to(o,t,r)}});function to(e,t,r){return He(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}const ro=Ee("$ZodReadonly",(e,t)=>{Qt.init(e,t),je(e._zod,"propValues",()=>t.innerType._zod.propValues),je(e._zod,"values",()=>t.innerType._zod.values),je(e._zod,"optin",()=>t.innerType._zod.optin),je(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(e,r)=>{const o=t.innerType._zod.run(e,r);return o instanceof Promise?o.then(oo):oo(o)}});function oo(e){return e.value=Object.freeze(e.value),e}const no=Ee("$ZodCustom",(e,t)=>{jt.init(e,t),Qt.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=r=>{const o=r.value,n=t.fn(o);if(n instanceof Promise)return n.then(t=>so(t,r,o,e));so(n,r,o,e)}});function so(e,t,r,o){if(!e){const e={code:"custom",input:r,inst:o,path:[...o._zod.def.path??[]],continue:!o._zod.def.abort};o._zod.def.params&&(e.params=o._zod.def.params),t.issues.push(Je(e))}}class ao{constructor(){this._map=new Map,this._idmap=new Map}add(e,...t){const r=t[0];if(this._map.set(e,r),r&&"object"==typeof r&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,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 r={...this.get(t)??{}};return delete r.id,{...r,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}}function io(){return new ao}const co=io();function uo(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...Fe(t)})}function lo(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...Fe(t)})}function ho(e,t){return new Ot({check:"less_than",...Fe(t),value:e,inclusive:!1})}function po(e,t){return new Ot({check:"less_than",...Fe(t),value:e,inclusive:!0})}function fo(e,t){return new zt({check:"greater_than",...Fe(t),value:e,inclusive:!1})}function mo(e,t){return new zt({check:"greater_than",...Fe(t),value:e,inclusive:!0})}function yo(e,t){return new At({check:"multiple_of",...Fe(t),value:e})}function go(e,t){return new Dt({check:"max_length",...Fe(t),maximum:e})}function vo(e,t){return new Ut({check:"min_length",...Fe(t),minimum:e})}function _o(e,t){return new qt({check:"length_equals",...Fe(t),length:e})}function wo(e){return new Bt({check:"overwrite",tx:e})}function $o(e){return!!e._zod}function bo(e,t){if($o(e)){return rt(e,t)}return e.safeParse(t)}function ko(e){if(!e)return;let t;if($o(e)){const r=e;t=r._zod?.def?.shape}else{t=e.shape}if(t){if("function"==typeof t)try{return t()}catch{return}return t}}const Eo=Ee("ZodISODateTime",(e,t)=>{dr.init(e,t),Vo.init(e,t)});function So(e){return function(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Fe(t)})}(Eo,e)}const Po=Ee("ZodISODate",(e,t)=>{hr.init(e,t),Vo.init(e,t)});function To(e){return function(e,t){return new e({type:"string",format:"date",check:"string_format",...Fe(t)})}(Po,e)}const Io=Ee("ZodISOTime",(e,t)=>{pr.init(e,t),Vo.init(e,t)});function xo(e){return function(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...Fe(t)})}(Io,e)}const No=Ee("ZodISODuration",(e,t)=>{fr.init(e,t),Vo.init(e,t)});function Co(e){return function(e,t){return new e({type:"string",format:"duration",check:"string_format",...Fe(t)})}(No,e)}const jo=Ee("ZodError",(e,t)=>{Qe.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>function(e,t){const r=t||function(e){return e.message},o={_errors:[]},n=e=>{for(const t of e.issues)if("invalid_union"===t.code&&t.errors.length)t.errors.map(e=>n({issues:e}));else if("invalid_key"===t.code)n({issues:t.issues});else if("invalid_element"===t.code)n({issues:t.issues});else if(0===t.path.length)o._errors.push(r(t));else{let e=o,n=0;for(;n<t.path.length;){const o=t.path[n];n===t.path.length-1?(e[o]=e[o]||{_errors:[]},e[o]._errors.push(r(t))):e[o]=e[o]||{_errors:[]},e=e[o],n++}}};return n(e),o}(e,t)},flatten:{value:t=>function(e,t=e=>e.message){const r={},o=[];for(const n of e.issues)n.path.length>0?(r[n.path[0]]=r[n.path[0]]||[],r[n.path[0]].push(t(n))):o.push(t(n));return{formErrors:o,fieldErrors:r}}(e,t)},addIssue:{value:t=>e.issues.push(t)},addIssues:{value:t=>e.issues.push(...t)},isEmpty:{get:()=>0===e.issues.length}})},{Parent:Error}),Ro=Xe(jo),Oo=et(jo),zo=tt(jo),Ao=ot(jo),Mo=Ee("ZodType",(e,t)=>(Qt.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),e.clone=(t,r)=>Ve(e,t,r),e.brand=()=>e,e.register=(t,r)=>(t.add(e,r),e),e.parse=(t,r)=>Ro(e,t,r,{callee:e.parse}),e.safeParse=(t,r)=>zo(e,t,r),e.parseAsync=async(t,r)=>Oo(e,t,r,{callee:e.parseAsync}),e.safeParseAsync=async(t,r)=>Ao(e,t,r),e.spa=e.safeParseAsync,e.refine=(t,r)=>e.check(function(e,t={}){return function(e,t,r){return new e({type:"custom",check:"custom",fn:t,...Fe(r)})}(Qn,e,t)}(t,r)),e.superRefine=t=>e.check(function(e){const t=function(e){const t=new jt({check:"custom"});return t._zod.check=e,t}(r=>(r.addIssue=e=>{if("string"==typeof e)r.issues.push(Je(e,r.value,t._zod.def));else{const o=e;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=t),o.continue??(o.continue=!t._zod.def.abort),r.issues.push(Je(o))}},e(r.value,r)));return t}(t)),e.overwrite=t=>e.check(wo(t)),e.optional=()=>Vn(e),e.nullable=()=>Ln(e),e.nullish=()=>Vn(Ln(e)),e.nonoptional=t=>function(e,t){return new Zn({type:"nonoptional",innerType:e,...Fe(t)})}(e,t),e.array=()=>bn(e),e.or=t=>Tn([e,t]),e.and=t=>Cn(e,t),e.transform=t=>Jn(e,Un(t)),e.default=t=>{return r=t,new Hn({type:"default",innerType:e,get defaultValue(){return"function"==typeof r?r():r}});var r},e.prefault=t=>{return r=t,new Kn({type:"prefault",innerType:e,get defaultValue(){return"function"==typeof r?r():r}});var r},e.catch=t=>{return new Gn({type:"catch",innerType:e,catchValue:"function"==typeof(r=t)?r:()=>r});var r},e.pipe=t=>Jn(e,t),e.readonly=()=>new Wn({type:"readonly",innerType:e}),e.describe=t=>{const r=e.clone();return co.add(r,{description:t}),r},Object.defineProperty(e,"description",{get:()=>co.get(e)?.description,configurable:!0}),e.meta=(...t)=>{if(0===t.length)return co.get(e);const r=e.clone();return co.add(r,t[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),Do=Ee("_ZodString",(e,t)=>{Yt.init(e,t),Mo.init(e,t);const r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...t)=>e.check(function(e,t){return new Ft({check:"string_format",format:"regex",...Fe(t),pattern:e})}(...t)),e.includes=(...t)=>e.check(function(e,t){return new Kt({check:"string_format",format:"includes",...Fe(t),includes:e})}(...t)),e.startsWith=(...t)=>e.check(function(e,t){return new Zt({check:"string_format",format:"starts_with",...Fe(t),prefix:e})}(...t)),e.endsWith=(...t)=>e.check(function(e,t){return new Gt({check:"string_format",format:"ends_with",...Fe(t),suffix:e})}(...t)),e.min=(...t)=>e.check(vo(...t)),e.max=(...t)=>e.check(go(...t)),e.length=(...t)=>e.check(_o(...t)),e.nonempty=(...t)=>e.check(vo(1,...t)),e.lowercase=t=>e.check(function(e){return new Lt({check:"string_format",format:"lowercase",...Fe(e)})}(t)),e.uppercase=t=>e.check(function(e){return new Ht({check:"string_format",format:"uppercase",...Fe(e)})}(t)),e.trim=()=>e.check(wo(e=>e.trim())),e.normalize=(...t)=>e.check(function(e){return wo(t=>t.normalize(e))}(...t)),e.toLowerCase=()=>e.check(wo(e=>e.toLowerCase())),e.toUpperCase=()=>e.check(wo(e=>e.toUpperCase()))}),Uo=Ee("ZodString",(e,t)=>{Yt.init(e,t),Do.init(e,t),e.email=t=>e.check(function(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...Fe(t)})}(Fo,t)),e.url=t=>e.check(lo(Ko,t)),e.jwt=t=>e.check(function(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...Fe(t)})}(an,t)),e.emoji=t=>e.check(function(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...Fe(t)})}(Zo,t)),e.guid=t=>e.check(uo(Lo,t)),e.uuid=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...Fe(t)})}(Ho,t)),e.uuidv4=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Fe(t)})}(Ho,t)),e.uuidv6=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Fe(t)})}(Ho,t)),e.uuidv7=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Fe(t)})}(Ho,t)),e.nanoid=t=>e.check(function(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...Fe(t)})}(Go,t)),e.guid=t=>e.check(uo(Lo,t)),e.cuid=t=>e.check(function(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...Fe(t)})}(Bo,t)),e.cuid2=t=>e.check(function(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...Fe(t)})}(Jo,t)),e.ulid=t=>e.check(function(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...Fe(t)})}(Wo,t)),e.base64=t=>e.check(function(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...Fe(t)})}(on,t)),e.base64url=t=>e.check(function(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...Fe(t)})}(nn,t)),e.xid=t=>e.check(function(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...Fe(t)})}(Qo,t)),e.ksuid=t=>e.check(function(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...Fe(t)})}(Yo,t)),e.ipv4=t=>e.check(function(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...Fe(t)})}(Xo,t)),e.ipv6=t=>e.check(function(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...Fe(t)})}(en,t)),e.cidrv4=t=>e.check(function(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Fe(t)})}(tn,t)),e.cidrv6=t=>e.check(function(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Fe(t)})}(rn,t)),e.e164=t=>e.check(function(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...Fe(t)})}(sn,t)),e.datetime=t=>e.check(So(t)),e.date=t=>e.check(To(t)),e.time=t=>e.check(xo(t)),e.duration=t=>e.check(Co(t))});function qo(e){return function(e,t){return new e({type:"string",...Fe(t)})}(Uo,e)}const Vo=Ee("ZodStringFormat",(e,t)=>{Xt.init(e,t),Do.init(e,t)}),Fo=Ee("ZodEmail",(e,t)=>{rr.init(e,t),Vo.init(e,t)}),Lo=Ee("ZodGUID",(e,t)=>{er.init(e,t),Vo.init(e,t)}),Ho=Ee("ZodUUID",(e,t)=>{tr.init(e,t),Vo.init(e,t)}),Ko=Ee("ZodURL",(e,t)=>{or.init(e,t),Vo.init(e,t)});const Zo=Ee("ZodEmoji",(e,t)=>{nr.init(e,t),Vo.init(e,t)}),Go=Ee("ZodNanoID",(e,t)=>{sr.init(e,t),Vo.init(e,t)}),Bo=Ee("ZodCUID",(e,t)=>{ar.init(e,t),Vo.init(e,t)}),Jo=Ee("ZodCUID2",(e,t)=>{ir.init(e,t),Vo.init(e,t)}),Wo=Ee("ZodULID",(e,t)=>{cr.init(e,t),Vo.init(e,t)}),Qo=Ee("ZodXID",(e,t)=>{ur.init(e,t),Vo.init(e,t)}),Yo=Ee("ZodKSUID",(e,t)=>{lr.init(e,t),Vo.init(e,t)}),Xo=Ee("ZodIPv4",(e,t)=>{mr.init(e,t),Vo.init(e,t)}),en=Ee("ZodIPv6",(e,t)=>{yr.init(e,t),Vo.init(e,t)}),tn=Ee("ZodCIDRv4",(e,t)=>{gr.init(e,t),Vo.init(e,t)}),rn=Ee("ZodCIDRv6",(e,t)=>{vr.init(e,t),Vo.init(e,t)}),on=Ee("ZodBase64",(e,t)=>{wr.init(e,t),Vo.init(e,t)}),nn=Ee("ZodBase64URL",(e,t)=>{$r.init(e,t),Vo.init(e,t)}),sn=Ee("ZodE164",(e,t)=>{br.init(e,t),Vo.init(e,t)}),an=Ee("ZodJWT",(e,t)=>{kr.init(e,t),Vo.init(e,t)}),cn=Ee("ZodNumber",(e,t)=>{Er.init(e,t),Mo.init(e,t),e.gt=(t,r)=>e.check(fo(t,r)),e.gte=(t,r)=>e.check(mo(t,r)),e.min=(t,r)=>e.check(mo(t,r)),e.lt=(t,r)=>e.check(ho(t,r)),e.lte=(t,r)=>e.check(po(t,r)),e.max=(t,r)=>e.check(po(t,r)),e.int=t=>e.check(dn(t)),e.safe=t=>e.check(dn(t)),e.positive=t=>e.check(fo(0,t)),e.nonnegative=t=>e.check(mo(0,t)),e.negative=t=>e.check(ho(0,t)),e.nonpositive=t=>e.check(po(0,t)),e.multipleOf=(t,r)=>e.check(yo(t,r)),e.step=(t,r)=>e.check(yo(t,r)),e.finite=()=>e;const r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function un(e){return function(e,t){return new e({type:"number",checks:[],...Fe(t)})}(cn,e)}const ln=Ee("ZodNumberFormat",(e,t)=>{Sr.init(e,t),cn.init(e,t)});function dn(e){return function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...Fe(t)})}(ln,e)}const hn=Ee("ZodBoolean",(e,t)=>{Pr.init(e,t),Mo.init(e,t)});function pn(e){return function(e,t){return new e({type:"boolean",...Fe(t)})}(hn,e)}const fn=Ee("ZodNull",(e,t)=>{Tr.init(e,t),Mo.init(e,t)});function mn(e){return function(e,t){return new e({type:"null",...Fe(t)})}(fn,e)}const yn=Ee("ZodAny",(e,t)=>{Ir.init(e,t),Mo.init(e,t)});const gn=Ee("ZodUnknown",(e,t)=>{xr.init(e,t),Mo.init(e,t)});function vn(){return new gn({type:"unknown"})}const _n=Ee("ZodNever",(e,t)=>{Nr.init(e,t),Mo.init(e,t)});function wn(e){return function(e,t){return new e({type:"never",...Fe(t)})}(_n,e)}const $n=Ee("ZodArray",(e,t)=>{jr.init(e,t),Mo.init(e,t),e.element=t.element,e.min=(t,r)=>e.check(vo(t,r)),e.nonempty=t=>e.check(vo(1,t)),e.max=(t,r)=>e.check(go(t,r)),e.length=(t,r)=>e.check(_o(t,r)),e.unwrap=()=>e.element});function bn(e,t){return function(e,t,r){return new e({type:"array",element:t,...Fe(r)})}($n,e,t)}const kn=Ee("ZodObject",(e,t)=>{zr.init(e,t),Mo.init(e,t),je(e,"shape",()=>t.shape),e.keyof=()=>zn(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:vn()}),e.loose=()=>e.clone({...e._zod.def,catchall:vn()}),e.strict=()=>e.clone({...e._zod.def,catchall:wn()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>function(e,t){if(!De(t))throw new Error("Invalid input to extend: expected a plain object");const r={...e._zod.def,get shape(){const r={...e._zod.def.shape,...t};return Re(this,"shape",r),r},checks:[]};return Ve(e,r)}(e,t),e.merge=t=>{return o=t,Ve(r=e,{...r._zod.def,get shape(){const e={...r._zod.def.shape,...o._zod.def.shape};return Re(this,"shape",e),e},catchall:o._zod.def.catchall,checks:[]});var r,o},e.pick=t=>function(e,t){const r={},o=e._zod.def;for(const e in t){if(!(e in o.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&(r[e]=o.shape[e])}return Ve(e,{...e._zod.def,shape:r,checks:[]})}(e,t),e.omit=t=>function(e,t){const r={...e._zod.def.shape},o=e._zod.def;for(const e in t){if(!(e in o.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return Ve(e,{...e._zod.def,shape:r,checks:[]})}(e,t),e.partial=(...t)=>function(e,t,r){const o=t._zod.def.shape,n={...o};if(r)for(const t in r){if(!(t in o))throw new Error(`Unrecognized key: "${t}"`);r[t]&&(n[t]=e?new e({type:"optional",innerType:o[t]}):o[t])}else for(const t in o)n[t]=e?new e({type:"optional",innerType:o[t]}):o[t];return Ve(t,{...t._zod.def,shape:n,checks:[]})}(qn,e,t[0]),e.required=(...t)=>function(e,t,r){const o=t._zod.def.shape,n={...o};if(r)for(const t in r){if(!(t in n))throw new Error(`Unrecognized key: "${t}"`);r[t]&&(n[t]=new e({type:"nonoptional",innerType:o[t]}))}else for(const t in o)n[t]=new e({type:"nonoptional",innerType:o[t]});return Ve(t,{...t._zod.def,shape:n,checks:[]})}(Zn,e,t[0])});function En(e,t){const r={type:"object",get shape(){return Re(this,"shape",{...e}),this.shape},...Fe(t)};return new kn(r)}function Sn(e,t){return new kn({type:"object",get shape(){return Re(this,"shape",{...e}),this.shape},catchall:vn(),...Fe(t)})}const Pn=Ee("ZodUnion",(e,t)=>{Mr.init(e,t),Mo.init(e,t),e.options=t.options});function Tn(e,t){return new Pn({type:"union",options:e,...Fe(t)})}const In=Ee("ZodDiscriminatedUnion",(e,t)=>{Pn.init(e,t),Dr.init(e,t)});function xn(e,t,r){return new In({type:"union",options:t,discriminator:e,...Fe(r)})}const Nn=Ee("ZodIntersection",(e,t)=>{Ur.init(e,t),Mo.init(e,t)});function Cn(e,t){return new Nn({type:"intersection",left:e,right:t})}const jn=Ee("ZodRecord",(e,t)=>{Fr.init(e,t),Mo.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function Rn(e,t,r){return new jn({type:"record",keyType:e,valueType:t,...Fe(r)})}const On=Ee("ZodEnum",(e,t)=>{Lr.init(e,t),Mo.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);const r=new Set(Object.keys(t.entries));e.extract=(e,o)=>{const n={};for(const o of e){if(!r.has(o))throw new Error(`Key ${o} not found in enum`);n[o]=t.entries[o]}return new On({...t,checks:[],...Fe(o),entries:n})},e.exclude=(e,o)=>{const n={...t.entries};for(const t of e){if(!r.has(t))throw new Error(`Key ${t} not found in enum`);delete n[t]}return new On({...t,checks:[],...Fe(o),entries:n})}});function zn(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new On({type:"enum",entries:r,...Fe(t)})}const An=Ee("ZodLiteral",(e,t)=>{Hr.init(e,t),Mo.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 Mn(e,t){return new An({type:"literal",values:Array.isArray(e)?e:[e],...Fe(t)})}const Dn=Ee("ZodTransform",(e,t)=>{Kr.init(e,t),Mo.init(e,t),e._zod.parse=(r,o)=>{r.addIssue=o=>{if("string"==typeof o)r.issues.push(Je(o,r.value,t));else{const t=o;t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=r.value),t.inst??(t.inst=e),t.continue??(t.continue=!0),r.issues.push(Je(t))}};const n=t.transform(r.value,r);return n instanceof Promise?n.then(e=>(r.value=e,r)):(r.value=n,r)}});function Un(e){return new Dn({type:"transform",transform:e})}const qn=Ee("ZodOptional",(e,t)=>{Zr.init(e,t),Mo.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Vn(e){return new qn({type:"optional",innerType:e})}const Fn=Ee("ZodNullable",(e,t)=>{Gr.init(e,t),Mo.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Ln(e){return new Fn({type:"nullable",innerType:e})}const Hn=Ee("ZodDefault",(e,t)=>{Br.init(e,t),Mo.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});const Kn=Ee("ZodPrefault",(e,t)=>{Wr.init(e,t),Mo.init(e,t),e.unwrap=()=>e._zod.def.innerType});const Zn=Ee("ZodNonOptional",(e,t)=>{Qr.init(e,t),Mo.init(e,t),e.unwrap=()=>e._zod.def.innerType});const Gn=Ee("ZodCatch",(e,t)=>{Xr.init(e,t),Mo.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});const Bn=Ee("ZodPipe",(e,t)=>{eo.init(e,t),Mo.init(e,t),e.in=t.in,e.out=t.out});function Jn(e,t){return new Bn({type:"pipe",in:e,out:t})}const Wn=Ee("ZodReadonly",(e,t)=>{ro.init(e,t),Mo.init(e,t)});const Qn=Ee("ZodCustom",(e,t)=>{no.init(e,t),Mo.init(e,t)});function Yn(e,t){return Jn(Un(e),t)}const Xn="custom";const es="2025-11-25",ts=[es,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],rs="io.modelcontextprotocol/related-task",os="2.0",ns=function(e,t,r){const o=Fe(r);return o.abort??(o.abort=!0),new e({type:"custom",check:"custom",fn:t,...o})}(Qn,(e=>null!==e&&("object"==typeof e||"function"==typeof e))??(()=>!0),ss);var ss;const as=Tn([qo(),un().int()]),is=qo();Sn({ttl:Tn([un(),mn()]).optional(),pollInterval:un().optional()});const cs=En({ttl:un().optional()}),us=En({taskId:qo()}),ls=Sn({progressToken:as.optional(),[rs]:us.optional()}),ds=En({_meta:ls.optional()}),hs=ds.extend({task:cs.optional()}),ps=En({method:qo(),params:ds.loose().optional()}),fs=En({_meta:ls.optional()}),ms=En({method:qo(),params:fs.loose().optional()}),ys=Sn({_meta:ls.optional()}),gs=Tn([qo(),un().int()]),vs=En({jsonrpc:Mn(os),id:gs,...ps.shape}).strict(),_s=e=>vs.safeParse(e).success,ws=En({jsonrpc:Mn(os),...ms.shape}).strict(),$s=En({jsonrpc:Mn(os),id:gs,result:ys}).strict(),bs=e=>$s.safeParse(e).success;var ks;!function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"}(ks||(ks={}));const Es=En({jsonrpc:Mn(os),id:gs.optional(),error:En({code:un().int(),message:qo(),data:vn().optional()})}).strict(),Ss=Tn([vs,ws,$s,Es]);Tn([$s,Es]);const Ps=ys.strict(),Ts=fs.extend({requestId:gs.optional(),reason:qo().optional()}),Is=ms.extend({method:Mn("notifications/cancelled"),params:Ts}),xs=En({src:qo(),mimeType:qo().optional(),sizes:bn(qo()).optional(),theme:zn(["light","dark"]).optional()}),Ns=En({icons:bn(xs).optional()}),Cs=En({name:qo(),title:qo().optional()}),js=Cs.extend({...Cs.shape,...Ns.shape,version:qo(),websiteUrl:qo().optional(),description:qo().optional()}),Rs=Cn(En({applyDefaults:pn().optional()}),Rn(qo(),vn())),Os=Yn(e=>e&&"object"==typeof e&&!Array.isArray(e)&&0===Object.keys(e).length?{form:{}}:e,Cn(En({form:Rs.optional(),url:ns.optional()}),Rn(qo(),vn()).optional())),zs=Sn({list:ns.optional(),cancel:ns.optional(),requests:Sn({sampling:Sn({createMessage:ns.optional()}).optional(),elicitation:Sn({create:ns.optional()}).optional()}).optional()}),As=Sn({list:ns.optional(),cancel:ns.optional(),requests:Sn({tools:Sn({call:ns.optional()}).optional()}).optional()}),Ms=En({experimental:Rn(qo(),ns).optional(),sampling:En({context:ns.optional(),tools:ns.optional()}).optional(),elicitation:Os.optional(),roots:En({listChanged:pn().optional()}).optional(),tasks:zs.optional()}),Ds=ds.extend({protocolVersion:qo(),capabilities:Ms,clientInfo:js}),Us=ps.extend({method:Mn("initialize"),params:Ds}),qs=En({experimental:Rn(qo(),ns).optional(),logging:ns.optional(),completions:ns.optional(),prompts:En({listChanged:pn().optional()}).optional(),resources:En({subscribe:pn().optional(),listChanged:pn().optional()}).optional(),tools:En({listChanged:pn().optional()}).optional(),tasks:As.optional()}),Vs=ys.extend({protocolVersion:qo(),capabilities:qs,serverInfo:js,instructions:qo().optional()}),Fs=ms.extend({method:Mn("notifications/initialized"),params:fs.optional()}),Ls=ps.extend({method:Mn("ping"),params:ds.optional()}),Hs=En({progress:un(),total:Vn(un()),message:Vn(qo())}),Ks=En({...fs.shape,...Hs.shape,progressToken:as}),Zs=ms.extend({method:Mn("notifications/progress"),params:Ks}),Gs=ds.extend({cursor:is.optional()}),Bs=ps.extend({params:Gs.optional()}),Js=ys.extend({nextCursor:is.optional()}),Ws=zn(["working","input_required","completed","failed","cancelled"]),Qs=En({taskId:qo(),status:Ws,ttl:Tn([un(),mn()]),createdAt:qo(),lastUpdatedAt:qo(),pollInterval:Vn(un()),statusMessage:Vn(qo())}),Ys=ys.extend({task:Qs}),Xs=fs.merge(Qs),ea=ms.extend({method:Mn("notifications/tasks/status"),params:Xs}),ta=ps.extend({method:Mn("tasks/get"),params:ds.extend({taskId:qo()})}),ra=ys.merge(Qs),oa=ps.extend({method:Mn("tasks/result"),params:ds.extend({taskId:qo()})});ys.loose();const na=Bs.extend({method:Mn("tasks/list")}),sa=Js.extend({tasks:bn(Qs)}),aa=ps.extend({method:Mn("tasks/cancel"),params:ds.extend({taskId:qo()})}),ia=ys.merge(Qs),ca=En({uri:qo(),mimeType:Vn(qo()),_meta:Rn(qo(),vn()).optional()}),ua=ca.extend({text:qo()}),la=qo().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),da=ca.extend({blob:la}),ha=zn(["user","assistant"]),pa=En({audience:bn(ha).optional(),priority:un().min(0).max(1).optional(),lastModified:So({offset:!0}).optional()}),fa=En({...Cs.shape,...Ns.shape,uri:qo(),description:Vn(qo()),mimeType:Vn(qo()),annotations:pa.optional(),_meta:Vn(Sn({}))}),ma=En({...Cs.shape,...Ns.shape,uriTemplate:qo(),description:Vn(qo()),mimeType:Vn(qo()),annotations:pa.optional(),_meta:Vn(Sn({}))}),ya=Bs.extend({method:Mn("resources/list")}),ga=Js.extend({resources:bn(fa)}),va=Bs.extend({method:Mn("resources/templates/list")}),_a=Js.extend({resourceTemplates:bn(ma)}),wa=ds.extend({uri:qo()}),$a=wa,ba=ps.extend({method:Mn("resources/read"),params:$a}),ka=ys.extend({contents:bn(Tn([ua,da]))}),Ea=ms.extend({method:Mn("notifications/resources/list_changed"),params:fs.optional()}),Sa=wa,Pa=ps.extend({method:Mn("resources/subscribe"),params:Sa}),Ta=wa,Ia=ps.extend({method:Mn("resources/unsubscribe"),params:Ta}),xa=fs.extend({uri:qo()}),Na=ms.extend({method:Mn("notifications/resources/updated"),params:xa}),Ca=En({name:qo(),description:Vn(qo()),required:Vn(pn())}),ja=En({...Cs.shape,...Ns.shape,description:Vn(qo()),arguments:Vn(bn(Ca)),_meta:Vn(Sn({}))}),Ra=Bs.extend({method:Mn("prompts/list")}),Oa=Js.extend({prompts:bn(ja)}),za=ds.extend({name:qo(),arguments:Rn(qo(),qo()).optional()}),Aa=ps.extend({method:Mn("prompts/get"),params:za}),Ma=En({type:Mn("text"),text:qo(),annotations:pa.optional(),_meta:Rn(qo(),vn()).optional()}),Da=En({type:Mn("image"),data:la,mimeType:qo(),annotations:pa.optional(),_meta:Rn(qo(),vn()).optional()}),Ua=En({type:Mn("audio"),data:la,mimeType:qo(),annotations:pa.optional(),_meta:Rn(qo(),vn()).optional()}),qa=En({type:Mn("tool_use"),name:qo(),id:qo(),input:Rn(qo(),vn()),_meta:Rn(qo(),vn()).optional()}),Va=En({type:Mn("resource"),resource:Tn([ua,da]),annotations:pa.optional(),_meta:Rn(qo(),vn()).optional()}),Fa=Tn([Ma,Da,Ua,fa.extend({type:Mn("resource_link")}),Va]),La=En({role:ha,content:Fa}),Ha=ys.extend({description:qo().optional(),messages:bn(La)}),Ka=ms.extend({method:Mn("notifications/prompts/list_changed"),params:fs.optional()}),Za=En({title:qo().optional(),readOnlyHint:pn().optional(),destructiveHint:pn().optional(),idempotentHint:pn().optional(),openWorldHint:pn().optional()}),Ga=En({taskSupport:zn(["required","optional","forbidden"]).optional()}),Ba=En({...Cs.shape,...Ns.shape,description:qo().optional(),inputSchema:En({type:Mn("object"),properties:Rn(qo(),ns).optional(),required:bn(qo()).optional()}).catchall(vn()),outputSchema:En({type:Mn("object"),properties:Rn(qo(),ns).optional(),required:bn(qo()).optional()}).catchall(vn()).optional(),annotations:Za.optional(),execution:Ga.optional(),_meta:Rn(qo(),vn()).optional()}),Ja=Bs.extend({method:Mn("tools/list")}),Wa=Js.extend({tools:bn(Ba)}),Qa=ys.extend({content:bn(Fa).default([]),structuredContent:Rn(qo(),vn()).optional(),isError:pn().optional()});Qa.or(ys.extend({toolResult:vn()}));const Ya=hs.extend({name:qo(),arguments:Rn(qo(),vn()).optional()}),Xa=ps.extend({method:Mn("tools/call"),params:Ya}),ei=ms.extend({method:Mn("notifications/tools/list_changed"),params:fs.optional()}),ti=En({autoRefresh:pn().default(!0),debounceMs:un().int().nonnegative().default(300)}),ri=zn(["debug","info","notice","warning","error","critical","alert","emergency"]),oi=ds.extend({level:ri}),ni=ps.extend({method:Mn("logging/setLevel"),params:oi}),si=fs.extend({level:ri,logger:qo().optional(),data:vn()}),ai=ms.extend({method:Mn("notifications/message"),params:si}),ii=En({name:qo().optional()}),ci=En({hints:bn(ii).optional(),costPriority:un().min(0).max(1).optional(),speedPriority:un().min(0).max(1).optional(),intelligencePriority:un().min(0).max(1).optional()}),ui=En({mode:zn(["auto","required","none"]).optional()}),li=En({type:Mn("tool_result"),toolUseId:qo().describe("The unique identifier for the corresponding tool call."),content:bn(Fa).default([]),structuredContent:En({}).loose().optional(),isError:pn().optional(),_meta:Rn(qo(),vn()).optional()}),di=xn("type",[Ma,Da,Ua]),hi=xn("type",[Ma,Da,Ua,qa,li]),pi=En({role:ha,content:Tn([hi,bn(hi)]),_meta:Rn(qo(),vn()).optional()}),fi=hs.extend({messages:bn(pi),modelPreferences:ci.optional(),systemPrompt:qo().optional(),includeContext:zn(["none","thisServer","allServers"]).optional(),temperature:un().optional(),maxTokens:un().int(),stopSequences:bn(qo()).optional(),metadata:ns.optional(),tools:bn(Ba).optional(),toolChoice:ui.optional()}),mi=ps.extend({method:Mn("sampling/createMessage"),params:fi}),yi=ys.extend({model:qo(),stopReason:Vn(zn(["endTurn","stopSequence","maxTokens"]).or(qo())),role:ha,content:di}),gi=ys.extend({model:qo(),stopReason:Vn(zn(["endTurn","stopSequence","maxTokens","toolUse"]).or(qo())),role:ha,content:Tn([hi,bn(hi)])}),vi=En({type:Mn("boolean"),title:qo().optional(),description:qo().optional(),default:pn().optional()}),_i=En({type:Mn("string"),title:qo().optional(),description:qo().optional(),minLength:un().optional(),maxLength:un().optional(),format:zn(["email","uri","date","date-time"]).optional(),default:qo().optional()}),wi=En({type:zn(["number","integer"]),title:qo().optional(),description:qo().optional(),minimum:un().optional(),maximum:un().optional(),default:un().optional()}),$i=En({type:Mn("string"),title:qo().optional(),description:qo().optional(),enum:bn(qo()),default:qo().optional()}),bi=En({type:Mn("string"),title:qo().optional(),description:qo().optional(),oneOf:bn(En({const:qo(),title:qo()})),default:qo().optional()}),ki=En({type:Mn("string"),title:qo().optional(),description:qo().optional(),enum:bn(qo()),enumNames:bn(qo()).optional(),default:qo().optional()}),Ei=Tn([$i,bi]),Si=Tn([En({type:Mn("array"),title:qo().optional(),description:qo().optional(),minItems:un().optional(),maxItems:un().optional(),items:En({type:Mn("string"),enum:bn(qo())}),default:bn(qo()).optional()}),En({type:Mn("array"),title:qo().optional(),description:qo().optional(),minItems:un().optional(),maxItems:un().optional(),items:En({anyOf:bn(En({const:qo(),title:qo()}))}),default:bn(qo()).optional()})]),Pi=Tn([ki,Ei,Si]),Ti=Tn([Pi,vi,_i,wi]),Ii=Tn([hs.extend({mode:Mn("form").optional(),message:qo(),requestedSchema:En({type:Mn("object"),properties:Rn(qo(),Ti),required:bn(qo()).optional()})}),hs.extend({mode:Mn("url"),message:qo(),elicitationId:qo(),url:qo().url()})]),xi=ps.extend({method:Mn("elicitation/create"),params:Ii}),Ni=fs.extend({elicitationId:qo()}),Ci=ms.extend({method:Mn("notifications/elicitation/complete"),params:Ni}),ji=ys.extend({action:zn(["accept","decline","cancel"]),content:Yn(e=>null===e?void 0:e,Rn(qo(),Tn([qo(),un(),pn(),bn(qo())])).optional())}),Ri=En({type:Mn("ref/resource"),uri:qo()}),Oi=En({type:Mn("ref/prompt"),name:qo()}),zi=ds.extend({ref:Tn([Oi,Ri]),argument:En({name:qo(),value:qo()}),context:En({arguments:Rn(qo(),qo()).optional()}).optional()}),Ai=ps.extend({method:Mn("completion/complete"),params:zi}),Mi=ys.extend({completion:Sn({values:bn(qo()).max(100),total:Vn(un().int()),hasMore:Vn(pn())})}),Di=En({uri:qo().startsWith("file://"),name:qo().optional(),_meta:Rn(qo(),vn()).optional()}),Ui=ps.extend({method:Mn("roots/list"),params:ds.optional()}),qi=ys.extend({roots:bn(Di)}),Vi=ms.extend({method:Mn("notifications/roots/list_changed"),params:fs.optional()});Tn([Ls,Us,Ai,ni,Aa,Ra,ya,va,ba,Pa,Ia,Xa,Ja,ta,oa,na,aa]),Tn([Is,Zs,Fs,Vi,ea]),Tn([Ps,yi,gi,ji,qi,ra,sa,Ys]),Tn([Ls,mi,xi,Ui,ta,oa,na,aa]),Tn([Is,Zs,ai,Na,Ea,ei,Ka,ea,Ci]),Tn([Ps,Vs,Mi,Ha,Oa,ga,_a,ka,Qa,Wa,ra,sa,Ys]);class Fi extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`),this.code=e,this.data=r,this.name="McpError"}static fromError(e,t,r){if(e===ks.UrlElicitationRequired&&r){const e=r;if(e.elicitations)return new Li(e.elicitations,t)}return new Fi(e,t,r)}}class Li extends Fi{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(ks.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}function Hi(e){return"completed"===e||"failed"===e||"cancelled"===e}function Ki(e){const t=ko(e),r=t?.method;if(!r)throw new Error("Schema is missing a method literal");const o=function(e){if($o(e)){const t=e,r=t._zod?.def;if(r){if(void 0!==r.value)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}}const t=e._def;if(t){if(void 0!==t.value)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}const r=e.value;if(void 0!==r)return r}(r);if("string"!=typeof o)throw new Error("Schema method literal must be a string");return o}function Zi(e,t){const r=bo(e,t);if(!r.success)throw r.error;return r.data}new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");class Gi{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Is,e=>{this._oncancel(e)}),this.setNotificationHandler(Zs,e=>{this._onprogress(e)}),this.setRequestHandler(Ls,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(ta,async(e,t)=>{const r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new Fi(ks.InvalidParams,"Failed to retrieve task: Task not found");return{...r}}),this.setRequestHandler(oa,async(e,t)=>{const r=async()=>{const o=e.params.taskId;if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(o,t.sessionId);){if("response"===e.type||"error"===e.type){const t=e.message,r=t.id,o=this._requestResolvers.get(r);if(o)if(this._requestResolvers.delete(r),"response"===e.type)o(t);else{const e=t;o(new Fi(e.error.code,e.error.message,e.error.data))}else{const t="response"===e.type?"Response":"Error";this._onerror(new Error(`${t} handler missing for request ${r}`))}continue}await(this._transport?.send(e.message,{relatedRequestId:t.requestId}))}}const n=await this._taskStore.getTask(o,t.sessionId);if(!n)throw new Fi(ks.InvalidParams,`Task not found: ${o}`);if(!Hi(n.status))return await this._waitForTaskUpdate(o,t.signal),await r();if(Hi(n.status)){const e=await this._taskStore.getTaskResult(o,t.sessionId);return this._clearTaskQueue(o),{...e,_meta:{...e._meta,[rs]:{taskId:o}}}}return await r()};return await r()}),this.setRequestHandler(na,async(e,t)=>{try{const{tasks:r,nextCursor:o}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:r,nextCursor:o,_meta:{}}}catch(e){throw new Fi(ks.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(aa,async(e,t)=>{try{const r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new Fi(ks.InvalidParams,`Task not found: ${e.params.taskId}`);if(Hi(r.status))throw new Fi(ks.InvalidParams,`Cannot cancel task in terminal status: ${r.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,"cancelled","Client cancelled task execution.",t.sessionId),this._clearTaskQueue(e.params.taskId);const o=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!o)throw new Fi(ks.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...o}}catch(e){if(e instanceof Fi)throw e;throw new Fi(ks.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;const t=this._requestHandlerAbortControllers.get(e.params.requestId);t?.abort(e.params.reason)}_setupTimeout(e,t,r,o,n=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:n,onTimeout:o})}_resetTimeout(e){const t=this._timeoutInfo.get(e);if(!t)return!1;const r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),Fi.fromError(ks.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){const t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;const t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};const r=this.transport?.onerror;this._transport.onerror=e=>{r?.(e),this._onerror(e)};const o=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{var r;o?.(e,t),bs(e)||(r=e,Es.safeParse(r).success)?this._onresponse(e):_s(e)?this._onrequest(e,t):(e=>ws.safeParse(e).success)(e)?this._onnotification(e):this._onerror(new Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){const e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(const e of this._requestHandlerAbortControllers.values())e.abort();this._requestHandlerAbortControllers.clear();const t=Fi.fromError(ks.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const r of e.values())r(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){const t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;void 0!==t&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(new Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){const r=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,n=e.params?._meta?.[rs]?.taskId;if(void 0===r){const t={jsonrpc:"2.0",id:e.id,error:{code:ks.MethodNotFound,message:"Method not found"}};return void(n&&this._taskMessageQueue?this._enqueueTaskMessage(n,{type:"error",message:t,timestamp:Date.now()},o?.sessionId).catch(e=>this._onerror(new Error(`Failed to enqueue error response: ${e}`))):o?.send(t).catch(e=>this._onerror(new Error(`Failed to send an error response: ${e}`))))}const s=new AbortController;this._requestHandlerAbortControllers.set(e.id,s);const a=(i=e.params,hs.safeParse(i).success?e.params.task:void 0);var i;const c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:s.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{if(s.signal.aborted)return;const r={relatedRequestId:e.id};n&&(r.relatedTask={taskId:n}),await this.notification(t,r)},sendRequest:async(t,r,o)=>{if(s.signal.aborted)throw new Fi(ks.ConnectionClosed,"Request was cancelled");const a={...o,relatedRequestId:e.id};n&&!a.relatedTask&&(a.relatedTask={taskId:n});const i=a.relatedTask?.taskId??n;return i&&c&&await c.updateTaskStatus(i,"input_required"),await this.request(t,r,a)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:n,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>r(e,u)).then(async t=>{if(s.signal.aborted)return;const r={result:t,jsonrpc:"2.0",id:e.id};n&&this._taskMessageQueue?await this._enqueueTaskMessage(n,{type:"response",message:r,timestamp:Date.now()},o?.sessionId):await(o?.send(r))},async t=>{if(s.signal.aborted)return;const r={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:ks.InternalError,message:t.message??"Internal error",...void 0!==t.data&&{data:t.data}}};n&&this._taskMessageQueue?await this._enqueueTaskMessage(n,{type:"error",message:r,timestamp:Date.now()},o?.sessionId):await(o?.send(r))}).catch(e=>this._onerror(new Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:t,...r}=e.params,o=Number(t),n=this._progressHandlers.get(o);if(!n)return void this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));const s=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&s&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(e){return this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),void s(e)}n(r)}_onresponse(e){const t=Number(e.id),r=this._requestResolvers.get(t);if(r){if(this._requestResolvers.delete(t),bs(e))r(e);else{r(new Fi(e.error.code,e.error.message,e.error.data))}return}const o=this._responseHandlers.get(t);if(void 0===o)return void this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));this._responseHandlers.delete(t),this._cleanupTimeout(t);let n=!1;if(bs(e)&&e.result&&"object"==typeof e.result){const r=e.result;if(r.task&&"object"==typeof r.task){const e=r.task;"string"==typeof e.taskId&&(n=!0,this._taskProgressTokens.set(e.taskId,t))}}if(n||this._progressHandlers.delete(t),bs(e))o(e);else{o(Fi.fromError(e.error.code,e.error.message,e.error.data))}}get transport(){return this._transport}async close(){await(this._transport?.close())}async*requestStream(e,t,r){const{task:o}=r??{};if(!o){try{const o=await this.request(e,t,r);yield{type:"result",result:o}}catch(e){yield{type:"error",error:e instanceof Fi?e:new Fi(ks.InternalError,String(e))}}return}let n;try{const o=await this.request(e,Ys,r);if(!o.task)throw new Fi(ks.InternalError,"Task creation did not return a task");for(n=o.task.taskId,yield{type:"taskCreated",task:o.task};;){const e=await this.getTask({taskId:n},r);if(yield{type:"taskStatus",task:e},Hi(e.status)){if("completed"===e.status){const e=await this.getTaskResult({taskId:n},t,r);yield{type:"result",result:e}}else"failed"===e.status?yield{type:"error",error:new Fi(ks.InternalError,`Task ${n} failed`)}:"cancelled"===e.status&&(yield{type:"error",error:new Fi(ks.InternalError,`Task ${n} was cancelled`)});return}if("input_required"===e.status){const e=await this.getTaskResult({taskId:n},t,r);return void(yield{type:"result",result:e})}const o=e.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,o)),r?.signal?.throwIfAborted()}}catch(e){yield{type:"error",error:e instanceof Fi?e:new Fi(ks.InternalError,String(e))}}}request(e,t,r){const{relatedRequestId:o,resumptionToken:n,onresumptiontoken:s,task:a,relatedTask:i}=r??{};return new Promise((c,u)=>{const l=e=>{u(e)};if(!this._transport)return void l(new Error("Not connected"));if(!0===this._options?.enforceStrictCapabilities)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(e){return void l(e)}r?.signal?.throwIfAborted();const d=this._requestMessageId++,h={...e,jsonrpc:"2.0",id:d};r?.onprogress&&(this._progressHandlers.set(d,r.onprogress),h.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),a&&(h.params={...h.params,task:a}),i&&(h.params={...h.params,_meta:{...h.params?._meta||{},[rs]:i}});const p=e=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:d,reason:String(e)}},{relatedRequestId:o,resumptionToken:n,onresumptiontoken:s}).catch(e=>this._onerror(new Error(`Failed to send cancellation: ${e}`)));const t=e instanceof Fi?e:new Fi(ks.RequestTimeout,String(e));u(t)};this._responseHandlers.set(d,e=>{if(!r?.signal?.aborted){if(e instanceof Error)return u(e);try{const r=bo(t,e.result);r.success?c(r.data):u(r.error)}catch(e){u(e)}}}),r?.signal?.addEventListener("abort",()=>{p(r?.signal?.reason)});const f=r?.timeout??6e4;this._setupTimeout(d,f,r?.maxTotalTimeout,()=>p(Fi.fromError(ks.RequestTimeout,"Request timed out",{timeout:f})),r?.resetTimeoutOnProgress??!1);const m=i?.taskId;if(m){const e=e=>{const t=this._responseHandlers.get(d);t?t(e):this._onerror(new Error(`Response handler missing for side-channeled request ${d}`))};this._requestResolvers.set(d,e),this._enqueueTaskMessage(m,{type:"request",message:h,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(d),u(e)})}else this._transport.send(h,{relatedRequestId:o,resumptionToken:n,onresumptiontoken:s}).catch(e=>{this._cleanupTimeout(d),u(e)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},ra,t)}async getTaskResult(e,t,r){return this.request({method:"tasks/result",params:e},t,r)}async listTasks(e,t){return this.request({method:"tasks/list",params:e},sa,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},ia,t)}async notification(e,t){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);const r=t?.relatedTask?.taskId;if(r){const o={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[rs]:t.relatedTask}}};return void await this._enqueueTaskMessage(r,{type:"notification",message:o,timestamp:Date.now()})}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;return this._pendingDebouncedNotifications.add(e.method),void Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let r={...e,jsonrpc:"2.0"};t?.relatedTask&&(r={...r,params:{...r.params,_meta:{...r.params?._meta||{},[rs]:t.relatedTask}}}),this._transport?.send(r,t).catch(e=>this._onerror(e))})}let o={...e,jsonrpc:"2.0"};t?.relatedTask&&(o={...o,params:{...o.params,_meta:{...o.params?._meta||{},[rs]:t.relatedTask}}}),await this._transport.send(o,t)}setRequestHandler(e,t){const r=Ki(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(r,o)=>{const n=Zi(e,r);return Promise.resolve(t(n,o))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){const r=Ki(e);this._notificationHandlers.set(r,r=>{const o=Zi(e,r);return Promise.resolve(t(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){const t=this._taskProgressTokens.get(e);void 0!==t&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,r){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,r,o)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){const r=await this._taskMessageQueue.dequeueAll(e,t);for(const t of r)if("request"===t.type&&_s(t.message)){const r=t.message.id,o=this._requestResolvers.get(r);o?(o(new Fi(ks.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(r)):this._onerror(new Error(`Resolver missing for request ${r} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let r=this._options?.defaultTaskPollInterval??1e3;try{const t=await(this._taskStore?.getTask(e));t?.pollInterval&&(r=t.pollInterval)}catch{}return new Promise((e,o)=>{if(t.aborted)return void o(new Fi(ks.InvalidRequest,"Request cancelled"));const n=setTimeout(e,r);t.addEventListener("abort",()=>{clearTimeout(n),o(new Fi(ks.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,t){const r=this._taskStore;if(!r)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await r.createTask(o,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{const o=await r.getTask(e,t);if(!o)throw new Fi(ks.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(e,o,n)=>{await r.storeTaskResult(e,o,n,t);const s=await r.getTask(e,t);if(s){const t=ea.parse({method:"notifications/tasks/status",params:s});await this.notification(t),Hi(s.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>r.getTaskResult(e,t),updateTaskStatus:async(e,o,n)=>{const s=await r.getTask(e,t);if(!s)throw new Fi(ks.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(Hi(s.status))throw new Fi(ks.InvalidParams,`Cannot update task "${e}" from terminal status "${s.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(e,o,n,t);const a=await r.getTask(e,t);if(a){const t=ea.parse({method:"notifications/tasks/status",params:a});await this.notification(t),Hi(a.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>r.listTasks(e,t)}}}function Bi(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function Ji(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Wi,Qi={exports:{}},Yi={},Xi={},ec={},tc={},rc={},oc={};function nc(){return Wi||(Wi=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;class t{}e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw new Error("CodeGen: name must be a valid identifier");this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=r;class o extends t{constructor(e){super(),this._items="string"==typeof e?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const e=this._items[0];return""===e||'""'===e}get str(){var e;return null!==(e=this._str)&&void 0!==e?e:this._str=this._items.reduce((e,t)=>`${e}${t}`,"")}get names(){var e;return null!==(e=this._names)&&void 0!==e?e:this._names=this._items.reduce((e,t)=>(t instanceof r&&(e[t.str]=(e[t.str]||0)+1),e),{})}}function n(e,...t){const r=[e[0]];let n=0;for(;n<t.length;)i(r,t[n]),r.push(e[++n]);return new o(r)}e._Code=o,e.nil=new o(""),e._=n;const s=new o("+");function a(e,...t){const r=[u(e[0])];let n=0;for(;n<t.length;)r.push(s),i(r,t[n]),r.push(s,u(e[++n]));return function(e){let t=1;for(;t<e.length-1;){if(e[t]===s){const r=c(e[t-1],e[t+1]);if(void 0!==r){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}(r),new o(r)}function i(e,t){var n;t instanceof o?e.push(...t._items):t instanceof r?e.push(t):e.push("number"==typeof(n=t)||"boolean"==typeof n||null===n?n:u(Array.isArray(n)?n.join(","):n))}function c(e,t){if('""'===t)return e;if('""'===e)return t;if("string"==typeof e){if(t instanceof r||'"'!==e[e.length-1])return;return"string"!=typeof t?`${e.slice(0,-1)}${t}"`:'"'===t[0]?e.slice(0,-1)+t.slice(1):void 0}return"string"!=typeof t||'"'!==t[0]||e instanceof r?void 0:`"${e}${t.slice(1)}`}function u(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.str=a,e.addCodeArg=i,e.strConcat=function(e,t){return t.emptyStr()?e:e.emptyStr()?t:a`${e}${t}`},e.stringify=function(e){return new o(u(e))},e.safeStringify=u,e.getProperty=function(t){return"string"==typeof t&&e.IDENTIFIER.test(t)?new o(`.${t}`):n`[${t}]`},e.getEsmExportName=function(t){if("string"==typeof t&&e.IDENTIFIER.test(t))return new o(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)},e.regexpCode=function(e){return new o(e.toString())}}(oc)),oc}var sc,ac,ic={};function cc(){return sc||(sc=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=nc();class r extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}}var o;!function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"}(o||(e.UsedValueState=o={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};class n{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof t.Name?e:this.name(e)}name(e){return new t.Name(this._newName(e))}_newName(e){return`${e}${(this._names[e]||this._nameGroup(e)).index++}`}_nameGroup(e){var t,r;if((null===(r=null===(t=this._parent)||void 0===t?void 0:t._prefixes)||void 0===r?void 0:r.has(e))||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}}e.Scope=n;class s extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:r,itemIndex:o}){this.value=e,this.scopePath=t._`.${new t.Name(r)}[${o}]`}}e.ValueScopeName=s;const a=t._`\n`;e.ValueScope=class extends n{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?a:t.nil}}get(){return this._scope}name(e){return new s(e,this._newName(e))}value(e,t){var r;if(void 0===t.ref)throw new Error("CodeGen: ref must be passed in value");const o=this.toName(e),{prefix:n}=o,s=null!==(r=t.key)&&void 0!==r?r:t.ref;let a=this._values[n];if(a){const e=a.get(s);if(e)return e}else a=this._values[n]=new Map;a.set(s,o);const i=this._scope[n]||(this._scope[n]=[]),c=i.length;return i[c]=t.ref,o.setValue(t,{property:n,itemIndex:c}),o}getValue(e,t){const r=this._values[e];if(r)return r.get(t)}scopeRefs(e,r=this._values){return this._reduceValues(r,r=>{if(void 0===r.scopePath)throw new Error(`CodeGen: name "${r}" has no value`);return t._`${e}${r.scopePath}`})}scopeCode(e=this._values,t,r){return this._reduceValues(e,e=>{if(void 0===e.value)throw new Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,r)}_reduceValues(n,s,a={},i){let c=t.nil;for(const u in n){const l=n[u];if(!l)continue;const d=a[u]=a[u]||new Map;l.forEach(n=>{if(d.has(n))return;d.set(n,o.Started);let a=s(n);if(a){const r=this.opts.es5?e.varKinds.var:e.varKinds.const;c=t._`${c}${r} ${n} = ${a};${this.opts._n}`}else{if(!(a=null==i?void 0:i(n)))throw new r(n);c=t._`${c}${a}${this.opts._n}`}d.set(n,o.Completed)})}return c}}}(ic)),ic}function uc(){return ac||(ac=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;const t=nc(),r=cc();var o=nc();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return o._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return o.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return o.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return o.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return o.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return o.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return o.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return o.Name}});var n=cc();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return n.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return n.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return n.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return n.varKinds}}),e.operators={GT:new t._Code(">"),GTE:new t._Code(">="),LT:new t._Code("<"),LTE:new t._Code("<="),EQ:new t._Code("==="),NEQ:new t._Code("!=="),NOT:new t._Code("!"),OR:new t._Code("||"),AND:new t._Code("&&"),ADD:new t._Code("+")};class s{optimizeNodes(){return this}optimizeNames(e,t){return this}}class a extends s{constructor(e,t,r){super(),this.varKind=e,this.name=t,this.rhs=r}render({es5:e,_n:t}){const o=e?r.varKinds.var:this.varKind,n=void 0===this.rhs?"":` = ${this.rhs}`;return`${o} ${this.name}${n};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&(this.rhs=x(this.rhs,e,t)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class i extends s{constructor(e,t,r){super(),this.lhs=e,this.rhs=t,this.sideEffects=r}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof t.Name)||e[this.lhs.str]||this.sideEffects)return this.rhs=x(this.rhs,e,r),this}get names(){return I(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}}class c extends i{constructor(e,t,r,o){super(e,r,o),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}}class u extends s{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}}class l extends s{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}}class d extends s{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}}class h extends s{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=x(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class p extends s{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,r)=>t+r.render(e),"")}optimizeNodes(){const{nodes:e}=this;let t=e.length;for(;t--;){const r=e[t].optimizeNodes();Array.isArray(r)?e.splice(t,1,...r):r?e[t]=r:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){const{nodes:r}=this;let o=r.length;for(;o--;){const n=r[o];n.optimizeNames(e,t)||(N(e,n.names),r.splice(o,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>T(e,t.names),{})}}class f extends p{render(e){return"{"+e._n+super.render(e)+"}"+e._n}}class m extends p{}class y extends f{}y.kind="else";class g extends f{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+="else "+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();const e=this.condition;if(!0===e)return this.nodes;let t=this.else;if(t){const e=t.optimizeNodes();t=this.else=Array.isArray(e)?new y(e):e}return t?!1===e?t instanceof g?t:t.nodes:this.nodes.length?this:new g(C(e),t instanceof g?[t]:t.nodes):!1!==e&&this.nodes.length?this:void 0}optimizeNames(e,t){var r;if(this.else=null===(r=this.else)||void 0===r?void 0:r.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=x(this.condition,e,t),this}get names(){const e=super.names;return I(e,this.condition),this.else&&T(e,this.else.names),e}}g.kind="if";class v extends f{}v.kind="for";class _ extends v{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=x(this.iteration,e,t),this}get names(){return T(super.names,this.iteration.names)}}class w extends v{constructor(e,t,r,o){super(),this.varKind=e,this.name=t,this.from=r,this.to=o}render(e){const t=e.es5?r.varKinds.var:this.varKind,{name:o,from:n,to:s}=this;return`for(${t} ${o}=${n}; ${o}<${s}; ${o}++)`+super.render(e)}get names(){const e=I(super.names,this.from);return I(e,this.to)}}class $ extends v{constructor(e,t,r,o){super(),this.loop=e,this.varKind=t,this.name=r,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=x(this.iterable,e,t),this}get names(){return T(super.names,this.iterable.names)}}class b extends f{constructor(e,t,r){super(),this.name=e,this.args=t,this.async=r}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}}b.kind="func";class k extends p{render(e){return"return "+super.render(e)}}k.kind="return";class E extends f{render(e){let t="try"+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),null===(e=this.catch)||void 0===e||e.optimizeNodes(),null===(t=this.finally)||void 0===t||t.optimizeNodes(),this}optimizeNames(e,t){var r,o;return super.optimizeNames(e,t),null===(r=this.catch)||void 0===r||r.optimizeNames(e,t),null===(o=this.finally)||void 0===o||o.optimizeNames(e,t),this}get names(){const e=super.names;return this.catch&&T(e,this.catch.names),this.finally&&T(e,this.finally.names),e}}class S extends f{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}}S.kind="catch";class P extends f{render(e){return"finally"+super.render(e)}}P.kind="finally";function T(e,t){for(const r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function I(e,r){return r instanceof t._CodeOrName?T(e,r.names):e}function x(e,r,o){return e instanceof t.Name?s(e):(n=e)instanceof t._Code&&n._items.some(e=>e instanceof t.Name&&1===r[e.str]&&void 0!==o[e.str])?new t._Code(e._items.reduce((e,r)=>(r instanceof t.Name&&(r=s(r)),r instanceof t._Code?e.push(...r._items):e.push(r),e),[])):e;var n;function s(e){const t=o[e.str];return void 0===t||1!==r[e.str]?e:(delete r[e.str],t)}}function N(e,t){for(const r in t)e[r]=(e[r]||0)-(t[r]||0)}function C(e){return"boolean"==typeof e||"number"==typeof e||null===e?!e:t._`!${z(e)}`}e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?"\n":""},this._extScope=e,this._scope=new r.Scope({parent:e}),this._nodes=[new m]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){const r=this._extScope.value(e,t);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,r,o){const n=this._scope.toName(t);return void 0!==r&&o&&(this._constants[n.str]=r),this._leafNode(new a(e,n,r)),n}const(e,t,o){return this._def(r.varKinds.const,e,t,o)}let(e,t,o){return this._def(r.varKinds.let,e,t,o)}var(e,t,o){return this._def(r.varKinds.var,e,t,o)}assign(e,t,r){return this._leafNode(new i(e,t,r))}add(t,r){return this._leafNode(new c(t,e.operators.ADD,r))}code(e){return"function"==typeof e?e():e!==t.nil&&this._leafNode(new h(e)),this}object(...e){const r=["{"];for(const[o,n]of e)r.length>1&&r.push(","),r.push(o),(o!==n||this.opts.es5)&&(r.push(":"),(0,t.addCodeArg)(r,n));return r.push("}"),new t._Code(r)}if(e,t,r){if(this._blockNode(new g(e)),t&&r)this.code(t).else().code(r).endIf();else if(t)this.code(t).endIf();else if(r)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new g(e))}else(){return this._elseNode(new y)}endIf(){return this._endBlockNode(g,y)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new _(e),t)}forRange(e,t,o,n,s=(this.opts.es5?r.varKinds.var:r.varKinds.let)){const a=this._scope.toName(e);return this._for(new w(s,a,t,o),()=>n(a))}forOf(e,o,n,s=r.varKinds.const){const a=this._scope.toName(e);if(this.opts.es5){const e=o instanceof t.Name?o:this.var("_arr",o);return this.forRange("_i",0,t._`${e}.length`,r=>{this.var(a,t._`${e}[${r}]`),n(a)})}return this._for(new $("of",s,a,o),()=>n(a))}forIn(e,o,n,s=(this.opts.es5?r.varKinds.var:r.varKinds.const)){if(this.opts.ownProperties)return this.forOf(e,t._`Object.keys(${o})`,n);const a=this._scope.toName(e);return this._for(new $("in",s,a,o),()=>n(a))}endFor(){return this._endBlockNode(v)}label(e){return this._leafNode(new u(e))}break(e){return this._leafNode(new l(e))}return(e){const t=new k;if(this._blockNode(t),this.code(e),1!==t.nodes.length)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(k)}try(e,t,r){if(!t&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');const o=new E;if(this._blockNode(o),this.code(e),t){const e=this.name("e");this._currNode=o.catch=new S(e),t(e)}return r&&(this._currNode=o.finally=new P,this.code(r)),this._endBlockNode(S,P)}throw(e){return this._leafNode(new d(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){const t=this._blockStarts.pop();if(void 0===t)throw new Error("CodeGen: not in self-balancing block");const r=this._nodes.length-t;if(r<0||void 0!==e&&r!==e)throw new Error(`CodeGen: wrong number of nodes: ${r} vs ${e} expected`);return this._nodes.length=t,this}func(e,r=t.nil,o,n){return this._blockNode(new b(e,r,o)),n&&this.code(n).endFunc(),this}endFunc(){return this._endBlockNode(b)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){const r=this._currNode;if(r instanceof e||t&&r instanceof t)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){const t=this._currNode;if(!(t instanceof g))throw new Error('CodeGen: "else" without "if"');return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){const e=this._nodes;return e[e.length-1]}set _currNode(e){const t=this._nodes;t[t.length-1]=e}},e.not=C;const j=O(e.operators.AND);e.and=function(...e){return e.reduce(j)};const R=O(e.operators.OR);function O(e){return(r,o)=>r===t.nil?o:o===t.nil?r:t._`${z(r)} ${e} ${z(o)}`}function z(e){return e instanceof t.Name?e:t._`(${e})`}e.or=function(...e){return e.reduce(R)}}(rc)),rc}var lc={};Object.defineProperty(lc,"__esModule",{value:!0}),lc.checkStrictMode=lc.getErrorPath=lc.Type=lc.useFunc=lc.setEvaluated=lc.evaluatedPropsToName=lc.mergeEvaluated=lc.eachItem=lc.unescapeJsonPointer=lc.escapeJsonPointer=lc.escapeFragment=lc.unescapeFragment=lc.schemaRefOrVal=lc.schemaHasRulesButRef=lc.schemaHasRules=lc.checkUnknownRules=lc.alwaysValidSchema=lc.toHash=void 0;const dc=uc(),hc=nc();function pc(e,t=e.schema){const{opts:r,self:o}=e;if(!r.strictSchema)return;if("boolean"==typeof t)return;const n=o.RULES.keywords;for(const r in t)n[r]||bc(e,`unknown keyword: "${r}"`)}function fc(e,t){if("boolean"==typeof e)return!e;for(const r in e)if(t[r])return!0;return!1}function mc(e){return"number"==typeof e?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}function yc(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function gc({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:o}){return(n,s,a,i)=>{const c=void 0===a?s:a instanceof dc.Name?(s instanceof dc.Name?e(n,s,a):t(n,s,a),a):s instanceof dc.Name?(t(n,a,s),s):r(s,a);return i!==dc.Name||c instanceof dc.Name?c:o(n,c)}}function vc(e,t){if(!0===t)return e.var("props",!0);const r=e.var("props",dc._`{}`);return void 0!==t&&_c(e,r,t),r}function _c(e,t,r){Object.keys(r).forEach(r=>e.assign(dc._`${t}${(0,dc.getProperty)(r)}`,!0))}lc.toHash=function(e){const t={};for(const r of e)t[r]=!0;return t},lc.alwaysValidSchema=function(e,t){return"boolean"==typeof t?t:0===Object.keys(t).length||(pc(e,t),!fc(t,e.self.RULES.all))},lc.checkUnknownRules=pc,lc.schemaHasRules=fc,lc.schemaHasRulesButRef=function(e,t){if("boolean"==typeof e)return!e;for(const r in e)if("$ref"!==r&&t.all[r])return!0;return!1},lc.schemaRefOrVal=function({topSchemaRef:e,schemaPath:t},r,o,n){if(!n){if("number"==typeof r||"boolean"==typeof r)return r;if("string"==typeof r)return dc._`${r}`}return dc._`${e}${t}${(0,dc.getProperty)(o)}`},lc.unescapeFragment=function(e){return yc(decodeURIComponent(e))},lc.escapeFragment=function(e){return encodeURIComponent(mc(e))},lc.escapeJsonPointer=mc,lc.unescapeJsonPointer=yc,lc.eachItem=function(e,t){if(Array.isArray(e))for(const r of e)t(r);else t(e)},lc.mergeEvaluated={props:gc({mergeNames:(e,t,r)=>e.if(dc._`${r} !== true && ${t} !== undefined`,()=>{e.if(dc._`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,dc._`${r} || {}`).code(dc._`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if(dc._`${r} !== true`,()=>{!0===t?e.assign(r,!0):(e.assign(r,dc._`${r} || {}`),_c(e,r,t))}),mergeValues:(e,t)=>!0===e||{...e,...t},resultToName:vc}),items:gc({mergeNames:(e,t,r)=>e.if(dc._`${r} !== true && ${t} !== undefined`,()=>e.assign(r,dc._`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if(dc._`${r} !== true`,()=>e.assign(r,!0===t||dc._`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>!0===e||Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})},lc.evaluatedPropsToName=vc,lc.setEvaluated=_c;const wc={};var $c;function bc(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,!0===r)throw new Error(t);e.self.logger.warn(t)}}lc.useFunc=function(e,t){return e.scopeValue("func",{ref:t,code:wc[t.code]||(wc[t.code]=new hc._Code(t.code))})},function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"}($c||(lc.Type=$c={})),lc.getErrorPath=function(e,t,r){if(e instanceof dc.Name){const o=t===$c.Num;return r?o?dc._`"[" + ${e} + "]"`:dc._`"['" + ${e} + "']"`:o?dc._`"/" + ${e}`:dc._`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,dc.getProperty)(e).toString():"/"+mc(e)},lc.checkStrictMode=bc;var kc,Ec,Sc,Pc={};function Tc(){if(kc)return Pc;kc=1,Object.defineProperty(Pc,"__esModule",{value:!0});const e=uc(),t={data:new e.Name("data"),valCxt:new e.Name("valCxt"),instancePath:new e.Name("instancePath"),parentData:new e.Name("parentData"),parentDataProperty:new e.Name("parentDataProperty"),rootData:new e.Name("rootData"),dynamicAnchors:new e.Name("dynamicAnchors"),vErrors:new e.Name("vErrors"),errors:new e.Name("errors"),this:new e.Name("this"),self:new e.Name("self"),scope:new e.Name("scope"),json:new e.Name("json"),jsonPos:new e.Name("jsonPos"),jsonLen:new e.Name("jsonLen"),jsonPart:new e.Name("jsonPart")};return Pc.default=t,Pc}function Ic(){return Ec||(Ec=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;const t=uc(),r=lc,o=Tc();function n(e,r){const n=e.const("err",r);e.if(t._`${o.default.vErrors} === null`,()=>e.assign(o.default.vErrors,t._`[${n}]`),t._`${o.default.vErrors}.push(${n})`),e.code(t._`${o.default.errors}++`)}function s(e,r){const{gen:o,validateName:n,schemaEnv:s}=e;s.$async?o.throw(t._`new ${e.ValidationError}(${r})`):(o.assign(t._`${n}.errors`,r),o.return(!1))}e.keywordError={message:({keyword:e})=>t.str`must pass "${e}" keyword validation`},e.keyword$DataError={message:({keyword:e,schemaType:r})=>r?t.str`"${e}" keyword must be ${r} ($data)`:t.str`"${e}" keyword is invalid ($data)`},e.reportError=function(r,o=e.keywordError,a,c){const{it:u}=r,{gen:l,compositeRule:d,allErrors:h}=u,p=i(r,o,a);(null!=c?c:d||h)?n(l,p):s(u,t._`[${p}]`)},e.reportExtraError=function(t,r=e.keywordError,a){const{it:c}=t,{gen:u,compositeRule:l,allErrors:d}=c;n(u,i(t,r,a)),l||d||s(c,o.default.vErrors)},e.resetErrorsCount=function(e,r){e.assign(o.default.errors,r),e.if(t._`${o.default.vErrors} !== null`,()=>e.if(r,()=>e.assign(t._`${o.default.vErrors}.length`,r),()=>e.assign(o.default.vErrors,null)))},e.extendErrors=function({gen:e,keyword:r,schemaValue:n,data:s,errsCount:a,it:i}){if(void 0===a)throw new Error("ajv implementation error");const c=e.name("err");e.forRange("i",a,o.default.errors,a=>{e.const(c,t._`${o.default.vErrors}[${a}]`),e.if(t._`${c}.instancePath === undefined`,()=>e.assign(t._`${c}.instancePath`,(0,t.strConcat)(o.default.instancePath,i.errorPath))),e.assign(t._`${c}.schemaPath`,t.str`${i.errSchemaPath}/${r}`),i.opts.verbose&&(e.assign(t._`${c}.schema`,n),e.assign(t._`${c}.data`,s))})};const a={keyword:new t.Name("keyword"),schemaPath:new t.Name("schemaPath"),params:new t.Name("params"),propertyName:new t.Name("propertyName"),message:new t.Name("message"),schema:new t.Name("schema"),parentSchema:new t.Name("parentSchema")};function i(e,r,n){const{createErrors:s}=e.it;return!1===s?t._`{}`:function(e,r,n={}){const{gen:s,it:i}=e,l=[c(i,n),u(e,n)];return function(e,{params:r,message:n},s){const{keyword:i,data:c,schemaValue:u,it:l}=e,{opts:d,propertyName:h,topSchemaRef:p,schemaPath:f}=l;s.push([a.keyword,i],[a.params,"function"==typeof r?r(e):r||t._`{}`]),d.messages&&s.push([a.message,"function"==typeof n?n(e):n]);d.verbose&&s.push([a.schema,u],[a.parentSchema,t._`${p}${f}`],[o.default.data,c]);h&&s.push([a.propertyName,h])}(e,r,l),s.object(...l)}(e,r,n)}function c({errorPath:e},{instancePath:n}){const s=n?t.str`${e}${(0,r.getErrorPath)(n,r.Type.Str)}`:e;return[o.default.instancePath,(0,t.strConcat)(o.default.instancePath,s)]}function u({keyword:e,it:{errSchemaPath:o}},{schemaPath:n,parentSchema:s}){let i=s?o:t.str`${o}/${e}`;return n&&(i=t.str`${i}${(0,r.getErrorPath)(n,r.Type.Str)}`),[a.schemaPath,i]}}(tc)),tc}var xc={},Nc={};Object.defineProperty(Nc,"__esModule",{value:!0}),Nc.getRules=Nc.isJSONType=void 0;const Cc=new Set(["string","number","integer","boolean","null","object","array"]);Nc.isJSONType=function(e){return"string"==typeof e&&Cc.has(e)},Nc.getRules=function(){const e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}};var jc,Rc={};function Oc(){if(jc)return Rc;function e(e,r){return r.rules.some(r=>t(e,r))}function t(e,t){var r;return void 0!==e[t.keyword]||(null===(r=t.definition.implements)||void 0===r?void 0:r.some(t=>void 0!==e[t]))}return jc=1,Object.defineProperty(Rc,"__esModule",{value:!0}),Rc.shouldUseRule=Rc.shouldUseGroup=Rc.schemaHasRulesForType=void 0,Rc.schemaHasRulesForType=function({schema:t,self:r},o){const n=r.RULES.types[o];return n&&!0!==n&&e(t,n)},Rc.shouldUseGroup=e,Rc.shouldUseRule=t,Rc}Object.defineProperty(xc,"__esModule",{value:!0}),xc.reportTypeError=xc.checkDataTypes=xc.checkDataType=xc.coerceAndCheckDataType=xc.getJSONTypes=xc.getSchemaTypes=xc.DataType=void 0;const zc=Nc,Ac=Oc(),Mc=Ic(),Dc=uc(),Uc=lc;var qc;function Vc(e){const t=Array.isArray(e)?e:e?[e]:[];if(t.every(zc.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}!function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"}(qc||(xc.DataType=qc={})),xc.getSchemaTypes=function(e){const t=Vc(e.type);if(t.includes("null")){if(!1===e.nullable)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&void 0!==e.nullable)throw new Error('"nullable" cannot be used without "type"');!0===e.nullable&&t.push("null")}return t},xc.getJSONTypes=Vc,xc.coerceAndCheckDataType=function(e,t){const{gen:r,data:o,opts:n}=e,s=function(e,t){return t?e.filter(e=>Fc.has(e)||"array"===t&&"array"===e):[]}(t,n.coerceTypes),a=t.length>0&&!(0===s.length&&1===t.length&&(0,Ac.schemaHasRulesForType)(e,t[0]));if(a){const a=Hc(t,o,n.strictNumbers,qc.Wrong);r.if(a,()=>{s.length?function(e,t,r){const{gen:o,data:n,opts:s}=e,a=o.let("dataType",Dc._`typeof ${n}`),i=o.let("coerced",Dc._`undefined`);"array"===s.coerceTypes&&o.if(Dc._`${a} == 'object' && Array.isArray(${n}) && ${n}.length == 1`,()=>o.assign(n,Dc._`${n}[0]`).assign(a,Dc._`typeof ${n}`).if(Hc(t,n,s.strictNumbers),()=>o.assign(i,n)));o.if(Dc._`${i} !== undefined`);for(const e of r)(Fc.has(e)||"array"===e&&"array"===s.coerceTypes)&&c(e);function c(e){switch(e){case"string":return void o.elseIf(Dc._`${a} == "number" || ${a} == "boolean"`).assign(i,Dc._`"" + ${n}`).elseIf(Dc._`${n} === null`).assign(i,Dc._`""`);case"number":return void o.elseIf(Dc._`${a} == "boolean" || ${n} === null
2
- || (${a} == "string" && ${n} && ${n} == +${n})`).assign(i,Dc._`+${n}`);case"integer":return void o.elseIf(Dc._`${a} === "boolean" || ${n} === null
3
- || (${a} === "string" && ${n} && ${n} == +${n} && !(${n} % 1))`).assign(i,Dc._`+${n}`);case"boolean":return void o.elseIf(Dc._`${n} === "false" || ${n} === 0 || ${n} === null`).assign(i,!1).elseIf(Dc._`${n} === "true" || ${n} === 1`).assign(i,!0);case"null":return o.elseIf(Dc._`${n} === "" || ${n} === 0 || ${n} === false`),void o.assign(i,null);case"array":o.elseIf(Dc._`${a} === "string" || ${a} === "number"
4
- || ${a} === "boolean" || ${n} === null`).assign(i,Dc._`[${n}]`)}}o.else(),Zc(e),o.endIf(),o.if(Dc._`${i} !== undefined`,()=>{o.assign(n,i),function({gen:e,parentData:t,parentDataProperty:r},o){e.if(Dc._`${t} !== undefined`,()=>e.assign(Dc._`${t}[${r}]`,o))}(e,i)})}(e,t,s):Zc(e)})}return a};const Fc=new Set(["string","number","integer","boolean","null"]);function Lc(e,t,r,o=qc.Correct){const n=o===qc.Correct?Dc.operators.EQ:Dc.operators.NEQ;let s;switch(e){case"null":return Dc._`${t} ${n} null`;case"array":s=Dc._`Array.isArray(${t})`;break;case"object":s=Dc._`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":s=a(Dc._`!(${t} % 1) && !isNaN(${t})`);break;case"number":s=a();break;default:return Dc._`typeof ${t} ${n} ${e}`}return o===qc.Correct?s:(0,Dc.not)(s);function a(e=Dc.nil){return(0,Dc.and)(Dc._`typeof ${t} == "number"`,e,r?Dc._`isFinite(${t})`:Dc.nil)}}function Hc(e,t,r,o){if(1===e.length)return Lc(e[0],t,r,o);let n;const s=(0,Uc.toHash)(e);if(s.array&&s.object){const e=Dc._`typeof ${t} != "object"`;n=s.null?e:Dc._`!${t} || ${e}`,delete s.null,delete s.array,delete s.object}else n=Dc.nil;s.number&&delete s.integer;for(const e in s)n=(0,Dc.and)(n,Lc(e,t,r,o));return n}xc.checkDataType=Lc,xc.checkDataTypes=Hc;const Kc={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>"string"==typeof e?Dc._`{type: ${e}}`:Dc._`{type: ${t}}`};function Zc(e){const t=function(e){const{gen:t,data:r,schema:o}=e,n=(0,Uc.schemaRefOrVal)(e,o,"type");return{gen:t,keyword:"type",data:r,schema:o.type,schemaCode:n,schemaValue:n,parentSchema:o,params:{},it:e}}(e);(0,Mc.reportError)(t,Kc)}xc.reportTypeError=Zc;var Gc,Bc={};var Jc,Wc,Qc={},Yc={};function Xc(){if(Jc)return Yc;Jc=1,Object.defineProperty(Yc,"__esModule",{value:!0}),Yc.validateUnion=Yc.validateArray=Yc.usePattern=Yc.callValidateCode=Yc.schemaProperties=Yc.allSchemaProperties=Yc.noPropertyInData=Yc.propertyInData=Yc.isOwnProperty=Yc.hasPropFunc=Yc.reportMissingProp=Yc.checkMissingProp=Yc.checkReportMissingProp=void 0;const e=uc(),t=lc,r=Tc(),o=lc;function n(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:e._`Object.prototype.hasOwnProperty`})}function s(t,r,o){return e._`${n(t)}.call(${r}, ${o})`}function a(t,r,o,n){const a=e._`${r}${(0,e.getProperty)(o)} === undefined`;return n?(0,e.or)(a,(0,e.not)(s(t,r,o))):a}function i(e){return e?Object.keys(e).filter(e=>"__proto__"!==e):[]}Yc.checkReportMissingProp=function(t,r){const{gen:o,data:n,it:s}=t;o.if(a(o,n,r,s.opts.ownProperties),()=>{t.setParams({missingProperty:e._`${r}`},!0),t.error()})},Yc.checkMissingProp=function({gen:t,data:r,it:{opts:o}},n,s){return(0,e.or)(...n.map(n=>(0,e.and)(a(t,r,n,o.ownProperties),e._`${s} = ${n}`)))},Yc.reportMissingProp=function(e,t){e.setParams({missingProperty:t},!0),e.error()},Yc.hasPropFunc=n,Yc.isOwnProperty=s,Yc.propertyInData=function(t,r,o,n){const a=e._`${r}${(0,e.getProperty)(o)} !== undefined`;return n?e._`${a} && ${s(t,r,o)}`:a},Yc.noPropertyInData=a,Yc.allSchemaProperties=i,Yc.schemaProperties=function(e,r){return i(r).filter(o=>!(0,t.alwaysValidSchema)(e,r[o]))},Yc.callValidateCode=function({schemaCode:t,data:o,it:{gen:n,topSchemaRef:s,schemaPath:a,errorPath:i},it:c},u,l,d){const h=d?e._`${t}, ${o}, ${s}${a}`:o,p=[[r.default.instancePath,(0,e.strConcat)(r.default.instancePath,i)],[r.default.parentData,c.parentData],[r.default.parentDataProperty,c.parentDataProperty],[r.default.rootData,r.default.rootData]];c.opts.dynamicRef&&p.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);const f=e._`${h}, ${n.object(...p)}`;return l!==e.nil?e._`${u}.call(${l}, ${f})`:e._`${u}(${f})`};const c=e._`new RegExp`;return Yc.usePattern=function({gen:t,it:{opts:r}},n){const s=r.unicodeRegExp?"u":"",{regExp:a}=r.code,i=a(n,s);return t.scopeValue("pattern",{key:i.toString(),ref:i,code:e._`${"new RegExp"===a.code?c:(0,o.useFunc)(t,a)}(${n}, ${s})`})},Yc.validateArray=function(r){const{gen:o,data:n,keyword:s,it:a}=r,i=o.name("valid");if(a.allErrors){const e=o.let("valid",!0);return c(()=>o.assign(e,!1)),e}return o.var(i,!0),c(()=>o.break()),i;function c(a){const c=o.const("len",e._`${n}.length`);o.forRange("i",0,c,n=>{r.subschema({keyword:s,dataProp:n,dataPropType:t.Type.Num},i),o.if((0,e.not)(i),a)})}},Yc.validateUnion=function(r){const{gen:o,schema:n,keyword:s,it:a}=r;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some(e=>(0,t.alwaysValidSchema)(a,e))&&!a.opts.unevaluated)return;const i=o.let("valid",!1),c=o.name("_valid");o.block(()=>n.forEach((t,n)=>{const a=r.subschema({keyword:s,schemaProp:n,compositeRule:!0},c);o.assign(i,e._`${i} || ${c}`);r.mergeValidEvaluated(a,c)||o.if((0,e.not)(i))})),r.result(i,()=>r.reset(),()=>r.error(!0))},Yc}function eu(){if(Wc)return Qc;Wc=1,Object.defineProperty(Qc,"__esModule",{value:!0}),Qc.validateKeywordUsage=Qc.validSchemaType=Qc.funcKeywordCode=Qc.macroKeywordCode=void 0;const e=uc(),t=Tc(),r=Xc(),o=Ic();function n(t){const{gen:r,data:o,it:n}=t;r.if(n.parentData,()=>r.assign(o,e._`${n.parentData}[${n.parentDataProperty}]`))}function s(t,r,o){if(void 0===o)throw new Error(`keyword "${r}" failed to compile`);return t.scopeValue("keyword","function"==typeof o?{ref:o}:{ref:o,code:(0,e.stringify)(o)})}return Qc.macroKeywordCode=function(t,r){const{gen:o,keyword:n,schema:a,parentSchema:i,it:c}=t,u=r.macro.call(c.self,a,i,c),l=s(o,n,u);!1!==c.opts.validateSchema&&c.self.validateSchema(u,!0);const d=o.name("valid");t.subschema({schema:u,schemaPath:e.nil,errSchemaPath:`${c.errSchemaPath}/${n}`,topSchemaRef:l,compositeRule:!0},d),t.pass(d,()=>t.error(!0))},Qc.funcKeywordCode=function(a,i){var c;const{gen:u,keyword:l,schema:d,parentSchema:h,$data:p,it:f}=a;!function({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}(f,i);const m=!p&&i.compile?i.compile.call(f.self,d,h,f):i.validate,y=s(u,l,m),g=u.let("valid");function v(o=(i.async?e._`await `:e.nil)){const n=f.opts.passContext?t.default.this:t.default.self,s=!("compile"in i&&!p||!1===i.schema);u.assign(g,e._`${o}${(0,r.callValidateCode)(a,y,n,s)}`,i.modifying)}function _(t){var r;u.if((0,e.not)(null!==(r=i.valid)&&void 0!==r?r:g),t)}a.block$data(g,function(){if(!1===i.errors)v(),i.modifying&&n(a),_(()=>a.error());else{const r=i.async?function(){const t=u.let("ruleErrs",null);return u.try(()=>v(e._`await `),r=>u.assign(g,!1).if(e._`${r} instanceof ${f.ValidationError}`,()=>u.assign(t,e._`${r}.errors`),()=>u.throw(r))),t}():function(){const t=e._`${y}.errors`;return u.assign(t,null),v(e.nil),t}();i.modifying&&n(a),_(()=>function(r,n){const{gen:s}=r;s.if(e._`Array.isArray(${n})`,()=>{s.assign(t.default.vErrors,e._`${t.default.vErrors} === null ? ${n} : ${t.default.vErrors}.concat(${n})`).assign(t.default.errors,e._`${t.default.vErrors}.length`),(0,o.extendErrors)(r)},()=>r.error())}(a,r))}}),a.ok(null!==(c=i.valid)&&void 0!==c?c:g)},Qc.validSchemaType=function(e,t,r=!1){return!t.length||t.some(t=>"array"===t?Array.isArray(e):"object"===t?e&&"object"==typeof e&&!Array.isArray(e):typeof e==t||r&&void 0===e)},Qc.validateKeywordUsage=function({schema:e,opts:t,self:r,errSchemaPath:o},n,s){if(Array.isArray(n.keyword)?!n.keyword.includes(s):n.keyword!==s)throw new Error("ajv implementation error");const a=n.dependencies;if(null==a?void 0:a.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw new Error(`parent schema must have dependencies of ${s}: ${a.join(",")}`);if(n.validateSchema){if(!n.validateSchema(e[s])){const e=`keyword "${s}" value is invalid at path "${o}": `+r.errorsText(n.validateSchema.errors);if("log"!==t.validateSchema)throw new Error(e);r.logger.error(e)}}},Qc}var tu,ru={};var ou={},nu=function e(t,r){if(t===r)return!0;if(t&&r&&"object"==typeof t&&"object"==typeof r){if(t.constructor!==r.constructor)return!1;var o,n,s;if(Array.isArray(t)){if((o=t.length)!=r.length)return!1;for(n=o;0!==n--;)if(!e(t[n],r[n]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if((o=(s=Object.keys(t)).length)!==Object.keys(r).length)return!1;for(n=o;0!==n--;)if(!Object.prototype.hasOwnProperty.call(r,s[n]))return!1;for(n=o;0!==n--;){var a=s[n];if(!e(t[a],r[a]))return!1}return!0}return t!=t&&r!=r},su={exports:{}},au=su.exports=function(e,t,r){"function"==typeof t&&(r=t,t={}),iu(t,"function"==typeof(r=t.cb||r)?r:r.pre||function(){},r.post||function(){},e,"",e)};function iu(e,t,r,o,n,s,a,i,c,u){if(o&&"object"==typeof o&&!Array.isArray(o)){for(var l in t(o,n,s,a,i,c,u),o){var d=o[l];if(Array.isArray(d)){if(l in au.arrayKeywords)for(var h=0;h<d.length;h++)iu(e,t,r,d[h],n+"/"+l+"/"+h,s,n,l,o,h)}else if(l in au.propsKeywords){if(d&&"object"==typeof d)for(var p in d)iu(e,t,r,d[p],n+"/"+l+"/"+cu(p),s,n,l,o,p)}else(l in au.keywords||e.allKeys&&!(l in au.skipKeywords))&&iu(e,t,r,d,n+"/"+l,s,n,l,o)}r(o,n,s,a,i,c,u)}}function cu(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}au.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},au.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},au.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},au.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};var uu=su.exports;Object.defineProperty(ou,"__esModule",{value:!0}),ou.getSchemaRefs=ou.resolveUrl=ou.normalizeId=ou._getFullPath=ou.getFullPath=ou.inlineRef=void 0;const lu=lc,du=nu,hu=uu,pu=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);ou.inlineRef=function(e,t=!0){return"boolean"==typeof e||(!0===t?!mu(e):!!t&&yu(e)<=t)};const fu=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function mu(e){for(const t in e){if(fu.has(t))return!0;const r=e[t];if(Array.isArray(r)&&r.some(mu))return!0;if("object"==typeof r&&mu(r))return!0}return!1}function yu(e){let t=0;for(const r in e){if("$ref"===r)return 1/0;if(t++,!pu.has(r)&&("object"==typeof e[r]&&(0,lu.eachItem)(e[r],e=>t+=yu(e)),t===1/0))return 1/0}return t}function gu(e,t="",r){!1!==r&&(t=wu(t));const o=e.parse(t);return vu(e,o)}function vu(e,t){return e.serialize(t).split("#")[0]+"#"}ou.getFullPath=gu,ou._getFullPath=vu;const _u=/#\/?$/;function wu(e){return e?e.replace(_u,""):""}ou.normalizeId=wu,ou.resolveUrl=function(e,t,r){return r=wu(r),e.resolve(t,r)};const $u=/^[a-z_][-a-z0-9._]*$/i;var bu;function ku(){if(bu)return Xi;bu=1,Object.defineProperty(Xi,"__esModule",{value:!0}),Xi.getData=Xi.KeywordCxt=Xi.validateFunctionCode=void 0;const e=function(){if(Sc)return ec;Sc=1,Object.defineProperty(ec,"__esModule",{value:!0}),ec.boolOrEmptySchema=ec.topBoolOrEmptySchema=void 0;const e=Ic(),t=uc(),r=Tc(),o={message:"boolean schema is false"};function n(t,r){const{gen:n,data:s}=t,a={gen:n,keyword:"false schema",data:s,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,e.reportError)(a,o,void 0,r)}return ec.topBoolOrEmptySchema=function(e){const{gen:o,schema:s,validateName:a}=e;!1===s?n(e,!1):"object"==typeof s&&!0===s.$async?o.return(r.default.data):(o.assign(t._`${a}.errors`,null),o.return(!0))},ec.boolOrEmptySchema=function(e,t){const{gen:r,schema:o}=e;!1===o?(r.var(t,!1),n(e)):r.var(t,!0)},ec}(),t=xc,r=Oc(),o=xc,n=function(){if(Gc)return Bc;Gc=1,Object.defineProperty(Bc,"__esModule",{value:!0}),Bc.assignDefaults=void 0;const e=uc(),t=lc;function r(r,o,n){const{gen:s,compositeRule:a,data:i,opts:c}=r;if(void 0===n)return;const u=e._`${i}${(0,e.getProperty)(o)}`;if(a)return void(0,t.checkStrictMode)(r,`default is ignored for: ${u}`);let l=e._`${u} === undefined`;"empty"===c.useDefaults&&(l=e._`${l} || ${u} === null || ${u} === ""`),s.if(l,e._`${u} = ${(0,e.stringify)(n)}`)}return Bc.assignDefaults=function(e,t){const{properties:o,items:n}=e.schema;if("object"===t&&o)for(const t in o)r(e,t,o[t].default);else"array"===t&&Array.isArray(n)&&n.forEach((t,o)=>r(e,o,t.default))},Bc}(),s=eu(),a=function(){if(tu)return ru;tu=1,Object.defineProperty(ru,"__esModule",{value:!0}),ru.extendSubschemaMode=ru.extendSubschemaData=ru.getSubschema=void 0;const e=uc(),t=lc;return ru.getSubschema=function(r,{keyword:o,schemaProp:n,schema:s,schemaPath:a,errSchemaPath:i,topSchemaRef:c}){if(void 0!==o&&void 0!==s)throw new Error('both "keyword" and "schema" passed, only one allowed');if(void 0!==o){const s=r.schema[o];return void 0===n?{schema:s,schemaPath:e._`${r.schemaPath}${(0,e.getProperty)(o)}`,errSchemaPath:`${r.errSchemaPath}/${o}`}:{schema:s[n],schemaPath:e._`${r.schemaPath}${(0,e.getProperty)(o)}${(0,e.getProperty)(n)}`,errSchemaPath:`${r.errSchemaPath}/${o}/${(0,t.escapeFragment)(n)}`}}if(void 0!==s){if(void 0===a||void 0===i||void 0===c)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:s,schemaPath:a,topSchemaRef:c,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')},ru.extendSubschemaData=function(r,o,{dataProp:n,dataPropType:s,data:a,dataTypes:i,propertyName:c}){if(void 0!==a&&void 0!==n)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:u}=o;if(void 0!==n){const{errorPath:a,dataPathArr:i,opts:c}=o;l(u.let("data",e._`${o.data}${(0,e.getProperty)(n)}`,!0)),r.errorPath=e.str`${a}${(0,t.getErrorPath)(n,s,c.jsPropertySyntax)}`,r.parentDataProperty=e._`${n}`,r.dataPathArr=[...i,r.parentDataProperty]}function l(e){r.data=e,r.dataLevel=o.dataLevel+1,r.dataTypes=[],o.definedProperties=new Set,r.parentData=o.data,r.dataNames=[...o.dataNames,e]}void 0!==a&&(l(a instanceof e.Name?a:u.let("data",a,!0)),void 0!==c&&(r.propertyName=c)),i&&(r.dataTypes=i)},ru.extendSubschemaMode=function(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:o,createErrors:n,allErrors:s}){void 0!==o&&(e.compositeRule=o),void 0!==n&&(e.createErrors=n),void 0!==s&&(e.allErrors=s),e.jtdDiscriminator=t,e.jtdMetadata=r},ru}(),i=uc(),c=Tc(),u=ou,l=lc,d=Ic();function h({gen:e,validateName:t,schema:r,schemaEnv:o,opts:n},s){n.code.es5?e.func(t,i._`${c.default.data}, ${c.default.valCxt}`,o.$async,()=>{e.code(i._`"use strict"; ${p(r,n)}`),function(e,t){e.if(c.default.valCxt,()=>{e.var(c.default.instancePath,i._`${c.default.valCxt}.${c.default.instancePath}`),e.var(c.default.parentData,i._`${c.default.valCxt}.${c.default.parentData}`),e.var(c.default.parentDataProperty,i._`${c.default.valCxt}.${c.default.parentDataProperty}`),e.var(c.default.rootData,i._`${c.default.valCxt}.${c.default.rootData}`),t.dynamicRef&&e.var(c.default.dynamicAnchors,i._`${c.default.valCxt}.${c.default.dynamicAnchors}`)},()=>{e.var(c.default.instancePath,i._`""`),e.var(c.default.parentData,i._`undefined`),e.var(c.default.parentDataProperty,i._`undefined`),e.var(c.default.rootData,c.default.data),t.dynamicRef&&e.var(c.default.dynamicAnchors,i._`{}`)})}(e,n),e.code(s)}):e.func(t,i._`${c.default.data}, ${function(e){return i._`{${c.default.instancePath}="", ${c.default.parentData}, ${c.default.parentDataProperty}, ${c.default.rootData}=${c.default.data}${e.dynamicRef?i._`, ${c.default.dynamicAnchors}={}`:i.nil}}={}`}(n)}`,o.$async,()=>e.code(p(r,n)).code(s))}function p(e,t){const r="object"==typeof e&&e[t.schemaId];return r&&(t.code.source||t.code.process)?i._`/*# sourceURL=${r} */`:i.nil}function f(t,r){y(t)&&(g(t),m(t))?function(e,t){const{schema:r,gen:o,opts:n}=e;n.$comment&&r.$comment&&_(e);(function(e){const t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,u.resolveUrl)(e.opts.uriResolver,e.baseId,t))})(e),function(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}(e);const s=o.const("_errs",c.default.errors);v(e,s),o.var(t,i._`${s} === ${c.default.errors}`)}(t,r):(0,e.boolOrEmptySchema)(t,r)}function m({schema:e,self:t}){if("boolean"==typeof e)return!e;for(const r in e)if(t.RULES.all[r])return!0;return!1}function y(e){return"boolean"!=typeof e.schema}function g(e){(0,l.checkUnknownRules)(e),function(e){const{schema:t,errSchemaPath:r,opts:o,self:n}=e;t.$ref&&o.ignoreKeywordsWithRef&&(0,l.schemaHasRulesButRef)(t,n.RULES)&&n.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}(e)}function v(e,r){if(e.opts.jtd)return w(e,[],!1,r);const o=(0,t.getSchemaTypes)(e.schema);w(e,o,!(0,t.coerceAndCheckDataType)(e,o),r)}function _({gen:e,schemaEnv:t,schema:r,errSchemaPath:o,opts:n}){const s=r.$comment;if(!0===n.$comment)e.code(i._`${c.default.self}.logger.log(${s})`);else if("function"==typeof n.$comment){const r=i.str`${o}/$comment`,n=e.scopeValue("root",{ref:t.root});e.code(i._`${c.default.self}.opts.$comment(${s}, ${r}, ${n}.schema)`)}}function w(e,t,n,s){const{gen:a,schema:u,data:d,allErrors:h,opts:p,self:f}=e,{RULES:m}=f;function y(l){(0,r.shouldUseGroup)(u,l)&&(l.type?(a.if((0,o.checkDataType)(l.type,d,p.strictNumbers)),$(e,l),1===t.length&&t[0]===l.type&&n&&(a.else(),(0,o.reportTypeError)(e)),a.endIf()):$(e,l),h||a.if(i._`${c.default.errors} === ${s||0}`))}!u.$ref||!p.ignoreKeywordsWithRef&&(0,l.schemaHasRulesButRef)(u,m)?(p.jtd||function(e,t){if(e.schemaEnv.meta||!e.opts.strictTypes)return;(function(e,t){if(!t.length)return;if(!e.dataTypes.length)return void(e.dataTypes=t);t.forEach(t=>{k(e.dataTypes,t)||E(e,`type "${t}" not allowed by context "${e.dataTypes.join(",")}"`)}),function(e,t){const r=[];for(const o of e.dataTypes)k(t,o)?r.push(o):t.includes("integer")&&"number"===o&&r.push("integer");e.dataTypes=r}(e,t)})(e,t),e.opts.allowUnionTypes||function(e,t){t.length>1&&(2!==t.length||!t.includes("null"))&&E(e,"use allowUnionTypes to allow union type keyword")}(e,t);!function(e,t){const o=e.self.RULES.all;for(const n in o){const s=o[n];if("object"==typeof s&&(0,r.shouldUseRule)(e.schema,s)){const{type:r}=s.definition;r.length&&!r.some(e=>b(t,e))&&E(e,`missing type "${r.join(",")}" for keyword "${n}"`)}}}(e,e.dataTypes)}(e,t),a.block(()=>{for(const e of m.rules)y(e);y(m.post)})):a.block(()=>P(e,"$ref",m.all.$ref.definition))}function $(e,t){const{gen:o,schema:s,opts:{useDefaults:a}}=e;a&&(0,n.assignDefaults)(e,t.type),o.block(()=>{for(const o of t.rules)(0,r.shouldUseRule)(s,o)&&P(e,o.keyword,o.definition,t.type)})}function b(e,t){return e.includes(t)||"number"===t&&e.includes("integer")}function k(e,t){return e.includes(t)||"integer"===t&&e.includes("number")}function E(e,t){t+=` at "${e.schemaEnv.baseId+e.errSchemaPath}" (strictTypes)`,(0,l.checkStrictMode)(e,t,e.opts.strictTypes)}Xi.validateFunctionCode=function(t){y(t)&&(g(t),m(t))?function(e){const{schema:t,opts:r,gen:o}=e;h(e,()=>{r.$comment&&t.$comment&&_(e),function(e){const{schema:t,opts:r}=e;void 0!==t.default&&r.useDefaults&&r.strictSchema&&(0,l.checkStrictMode)(e,"default is ignored in the schema root")}(e),o.let(c.default.vErrors,null),o.let(c.default.errors,0),r.unevaluated&&function(e){const{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",i._`${r}.evaluated`),t.if(i._`${e.evaluated}.dynamicProps`,()=>t.assign(i._`${e.evaluated}.props`,i._`undefined`)),t.if(i._`${e.evaluated}.dynamicItems`,()=>t.assign(i._`${e.evaluated}.items`,i._`undefined`))}(e),v(e),function(e){const{gen:t,schemaEnv:r,validateName:o,ValidationError:n,opts:s}=e;r.$async?t.if(i._`${c.default.errors} === 0`,()=>t.return(c.default.data),()=>t.throw(i._`new ${n}(${c.default.vErrors})`)):(t.assign(i._`${o}.errors`,c.default.vErrors),s.unevaluated&&function({gen:e,evaluated:t,props:r,items:o}){r instanceof i.Name&&e.assign(i._`${t}.props`,r);o instanceof i.Name&&e.assign(i._`${t}.items`,o)}(e),t.return(i._`${c.default.errors} === 0`))}(e)})}(t):h(t,()=>(0,e.topBoolOrEmptySchema)(t))};class S{constructor(e,t,r){if((0,s.validateKeywordUsage)(e,t,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,l.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const("vSchema",x(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,s.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw new Error(`${r} value must be ${JSON.stringify(t.schemaType)}`);("code"in t?t.trackErrors:!1!==t.errors)&&(this.errsCount=e.gen.const("_errs",c.default.errors))}result(e,t,r){this.failResult((0,i.not)(e),t,r)}failResult(e,t,r){this.gen.if(e),r?r():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,i.not)(e),void 0,t)}fail(e){if(void 0===e)return this.error(),void(this.allErrors||this.gen.if(!1));this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);const{schemaCode:t}=this;this.fail(i._`${t} !== undefined && (${(0,i.or)(this.invalid$data(),e)})`)}error(e,t,r){if(t)return this.setParams(t),this._error(e,r),void this.setParams({});this._error(e,r)}_error(e,t){(e?d.reportExtraError:d.reportError)(this,this.def.error,t)}$dataError(){(0,d.reportError)(this,this.def.$dataError||d.keyword$DataError)}reset(){if(void 0===this.errsCount)throw new Error('add "trackErrors" to keyword definition');(0,d.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,r=i.nil){this.gen.block(()=>{this.check$data(e,r),t()})}check$data(e=i.nil,t=i.nil){if(!this.$data)return;const{gen:r,schemaCode:o,schemaType:n,def:s}=this;r.if((0,i.or)(i._`${o} === undefined`,t)),e!==i.nil&&r.assign(e,!0),(n.length||s.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==i.nil&&r.assign(e,!1)),r.else()}invalid$data(){const{gen:e,schemaCode:t,schemaType:r,def:n,it:s}=this;return(0,i.or)(function(){if(r.length){if(!(t instanceof i.Name))throw new Error("ajv implementation error");const e=Array.isArray(r)?r:[r];return i._`${(0,o.checkDataTypes)(e,t,s.opts.strictNumbers,o.DataType.Wrong)}`}return i.nil}(),function(){if(n.validateSchema){const r=e.scopeValue("validate$data",{ref:n.validateSchema});return i._`!${r}(${t})`}return i.nil}())}subschema(e,t){const r=(0,a.getSubschema)(this.it,e);(0,a.extendSubschemaData)(r,this.it,e),(0,a.extendSubschemaMode)(r,e);const o={...this.it,...r,items:void 0,props:void 0};return f(o,t),o}mergeEvaluated(e,t){const{it:r,gen:o}=this;r.opts.unevaluated&&(!0!==r.props&&void 0!==e.props&&(r.props=l.mergeEvaluated.props(o,e.props,r.props,t)),!0!==r.items&&void 0!==e.items&&(r.items=l.mergeEvaluated.items(o,e.items,r.items,t)))}mergeValidEvaluated(e,t){const{it:r,gen:o}=this;if(r.opts.unevaluated&&(!0!==r.props||!0!==r.items))return o.if(t,()=>this.mergeEvaluated(e,i.Name)),!0}}function P(e,t,r,o){const n=new S(e,r,t);"code"in r?r.code(n,o):n.$data&&r.validate?(0,s.funcKeywordCode)(n,r):"macro"in r?(0,s.macroKeywordCode)(n,r):(r.compile||r.validate)&&(0,s.funcKeywordCode)(n,r)}Xi.KeywordCxt=S;const T=/^\/(?:[^~]|~0|~1)*$/,I=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function x(e,{dataLevel:t,dataNames:r,dataPathArr:o}){let n,s;if(""===e)return c.default.rootData;if("/"===e[0]){if(!T.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);n=e,s=c.default.rootData}else{const a=I.exec(e);if(!a)throw new Error(`Invalid JSON-pointer: ${e}`);const i=+a[1];if(n=a[2],"#"===n){if(i>=t)throw new Error(d("property/index",i));return o[t-i]}if(i>t)throw new Error(d("data",i));if(s=r[t-i],!n)return s}let a=s;const u=n.split("/");for(const e of u)e&&(s=i._`${s}${(0,i.getProperty)((0,l.unescapeJsonPointer)(e))}`,a=i._`${a} && ${s}`);return a;function d(e,r){return`Cannot access ${e} ${r} levels up, current level is ${t}`}}return Xi.getData=x,Xi}ou.getSchemaRefs=function(e,t){if("boolean"==typeof e)return{};const{schemaId:r,uriResolver:o}=this.opts,n=wu(e[r]||t),s={"":n},a=gu(o,n,!1),i={},c=new Set;return hu(e,{allKeys:!0},(e,t,o,n)=>{if(void 0===n)return;const d=a+t;let h=s[n];function p(t){const r=this.opts.uriResolver.resolve;if(t=wu(h?r(h,t):t),c.has(t))throw l(t);c.add(t);let o=this.refs[t];return"string"==typeof o&&(o=this.refs[o]),"object"==typeof o?u(e,o.schema,t):t!==wu(d)&&("#"===t[0]?(u(e,i[t],t),i[t]=e):this.refs[t]=d),t}function f(e){if("string"==typeof e){if(!$u.test(e))throw new Error(`invalid anchor "${e}"`);p.call(this,`#${e}`)}}"string"==typeof e[r]&&(h=p.call(this,e[r])),f.call(this,e.$anchor),f.call(this,e.$dynamicAnchor),s[t]=h}),i;function u(e,t,r){if(void 0!==t&&!du(e,t))throw l(r)}function l(e){return new Error(`reference "${e}" resolves to more than one schema`)}};var Eu,Su={};function Pu(){if(Eu)return Su;Eu=1,Object.defineProperty(Su,"__esModule",{value:!0});class e extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}}return Su.default=e,Su}var Tu,Iu={};function xu(){if(Tu)return Iu;Tu=1,Object.defineProperty(Iu,"__esModule",{value:!0});const e=ou;class t extends Error{constructor(t,r,o,n){super(n||`can't resolve reference ${o} from id ${r}`),this.missingRef=(0,e.resolveUrl)(t,r,o),this.missingSchema=(0,e.normalizeId)((0,e.getFullPath)(t,this.missingRef))}}return Iu.default=t,Iu}var Nu={};Object.defineProperty(Nu,"__esModule",{value:!0}),Nu.resolveSchema=Nu.getCompilingSchema=Nu.resolveRef=Nu.compileSchema=Nu.SchemaEnv=void 0;const Cu=uc(),ju=Pu(),Ru=Tc(),Ou=ou,zu=lc,Au=ku();let Mu=class{constructor(e){var t;let r;this.refs={},this.dynamicAnchors={},"object"==typeof e.schema&&(r=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=null!==(t=e.baseId)&&void 0!==t?t:(0,Ou.normalizeId)(null==r?void 0:r[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=null==r?void 0:r.$async,this.refs={}}};function Du(e){const t=qu.call(this,e);if(t)return t;const r=(0,Ou.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:o,lines:n}=this.opts.code,{ownProperties:s}=this.opts,a=new Cu.CodeGen(this.scope,{es5:o,lines:n,ownProperties:s});let i;e.$async&&(i=a.scopeValue("Error",{ref:ju.default,code:Cu._`require("ajv/dist/runtime/validation_error").default`}));const c=a.scopeName("validate");e.validateName=c;const u={gen:a,allErrors:this.opts.allErrors,data:Ru.default.data,parentData:Ru.default.parentData,parentDataProperty:Ru.default.parentDataProperty,dataNames:[Ru.default.data],dataPathArr:[Cu.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:a.scopeValue("schema",!0===this.opts.code.source?{ref:e.schema,code:(0,Cu.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:i,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:Cu.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:Cu._`""`,opts:this.opts,self:this};let l;try{this._compilations.add(e),(0,Au.validateFunctionCode)(u),a.optimize(this.opts.code.optimize);const t=a.toString();l=`${a.scopeRefs(Ru.default.scope)}return ${t}`,this.opts.code.process&&(l=this.opts.code.process(l,e));const r=new Function(`${Ru.default.self}`,`${Ru.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:r}),r.errors=null,r.schema=e.schema,r.schemaEnv=e,e.$async&&(r.$async=!0),!0===this.opts.code.source&&(r.source={validateName:c,validateCode:t,scopeValues:a._values}),this.opts.unevaluated){const{props:e,items:t}=u;r.evaluated={props:e instanceof Cu.Name?void 0:e,items:t instanceof Cu.Name?void 0:t,dynamicProps:e instanceof Cu.Name,dynamicItems:t instanceof Cu.Name},r.source&&(r.source.evaluated=(0,Cu.stringify)(r.evaluated))}return e.validate=r,e}catch(t){throw delete e.validate,delete e.validateName,l&&this.logger.error("Error compiling schema, function code:",l),t}finally{this._compilations.delete(e)}}function Uu(e){return(0,Ou.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:Du.call(this,e)}function qu(e){for(const t of this._compilations)if(Vu(t,e))return t}function Vu(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function Fu(e,t){let r;for(;"string"==typeof(r=this.refs[t]);)t=r;return r||this.schemas[t]||Lu.call(this,e,t)}function Lu(e,t){const r=this.opts.uriResolver.parse(t),o=(0,Ou._getFullPath)(this.opts.uriResolver,r);let n=(0,Ou.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&o===n)return Ku.call(this,r,e);const s=(0,Ou.normalizeId)(o),a=this.refs[s]||this.schemas[s];if("string"==typeof a){const t=Lu.call(this,e,a);if("object"!=typeof(null==t?void 0:t.schema))return;return Ku.call(this,r,t)}if("object"==typeof(null==a?void 0:a.schema)){if(a.validate||Du.call(this,a),s===(0,Ou.normalizeId)(t)){const{schema:t}=a,{schemaId:r}=this.opts,o=t[r];return o&&(n=(0,Ou.resolveUrl)(this.opts.uriResolver,n,o)),new Mu({schema:t,schemaId:r,root:e,baseId:n})}return Ku.call(this,r,a)}}Nu.SchemaEnv=Mu,Nu.compileSchema=Du,Nu.resolveRef=function(e,t,r){var o;r=(0,Ou.resolveUrl)(this.opts.uriResolver,t,r);const n=e.refs[r];if(n)return n;let s=Fu.call(this,e,r);if(void 0===s){const n=null===(o=e.localRefs)||void 0===o?void 0:o[r],{schemaId:a}=this.opts;n&&(s=new Mu({schema:n,schemaId:a,root:e,baseId:t}))}return void 0!==s?e.refs[r]=Uu.call(this,s):void 0},Nu.getCompilingSchema=qu,Nu.resolveSchema=Lu;const Hu=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Ku(e,{baseId:t,schema:r,root:o}){var n;if("/"!==(null===(n=e.fragment)||void 0===n?void 0:n[0]))return;for(const o of e.fragment.slice(1).split("/")){if("boolean"==typeof r)return;const e=r[(0,zu.unescapeFragment)(o)];if(void 0===e)return;const n="object"==typeof(r=e)&&r[this.opts.schemaId];!Hu.has(o)&&n&&(t=(0,Ou.resolveUrl)(this.opts.uriResolver,t,n))}let s;if("boolean"!=typeof r&&r.$ref&&!(0,zu.schemaHasRulesButRef)(r,this.RULES)){const e=(0,Ou.resolveUrl)(this.opts.uriResolver,t,r.$ref);s=Lu.call(this,o,e)}const{schemaId:a}=this.opts;return s=s||new Mu({schema:r,schemaId:a,root:o,baseId:t}),s.schema!==s.root.schema?s:void 0}var Zu={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1},Gu={},Bu={exports:{}};const Ju=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Wu=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function Qu(e){let t="",r=0,o=0;for(o=0;o<e.length;o++)if(r=e[o].charCodeAt(0),48!==r){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[o];break}for(o+=1;o<e.length;o++){if(r=e[o].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[o]}return t}function Yu(e){return e.length=0,!0}function Xu(e,t,r){if(e.length){const o=Qu(e);if(""===o)return r.error=!0,!1;t.push(o),e.length=0}return!0}function el(e){if(function(e,t){let r=0;for(let o=0;o<e.length;o++)e[o]===t&&r++;return r}(e,":")<2)return{host:e,isIPV6:!1};const t=function(e){let t=0;const r={error:!1,address:"",zone:""},o=[],n=[];let s=!1,a=!1,i=Xu;for(let c=0;c<e.length;c++){const u=e[c];if("["!==u&&"]"!==u)if(":"!==u)if("%"===u){if(!i(n,o,r))break;i=Yu}else n.push(u);else{if(!0===s&&(a=!0),!i(n,o,r))break;if(++t>7){r.error=!0;break}c>0&&":"===e[c-1]&&(s=!0),o.push(":")}}return n.length&&(i===Yu?r.zone=n.join(""):a?o.push(n.join("")):o.push(Qu(n))),r.address=o.join(""),r}(e);if(t.error)return{host:e,isIPV6:!1};{let e=t.address,r=t.address;return t.zone&&(e+="%"+t.zone,r+="%25"+t.zone),{host:e,isIPV6:!0,escapedHost:r}}}var tl={nonSimpleDomain:RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u),recomposeAuthority:function(e){const t=[];if(void 0!==e.userinfo&&(t.push(e.userinfo),t.push("@")),void 0!==e.host){let r=unescape(e.host);if(!Wu(r)){const t=el(r);r=!0===t.isIPV6?`[${t.escapedHost}]`:e.host}t.push(r)}return"number"!=typeof e.port&&"string"!=typeof e.port||(t.push(":"),t.push(String(e.port))),t.length?t.join(""):void 0},normalizeComponentEncoding:function(e,t){const r=!0!==t?escape:unescape;return void 0!==e.scheme&&(e.scheme=r(e.scheme)),void 0!==e.userinfo&&(e.userinfo=r(e.userinfo)),void 0!==e.host&&(e.host=r(e.host)),void 0!==e.path&&(e.path=r(e.path)),void 0!==e.query&&(e.query=r(e.query)),void 0!==e.fragment&&(e.fragment=r(e.fragment)),e},removeDotSegments:function(e){let t=e;const r=[];let o=-1,n=0;for(;n=t.length;){if(1===n){if("."===t)break;if("/"===t){r.push("/");break}r.push(t);break}if(2===n){if("."===t[0]){if("."===t[1])break;if("/"===t[1]){t=t.slice(2);continue}}else if("/"===t[0]&&("."===t[1]||"/"===t[1])){r.push("/");break}}else if(3===n&&"/.."===t){0!==r.length&&r.pop(),r.push("/");break}if("."===t[0]){if("."===t[1]){if("/"===t[2]){t=t.slice(3);continue}}else if("/"===t[1]){t=t.slice(2);continue}}else if("/"===t[0]&&"."===t[1]){if("/"===t[2]){t=t.slice(2);continue}if("."===t[2]&&"/"===t[3]){t=t.slice(3),0!==r.length&&r.pop();continue}}if(-1===(o=t.indexOf("/",1))){r.push(t);break}r.push(t.slice(0,o)),t=t.slice(o)}return r.join("")},isIPv4:Wu,isUUID:Ju,normalizeIPv6:el,stringArrayToHexStripped:Qu};const{isUUID:rl}=tl,ol=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,nl=["http","https","ws","wss","urn","urn:uuid"];function sl(e){return!0===e.secure||!1!==e.secure&&(!!e.scheme&&!(3!==e.scheme.length||"w"!==e.scheme[0]&&"W"!==e.scheme[0]||"s"!==e.scheme[1]&&"S"!==e.scheme[1]||"s"!==e.scheme[2]&&"S"!==e.scheme[2]))}function al(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function il(e){const t="https"===String(e.scheme).toLowerCase();return e.port!==(t?443:80)&&""!==e.port||(e.port=void 0),e.path||(e.path="/"),e}const cl={scheme:"http",domainHost:!0,parse:al,serialize:il},ul={scheme:"ws",domainHost:!0,parse:function(e){return e.secure=sl(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e},serialize:function(e){if(e.port!==(sl(e)?443:80)&&""!==e.port||(e.port=void 0),"boolean"==typeof e.secure&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){const[t,r]=e.resourceName.split("?");e.path=t&&"/"!==t?t:void 0,e.query=r,e.resourceName=void 0}return e.fragment=void 0,e}},ll={http:cl,https:{scheme:"https",domainHost:cl.domainHost,parse:al,serialize:il},ws:ul,wss:{scheme:"wss",domainHost:ul.domainHost,parse:ul.parse,serialize:ul.serialize},urn:{scheme:"urn",parse:function(e,t){if(!e.path)return e.error="URN can not be parsed",e;const r=e.path.match(ol);if(r){const o=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];const n=dl(`${o}:${t.nid||e.nid}`);e.path=void 0,n&&(e=n.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e},serialize:function(e,t){if(void 0===e.nid)throw new Error("URN without nid cannot be serialized");const r=t.scheme||e.scheme||"urn",o=e.nid.toLowerCase(),n=dl(`${r}:${t.nid||o}`);n&&(e=n.serialize(e,t));const s=e,a=e.nss;return s.path=`${o||t.nid}:${a}`,t.skipEscape=!0,s},skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:function(e,t){const r=e;return r.uuid=r.nss,r.nss=void 0,t.tolerant||r.uuid&&rl(r.uuid)||(r.error=r.error||"UUID is not valid."),r},serialize:function(e){const t=e;return t.nss=(e.uuid||"").toLowerCase(),t},skipNormalize:!0}};function dl(e){return e&&(ll[e]||ll[e.toLowerCase()])||void 0}Object.setPrototypeOf(ll,null);var hl={wsIsSecure:sl,SCHEMES:ll,isValidSchemeName:function(e){return-1!==nl.indexOf(e)},getSchemeHandler:dl};const{normalizeIPv6:pl,removeDotSegments:fl,recomposeAuthority:ml,normalizeComponentEncoding:yl,isIPv4:gl,nonSimpleDomain:vl}=tl,{SCHEMES:_l,getSchemeHandler:wl}=hl;function $l(e,t,r,o){const n={};return o||(e=El(bl(e,r),r),t=El(bl(t,r),r)),!(r=r||{}).tolerant&&t.scheme?(n.scheme=t.scheme,n.userinfo=t.userinfo,n.host=t.host,n.port=t.port,n.path=fl(t.path||""),n.query=t.query):(void 0!==t.userinfo||void 0!==t.host||void 0!==t.port?(n.userinfo=t.userinfo,n.host=t.host,n.port=t.port,n.path=fl(t.path||""),n.query=t.query):(t.path?("/"===t.path[0]?n.path=fl(t.path):(void 0===e.userinfo&&void 0===e.host&&void 0===e.port||e.path?e.path?n.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:n.path=t.path:n.path="/"+t.path,n.path=fl(n.path)),n.query=t.query):(n.path=e.path,void 0!==t.query?n.query=t.query:n.query=e.query),n.userinfo=e.userinfo,n.host=e.host,n.port=e.port),n.scheme=e.scheme),n.fragment=t.fragment,n}function bl(e,t){const r={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},o=Object.assign({},t),n=[],s=wl(o.scheme||r.scheme);s&&s.serialize&&s.serialize(r,o),void 0!==r.path&&(o.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),void 0!==r.scheme&&(r.path=r.path.split("%3A").join(":")))),"suffix"!==o.reference&&r.scheme&&n.push(r.scheme,":");const a=ml(r);if(void 0!==a&&("suffix"!==o.reference&&n.push("//"),n.push(a),r.path&&"/"!==r.path[0]&&n.push("/")),void 0!==r.path){let e=r.path;o.absolutePath||s&&s.absolutePath||(e=fl(e)),void 0===a&&"/"===e[0]&&"/"===e[1]&&(e="/%2F"+e.slice(2)),n.push(e)}return void 0!==r.query&&n.push("?",r.query),void 0!==r.fragment&&n.push("#",r.fragment),n.join("")}const kl=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function El(e,t){const r=Object.assign({},t),o={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let n=!1;"suffix"===r.reference&&(e=r.scheme?r.scheme+":"+e:"//"+e);const s=e.match(kl);if(s){if(o.scheme=s[1],o.userinfo=s[3],o.host=s[4],o.port=parseInt(s[5],10),o.path=s[6]||"",o.query=s[7],o.fragment=s[8],isNaN(o.port)&&(o.port=s[5]),o.host){if(!1===gl(o.host)){const e=pl(o.host);o.host=e.host.toLowerCase(),n=e.isIPV6}else n=!0}void 0!==o.scheme||void 0!==o.userinfo||void 0!==o.host||void 0!==o.port||void 0!==o.query||o.path?void 0===o.scheme?o.reference="relative":void 0===o.fragment?o.reference="absolute":o.reference="uri":o.reference="same-document",r.reference&&"suffix"!==r.reference&&r.reference!==o.reference&&(o.error=o.error||"URI is not a "+r.reference+" reference.");const t=wl(r.scheme||o.scheme);if(!(r.unicodeSupport||t&&t.unicodeSupport)&&o.host&&(r.domainHost||t&&t.domainHost)&&!1===n&&vl(o.host))try{o.host=URL.domainToASCII(o.host.toLowerCase())}catch(e){o.error=o.error||"Host's domain name can not be converted to ASCII: "+e}(!t||t&&!t.skipNormalize)&&(-1!==e.indexOf("%")&&(void 0!==o.scheme&&(o.scheme=unescape(o.scheme)),void 0!==o.host&&(o.host=unescape(o.host))),o.path&&(o.path=escape(unescape(o.path))),o.fragment&&(o.fragment=encodeURI(decodeURIComponent(o.fragment)))),t&&t.parse&&t.parse(o,r)}else o.error=o.error||"URI can not be parsed.";return o}const Sl={SCHEMES:_l,normalize:function(e,t){return"string"==typeof e?e=bl(El(e,t),t):"object"==typeof e&&(e=El(bl(e,t),t)),e},resolve:function(e,t,r){const o=r?Object.assign({scheme:"null"},r):{scheme:"null"},n=$l(El(e,o),El(t,o),o,!0);return o.skipEscape=!0,bl(n,o)},resolveComponent:$l,equal:function(e,t,r){return"string"==typeof e?(e=unescape(e),e=bl(yl(El(e,r),!0),{...r,skipEscape:!0})):"object"==typeof e&&(e=bl(yl(e,!0),{...r,skipEscape:!0})),"string"==typeof t?(t=unescape(t),t=bl(yl(El(t,r),!0),{...r,skipEscape:!0})):"object"==typeof t&&(t=bl(yl(t,!0),{...r,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()},serialize:bl,parse:El};Bu.exports=Sl,Bu.exports.default=Sl,Bu.exports.fastUri=Sl;var Pl=Bu.exports;Object.defineProperty(Gu,"__esModule",{value:!0});const Tl=Pl;Tl.code='require("ajv/dist/runtime/uri").default',Gu.default=Tl,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=ku();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var r=uc();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return r.CodeGen}});const o=Pu(),n=xu(),s=Nc,a=Nu,i=uc(),c=ou,u=xc,l=lc,d=Zu,h=Gu,p=(e,t)=>new RegExp(e,t);p.code="new RegExp";const f=["removeAdditional","useDefaults","coerceTypes"],m=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),y={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},g={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'};function v(e){var t,r,o,n,s,a,i,c,u,l,d,f,m,y,g,v,_,w,$,b,k,E,S,P,T;const I=e.strict,x=null===(t=e.code)||void 0===t?void 0:t.optimize,N=!0===x||void 0===x?1:x||0,C=null!==(o=null===(r=e.code)||void 0===r?void 0:r.regExp)&&void 0!==o?o:p,j=null!==(n=e.uriResolver)&&void 0!==n?n:h.default;return{strictSchema:null===(a=null!==(s=e.strictSchema)&&void 0!==s?s:I)||void 0===a||a,strictNumbers:null===(c=null!==(i=e.strictNumbers)&&void 0!==i?i:I)||void 0===c||c,strictTypes:null!==(l=null!==(u=e.strictTypes)&&void 0!==u?u:I)&&void 0!==l?l:"log",strictTuples:null!==(f=null!==(d=e.strictTuples)&&void 0!==d?d:I)&&void 0!==f?f:"log",strictRequired:null!==(y=null!==(m=e.strictRequired)&&void 0!==m?m:I)&&void 0!==y&&y,code:e.code?{...e.code,optimize:N,regExp:C}:{optimize:N,regExp:C},loopRequired:null!==(g=e.loopRequired)&&void 0!==g?g:200,loopEnum:null!==(v=e.loopEnum)&&void 0!==v?v:200,meta:null===(_=e.meta)||void 0===_||_,messages:null===(w=e.messages)||void 0===w||w,inlineRefs:null===($=e.inlineRefs)||void 0===$||$,schemaId:null!==(b=e.schemaId)&&void 0!==b?b:"$id",addUsedSchema:null===(k=e.addUsedSchema)||void 0===k||k,validateSchema:null===(E=e.validateSchema)||void 0===E||E,validateFormats:null===(S=e.validateFormats)||void 0===S||S,unicodeRegExp:null===(P=e.unicodeRegExp)||void 0===P||P,int32range:null===(T=e.int32range)||void 0===T||T,uriResolver:j}}class _{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...v(e)};const{es5:t,lines:r}=this.opts.code;this.scope=new i.ValueScope({scope:{},prefixes:m,es5:t,lines:r}),this.logger=function(e){if(!1===e)return P;if(void 0===e)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}(e.logger);const o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,s.getRules)(),w.call(this,y,e,"NOT SUPPORTED"),w.call(this,g,e,"DEPRECATED","warn"),this._metaOpts=S.call(this),e.formats&&k.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&E.call(this,e.keywords),"object"==typeof e.meta&&this.addMetaSchema(e.meta),b.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:e,meta:t,schemaId:r}=this.opts;let o=d;"id"===r&&(o={...d},o.id=o.$id,delete o.$id),t&&e&&this.addMetaSchema(o,o[r],!1)}defaultMeta(){const{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta="object"==typeof e?e[t]||e:void 0}validate(e,t){let r;if("string"==typeof e){if(r=this.getSchema(e),!r)throw new Error(`no schema with key or ref "${e}"`)}else r=this.compile(e);const o=r(t);return"$async"in r||(this.errors=r.errors),o}compile(e,t){const r=this._addSchema(e,t);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,t){if("function"!=typeof this.opts.loadSchema)throw new Error("options.loadSchema should be a function");const{loadSchema:r}=this.opts;return o.call(this,e,t);async function o(e,t){await s.call(this,e.$schema);const r=this._addSchema(e,t);return r.validate||a.call(this,r)}async function s(e){e&&!this.getSchema(e)&&await o.call(this,{$ref:e},!0)}async function a(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof n.default))throw t;return i.call(this,t),await c.call(this,t.missingSchema),a.call(this,e)}}function i({missingSchema:e,missingRef:t}){if(this.refs[e])throw new Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function c(e){const r=await u.call(this,e);this.refs[e]||await s.call(this,r.$schema),this.refs[e]||this.addSchema(r,e,t)}async function u(e){const t=this._loading[e];if(t)return t;try{return await(this._loading[e]=r(e))}finally{delete this._loading[e]}}}addSchema(e,t,r,o=this.opts.validateSchema){if(Array.isArray(e)){for(const t of e)this.addSchema(t,void 0,r,o);return this}let n;if("object"==typeof e){const{schemaId:t}=this.opts;if(n=e[t],void 0!==n&&"string"!=typeof n)throw new Error(`schema ${t} must be string`)}return t=(0,c.normalizeId)(t||n),this._checkUnique(t),this.schemas[t]=this._addSchema(e,r,t,o,!0),this}addMetaSchema(e,t,r=this.opts.validateSchema){return this.addSchema(e,t,!0,r),this}validateSchema(e,t){if("boolean"==typeof e)return!0;let r;if(r=e.$schema,void 0!==r&&"string"!=typeof r)throw new Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const o=this.validate(r,e);if(!o&&t){const e="schema is invalid: "+this.errorsText();if("log"!==this.opts.validateSchema)throw new Error(e);this.logger.error(e)}return o}getSchema(e){let t;for(;"string"==typeof(t=$.call(this,e));)e=t;if(void 0===t){const{schemaId:r}=this.opts,o=new a.SchemaEnv({schema:{},schemaId:r});if(t=a.resolveSchema.call(this,o,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const t=$.call(this,e);return"object"==typeof t&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{const t=e;this._cache.delete(t);let r=e[this.opts.schemaId];return r&&(r=(0,c.normalizeId)(r),delete this.schemas[r],delete this.refs[r]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(const t of e)this.addKeyword(t);return this}addKeyword(e,t){let r;if("string"==typeof e)r=e,"object"==typeof t&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=r);else{if("object"!=typeof e||void 0!==t)throw new Error("invalid addKeywords parameters");if(r=(t=e).keyword,Array.isArray(r)&&!r.length)throw new Error("addKeywords: keyword must be string or non-empty array")}if(I.call(this,r,t),!t)return(0,l.eachItem)(r,e=>x.call(this,e)),this;C.call(this,t);const o={...t,type:(0,u.getJSONTypes)(t.type),schemaType:(0,u.getJSONTypes)(t.schemaType)};return(0,l.eachItem)(r,0===o.type.length?e=>x.call(this,e,o):e=>o.type.forEach(t=>x.call(this,e,o,t))),this}getKeyword(e){const t=this.RULES.all[e];return"object"==typeof t?t.definition:!!t}removeKeyword(e){const{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(const r of t.rules){const t=r.rules.findIndex(t=>t.keyword===e);t>=0&&r.rules.splice(t,1)}return this}addFormat(e,t){return"string"==typeof t&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=", ",dataVar:r="data"}={}){return e&&0!==e.length?e.map(e=>`${r}${e.instancePath} ${e.message}`).reduce((e,r)=>e+t+r):"No errors"}$dataMetaSchema(e,t){const r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(const o of t){const t=o.split("/").slice(1);let n=e;for(const e of t)n=n[e];for(const e in r){const t=r[e];if("object"!=typeof t)continue;const{$data:o}=t.definition,s=n[e];o&&s&&(n[e]=R(s))}}return e}_removeAllSchemas(e,t){for(const r in e){const o=e[r];t&&!t.test(r)||("string"==typeof o?delete e[r]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[r]))}}_addSchema(e,t,r,o=this.opts.validateSchema,n=this.opts.addUsedSchema){let s;const{schemaId:i}=this.opts;if("object"==typeof e)s=e[i];else{if(this.opts.jtd)throw new Error("schema must be object");if("boolean"!=typeof e)throw new Error("schema must be object or boolean")}let u=this._cache.get(e);if(void 0!==u)return u;r=(0,c.normalizeId)(s||r);const l=c.getSchemaRefs.call(this,e,r);return u=new a.SchemaEnv({schema:e,schemaId:i,meta:t,baseId:r,localRefs:l}),this._cache.set(u.schema,u),n&&!r.startsWith("#")&&(r&&this._checkUnique(r),this.refs[r]=u),o&&this.validateSchema(e,!0),u}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):a.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){const t=this.opts;this.opts=this._metaOpts;try{a.compileSchema.call(this,e)}finally{this.opts=t}}}function w(e,t,r,o="error"){for(const n in e){const s=n;s in t&&this.logger[o](`${r}: option ${n}. ${e[s]}`)}}function $(e){return e=(0,c.normalizeId)(e),this.schemas[e]||this.refs[e]}function b(){const e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(const t in e)this.addSchema(e[t],t)}function k(){for(const e in this.opts.formats){const t=this.opts.formats[e];t&&this.addFormat(e,t)}}function E(e){if(Array.isArray(e))this.addVocabulary(e);else{this.logger.warn("keywords option as map is deprecated, pass array");for(const t in e){const r=e[t];r.keyword||(r.keyword=t),this.addKeyword(r)}}}function S(){const e={...this.opts};for(const t of f)delete e[t];return e}_.ValidationError=o.default,_.MissingRefError=n.default,e.default=_;const P={log(){},warn(){},error(){}};const T=/^[a-z_$][a-z0-9_$:-]*$/i;function I(e,t){const{RULES:r}=this;if((0,l.eachItem)(e,e=>{if(r.keywords[e])throw new Error(`Keyword ${e} is already defined`);if(!T.test(e))throw new Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!("code"in t)&&!("validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}function x(e,t,r){var o;const n=null==t?void 0:t.post;if(r&&n)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:s}=this;let a=n?s.post:s.rules.find(({type:e})=>e===r);if(a||(a={type:r,rules:[]},s.rules.push(a)),s.keywords[e]=!0,!t)return;const i={keyword:e,definition:{...t,type:(0,u.getJSONTypes)(t.type),schemaType:(0,u.getJSONTypes)(t.schemaType)}};t.before?N.call(this,a,i,t.before):a.rules.push(i),s.all[e]=i,null===(o=t.implements)||void 0===o||o.forEach(e=>this.addKeyword(e))}function N(e,t,r){const o=e.rules.findIndex(e=>e.keyword===r);o>=0?e.rules.splice(o,0,t):(e.rules.push(t),this.logger.warn(`rule ${r} is not defined`))}function C(e){let{metaSchema:t}=e;void 0!==t&&(e.$data&&this.opts.$data&&(t=R(t)),e.validateSchema=this.compile(t,!0))}const j={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function R(e){return{anyOf:[e,j]}}}(Yi);var Il={},xl={},Nl={};Object.defineProperty(Nl,"__esModule",{value:!0});const Cl={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Nl.default=Cl;var jl={};Object.defineProperty(jl,"__esModule",{value:!0}),jl.callRef=jl.getValidate=void 0;const Rl=xu(),Ol=Xc(),zl=uc(),Al=Tc(),Ml=Nu,Dl=lc,Ul={keyword:"$ref",schemaType:"string",code(e){const{gen:t,schema:r,it:o}=e,{baseId:n,schemaEnv:s,validateName:a,opts:i,self:c}=o,{root:u}=s;if(("#"===r||"#/"===r)&&n===u.baseId)return function(){if(s===u)return Vl(e,a,s,s.$async);const r=t.scopeValue("root",{ref:u});return Vl(e,zl._`${r}.validate`,u,u.$async)}();const l=Ml.resolveRef.call(c,u,n,r);if(void 0===l)throw new Rl.default(o.opts.uriResolver,n,r);return l instanceof Ml.SchemaEnv?function(t){const r=ql(e,t);Vl(e,r,t,t.$async)}(l):function(o){const n=t.scopeValue("schema",!0===i.code.source?{ref:o,code:(0,zl.stringify)(o)}:{ref:o}),s=t.name("valid"),a=e.subschema({schema:o,dataTypes:[],schemaPath:zl.nil,topSchemaRef:n,errSchemaPath:r},s);e.mergeEvaluated(a),e.ok(s)}(l)}};function ql(e,t){const{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):zl._`${r.scopeValue("wrapper",{ref:t})}.validate`}function Vl(e,t,r,o){const{gen:n,it:s}=e,{allErrors:a,schemaEnv:i,opts:c}=s,u=c.passContext?Al.default.this:zl.nil;function l(e){const t=zl._`${e}.errors`;n.assign(Al.default.vErrors,zl._`${Al.default.vErrors} === null ? ${t} : ${Al.default.vErrors}.concat(${t})`),n.assign(Al.default.errors,zl._`${Al.default.vErrors}.length`)}function d(e){var t;if(!s.opts.unevaluated)return;const o=null===(t=null==r?void 0:r.validate)||void 0===t?void 0:t.evaluated;if(!0!==s.props)if(o&&!o.dynamicProps)void 0!==o.props&&(s.props=Dl.mergeEvaluated.props(n,o.props,s.props));else{const t=n.var("props",zl._`${e}.evaluated.props`);s.props=Dl.mergeEvaluated.props(n,t,s.props,zl.Name)}if(!0!==s.items)if(o&&!o.dynamicItems)void 0!==o.items&&(s.items=Dl.mergeEvaluated.items(n,o.items,s.items));else{const t=n.var("items",zl._`${e}.evaluated.items`);s.items=Dl.mergeEvaluated.items(n,t,s.items,zl.Name)}}o?function(){if(!i.$async)throw new Error("async schema referenced by sync schema");const r=n.let("valid");n.try(()=>{n.code(zl._`await ${(0,Ol.callValidateCode)(e,t,u)}`),d(t),a||n.assign(r,!0)},e=>{n.if(zl._`!(${e} instanceof ${s.ValidationError})`,()=>n.throw(e)),l(e),a||n.assign(r,!1)}),e.ok(r)}():e.result((0,Ol.callValidateCode)(e,t,u),()=>d(t),()=>l(t))}jl.getValidate=ql,jl.callRef=Vl,jl.default=Ul,Object.defineProperty(xl,"__esModule",{value:!0});const Fl=jl,Ll=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Nl.default,Fl.default];xl.default=Ll;var Hl={},Kl={};Object.defineProperty(Kl,"__esModule",{value:!0});const Zl=uc(),Gl=Zl.operators,Bl={maximum:{okStr:"<=",ok:Gl.LTE,fail:Gl.GT},minimum:{okStr:">=",ok:Gl.GTE,fail:Gl.LT},exclusiveMaximum:{okStr:"<",ok:Gl.LT,fail:Gl.GTE},exclusiveMinimum:{okStr:">",ok:Gl.GT,fail:Gl.LTE}},Jl={message:({keyword:e,schemaCode:t})=>Zl.str`must be ${Bl[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>Zl._`{comparison: ${Bl[e].okStr}, limit: ${t}}`},Wl={keyword:Object.keys(Bl),type:"number",schemaType:"number",$data:!0,error:Jl,code(e){const{keyword:t,data:r,schemaCode:o}=e;e.fail$data(Zl._`${r} ${Bl[t].fail} ${o} || isNaN(${r})`)}};Kl.default=Wl;var Ql={};Object.defineProperty(Ql,"__esModule",{value:!0});const Yl=uc(),Xl={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:e})=>Yl.str`must be multiple of ${e}`,params:({schemaCode:e})=>Yl._`{multipleOf: ${e}}`},code(e){const{gen:t,data:r,schemaCode:o,it:n}=e,s=n.opts.multipleOfPrecision,a=t.let("res"),i=s?Yl._`Math.abs(Math.round(${a}) - ${a}) > 1e-${s}`:Yl._`${a} !== parseInt(${a})`;e.fail$data(Yl._`(${o} === 0 || (${a} = ${r}/${o}, ${i}))`)}};Ql.default=Xl;var ed={},td={};function rd(e){const t=e.length;let r,o=0,n=0;for(;n<t;)o++,r=e.charCodeAt(n++),r>=55296&&r<=56319&&n<t&&(r=e.charCodeAt(n),56320==(64512&r)&&n++);return o}Object.defineProperty(td,"__esModule",{value:!0}),td.default=rd,rd.code='require("ajv/dist/runtime/ucs2length").default',Object.defineProperty(ed,"__esModule",{value:!0});const od=uc(),nd=lc,sd=td,ad={message({keyword:e,schemaCode:t}){const r="maxLength"===e?"more":"fewer";return od.str`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>od._`{limit: ${e}}`},id={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:ad,code(e){const{keyword:t,data:r,schemaCode:o,it:n}=e,s="maxLength"===t?od.operators.GT:od.operators.LT,a=!1===n.opts.unicode?od._`${r}.length`:od._`${(0,nd.useFunc)(e.gen,sd.default)}(${r})`;e.fail$data(od._`${a} ${s} ${o}`)}};ed.default=id;var cd={};Object.defineProperty(cd,"__esModule",{value:!0});const ud=Xc(),ld=uc(),dd={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>ld.str`must match pattern "${e}"`,params:({schemaCode:e})=>ld._`{pattern: ${e}}`},code(e){const{data:t,$data:r,schema:o,schemaCode:n,it:s}=e,a=s.opts.unicodeRegExp?"u":"",i=r?ld._`(new RegExp(${n}, ${a}))`:(0,ud.usePattern)(e,o);e.fail$data(ld._`!${i}.test(${t})`)}};cd.default=dd;var hd={};Object.defineProperty(hd,"__esModule",{value:!0});const pd=uc(),fd={message({keyword:e,schemaCode:t}){const r="maxProperties"===e?"more":"fewer";return pd.str`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>pd._`{limit: ${e}}`},md={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:fd,code(e){const{keyword:t,data:r,schemaCode:o}=e,n="maxProperties"===t?pd.operators.GT:pd.operators.LT;e.fail$data(pd._`Object.keys(${r}).length ${n} ${o}`)}};hd.default=md;var yd={};Object.defineProperty(yd,"__esModule",{value:!0});const gd=Xc(),vd=uc(),_d=lc,wd={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:e}})=>vd.str`must have required property '${e}'`,params:({params:{missingProperty:e}})=>vd._`{missingProperty: ${e}}`},code(e){const{gen:t,schema:r,schemaCode:o,data:n,$data:s,it:a}=e,{opts:i}=a;if(!s&&0===r.length)return;const c=r.length>=i.loopRequired;if(a.allErrors?function(){if(c||s)e.block$data(vd.nil,u);else for(const t of r)(0,gd.checkReportMissingProp)(e,t)}():function(){const a=t.let("missing");if(c||s){const r=t.let("valid",!0);e.block$data(r,()=>function(r,s){e.setParams({missingProperty:r}),t.forOf(r,o,()=>{t.assign(s,(0,gd.propertyInData)(t,n,r,i.ownProperties)),t.if((0,vd.not)(s),()=>{e.error(),t.break()})},vd.nil)}(a,r)),e.ok(r)}else t.if((0,gd.checkMissingProp)(e,r,a)),(0,gd.reportMissingProp)(e,a),t.else()}(),i.strictRequired){const t=e.parentSchema.properties,{definedProperties:o}=e.it;for(const e of r)if(void 0===(null==t?void 0:t[e])&&!o.has(e)){const t=`required property "${e}" is not defined at "${a.schemaEnv.baseId+a.errSchemaPath}" (strictRequired)`;(0,_d.checkStrictMode)(a,t,a.opts.strictRequired)}}function u(){t.forOf("prop",o,r=>{e.setParams({missingProperty:r}),t.if((0,gd.noPropertyInData)(t,n,r,i.ownProperties),()=>e.error())})}}};yd.default=wd;var $d={};Object.defineProperty($d,"__esModule",{value:!0});const bd=uc(),kd={message({keyword:e,schemaCode:t}){const r="maxItems"===e?"more":"fewer";return bd.str`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>bd._`{limit: ${e}}`},Ed={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:kd,code(e){const{keyword:t,data:r,schemaCode:o}=e,n="maxItems"===t?bd.operators.GT:bd.operators.LT;e.fail$data(bd._`${r}.length ${n} ${o}`)}};$d.default=Ed;var Sd={},Pd={};Object.defineProperty(Pd,"__esModule",{value:!0});const Td=nu;Td.code='require("ajv/dist/runtime/equal").default',Pd.default=Td,Object.defineProperty(Sd,"__esModule",{value:!0});const Id=xc,xd=uc(),Nd=lc,Cd=Pd,jd={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:e,j:t}})=>xd.str`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>xd._`{i: ${e}, j: ${t}}`},code(e){const{gen:t,data:r,$data:o,schema:n,parentSchema:s,schemaCode:a,it:i}=e;if(!o&&!n)return;const c=t.let("valid"),u=s.items?(0,Id.getSchemaTypes)(s.items):[];function l(o,n){const s=t.name("item"),a=(0,Id.checkDataTypes)(u,s,i.opts.strictNumbers,Id.DataType.Wrong),l=t.const("indices",xd._`{}`);t.for(xd._`;${o}--;`,()=>{t.let(s,xd._`${r}[${o}]`),t.if(a,xd._`continue`),u.length>1&&t.if(xd._`typeof ${s} == "string"`,xd._`${s} += "_"`),t.if(xd._`typeof ${l}[${s}] == "number"`,()=>{t.assign(n,xd._`${l}[${s}]`),e.error(),t.assign(c,!1).break()}).code(xd._`${l}[${s}] = ${o}`)})}function d(o,n){const s=(0,Nd.useFunc)(t,Cd.default),a=t.name("outer");t.label(a).for(xd._`;${o}--;`,()=>t.for(xd._`${n} = ${o}; ${n}--;`,()=>t.if(xd._`${s}(${r}[${o}], ${r}[${n}])`,()=>{e.error(),t.assign(c,!1).break(a)})))}e.block$data(c,function(){const o=t.let("i",xd._`${r}.length`),n=t.let("j");e.setParams({i:o,j:n}),t.assign(c,!0),t.if(xd._`${o} > 1`,()=>(u.length>0&&!u.some(e=>"object"===e||"array"===e)?l:d)(o,n))},xd._`${a} === false`),e.ok(c)}};Sd.default=jd;var Rd={};Object.defineProperty(Rd,"__esModule",{value:!0});const Od=uc(),zd=lc,Ad=Pd,Md={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:e})=>Od._`{allowedValue: ${e}}`},code(e){const{gen:t,data:r,$data:o,schemaCode:n,schema:s}=e;o||s&&"object"==typeof s?e.fail$data(Od._`!${(0,zd.useFunc)(t,Ad.default)}(${r}, ${n})`):e.fail(Od._`${s} !== ${r}`)}};Rd.default=Md;var Dd={};Object.defineProperty(Dd,"__esModule",{value:!0});const Ud=uc(),qd=lc,Vd=Pd,Fd={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:e})=>Ud._`{allowedValues: ${e}}`},code(e){const{gen:t,data:r,$data:o,schema:n,schemaCode:s,it:a}=e;if(!o&&0===n.length)throw new Error("enum must have non-empty array");const i=n.length>=a.opts.loopEnum;let c;const u=()=>null!=c?c:c=(0,qd.useFunc)(t,Vd.default);let l;if(i||o)l=t.let("valid"),e.block$data(l,function(){t.assign(l,!1),t.forOf("v",s,e=>t.if(Ud._`${u()}(${r}, ${e})`,()=>t.assign(l,!0).break()))});else{if(!Array.isArray(n))throw new Error("ajv implementation error");const e=t.const("vSchema",s);l=(0,Ud.or)(...n.map((t,o)=>function(e,t){const o=n[t];return"object"==typeof o&&null!==o?Ud._`${u()}(${r}, ${e}[${t}])`:Ud._`${r} === ${o}`}(e,o)))}e.pass(l)}};Dd.default=Fd,Object.defineProperty(Hl,"__esModule",{value:!0});const Ld=Ql,Hd=ed,Kd=cd,Zd=hd,Gd=yd,Bd=$d,Jd=Sd,Wd=Rd,Qd=Dd,Yd=[Kl.default,Ld.default,Hd.default,Kd.default,Zd.default,Gd.default,Bd.default,Jd.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Wd.default,Qd.default];Hl.default=Yd;var Xd={},eh={};Object.defineProperty(eh,"__esModule",{value:!0}),eh.validateAdditionalItems=void 0;const th=uc(),rh=lc,oh={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:e}})=>th.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>th._`{limit: ${e}}`},code(e){const{parentSchema:t,it:r}=e,{items:o}=t;Array.isArray(o)?nh(e,o):(0,rh.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas')}};function nh(e,t){const{gen:r,schema:o,data:n,keyword:s,it:a}=e;a.items=!0;const i=r.const("len",th._`${n}.length`);if(!1===o)e.setParams({len:t.length}),e.pass(th._`${i} <= ${t.length}`);else if("object"==typeof o&&!(0,rh.alwaysValidSchema)(a,o)){const o=r.var("valid",th._`${i} <= ${t.length}`);r.if((0,th.not)(o),()=>function(o){r.forRange("i",t.length,i,t=>{e.subschema({keyword:s,dataProp:t,dataPropType:rh.Type.Num},o),a.allErrors||r.if((0,th.not)(o),()=>r.break())})}(o)),e.ok(o)}}eh.validateAdditionalItems=nh,eh.default=oh;var sh={},ah={};Object.defineProperty(ah,"__esModule",{value:!0}),ah.validateTuple=void 0;const ih=uc(),ch=lc,uh=Xc(),lh={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){const{schema:t,it:r}=e;if(Array.isArray(t))return dh(e,"additionalItems",t);r.items=!0,(0,ch.alwaysValidSchema)(r,t)||e.ok((0,uh.validateArray)(e))}};function dh(e,t,r=e.schema){const{gen:o,parentSchema:n,data:s,keyword:a,it:i}=e;!function(e){const{opts:o,errSchemaPath:n}=i,s=r.length,c=s===e.minItems&&(s===e.maxItems||!1===e[t]);if(o.strictTuples&&!c){const e=`"${a}" is ${s}-tuple, but minItems or maxItems/${t} are not specified or different at path "${n}"`;(0,ch.checkStrictMode)(i,e,o.strictTuples)}}(n),i.opts.unevaluated&&r.length&&!0!==i.items&&(i.items=ch.mergeEvaluated.items(o,r.length,i.items));const c=o.name("valid"),u=o.const("len",ih._`${s}.length`);r.forEach((t,r)=>{(0,ch.alwaysValidSchema)(i,t)||(o.if(ih._`${u} > ${r}`,()=>e.subschema({keyword:a,schemaProp:r,dataProp:r},c)),e.ok(c))})}ah.validateTuple=dh,ah.default=lh,Object.defineProperty(sh,"__esModule",{value:!0});const hh=ah,ph={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,hh.validateTuple)(e,"items")};sh.default=ph;var fh={};Object.defineProperty(fh,"__esModule",{value:!0});const mh=uc(),yh=lc,gh=Xc(),vh=eh,_h={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:e}})=>mh.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>mh._`{limit: ${e}}`},code(e){const{schema:t,parentSchema:r,it:o}=e,{prefixItems:n}=r;o.items=!0,(0,yh.alwaysValidSchema)(o,t)||(n?(0,vh.validateAdditionalItems)(e,n):e.ok((0,gh.validateArray)(e)))}};fh.default=_h;var wh={};Object.defineProperty(wh,"__esModule",{value:!0});const $h=uc(),bh=lc,kh={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:e,max:t}})=>void 0===t?$h.str`must contain at least ${e} valid item(s)`:$h.str`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>void 0===t?$h._`{minContains: ${e}}`:$h._`{minContains: ${e}, maxContains: ${t}}`},code(e){const{gen:t,schema:r,parentSchema:o,data:n,it:s}=e;let a,i;const{minContains:c,maxContains:u}=o;s.opts.next?(a=void 0===c?1:c,i=u):a=1;const l=t.const("len",$h._`${n}.length`);if(e.setParams({min:a,max:i}),void 0===i&&0===a)return void(0,bh.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');if(void 0!==i&&a>i)return(0,bh.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),void e.fail();if((0,bh.alwaysValidSchema)(s,r)){let t=$h._`${l} >= ${a}`;return void 0!==i&&(t=$h._`${t} && ${l} <= ${i}`),void e.pass(t)}s.items=!0;const d=t.name("valid");function h(){const e=t.name("_valid"),r=t.let("count",0);p(e,()=>t.if(e,()=>function(e){t.code($h._`${e}++`),void 0===i?t.if($h._`${e} >= ${a}`,()=>t.assign(d,!0).break()):(t.if($h._`${e} > ${i}`,()=>t.assign(d,!1).break()),1===a?t.assign(d,!0):t.if($h._`${e} >= ${a}`,()=>t.assign(d,!0)))}(r)))}function p(r,o){t.forRange("i",0,l,t=>{e.subschema({keyword:"contains",dataProp:t,dataPropType:bh.Type.Num,compositeRule:!0},r),o()})}void 0===i&&1===a?p(d,()=>t.if(d,()=>t.break())):0===a?(t.let(d,!0),void 0!==i&&t.if($h._`${n}.length > 0`,h)):(t.let(d,!1),h()),e.result(d,()=>e.reset())}};wh.default=kh;var Eh={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=uc(),r=lc,o=Xc();e.error={message:({params:{property:e,depsCount:r,deps:o}})=>{const n=1===r?"property":"properties";return t.str`must have ${n} ${o} when property ${e} is present`},params:({params:{property:e,depsCount:r,deps:o,missingProperty:n}})=>t._`{property: ${e},
5
- missingProperty: ${n},
1
+ import e from"os";import t,{dirname as r,join as n}from"path";import o from"fs/promises";import{jwtVerify as s,createRemoteJWKSet as a}from"jose";import i from"crypto";import c from"http";import u,{fileURLToPath as l}from"url";import{spawn as d}from"child_process";import h from"readline";import p from"pkce-challenge";import{readFileSync as f}from"fs";class m extends Error{constructor(e){super(e),this.name="BarndoorError"}}class y extends m{constructor(e,t=null){super(e),this.name="AuthenticationError",this.errorCode=t}}class g extends y{constructor(e,t=null){let r=e;r+=t?` ${t}`:" Run 'barndoor-login' to authenticate.",super(r),this.name="TokenError",this.helpText=t}}class v extends g{}class _ extends g{}class w extends m{constructor(e,t){let r;const n=t.toString().toLowerCase();r=n.includes("timeout")?`Connection to ${e} timed out. Please check your internet connection and try again.`:n.includes("connection refused")?`Could not connect to ${e}. The service may be unavailable.`:n.includes("name resolution")||n.includes("getaddrinfo")?`Could not resolve hostname for ${e}. Please check the URL and your DNS settings.`:`Failed to connect to ${e}. Please check your internet connection.`,super(r),this.url=e,this.originalError=t}}class $ extends m{constructor(e,t,r=null){super($._createUserFriendlyMessage(e,t,r)),this.name="HTTPError",this.statusCode=e,this.responseBody=r}static _createUserFriendlyMessage(e,t,r){const n=`Request failed (HTTP ${e})`;return 400===e?`${n}: Invalid request. Please check your input parameters.`:401===e?`${n}: Authentication failed. Please check your token or re-authenticate.`:403===e?`${n}: Access denied. You don't have permission for this operation.`:404===e?`${n}: Resource not found. Please check the server ID or URL.`:429===e?`${n}: Rate limit exceeded. Please wait before making more requests.`:e>=500&&e<600?`${n}: Server error. Please try again later or contact support.`:`${n}: ${t}`}}class b extends m{constructor(e,t=null){let r=`Server '${e}' not found`;r+=t?`. Available servers: ${t.join(", ")}`:". Use listServers() to see available servers.",super(r),this.serverIdentifier=e,this.availableServers=t}}let k=class extends y{};class E extends m{}class P extends m{}class S{constructor(e=30,t=10){this.read=1e3*e,this.connect=1e3*t}}class T{constructor(e=new S,t=3){this.timeoutConfig=e,this.maxRetries=t,this.closed=!1}async request(e,t,r={}){if(this.closed)throw new Error("HTTP client has been closed");const{headers:n={},json:o,params:s,...a}=r,i=this._buildUrl(t,s),c={method:e.toUpperCase(),headers:{"Content-Type":"application/json","User-Agent":"barndoor-js-sdk/0.1.0",...n},...a};let u;o&&(c.body=JSON.stringify(o));for(let t=0;t<=this.maxRetries;t++){const r=new AbortController,n=this.timeoutConfig.connect+this.timeoutConfig.read,o=setTimeout(()=>r.abort(),n),s={...c,signal:r.signal};try{const e=await globalThis.fetch(i,s);if(clearTimeout(o),!e.ok){let t="";try{const r=e;"function"==typeof r.text?t=await r.text():"function"==typeof r.json&&(t=JSON.stringify(await r.json()))}catch{}throw new $(e.status,e.statusText,t)}let t="";const r=e,n=r&&r.headers;let a;return n&&("function"==typeof n.get?t=n.get("content-type")||n.get("Content-Type")||"":"object"==typeof n&&(t=n["content-type"]||n["Content-Type"]||"")),a=t.includes("application/json")||!t&&"function"==typeof r.json?await e.json():t.includes("text/")||!t&&"function"==typeof r.text?await e.text():"function"==typeof r.arrayBuffer?await e.arrayBuffer():e,a}catch(r){if(clearTimeout(o),r instanceof Error&&"AbortError"===r.name){const e=this.timeoutConfig.connect+this.timeoutConfig.read;u=new P(`Request to ${i} timed out after ${e}ms`)}else if(r instanceof $){if(r.statusCode>=400&&r.statusCode<500)throw r;if(!(r.statusCode>=500&&r.statusCode<600))throw r;{const t=e.toUpperCase();if(!("GET"===t||"HEAD"===t||"OPTIONS"===t))throw r;u=r}}else u=r instanceof Error&&"TypeError"===r.name&&r.message.includes("fetch")?new w(i,r):r instanceof Error?r:new Error(String(r));if(t===this.maxRetries)break;const n=Math.min(1e3*Math.pow(2,t),1e4);await this._sleep(n)}}throw u||(u=new Error(`Request to ${i} failed after ${this.maxRetries+1} attempts with no specific error`)),u}_buildUrl(e,t){if(!t||0===Object.keys(t).length)return e;const r=new URL(e);return Object.entries(t).forEach(([e,t])=>{null!=t&&r.searchParams.append(e,String(t))}),r.toString()}_sleep(e){return new Promise(t=>setTimeout(t,e))}async close(){this.closed=!0}async aclose(){await this.close()}}class I{constructor(e){if(this.id=e.id,this.name=e.name,this.slug=e.slug,this.provider=e.provider??null,this.connection_status=e.connection_status,!(this.id&&this.name&&this.slug&&this.connection_status))throw new Error("ServerSummary missing required fields")}static fromApiResponse(e){return new I(e)}}class x extends I{constructor(e){super(e),this.url=e.url??null}static fromApiResponse(e){return new x(e)}}class N{constructor(e){if(this.agent_token=e.agent_token,this.expires_in=e.expires_in,!this.agent_token||"number"!=typeof this.expires_in)throw new Error("AgentToken missing required fields")}static fromApiResponse(e){return new N(e)}}const C={production:{issuer:"https://auth.barndoor.ai/realms/barndoor",audience:"https://barndoor.ai/",baseUrl:"https://{org_slug}.platform.barndoor.ai"},uat:{issuer:"https://auth.barndooruat.com/realms/barndoor",audience:"https://barndoor.ai/",baseUrl:"https://{org_slug}.trial.barndooruat.com"},dev:{issuer:"https://auth.barndoordev.com/realms/barndoor",audience:"https://barndoor.ai/",baseUrl:"https://{org_slug}.platform.barndoordev.com"},"enterprise-production":{issuer:"https://auth.barndoor.ai",audience:"https://barndoor.ai/",baseUrl:"https://{org_slug}.mcp.barndoor.ai"},"enterprise-uat":{issuer:"https://auth.barndooruat.com",audience:"https://barndoor.ai/",baseUrl:"https://{org_slug}.mcp.barndooruat.com"},"enterprise-dev":{issuer:"https://auth.barndoordev.com",audience:"https://barndoor.ai/",baseUrl:"https://{org_slug}.mcp.barndoordev.com"},localdev:{issuer:"http://localhost:8080/realms/barndoor",audience:"https://barndoor.ai/",baseUrl:"http://localhost:8000"}},j="undefined"!=typeof window&&void 0!==window.document,R="undefined"==typeof window&&"undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node;function O(e,t=""){return R?process.env[e]??t:j&&window.ENV?window.ENV[e]??t:t}class z{constructor(e={}){const t=e.environment??(O("MODE")||O("BARNDOOR_ENV")||"production");this.environment={production:"production",prod:"production",uat:"uat",dev:"dev",development:"dev","enterprise-production":"enterprise-production","enterprise-prod":"enterprise-production","enterprise-uat":"enterprise-uat","enterprise-dev":"enterprise-dev",enterprise:"enterprise-production",localdev:"localdev",local:"localdev"}[t.toLowerCase()]??"production";const r=C[this.environment]??C.production,n=O("AUTH_URL"),o=e.authDomain??O("AUTH_DOMAIN");e.authIssuer?this.authIssuer=e.authIssuer:this.authIssuer=n||(o?o.startsWith("http")?o:`https://${o}`:r.issuer),this.clientId=e.clientId??(O("AGENT_CLIENT_ID")||O("AUTH_CLIENT_ID")||""),this.clientSecret=e.clientSecret??(O("AGENT_CLIENT_SECRET")||O("AUTH_CLIENT_SECRET")||""),this.apiAudience=e.apiAudience??(O("API_AUDIENCE")||r.audience),this.promptForLogin=e.promptForLogin??!1,this.skipLoginLocal=e.skipLoginLocal??!1,this.baseUrl=e.baseUrl??(O("BARNDOOR_API")||O("BARNDOOR_URL")||r.baseUrl)}get authDomain(){let e=this.authIssuer;return e.startsWith("https://")?e=e.slice(8):e.startsWith("http://")&&(e=e.slice(7)),e}static getStaticConfig(){return new z}static getDynamicConfig(e,t={}){const{requireOrganization:r=!0,fallbackOrganizationId:n}=t,o=new z,s=A(e);if(s.hasOrganization){const e=String(s.organizationId??"").trim().toLowerCase();if(!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(e))throw new E("Invalid organization subdomain format from token");return o.baseUrl=o.baseUrl.replace("{org_slug}",e),o}if(n)return o.baseUrl=o.baseUrl.replace("{org_slug}",n),o;if(r){const e=s.error||"No organization information found in token";throw new E(`Failed to extract organization ID from token: ${e}. This token may be for a personal account or may be missing organization claims. Consider using getStaticConfig() for organization-independent operations or provide a fallbackOrganizationId in the options.`)}return o}validate(){if(!this.authIssuer||""===this.authIssuer.trim())throw new E("authIssuer is required");if(!this.apiAudience||""===this.apiAudience.trim())throw new E("apiAudience is required");if(!this.baseUrl||""===this.baseUrl.trim())throw new E("baseUrl is required")}}function A(e){try{const t=e.split(".");if(3!==t.length)return{hasOrganization:!1,error:"Invalid JWT format - expected 3 parts separated by dots"};let r,n;try{r=JSON.parse(function(e){if("undefined"!=typeof globalThis&&globalThis.atob)return globalThis.atob(e);if("undefined"!=typeof Buffer)return Buffer.from(e,"base64").toString("utf-8");throw new Error("No base64 decode function available")}(t[1].replace(/-/g,"+").replace(/_/g,"/")))}catch(e){return{hasOrganization:!1,error:"Failed to parse JWT payload - token may be corrupted"}}if(r.user&&"object"==typeof r.user&&(n=r.user.organization_name??r.user.organization_slug),!n){const e=r["https://barndoor.ai/organization_slug"],t=r.organization_slug,o=r.organization_name,s=r.org_slug;n=("string"==typeof o?o:void 0)??("string"==typeof e?e:void 0)??("string"==typeof t?t:void 0)??("string"==typeof s?s:void 0)}return n&&"string"==typeof n&&""!==n.trim()?{organizationId:n.trim(),hasOrganization:!0}:{hasOrganization:!1,error:"No organization information found in token. This token may be for a personal account or may be missing organization claims."}}catch(e){return{hasOrganization:!1,error:`Failed to decode JWT token: ${e instanceof Error?e.message:String(e)}`}}}function M(){return z.getStaticConfig()}function D(e,t){return z.getDynamicConfig(e,t)}function U(e){return A(e)}function q(e){return A(e).hasOrganization}let V={debug:(e,...t)=>{"undefined"!=typeof console&&console.debug&&console.debug(e,...t)},info:(e,...t)=>{"undefined"!=typeof console&&console.info&&console.info(e,...t)},warn:(e,...t)=>{"undefined"!=typeof console&&console.warn&&console.warn(e,...t)},error:(e,...t)=>{"undefined"!=typeof console&&console.error&&console.error(e,...t)}};function F(e){V=e}function L(){return V}function K(e){return{debug:(t,...r)=>{V.debug(`[${e}] ${t}`,...r)},info:(t,...r)=>{V.info(`[${e}] ${t}`,...r)},warn:(t,...r)=>{V.warn(`[${e}] ${t}`,...r)},error:(t,...r)=>{V.error(`[${e}] ${t}`,...r)}}}function H(e,...t){V.debug(e,...t)}function Z(e,...t){V.info(e,...t)}function G(e,...t){V.warn(e,...t)}function B(e,...t){V.error(e,...t)}const J=K("token"),W=new Map;async function Q(e){if(W.has(e))return W.get(e);const t=e.replace(/\/$/,""),r=`${t}/.well-known/openid-configuration`;try{const t=new AbortController,n=setTimeout(()=>t.abort(),5e3);try{const n=await fetch(r,{signal:t.signal});if(!n.ok)throw new Error(`HTTP ${n.status}`);const o=await n.json();return W.set(e,o),J.debug(`OIDC discovery successful for ${e}`),o}finally{clearTimeout(n)}}catch(r){return J.warn(`OIDC discovery failed for ${e}:`,r),t.includes("/realms/")?{issuer:t,token_endpoint:`${t}/protocol/openid-connect/token`,authorization_endpoint:`${t}/protocol/openid-connect/auth`,userinfo_endpoint:`${t}/protocol/openid-connect/userinfo`,jwks_uri:`${t}/protocol/openid-connect/certs`}:{issuer:t,token_endpoint:`${t}/oauth/token`,authorization_endpoint:`${t}/authorize`,userinfo_endpoint:`${t}/userinfo`,jwks_uri:`${t}/.well-known/jwks.json`}}}function Y(){W.clear()}function X(e){console.warn("setTokenLogger is deprecated. Use setLogger from the main logging module instead.")}function ee(e){try{const t=e.split(".");if(3!==t.length)return null;const r=JSON.parse(function(e){const t=e.replace(/-/g,"+").replace(/_/g,"/");if(R)return Buffer.from(t,"base64").toString("utf8");if("undefined"!=typeof globalThis&&globalThis.atob)return globalThis.atob(t);throw new Error("No base64 decode function available")}(t[1]));return r}catch(e){return null}}function te(e,t){return"undefined"!=typeof AbortSignal&&"timeout"in AbortSignal?e:Promise.race([e,new Promise((e,r)=>{setTimeout(()=>r(new Error("Request timeout")),t)})])}var re;!function(e){e.VALID="valid",e.EXPIRED="expired",e.INVALID="invalid"}(re||(re={}));const ne=new Map;class oe{constructor(e){this.lockAcquired=!1,this.lockFile=`${e}.lock`}async acquire(e=5e3){if(!R)return;const t=Date.now();for(;Date.now()-t<e;)try{return await o.writeFile(this.lockFile,process.pid.toString(),{flag:"wx"}),void(this.lockAcquired=!0)}catch(e){if(!e||"object"!=typeof e||!("code"in e)||"EEXIST"!==e.code)throw new g(`Failed to acquire file lock: ${e}`);try{const e=await o.readFile(this.lockFile,"utf8"),t=parseInt(e.trim(),10);try{process.kill(t,0),await new Promise(e=>setTimeout(e,100));continue}catch(e){if(e&&"object"==typeof e&&"code"in e){const t=e;if("EPERM"===t.code){await new Promise(e=>setTimeout(e,100));continue}if("ESRCH"===t.code){await o.unlink(this.lockFile).catch(()=>{});continue}}await o.unlink(this.lockFile).catch(()=>{});continue}}catch{await o.unlink(this.lockFile).catch(()=>{});continue}}throw new g("Failed to acquire file lock: timeout")}async release(){if(R&&this.lockAcquired)try{await o.unlink(this.lockFile),this.lockAcquired=!1}catch(e){console.debug("Failed to release file lock:",e)}}}class se{}class ae extends se{constructor(){super(),this.storageKey="barndoor_token"}async loadToken(){try{const e=localStorage.getItem(this.storageKey);return e?JSON.parse(e):null}catch(e){return J.warn("Failed to load token from localStorage:",e),null}}async saveToken(e){try{localStorage.setItem(this.storageKey,JSON.stringify(e))}catch(e){const t=e instanceof Error?e.message:String(e);throw new g(`Failed to save token: ${t}`)}}async clearToken(){try{localStorage.removeItem(this.storageKey)}catch(e){J.warn("Failed to clear token from localStorage:",e)}}}class ie extends se{constructor(){super(),this.tokenFile=this._getTokenFilePath()}_getTokenFilePath(){if(R)return t.join(e.homedir(),".barndoor","token.json");throw new Error("NodeTokenStorage can only be used in Node.js environment")}async loadToken(){if(!R)throw new Error("NodeTokenStorage can only be used in Node.js environment");const e=new oe(this.tokenFile);try{await e.acquire();const t=await o.readFile(this.tokenFile,"utf8");return JSON.parse(t)}catch(e){return e&&"object"==typeof e&&"code"in e&&"ENOENT"===e.code||J.warn("Failed to load token from file:",e),null}finally{await e.release()}}async saveToken(e){if(!R)throw new Error("NodeTokenStorage can only be used in Node.js environment");const r=new oe(this.tokenFile);try{await r.acquire(),await o.mkdir(t.dirname(this.tokenFile),{recursive:!0}),await o.writeFile(this.tokenFile,JSON.stringify(e,null,2)),await o.chmod(this.tokenFile,384),J.debug("Token saved to storage")}catch(e){const t=e instanceof Error?e.message:String(e);throw new g(`Failed to save token: ${t}`)}finally{await r.release()}}async clearToken(){if(!R)throw new Error("NodeTokenStorage can only be used in Node.js environment");try{await o.unlink(this.tokenFile)}catch(e){e&&"object"==typeof e&&"code"in e&&"ENOENT"!==e.code&&J.warn("Failed to clear token file:",e)}}}function ce(){if(j)return new ae;if(R)return new ie;throw new Error("Unsupported environment for token storage")}async function ue(e,t,r){try{const n=await async function(e){if(ne.has(e))return ne.get(e);try{const t=(await Q(e)).jwks_uri;if(!t)throw J.debug(`No jwks_uri in OIDC config for ${e}`),new Error("No jwks_uri available");const r=a(new URL(t));return ne.set(e,r),r}catch(t){throw J.debug(`Failed to get JWKS for ${e}:`,t),t}}(t),o=`${t.replace(/\/$/,"")}/`;return await s(e,n,{issuer:o,audience:r}),J.debug("Token verified locally using JWKS"),re.VALID}catch(e){return e&&"object"==typeof e&&"code"in e&&"ERR_JWT_EXPIRED"===e.code?(J.debug("Token expired (verified locally)"),re.EXPIRED):(J.debug("JWT verification failed:",e),re.INVALID)}}class le{constructor(){this._locked=!1,this._waitQueue=[]}async acquire(){return new Promise(e=>{this._locked?this._waitQueue.push(e):(this._locked=!0,e())})}release(){if(this._waitQueue.length>0){const e=this._waitQueue.shift();e&&e()}else this._locked=!1}async withLock(e){await this.acquire();try{return await e()}finally{this.release()}}}class de{constructor(e){this._refreshMutex=new le,this.storage=ce()}async getValidToken(){return this._refreshMutex.withLock(async()=>{const e=await this.storage.loadToken();if(!e)throw new g("No token found. Please authenticate.");try{if(this._shouldRefreshToken(e)&&e.refresh_token){J.debug("Proactively refreshing token before expiration");const t=await this._refreshToken(e),r={...e,...t};return await this.storage.saveToken(r),r.access_token}const t=await this._validateOrRefresh(e);return await this.storage.saveToken(t),t.access_token}catch(e){throw J.error("Token validation/refresh failed:",e),new v("Token expired and refresh failed. Please re-authenticate.")}})}_shouldRefreshToken(e){const t=ee(e.access_token);if(!t?.exp)return!0;const r=Math.floor(Date.now()/1e3);return t.exp-r<300}async _validateOrRefresh(e){const t=e.access_token,r=M(),n=await ue(t,r.authIssuer,r.apiAudience);if(n===re.VALID)return J.debug("Token validated locally"),e;if(n===re.INVALID&&(J.debug("Local validation failed, trying remote"),await this._isTokenValidRemote(t)))return J.debug("Token validated remotely"),e;if(J.info("Token invalid or expired, attempting refresh"),e.refresh_token){const t=await this._refreshToken(e);return{...e,...t}}throw new v("Token expired and no refresh token available")}async _isTokenValidRemote(e){try{const t=M(),r=(await Q(t.authIssuer)).userinfo_endpoint,n=fetch(r,{headers:{Authorization:`Bearer ${e}`},..."undefined"!=typeof AbortSignal&&"timeout"in AbortSignal?{signal:AbortSignal.timeout(5e3)}:{}});return(await te(n,5e3)).ok}catch(e){return J.debug("Remote token validation failed:",e),!1}}async _refreshToken(e){const t=e.refresh_token;if(!t)throw new g("No refresh token available");const r=M();if(j&&r.clientSecret)throw new g("Refresh flow requires a confidential client; run interactive login again.");const n=(await Q(r.authIssuer)).token_endpoint,o=new URLSearchParams({grant_type:"refresh_token",client_id:r.clientId,refresh_token:t});r.clientSecret&&!j&&o.set("client_secret",r.clientSecret);try{const e=fetch(n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString(),..."undefined"!=typeof AbortSignal&&"timeout"in AbortSignal?{signal:AbortSignal.timeout(15e3)}:{}}),t=await te(e,15e3);if(400===t.status){let e="Invalid refresh token";try{e=(await t.json()).error_description||e}catch{}throw J.warn(`Refresh token invalid: ${e}`),new v(`Refresh token expired or invalid: ${e}`)}if(429===t.status)throw J.warn("Rate limited during token refresh"),new g("Rate limited during token refresh. Please try again later.");if(t.status>=500)throw J.warn(`Auth server error during refresh: ${t.status}`),new g(`Auth server temporarily unavailable (HTTP ${t.status})`);if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);return await t.json()}catch(e){if(e instanceof g||e instanceof v)throw e;if(e&&"object"==typeof e&&"name"in e){if("TimeoutError"===e.name||"AbortError"===e.name)throw J.warn("Timeout during token refresh"),new g("Token refresh timed out. Please check your connection.");if("TypeError"===e.name&&"message"in e&&"string"==typeof e.message&&e.message.includes("fetch"))throw J.warn(`Network error during token refresh: ${e.message}`),new g("Network error during token refresh. Please check your connection.")}J.error("Unexpected error during token refresh:",e);const t=e instanceof Error?e.message:String(e);throw new g(`Token refresh failed: ${t}`)}}}async function he(){try{const e=ce(),t=await e.loadToken();return t?.access_token??null}catch(e){return null}}async function pe(e){const t=ce();let r;r="string"==typeof e?{access_token:e}:e,await t.saveToken(r)}async function fe(){const e=ce();await e.clearToken()}async function me(e){try{const e=ce(),t=await e.loadToken();if(!t?.access_token)return!1;const r=M(),n=(await Q(r.authIssuer)).userinfo_endpoint,o=fetch(n,{headers:{Authorization:`Bearer ${t.access_token}`},..."undefined"!=typeof AbortSignal&&"timeout"in AbortSignal?{signal:AbortSignal.timeout(1e4)}:{}});return(await te(o,1e4)).ok}catch(e){return!1}}async function ye(e){try{const t=new de(e||"");return await t.getValidToken(),!0}catch(e){return J.warn("Token validation/refresh failed:",e),!1}}async function ge(e,t){try{const t=M(),r=await ue(e,t.authIssuer,t.apiAudience);if(r===re.VALID)return{valid:!0};if(r===re.INVALID)try{const r=(await Q(t.authIssuer)).userinfo_endpoint,n=fetch(r,{headers:{Authorization:`Bearer ${e}`},..."undefined"!=typeof AbortSignal&&"timeout"in AbortSignal?{signal:AbortSignal.timeout(5e3)}:{}});return{valid:(await te(n,5e3)).ok}}catch(e){return J.warn("Remote token validation failed:",e),{valid:!1}}return{valid:!1}}catch(e){return J.warn("Token validation failed:",e),{valid:!1}}}class ve{constructor(){this._codeVerifier=null,this._currentState=null,this._logger=K("pkce")}async buildAuthorizationUrl({domain:e,clientId:t,redirectUri:r,audience:n,scope:o="openid profile email",issuer:s}){this._codeVerifier=_e(32);const a=we(await async function(e){const t=(new TextEncoder).encode(e);if(j&&window.crypto&&window.crypto.subtle){const e=await window.crypto.subtle.digest("SHA-256",t);return new Uint8Array(e)}if(R){const t=i.createHash("sha256").update(e).digest();return new Uint8Array(t)}throw new Error("SHA256 not available in this environment")}(this._codeVerifier));this._currentState=_e(16);const c=new URLSearchParams({response_type:"code",client_id:t,redirect_uri:r,scope:o,audience:n,state:this._currentState,code_challenge:a,code_challenge_method:"S256"});let u;if(s){u=(await Q(s)).authorization_endpoint}else{if(!e)throw new k("Either issuer or domain must be provided");u=`https://${e}/authorize`}return`${u}?${c.toString()}`}async exchangeCodeForToken({domain:e,clientId:t,code:r,redirectUri:n,clientSecret:o,issuer:s}){const a=new URLSearchParams({grant_type:"authorization_code",client_id:t,code:r,redirect_uri:n});if(o&&a.set("client_secret",o),this._codeVerifier&&a.set("code_verifier",this._codeVerifier),!o&&!this._codeVerifier)throw new k("Either client_secret or PKCE verifier must be provided");let i;if(s){i=(await Q(s)).token_endpoint}else{if(!e)throw new k("Either issuer or domain must be provided");i=`https://${e}/oauth/token`}try{const e=await fetch(i,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:a.toString()});if(!e.ok){const t=await e.json().catch(()=>({}));throw this._logger.error("Token endpoint response:",t),new k(`Token exchange failed: ${t.error??t.error_description??e.statusText}`)}const t=await e.json();return this.clearState(),t}catch(e){if(e instanceof k)throw e;const t=e instanceof Error?e.message:String(e);throw new k(`Token exchange failed: ${t}`)}}validateState(e){return Boolean(this._currentState&&e===this._currentState)}clearState(){this._codeVerifier=null,this._currentState=null}getState(){return this._codeVerifier&&this._currentState?{codeVerifier:this._codeVerifier,codeChallenge:"",state:this._currentState,timestamp:Date.now()}:null}}function _e(e){const t=new Uint8Array(e);if(j&&window.crypto&&window.crypto.getRandomValues)window.crypto.getRandomValues(t);else{if(!R)throw new Error("Secure random generator not available for PKCE.");i.randomFillSync(t)}return we(t)}function we(e){const t=function(e){if("undefined"!=typeof globalThis&&globalThis.btoa)return globalThis.btoa(String.fromCharCode(...e));if("undefined"!=typeof Buffer)return Buffer.from(e).toString("base64");throw new Error("No base64 encode function available")}(e);return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function $e(e=52765){if(!R)throw new Error("Local callback server is only available in Node.js environment");const t=K("pkce"),r="undefined"!=typeof process&&process.env&&process.env.BARNDOOR_REDIRECT_HOST||"127.0.0.1",n=r.startsWith("http")?`${r}:${e}/cb`:`http://${r}:${e}/cb`,o=new Promise((r,o)=>{const s=c.createServer((e,n)=>{t.debug(`Callback server received request: ${e.method} ${e.url}`);const a=u.parse(e.url??"",!0);if(t.debug(`Parsed URL - pathname: ${a.pathname}, query:`,a.query),"/cb"===a.pathname){const{code:i,state:c,error:u,error_description:l}=a.query;t.debug(`Callback params - code: ${!!i}, state: ${!!c}, error: ${u}`),n.writeHead(200,{"Content-Type":"text/html"}),u?(t.error(`OAuth error: ${u} - ${l}`),n.end("\n <html>\n <body>\n <h1>Authentication Failed</h1>\n <p>Error: Authentication error occurred.</p>\n <p>Description: Please return to the application for details.</p>\n <p>You can close this window.</p>\n </body>\n </html>\n "),s.close(),o(new k(`OAuth error: ${u} - ${l}`))):i?(t.info("OAuth callback received successfully, closing server"),n.end("\n <html>\n <body>\n <h1>Authentication Successful</h1>\n <p>You can close this window and return to your application.</p>\n <script>\n console.log('Authentication callback received. You can close this window.');\n setTimeout(() => window.close(), 1000);\n <\/script>\n </body>\n </html>\n "),s.close(),r([i,c])):(t.warn("No authorization code received in callback"),t.warn(`Full URL: ${e.url}`),t.warn("Query params:",a.query),n.end(`\n <html>\n <body>\n <h1>Authentication Failed</h1>\n <p>No authorization code received.</p>\n <p>Full URL: ${e.url}</p>\n <p>You can close this window.</p>\n </body>\n </html>\n `),s.close(),o(new k("No authorization code received")))}else t.debug(`404 for path: ${a.pathname}`),n.writeHead(404,{"Content-Type":"text/plain"}),n.end("Not found")});s.listen(e,"0.0.0.0",()=>{console.log(`OAuth callback server listening on ${n}`)}),s.on("error",e=>{o(new k(`Failed to start callback server: ${e.message}`))}),s.on("connection",e=>{t.debug(`New connection from ${e.remoteAddress}:${e.remotePort}`)})});return[n,o]}const be=K("client-credentials");async function ke(e){const{timeoutMs:t=15e3}=e,{tokenEndpoint:r,body:n}=await async function(e){const{clientId:t,clientSecret:r,audience:n,issuer:o,domain:s}=e;let a;if(o)a=(await Q(o)).token_endpoint;else{if(!s)throw new k("Either 'issuer' or 'domain' must be provided");a=`https://${s}/oauth/token`}return{tokenEndpoint:a,body:new URLSearchParams({grant_type:"client_credentials",client_id:t,client_secret:r,audience:n})}}(e),o=new AbortController,s=setTimeout(()=>o.abort(),t);try{const e=await fetch(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString(),signal:o.signal});if(!e.ok){const t=await e.json().catch(()=>({}));throw be.error("Client-credentials token endpoint error:",t),new k(`Client-credentials grant failed: ${t.error_description??t.error??e.statusText}`)}const t=await e.json();if(!t.access_token)throw new k("Client-credentials grant: response missing access_token");return t.access_token}catch(e){if(e instanceof k)throw e;if(e instanceof Error&&"AbortError"===e.name)throw new k(`Client-credentials grant timed out after ${t}ms`);const r=e instanceof Error?e.message:String(e);throw new k(`Client-credentials grant failed: ${r}`)}finally{clearTimeout(s)}}class Ee{constructor(e,t={}){this._credentials=null,this._logger=K("client");const{token:r,timeout:n=30,maxRetries:o=3}=t;this.base=this._validateUrl(e,"API base URL").replace(/\/$/,"");const s=Object.prototype.hasOwnProperty.call(t,"token");if(this._token=s?this._validateToken(r):null,"number"!=typeof n||n<=0)throw new E("timeout must be a positive number");if(!Number.isInteger(o)||o<0)throw new E("maxRetries must be a non-negative integer");const a=new S(n,n/3);this._http=new T(a,o),this._tokenValidated=!1,this._closed=!1,this._logger.info(`Initialized BarndoorSDK for ${this.base}`)}static async fromClientCredentials(e,t){const{timeout:r,maxRetries:n,...o}=t,s={token:await ke(o)};void 0!==r&&(s.timeout=r),void 0!==n&&(s.maxRetries=n);const a=new Ee(e,s);return a._credentials={...o},a._tokenValidated=!0,a}get token(){if(!this._token)throw new Error("No token available. Call authenticate() first or provide token in constructor.");return this._token}async authenticate(e){this._token=this._validateToken(e),this._tokenValidated=!1,await this.ensureValidToken(),this._logger.info("Authentication successful")}_validateUrl(e,t){if(!e||"string"!=typeof e)throw new E(`${t} must be a non-empty string`);try{return new URL(e),e}catch(e){throw new E(`${t} must be a valid URL`)}}_validateToken(e){if(!e||"string"!=typeof e)throw new g("Token must be a non-empty string");if(3!==e.split(".").length)throw new g("Token must be a valid JWT");return e}_ensureNotClosed(){if(this._closed)throw new Error("SDK has been closed. Create a new instance or use as context manager.")}async _req(e,t,r={}){this._ensureNotClosed(),await this.ensureValidToken(),await this._maybeRefreshM2MToken();const n=`${this.base}${t}`,o=()=>{const e={...r.headers??{}};return e.Authorization=`Bearer ${this.token}`,{...r,headers:e}};try{return await this._http.request(e,n,o())}catch(t){if(t instanceof $&&401===t.statusCode&&null!==this._credentials)return this._logger.info("M2M token rejected (401); refreshing and retrying once"),await this._refreshM2MToken(),await this._http.request(e,n,o());throw t}}async _maybeRefreshM2MToken(){null!==this._credentials&&function(e,t){const r=e.split(".");if(3!==r.length)return!0;const n=r[1];if(!n)return!0;let o;try{const e=n.replace(/-/g,"+").replace(/_/g,"/"),t="undefined"!=typeof Buffer?Buffer.from(e,"base64").toString("utf8"):globalThis.atob(e);o=JSON.parse(t)}catch{return!0}const s=o.exp;return"number"!=typeof s||s-Date.now()/1e3<=t}(this.token,60)&&(this._logger.debug("M2M token near expiry; refreshing"),await this._refreshM2MToken())}async _refreshM2MToken(){if(null===this._credentials)throw new Error("_refreshM2MToken() called on an SDK not created via BarndoorSDK.fromClientCredentials()");this._token=await ke(this._credentials),this._tokenValidated=!0}async validateCachedToken(){if(!this.token)return!1;try{const e=M(),t=(await Q(e.authIssuer)).userinfo_endpoint,r=new AbortController,n=setTimeout(()=>r.abort(),1e4);try{const e=(await fetch(t,{headers:{Authorization:`Bearer ${this.token}`},signal:r.signal})).ok;return e&&(this._tokenValidated=!0),e}finally{clearTimeout(n)}}catch(e){return!1}}async ensureValidToken(){if(!this._token)throw new Error("No token available. Call authenticate() first or provide token in constructor.");if(this._tokenValidated)return;const e=(R?process.env.BARNDOOR_ENV:"")??"";if(["test","ci"].includes(e.toLowerCase()))return void(this._tokenValidated=!0);if(!await this.validateCachedToken())throw new g("Token validation failed. Please re-authenticate.");this._tokenValidated=!0}async listServers(){this._logger.debug("Fetching server list");try{const e=[];let t=1;for(;null!==t;){const r=1===t?"/api/servers":`/api/servers?page=${t}`,n=await this._req("GET",r),o=n.data.map(e=>I.fromApiResponse(e));e.push(...o),t=n.pagination.next_page}return this._logger.info(`Retrieved ${e.length} servers total`),e}catch(e){throw this._logger.error("Failed to list servers:",e),e}}async getServer(e){const t=this._validateServerId(e);this._logger.info(`Fetching server details for ${t}`);const r=this._isUuid(t)?`/api/servers/${t}`:`/api/servers/by-slug/${t}`,n=await this._req("GET",r);return x.fromApiResponse(n)}async initiateConnection(e,t){const r=this._validateServerId(e);let n;t&&(n=this._validateUrl(t,"Return URL")),this._logger.info(`Initiating connection for server ${r}`);const o=n?{return_url:n}:void 0;try{const e=this._isUuid(r)?`/api/servers/${r}/connect`:`/api/servers/by-slug/${r}/connect`;return await this._req("POST",e,{params:o,json:{}})}catch(e){if(e instanceof $&&500===e.statusCode&&e.responseBody?.includes("OAuth server configuration not found"))throw new Error("Server is missing OAuth configuration. Ask an admin to configure credentials before initiating a connection.");throw e}}async getConnectionStatus(e){const t=this._validateServerId(e);this._logger.info(`Checking connection status for server ${t}`);const r=this._isUuid(t)?`/api/servers/${t}/connection`:`/api/servers/by-slug/${t}/connection`;return(await this._req("GET",r)).status}async disconnectServer(e){const t=this._validateServerId(e);this._logger.info(`Disconnecting from server ${t}`);try{const e=this._isUuid(t)?`/api/servers/${t}/connection`:`/api/servers/by-slug/${t}/connection`;await this._req("DELETE",e),this._logger.info(`Successfully disconnected from server ${t}`)}catch(e){if(e instanceof $&&404===e.statusCode)throw new Error(`Connection not found for server ${t}. Server may not be connected.`);throw e}}_validateServerId(e){if(!e||"string"!=typeof e)throw new Error("Server ID must be a non-empty string");if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)&&!/^[a-z0-9-]+$/.test(e))throw new Error("Server ID must be a valid UUID or slug (lowercase letters, numbers, and hyphens only)");return e}_isUuid(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}async listPolicies(e=1,t=10,r={}){if(!Number.isInteger(e)||e<1)throw new Error("Page must be a positive integer");if(!Number.isInteger(t)||t<1||t>1e3)throw new Error("Limit must be a positive integer between 1 and 1000");this._logger.debug(`Listing policies (page=${e}, limit=${t})`);const n={page:e,limit:t,...r};return this._req("GET","/api/v2/policies",{params:n})}async getPolicy(e){if(!e||"string"!=typeof e)throw new Error("Policy ID must be a non-empty string");if(!this._isUuid(e))throw new Error("Policy ID must be a valid UUID");return this._logger.debug(`Fetching policy details for ${e}`),this._req("GET",`/api/v2/policies/${e}`)}async createPolicy(e){if(!e||"object"!=typeof e)throw new Error("Policy data must be a non-empty object");return this._logger.debug("Creating new policy"),this._req("POST","/api/v2/policies",{json:e})}async updatePolicy(e,t){if(!e||"string"!=typeof e)throw new Error("Policy ID must be a non-empty string");if(!this._isUuid(e))throw new Error("Policy ID must be a valid UUID");if(!t||"object"!=typeof t)throw new Error("Policy data must be a non-empty object");return this._logger.debug(`Updating policy ${e}`),this._req("PATCH",`/api/v2/policies/${e}`,{json:t})}async clonePolicy(e,t){if(!e||"string"!=typeof e)throw new Error("Policy ID must be a non-empty string");if(!this._isUuid(e))throw new Error("Policy ID must be a valid UUID");if(!t||"string"!=typeof t)throw new Error("New name must be a non-empty string");return this._logger.debug(`Cloning policy ${e} with new name: ${t}`),this._req("POST",`/api/v2/policies/${e}/clone`,{json:{name:t}})}async validatePolicy(e){if(!e||"object"!=typeof e)throw new Error("Validation data must be a non-empty object");return this._logger.debug("Validating policy configuration"),this._req("POST","/api/v2/policies/validate",{json:e})}async getPolicySummary(){return this._logger.debug("Fetching policy summary"),this._req("GET","/api/v2/policies/summary")}async getPolicyFilterDefinitions(){return this._logger.debug("Fetching policy filter definitions"),this._req("GET","/api/v2/policies/filter-definitions")}async close(){this._closed||(await this._http.close(),this._closed=!0)}async aclose(){await this.close()}async ensureServerConnected(t,r={}){const{pollSeconds:n=60}=r;if(!R)throw new Error("ensureServerConnected requires Node.js environment for browser opening");let o;try{o=await this.getServer(t)}catch(e){if(e instanceof $&&404===e.statusCode)throw new b(t);throw e}if("connected"===o.connection_status)return;const s=o.slug||t,a=(await this.initiateConnection(s)).auth_url;if(!a)throw new Error("Registry did not return auth_url");const i=e.platform();let c;try{c=new URL(a)}catch{throw new Error("Invalid auth_url returned by server")}if("https:"!==c.protocol&&("http:"!==c.protocol||"localhost"!==c.hostname&&"127.0.0.1"!==c.hostname))throw new Error("Auth URL must use HTTPS (http allowed only for localhost)");try{"darwin"===i?d("open",[a],{detached:!0,stdio:"ignore"}).unref():"win32"===i?d("powershell",["-NoProfile","Start-Process",a],{detached:!0,stdio:"ignore"}).unref():d("xdg-open",[a],{detached:!0,stdio:"ignore"}).unref()}catch(e){this._logger.warn("Failed to open browser",e)}for(let e=0;e<n;e++){if("connected"===await this.getConnectionStatus(s))return;await new Promise(e=>setTimeout(e,1e3))}throw new Error("OAuth connection was not completed in time")}}const Pe=Object.freeze({status:"aborted"});function Se(e,t,r){function n(r,n){var o;Object.defineProperty(r,"_zod",{value:r._zod??{},enumerable:!1}),(o=r._zod).traits??(o.traits=new Set),r._zod.traits.add(e),t(r,n);for(const e in a.prototype)e in r||Object.defineProperty(r,e,{value:a.prototype[e].bind(r)});r._zod.constr=a,r._zod.def=n}const o=r?.Parent??Object;class s extends o{}function a(e){var t;const o=r?.Parent?new s:this;n(o,e),(t=o._zod).deferred??(t.deferred=[]);for(const e of o._zod.deferred)e();return o}return Object.defineProperty(s,"name",{value:e}),Object.defineProperty(a,"init",{value:n}),Object.defineProperty(a,Symbol.hasInstance,{value:t=>!!(r?.Parent&&t instanceof r.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(a,"name",{value:e}),a}class Te extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const Ie={};function xe(e){return e&&Object.assign(Ie,e),Ie}function Ne(e,t){return"bigint"==typeof t?t.toString():t}function Ce(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function je(e){return null==e}function Re(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function Oe(e,t,r){Object.defineProperty(e,t,{get(){{const n=r();return e[t]=n,n}},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function ze(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Ae(e){return JSON.stringify(e)}const Me=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function De(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const Ue=Ce(()=>{if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function qe(e){if(!1===De(e))return!1;const t=e.constructor;if(void 0===t)return!0;const r=t.prototype;return!1!==De(r)&&!1!==Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")}const Ve=new Set(["string","number","symbol"]);function Fe(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Le(e,t,r){const n=new e._zod.constr(t??e._zod.def);return t&&!r?.parent||(n._zod.parent=e),n}function Ke(e){const t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==t?.message){if(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}const He={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Ze(e,t=0){for(let r=t;r<e.issues.length;r++)if(!0!==e.issues[r]?.continue)return!0;return!1}function Ge(e,t){return t.map(t=>{var r;return(r=t).path??(r.path=[]),t.path.unshift(e),t})}function Be(e){return"string"==typeof e?e:e?.message}function Je(e,t,r){const n={...e,path:e.path??[]};if(!e.message){const o=Be(e.inst?._zod.def?.error?.(e))??Be(t?.error?.(e))??Be(r.customError?.(e))??Be(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function We(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function Qe(...e){const[t,r,n]=e;return"string"==typeof t?{message:t,code:"custom",input:r,inst:n}:{...t}}const Ye=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get:()=>JSON.stringify(t,Ne,2),enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Xe=Se("$ZodError",Ye),et=Se("$ZodError",Ye,{Parent:Error});const tt=e=>(t,r,n,o)=>{const s=n?Object.assign(n,{async:!1}):{async:!1},a=t._zod.run({value:r,issues:[]},s);if(a instanceof Promise)throw new Te;if(a.issues.length){const t=new(o?.Err??e)(a.issues.map(e=>Je(e,s,xe())));throw Me(t,o?.callee),t}return a.value},rt=e=>async(t,r,n,o)=>{const s=n?Object.assign(n,{async:!0}):{async:!0};let a=t._zod.run({value:r,issues:[]},s);if(a instanceof Promise&&(a=await a),a.issues.length){const t=new(o?.Err??e)(a.issues.map(e=>Je(e,s,xe())));throw Me(t,o?.callee),t}return a.value},nt=e=>(t,r,n)=>{const o=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Te;return s.issues.length?{success:!1,error:new(e??Xe)(s.issues.map(e=>Je(e,o,xe())))}:{success:!0,data:s.value}},ot=nt(et),st=e=>async(t,r,n)=>{const o=n?Object.assign(n,{async:!0}):{async:!0};let s=t._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(e=>Je(e,o,xe())))}:{success:!0,data:s.value}},at=st(et),it=/^[cC][^\s-]{8,}$/,ct=/^[0-9a-z]+$/,ut=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,lt=/^[0-9a-vA-V]{20}$/,dt=/^[A-Za-z0-9]{27}$/,ht=/^[a-zA-Z0-9_-]{21}$/,pt=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,ft=/^([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})$/,mt=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)$/,yt=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;const gt=/^(?:(?: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])$/,vt=/^(([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})$/,_t=/^((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])$/,wt=/^(([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])$/,$t=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,bt=/^[A-Za-z0-9_-]*$/,kt=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Et=/^\+(?:[0-9]){6,14}[0-9]$/,Pt="(?:(?:\\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])))",St=new RegExp(`^${Pt}$`);function Tt(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+)?)?`}const It=/^\d+$/,xt=/^-?\d+(?:\.\d+)?/i,Nt=/true|false/i,Ct=/null/i,jt=/^[^A-Z]*$/,Rt=/^[^a-z]*$/,Ot=Se("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),zt={number:"number",bigint:"bigint",object:"date"},At=Se("$ZodCheckLessThan",(e,t)=>{Ot.init(e,t);const r=zt[typeof t.value];e._zod.onattach.push(e=>{const r=e._zod.bag,n=(t.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<n&&(t.inclusive?r.maximum=t.value:r.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Mt=Se("$ZodCheckGreaterThan",(e,t)=>{Ot.init(e,t);const r=zt[typeof t.value];e._zod.onattach.push(e=>{const r=e._zod.bag,n=(t.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>n&&(t.inclusive?r.minimum=t.value:r.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Dt=Se("$ZodCheckMultipleOf",(e,t)=>{Ot.init(e,t),e._zod.onattach.push(e=>{var r;(r=e._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof r.value?r.value%t.value===BigInt(0):0===function(e,t){const r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n;return Number.parseInt(e.toFixed(o).replace(".",""))%Number.parseInt(t.toFixed(o).replace(".",""))/10**o}(r.value,t.value))||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),Ut=Se("$ZodCheckNumberFormat",(e,t)=>{Ot.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),n=r?"int":"number",[o,s]=He[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=It)}),e._zod.check=a=>{const i=a.value;if(r){if(!Number.isInteger(i))return void a.issues.push({expected:n,format:t.format,code:"invalid_type",input:i,inst:e});if(!Number.isSafeInteger(i))return void(i>0?a.issues.push({input:i,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort}):a.issues.push({input:i,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort}))}i<o&&a.issues.push({origin:"number",input:i,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),i>s&&a.issues.push({origin:"number",input:i,code:"too_big",maximum:s,inst:e})}}),qt=Se("$ZodCheckMaxLength",(e,t)=>{var r;Ot.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!je(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const r=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<r&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{const n=r.value;if(n.length<=t.maximum)return;const o=We(n);r.issues.push({origin:o,code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),Vt=Se("$ZodCheckMinLength",(e,t)=>{var r;Ot.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!je(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const r=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>r&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const n=r.value;if(n.length>=t.minimum)return;const o=We(n);r.issues.push({origin:o,code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),Ft=Se("$ZodCheckLengthEquals",(e,t)=>{var r;Ot.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!je(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const r=e._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=r=>{const n=r.value,o=n.length;if(o===t.length)return;const s=We(n),a=o>t.length;r.issues.push({origin:s,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),Lt=Se("$ZodCheckStringFormat",(e,t)=>{var r,n;Ot.init(e,t),e._zod.onattach.push(e=>{const r=e._zod.bag;r.format=t.format,t.pattern&&(r.patterns??(r.patterns=new Set),r.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),Kt=Se("$ZodCheckRegex",(e,t)=>{Lt.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Ht=Se("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=jt),Lt.init(e,t)}),Zt=Se("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Rt),Lt.init(e,t)}),Gt=Se("$ZodCheckIncludes",(e,t)=>{Ot.init(e,t);const r=Fe(t.includes),n=new RegExp("number"==typeof t.position?`^.{${t.position}}${r}`:r);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=r=>{r.value.includes(t.includes,t.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),Bt=Se("$ZodCheckStartsWith",(e,t)=>{Ot.init(e,t);const r=new RegExp(`^${Fe(t.prefix)}.*`);t.pattern??(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=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),Jt=Se("$ZodCheckEndsWith",(e,t)=>{Ot.init(e,t);const r=new RegExp(`.*${Fe(t.suffix)}$`);t.pattern??(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=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),Wt=Se("$ZodCheckOverwrite",(e,t)=>{Ot.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class Qt{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),r=Math.min(...t.map(e=>e.length-e.trimStart().length)),n=t.map(e=>e.slice(r)).map(e=>" ".repeat(2*this.indent)+e);for(const e of n)this.content.push(e)}compile(){const e=Function,t=this?.args;return new e(...t,[...(this?.content??[""]).map(e=>` ${e}`)].join("\n"))}}const Yt={major:4,minor:0,patch:0},Xt=Se("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Yt;const n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(const t of n)for(const r of t._zod.onattach)r(e);if(0===n.length)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const t=(e,t,r)=>{let n,o=Ze(e);for(const s of t){if(s._zod.def.when){if(!s._zod.def.when(e))continue}else if(o)continue;const t=e.issues.length,a=s._zod.check(e);if(a instanceof Promise&&!1===r?.async)throw new Te;if(n||a instanceof Promise)n=(n??Promise.resolve()).then(async()=>{await a;e.issues.length!==t&&(o||(o=Ze(e,t)))});else{if(e.issues.length===t)continue;o||(o=Ze(e,t))}}return n?n.then(()=>e):e};e._zod.run=(r,o)=>{const s=e._zod.parse(r,o);if(s instanceof Promise){if(!1===o.async)throw new Te;return s.then(e=>t(e,n,o))}return t(s,n,o)}}e["~standard"]={validate:t=>{try{const r=ot(e,t);return r.success?{value:r.data}:{issues:r.error?.issues}}catch(r){return at(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}}),er=Se("$ZodString",(e,t)=>{var r;Xt.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??(r=e._zod.bag,new RegExp(`^${r?`[\\s\\S]{${r?.minimum??0},${r?.maximum??""}}`:"[\\s\\S]*"}$`)),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch(n){}return"string"==typeof r.value||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),tr=Se("$ZodStringFormat",(e,t)=>{Lt.init(e,t),er.init(e,t)}),rr=Se("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=ft),tr.init(e,t)}),nr=Se("$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=mt(e))}else t.pattern??(t.pattern=mt());tr.init(e,t)}),or=Se("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=yt),tr.init(e,t)}),sr=Se("$ZodURL",(e,t)=>{tr.init(e,t),e._zod.check=r=>{try{const n=r.value,o=new URL(n),s=o.href;return t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:kt.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),void(!n.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s)}catch(n){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),ar=Se("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),tr.init(e,t)}),ir=Se("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=ht),tr.init(e,t)}),cr=Se("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=it),tr.init(e,t)}),ur=Se("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=ct),tr.init(e,t)}),lr=Se("$ZodULID",(e,t)=>{t.pattern??(t.pattern=ut),tr.init(e,t)}),dr=Se("$ZodXID",(e,t)=>{t.pattern??(t.pattern=lt),tr.init(e,t)}),hr=Se("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=dt),tr.init(e,t)}),pr=Se("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=function(e){const t=Tt({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-]\\d{2}:\\d{2})");const n=`${t}(?:${r.join("|")})`;return new RegExp(`^${Pt}T(?:${n})$`)}(t)),tr.init(e,t)}),fr=Se("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=St),tr.init(e,t)}),mr=Se("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=new RegExp(`^${Tt(t)}$`)),tr.init(e,t)}),yr=Se("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=pt),tr.init(e,t)}),gr=Se("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=gt),tr.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.format="ipv4"})}),vr=Se("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=vt),tr.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.format="ipv6"}),e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),_r=Se("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=_t),tr.init(e,t)}),wr=Se("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=wt),tr.init(e,t),e._zod.check=r=>{const[n,o]=r.value.split("/");try{if(!o)throw new Error;const e=Number(o);if(`${e}`!==o)throw new Error;if(e<0||e>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function $r(e){if(""===e)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const br=Se("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=$t),tr.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{$r(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});const kr=Se("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=bt),tr.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{(function(e){if(!bt.test(e))return!1;const t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return $r(t.padEnd(4*Math.ceil(t.length/4),"="))})(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),Er=Se("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Et),tr.init(e,t)});const Pr=Se("$ZodJWT",(e,t)=>{tr.init(e,t),e._zod.check=r=>{(function(e,t=null){try{const r=e.split(".");if(3!==r.length)return!1;const[n]=r;if(!n)return!1;const o=JSON.parse(atob(n));return!("typ"in o&&"JWT"!==o?.typ||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}})(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),Sr=Se("$ZodNumber",(e,t)=>{Xt.init(e,t),e._zod.pattern=e._zod.bag.pattern??xt,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch(e){}const o=r.value;if("number"==typeof o&&!Number.isNaN(o)&&Number.isFinite(o))return r;const s="number"==typeof o?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...s?{received:s}:{}}),r}}),Tr=Se("$ZodNumber",(e,t)=>{Ut.init(e,t),Sr.init(e,t)}),Ir=Se("$ZodBoolean",(e,t)=>{Xt.init(e,t),e._zod.pattern=Nt,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Boolean(r.value)}catch(e){}const o=r.value;return"boolean"==typeof o||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),r}}),xr=Se("$ZodNull",(e,t)=>{Xt.init(e,t),e._zod.pattern=Ct,e._zod.values=new Set([null]),e._zod.parse=(t,r)=>{const n=t.value;return null===n||t.issues.push({expected:"null",code:"invalid_type",input:n,inst:e}),t}}),Nr=Se("$ZodAny",(e,t)=>{Xt.init(e,t),e._zod.parse=e=>e}),Cr=Se("$ZodUnknown",(e,t)=>{Xt.init(e,t),e._zod.parse=e=>e}),jr=Se("$ZodNever",(e,t)=>{Xt.init(e,t),e._zod.parse=(t,r)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function Rr(e,t,r){e.issues.length&&t.issues.push(...Ge(r,e.issues)),t.value[r]=e.value}const Or=Se("$ZodArray",(e,t)=>{Xt.init(e,t),e._zod.parse=(r,n)=>{const o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=Array(o.length);const s=[];for(let e=0;e<o.length;e++){const a=o[e],i=t.element._zod.run({value:a,issues:[]},n);i instanceof Promise?s.push(i.then(t=>Rr(t,r,e))):Rr(i,r,e)}return s.length?Promise.all(s).then(()=>r):r}});function zr(e,t,r){e.issues.length&&t.issues.push(...Ge(r,e.issues)),t.value[r]=e.value}function Ar(e,t,r,n){e.issues.length?void 0===n[r]?t.value[r]=r in n?void 0:e.value:t.issues.push(...Ge(r,e.issues)):void 0===e.value?r in n&&(t.value[r]=void 0):t.value[r]=e.value}const Mr=Se("$ZodObject",(e,t)=>{Xt.init(e,t);const r=Ce(()=>{const e=Object.keys(t.shape);for(const r of e)if(!(t.shape[r]instanceof Xt))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const r=(n=t.shape,Object.keys(n).filter(e=>"optional"===n[e]._zod.optin&&"optional"===n[e]._zod.optout));var n;return{shape:t.shape,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(r)}});Oe(e._zod,"propValues",()=>{const e=t.shape,r={};for(const t in e){const n=e[t]._zod;if(n.values){r[t]??(r[t]=new Set);for(const e of n.values)r[t].add(e)}}return r});let n;const o=De,s=!Ie.jitless,a=s&&Ue.value,i=t.catchall;let c;e._zod.parse=(u,l)=>{c??(c=r.value);const d=u.value;if(!o(d))return u.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),u;const h=[];if(s&&a&&!1===l?.async&&!0!==l.jitless)n||(n=(e=>{const t=new Qt(["shape","payload","ctx"]),n=r.value,o=e=>{const t=Ae(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");const s=Object.create(null);let a=0;for(const e of n.keys)s[e]="key_"+a++;t.write("const newResult = {}");for(const e of n.keys)if(n.optionalKeys.has(e)){const r=s[e];t.write(`const ${r} = ${o(e)};`);const n=Ae(e);t.write(`\n if (${r}.issues.length) {\n if (input[${n}] === undefined) {\n if (${n} in input) {\n newResult[${n}] = undefined;\n }\n } else {\n payload.issues = payload.issues.concat(\n ${r}.issues.map((iss) => ({\n ...iss,\n path: iss.path ? [${n}, ...iss.path] : [${n}],\n }))\n );\n }\n } else if (${r}.value === undefined) {\n if (${n} in input) newResult[${n}] = undefined;\n } else {\n newResult[${n}] = ${r}.value;\n }\n `)}else{const r=s[e];t.write(`const ${r} = ${o(e)};`),t.write(`\n if (${r}.issues.length) payload.issues = payload.issues.concat(${r}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${Ae(e)}, ...iss.path] : [${Ae(e)}]\n })));`),t.write(`newResult[${Ae(e)}] = ${r}.value`)}t.write("payload.value = newResult;"),t.write("return payload;");const i=t.compile();return(t,r)=>i(e,t,r)})(t.shape)),u=n(u,l);else{u.value={};const e=c.shape;for(const t of c.keys){const r=e[t],n=r._zod.run({value:d[t],issues:[]},l),o="optional"===r._zod.optin&&"optional"===r._zod.optout;n instanceof Promise?h.push(n.then(e=>o?Ar(e,u,t,d):zr(e,u,t))):o?Ar(n,u,t,d):zr(n,u,t)}}if(!i)return h.length?Promise.all(h).then(()=>u):u;const p=[],f=c.keySet,m=i._zod,y=m.def.type;for(const e of Object.keys(d)){if(f.has(e))continue;if("never"===y){p.push(e);continue}const t=m.run({value:d[e],issues:[]},l);t instanceof Promise?h.push(t.then(t=>zr(t,u,e))):zr(t,u,e)}return p.length&&u.issues.push({code:"unrecognized_keys",keys:p,input:d,inst:e}),h.length?Promise.all(h).then(()=>u):u}});function Dr(e,t,r,n){for(const r of e)if(0===r.issues.length)return t.value=r.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(e=>e.issues.map(e=>Je(e,n,xe())))}),t}const Ur=Se("$ZodUnion",(e,t)=>{Xt.init(e,t),Oe(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),Oe(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),Oe(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),Oe(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=>Re(e.source)).join("|")})$`)}}),e._zod.parse=(r,n)=>{let o=!1;const s=[];for(const e of t.options){const t=e._zod.run({value:r.value,issues:[]},n);if(t instanceof Promise)s.push(t),o=!0;else{if(0===t.issues.length)return t;s.push(t)}}return o?Promise.all(s).then(t=>Dr(t,r,e,n)):Dr(s,r,e,n)}}),qr=Se("$ZodDiscriminatedUnion",(e,t)=>{Ur.init(e,t);const r=e._zod.parse;Oe(e._zod,"propValues",()=>{const e={};for(const r of t.options){const n=r._zod.propValues;if(!n||0===Object.keys(n).length)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(const[t,r]of Object.entries(n)){e[t]||(e[t]=new Set);for(const n of r)e[t].add(n)}}return e});const n=Ce(()=>{const e=t.options,r=new Map;for(const n of e){const e=n._zod.propValues[t.discriminator];if(!e||0===e.size)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(const t of e){if(r.has(t))throw new Error(`Duplicate discriminator value "${String(t)}"`);r.set(t,n)}}return r});e._zod.parse=(o,s)=>{const a=o.value;if(!De(a))return o.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),o;const i=n.value.get(a?.[t.discriminator]);return i?i._zod.run(o,s):t.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:a,path:[t.discriminator],inst:e}),o)}}),Vr=Se("$ZodIntersection",(e,t)=>{Xt.init(e,t),e._zod.parse=(e,r)=>{const n=e.value,o=t.left._zod.run({value:n,issues:[]},r),s=t.right._zod.run({value:n,issues:[]},r);return o instanceof Promise||s instanceof Promise?Promise.all([o,s]).then(([t,r])=>Lr(e,t,r)):Lr(e,o,s)}});function Fr(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(qe(e)&&qe(t)){const r=Object.keys(t),n=Object.keys(e).filter(e=>-1!==r.indexOf(e)),o={...e,...t};for(const r of n){const n=Fr(e[r],t[r]);if(!n.valid)return{valid:!1,mergeErrorPath:[r,...n.mergeErrorPath]};o[r]=n.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let n=0;n<e.length;n++){const o=Fr(e[n],t[n]);if(!o.valid)return{valid:!1,mergeErrorPath:[n,...o.mergeErrorPath]};r.push(o.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Lr(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),Ze(e))return e;const n=Fr(t.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return e.value=n.data,e}const Kr=Se("$ZodRecord",(e,t)=>{Xt.init(e,t),e._zod.parse=(r,n)=>{const o=r.value;if(!qe(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;const s=[];if(t.keyType._zod.values){const a=t.keyType._zod.values;r.value={};for(const e of a)if("string"==typeof e||"number"==typeof e||"symbol"==typeof e){const a=t.valueType._zod.run({value:o[e],issues:[]},n);a instanceof Promise?s.push(a.then(t=>{t.issues.length&&r.issues.push(...Ge(e,t.issues)),r.value[e]=t.value})):(a.issues.length&&r.issues.push(...Ge(e,a.issues)),r.value[e]=a.value)}let i;for(const e in o)a.has(e)||(i=i??[],i.push(e));i&&i.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:i})}else{r.value={};for(const a of Reflect.ownKeys(o)){if("__proto__"===a)continue;const i=t.keyType._zod.run({value:a,issues:[]},n);if(i instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(i.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:i.issues.map(e=>Je(e,n,xe())),input:a,path:[a],inst:e}),r.value[i.value]=i.value;continue}const c=t.valueType._zod.run({value:o[a],issues:[]},n);c instanceof Promise?s.push(c.then(e=>{e.issues.length&&r.issues.push(...Ge(a,e.issues)),r.value[i.value]=e.value})):(c.issues.length&&r.issues.push(...Ge(a,c.issues)),r.value[i.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),Hr=Se("$ZodEnum",(e,t)=>{Xt.init(e,t);const r=function(e){const t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,r])=>-1===t.indexOf(+e)).map(([e,t])=>t)}(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(e=>Ve.has(typeof e)).map(e=>"string"==typeof e?Fe(e):e.toString()).join("|")})$`),e._zod.parse=(t,n)=>{const o=t.value;return e._zod.values.has(o)||t.issues.push({code:"invalid_value",values:r,input:o,inst:e}),t}}),Zr=Se("$ZodLiteral",(e,t)=>{Xt.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(e=>"string"==typeof e?Fe(e):e?e.toString():String(e)).join("|")})$`),e._zod.parse=(r,n)=>{const o=r.value;return e._zod.values.has(o)||r.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),r}}),Gr=Se("$ZodTransform",(e,t)=>{Xt.init(e,t),e._zod.parse=(e,r)=>{const n=t.transform(e.value,e);if(r.async){return(n instanceof Promise?n:Promise.resolve(n)).then(t=>(e.value=t,e))}if(n instanceof Promise)throw new Te;return e.value=n,e}}),Br=Se("$ZodOptional",(e,t)=>{Xt.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Oe(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Oe(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${Re(e.source)})?$`):void 0}),e._zod.parse=(e,r)=>"optional"===t.innerType._zod.optin?t.innerType._zod.run(e,r):void 0===e.value?e:t.innerType._zod.run(e,r)}),Jr=Se("$ZodNullable",(e,t)=>{Xt.init(e,t),Oe(e._zod,"optin",()=>t.innerType._zod.optin),Oe(e._zod,"optout",()=>t.innerType._zod.optout),Oe(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${Re(e.source)}|null)$`):void 0}),Oe(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,r)=>null===e.value?e:t.innerType._zod.run(e,r)}),Wr=Se("$ZodDefault",(e,t)=>{Xt.init(e,t),e._zod.optin="optional",Oe(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>{if(void 0===e.value)return e.value=t.defaultValue,e;const n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(e=>Qr(e,t)):Qr(n,t)}});function Qr(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}const Yr=Se("$ZodPrefault",(e,t)=>{Xt.init(e,t),e._zod.optin="optional",Oe(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>(void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,r))}),Xr=Se("$ZodNonOptional",(e,t)=>{Xt.init(e,t),Oe(e._zod,"values",()=>{const e=t.innerType._zod.values;return e?new Set([...e].filter(e=>void 0!==e)):void 0}),e._zod.parse=(r,n)=>{const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(t=>en(t,e)):en(o,e)}});function en(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 tn=Se("$ZodCatch",(e,t)=>{Xt.init(e,t),e._zod.optin="optional",Oe(e._zod,"optout",()=>t.innerType._zod.optout),Oe(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>{const n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(n=>(e.value=n.value,n.issues.length&&(e.value=t.catchValue({...e,error:{issues:n.issues.map(e=>Je(e,r,xe()))},input:e.value}),e.issues=[]),e)):(e.value=n.value,n.issues.length&&(e.value=t.catchValue({...e,error:{issues:n.issues.map(e=>Je(e,r,xe()))},input:e.value}),e.issues=[]),e)}}),rn=Se("$ZodPipe",(e,t)=>{Xt.init(e,t),Oe(e._zod,"values",()=>t.in._zod.values),Oe(e._zod,"optin",()=>t.in._zod.optin),Oe(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(e,r)=>{const n=t.in._zod.run(e,r);return n instanceof Promise?n.then(e=>nn(e,t,r)):nn(n,t,r)}});function nn(e,t,r){return Ze(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}const on=Se("$ZodReadonly",(e,t)=>{Xt.init(e,t),Oe(e._zod,"propValues",()=>t.innerType._zod.propValues),Oe(e._zod,"values",()=>t.innerType._zod.values),Oe(e._zod,"optin",()=>t.innerType._zod.optin),Oe(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(e,r)=>{const n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(sn):sn(n)}});function sn(e){return e.value=Object.freeze(e.value),e}const an=Se("$ZodCustom",(e,t)=>{Ot.init(e,t),Xt.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=r=>{const n=r.value,o=t.fn(n);if(o instanceof Promise)return o.then(t=>cn(t,r,n,e));cn(o,r,n,e)}});function cn(e,t,r,n){if(!e){const e={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(e.params=n._zod.def.params),t.issues.push(Qe(e))}}class un{constructor(){this._map=new Map,this._idmap=new Map}add(e,...t){const r=t[0];if(this._map.set(e,r),r&&"object"==typeof r&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,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 r={...this.get(t)??{}};return delete r.id,{...r,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}}function ln(){return new un}const dn=ln();function hn(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...Ke(t)})}function pn(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...Ke(t)})}function fn(e,t){return new At({check:"less_than",...Ke(t),value:e,inclusive:!1})}function mn(e,t){return new At({check:"less_than",...Ke(t),value:e,inclusive:!0})}function yn(e,t){return new Mt({check:"greater_than",...Ke(t),value:e,inclusive:!1})}function gn(e,t){return new Mt({check:"greater_than",...Ke(t),value:e,inclusive:!0})}function vn(e,t){return new Dt({check:"multiple_of",...Ke(t),value:e})}function _n(e,t){return new qt({check:"max_length",...Ke(t),maximum:e})}function wn(e,t){return new Vt({check:"min_length",...Ke(t),minimum:e})}function $n(e,t){return new Ft({check:"length_equals",...Ke(t),length:e})}function bn(e){return new Wt({check:"overwrite",tx:e})}function kn(e){return!!e._zod}function En(e,t){if(kn(e)){return ot(e,t)}return e.safeParse(t)}function Pn(e){if(!e)return;let t;if(kn(e)){const r=e;t=r._zod?.def?.shape}else{t=e.shape}if(t){if("function"==typeof t)try{return t()}catch{return}return t}}const Sn=Se("ZodISODateTime",(e,t)=>{pr.init(e,t),Ln.init(e,t)});function Tn(e){return function(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Ke(t)})}(Sn,e)}const In=Se("ZodISODate",(e,t)=>{fr.init(e,t),Ln.init(e,t)});function xn(e){return function(e,t){return new e({type:"string",format:"date",check:"string_format",...Ke(t)})}(In,e)}const Nn=Se("ZodISOTime",(e,t)=>{mr.init(e,t),Ln.init(e,t)});function Cn(e){return function(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...Ke(t)})}(Nn,e)}const jn=Se("ZodISODuration",(e,t)=>{yr.init(e,t),Ln.init(e,t)});function Rn(e){return function(e,t){return new e({type:"string",format:"duration",check:"string_format",...Ke(t)})}(jn,e)}const On=Se("ZodError",(e,t)=>{Xe.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>function(e,t){const r=t||function(e){return e.message},n={_errors:[]},o=e=>{for(const t of e.issues)if("invalid_union"===t.code&&t.errors.length)t.errors.map(e=>o({issues:e}));else if("invalid_key"===t.code)o({issues:t.issues});else if("invalid_element"===t.code)o({issues:t.issues});else if(0===t.path.length)n._errors.push(r(t));else{let e=n,o=0;for(;o<t.path.length;){const n=t.path[o];o===t.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(r(t))):e[n]=e[n]||{_errors:[]},e=e[n],o++}}};return o(e),n}(e,t)},flatten:{value:t=>function(e,t=e=>e.message){const r={},n=[];for(const o of e.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o))):n.push(t(o));return{formErrors:n,fieldErrors:r}}(e,t)},addIssue:{value:t=>e.issues.push(t)},addIssues:{value:t=>e.issues.push(...t)},isEmpty:{get:()=>0===e.issues.length}})},{Parent:Error}),zn=tt(On),An=rt(On),Mn=nt(On),Dn=st(On),Un=Se("ZodType",(e,t)=>(Xt.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),e.clone=(t,r)=>Le(e,t,r),e.brand=()=>e,e.register=(t,r)=>(t.add(e,r),e),e.parse=(t,r)=>zn(e,t,r,{callee:e.parse}),e.safeParse=(t,r)=>Mn(e,t,r),e.parseAsync=async(t,r)=>An(e,t,r,{callee:e.parseAsync}),e.safeParseAsync=async(t,r)=>Dn(e,t,r),e.spa=e.safeParseAsync,e.refine=(t,r)=>e.check(function(e,t={}){return function(e,t,r){return new e({type:"custom",check:"custom",fn:t,...Ke(r)})}(Xo,e,t)}(t,r)),e.superRefine=t=>e.check(function(e){const t=function(e){const t=new Ot({check:"custom"});return t._zod.check=e,t}(r=>(r.addIssue=e=>{if("string"==typeof e)r.issues.push(Qe(e,r.value,t._zod.def));else{const n=e;n.fatal&&(n.continue=!1),n.code??(n.code="custom"),n.input??(n.input=r.value),n.inst??(n.inst=t),n.continue??(n.continue=!t._zod.def.abort),r.issues.push(Qe(n))}},e(r.value,r)));return t}(t)),e.overwrite=t=>e.check(bn(t)),e.optional=()=>Lo(e),e.nullable=()=>Ho(e),e.nullish=()=>Lo(Ho(e)),e.nonoptional=t=>function(e,t){return new Bo({type:"nonoptional",innerType:e,...Ke(t)})}(e,t),e.array=()=>Eo(e),e.or=t=>xo([e,t]),e.and=t=>Ro(e,t),e.transform=t=>Qo(e,Vo(t)),e.default=t=>{return r=t,new Zo({type:"default",innerType:e,get defaultValue(){return"function"==typeof r?r():r}});var r},e.prefault=t=>{return r=t,new Go({type:"prefault",innerType:e,get defaultValue(){return"function"==typeof r?r():r}});var r},e.catch=t=>{return new Jo({type:"catch",innerType:e,catchValue:"function"==typeof(r=t)?r:()=>r});var r},e.pipe=t=>Qo(e,t),e.readonly=()=>new Yo({type:"readonly",innerType:e}),e.describe=t=>{const r=e.clone();return dn.add(r,{description:t}),r},Object.defineProperty(e,"description",{get:()=>dn.get(e)?.description,configurable:!0}),e.meta=(...t)=>{if(0===t.length)return dn.get(e);const r=e.clone();return dn.add(r,t[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),qn=Se("_ZodString",(e,t)=>{er.init(e,t),Un.init(e,t);const r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...t)=>e.check(function(e,t){return new Kt({check:"string_format",format:"regex",...Ke(t),pattern:e})}(...t)),e.includes=(...t)=>e.check(function(e,t){return new Gt({check:"string_format",format:"includes",...Ke(t),includes:e})}(...t)),e.startsWith=(...t)=>e.check(function(e,t){return new Bt({check:"string_format",format:"starts_with",...Ke(t),prefix:e})}(...t)),e.endsWith=(...t)=>e.check(function(e,t){return new Jt({check:"string_format",format:"ends_with",...Ke(t),suffix:e})}(...t)),e.min=(...t)=>e.check(wn(...t)),e.max=(...t)=>e.check(_n(...t)),e.length=(...t)=>e.check($n(...t)),e.nonempty=(...t)=>e.check(wn(1,...t)),e.lowercase=t=>e.check(function(e){return new Ht({check:"string_format",format:"lowercase",...Ke(e)})}(t)),e.uppercase=t=>e.check(function(e){return new Zt({check:"string_format",format:"uppercase",...Ke(e)})}(t)),e.trim=()=>e.check(bn(e=>e.trim())),e.normalize=(...t)=>e.check(function(e){return bn(t=>t.normalize(e))}(...t)),e.toLowerCase=()=>e.check(bn(e=>e.toLowerCase())),e.toUpperCase=()=>e.check(bn(e=>e.toUpperCase()))}),Vn=Se("ZodString",(e,t)=>{er.init(e,t),qn.init(e,t),e.email=t=>e.check(function(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...Ke(t)})}(Kn,t)),e.url=t=>e.check(pn(Gn,t)),e.jwt=t=>e.check(function(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...Ke(t)})}(co,t)),e.emoji=t=>e.check(function(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...Ke(t)})}(Bn,t)),e.guid=t=>e.check(hn(Hn,t)),e.uuid=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...Ke(t)})}(Zn,t)),e.uuidv4=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Ke(t)})}(Zn,t)),e.uuidv6=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Ke(t)})}(Zn,t)),e.uuidv7=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Ke(t)})}(Zn,t)),e.nanoid=t=>e.check(function(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...Ke(t)})}(Jn,t)),e.guid=t=>e.check(hn(Hn,t)),e.cuid=t=>e.check(function(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...Ke(t)})}(Wn,t)),e.cuid2=t=>e.check(function(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...Ke(t)})}(Qn,t)),e.ulid=t=>e.check(function(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...Ke(t)})}(Yn,t)),e.base64=t=>e.check(function(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...Ke(t)})}(so,t)),e.base64url=t=>e.check(function(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...Ke(t)})}(ao,t)),e.xid=t=>e.check(function(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...Ke(t)})}(Xn,t)),e.ksuid=t=>e.check(function(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...Ke(t)})}(eo,t)),e.ipv4=t=>e.check(function(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...Ke(t)})}(to,t)),e.ipv6=t=>e.check(function(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...Ke(t)})}(ro,t)),e.cidrv4=t=>e.check(function(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Ke(t)})}(no,t)),e.cidrv6=t=>e.check(function(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Ke(t)})}(oo,t)),e.e164=t=>e.check(function(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...Ke(t)})}(io,t)),e.datetime=t=>e.check(Tn(t)),e.date=t=>e.check(xn(t)),e.time=t=>e.check(Cn(t)),e.duration=t=>e.check(Rn(t))});function Fn(e){return function(e,t){return new e({type:"string",...Ke(t)})}(Vn,e)}const Ln=Se("ZodStringFormat",(e,t)=>{tr.init(e,t),qn.init(e,t)}),Kn=Se("ZodEmail",(e,t)=>{or.init(e,t),Ln.init(e,t)}),Hn=Se("ZodGUID",(e,t)=>{rr.init(e,t),Ln.init(e,t)}),Zn=Se("ZodUUID",(e,t)=>{nr.init(e,t),Ln.init(e,t)}),Gn=Se("ZodURL",(e,t)=>{sr.init(e,t),Ln.init(e,t)});const Bn=Se("ZodEmoji",(e,t)=>{ar.init(e,t),Ln.init(e,t)}),Jn=Se("ZodNanoID",(e,t)=>{ir.init(e,t),Ln.init(e,t)}),Wn=Se("ZodCUID",(e,t)=>{cr.init(e,t),Ln.init(e,t)}),Qn=Se("ZodCUID2",(e,t)=>{ur.init(e,t),Ln.init(e,t)}),Yn=Se("ZodULID",(e,t)=>{lr.init(e,t),Ln.init(e,t)}),Xn=Se("ZodXID",(e,t)=>{dr.init(e,t),Ln.init(e,t)}),eo=Se("ZodKSUID",(e,t)=>{hr.init(e,t),Ln.init(e,t)}),to=Se("ZodIPv4",(e,t)=>{gr.init(e,t),Ln.init(e,t)}),ro=Se("ZodIPv6",(e,t)=>{vr.init(e,t),Ln.init(e,t)}),no=Se("ZodCIDRv4",(e,t)=>{_r.init(e,t),Ln.init(e,t)}),oo=Se("ZodCIDRv6",(e,t)=>{wr.init(e,t),Ln.init(e,t)}),so=Se("ZodBase64",(e,t)=>{br.init(e,t),Ln.init(e,t)}),ao=Se("ZodBase64URL",(e,t)=>{kr.init(e,t),Ln.init(e,t)}),io=Se("ZodE164",(e,t)=>{Er.init(e,t),Ln.init(e,t)}),co=Se("ZodJWT",(e,t)=>{Pr.init(e,t),Ln.init(e,t)}),uo=Se("ZodNumber",(e,t)=>{Sr.init(e,t),Un.init(e,t),e.gt=(t,r)=>e.check(yn(t,r)),e.gte=(t,r)=>e.check(gn(t,r)),e.min=(t,r)=>e.check(gn(t,r)),e.lt=(t,r)=>e.check(fn(t,r)),e.lte=(t,r)=>e.check(mn(t,r)),e.max=(t,r)=>e.check(mn(t,r)),e.int=t=>e.check(po(t)),e.safe=t=>e.check(po(t)),e.positive=t=>e.check(yn(0,t)),e.nonnegative=t=>e.check(gn(0,t)),e.negative=t=>e.check(fn(0,t)),e.nonpositive=t=>e.check(mn(0,t)),e.multipleOf=(t,r)=>e.check(vn(t,r)),e.step=(t,r)=>e.check(vn(t,r)),e.finite=()=>e;const r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function lo(e){return function(e,t){return new e({type:"number",checks:[],...Ke(t)})}(uo,e)}const ho=Se("ZodNumberFormat",(e,t)=>{Tr.init(e,t),uo.init(e,t)});function po(e){return function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...Ke(t)})}(ho,e)}const fo=Se("ZodBoolean",(e,t)=>{Ir.init(e,t),Un.init(e,t)});function mo(e){return function(e,t){return new e({type:"boolean",...Ke(t)})}(fo,e)}const yo=Se("ZodNull",(e,t)=>{xr.init(e,t),Un.init(e,t)});function go(e){return function(e,t){return new e({type:"null",...Ke(t)})}(yo,e)}const vo=Se("ZodAny",(e,t)=>{Nr.init(e,t),Un.init(e,t)});const _o=Se("ZodUnknown",(e,t)=>{Cr.init(e,t),Un.init(e,t)});function wo(){return new _o({type:"unknown"})}const $o=Se("ZodNever",(e,t)=>{jr.init(e,t),Un.init(e,t)});function bo(e){return function(e,t){return new e({type:"never",...Ke(t)})}($o,e)}const ko=Se("ZodArray",(e,t)=>{Or.init(e,t),Un.init(e,t),e.element=t.element,e.min=(t,r)=>e.check(wn(t,r)),e.nonempty=t=>e.check(wn(1,t)),e.max=(t,r)=>e.check(_n(t,r)),e.length=(t,r)=>e.check($n(t,r)),e.unwrap=()=>e.element});function Eo(e,t){return function(e,t,r){return new e({type:"array",element:t,...Ke(r)})}(ko,e,t)}const Po=Se("ZodObject",(e,t)=>{Mr.init(e,t),Un.init(e,t),Oe(e,"shape",()=>t.shape),e.keyof=()=>Mo(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:wo()}),e.loose=()=>e.clone({...e._zod.def,catchall:wo()}),e.strict=()=>e.clone({...e._zod.def,catchall:bo()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>function(e,t){if(!qe(t))throw new Error("Invalid input to extend: expected a plain object");const r={...e._zod.def,get shape(){const r={...e._zod.def.shape,...t};return ze(this,"shape",r),r},checks:[]};return Le(e,r)}(e,t),e.merge=t=>{return n=t,Le(r=e,{...r._zod.def,get shape(){const e={...r._zod.def.shape,...n._zod.def.shape};return ze(this,"shape",e),e},catchall:n._zod.def.catchall,checks:[]});var r,n},e.pick=t=>function(e,t){const r={},n=e._zod.def;for(const e in t){if(!(e in n.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&(r[e]=n.shape[e])}return Le(e,{...e._zod.def,shape:r,checks:[]})}(e,t),e.omit=t=>function(e,t){const r={...e._zod.def.shape},n=e._zod.def;for(const e in t){if(!(e in n.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return Le(e,{...e._zod.def,shape:r,checks:[]})}(e,t),e.partial=(...t)=>function(e,t,r){const n=t._zod.def.shape,o={...n};if(r)for(const t in r){if(!(t in n))throw new Error(`Unrecognized key: "${t}"`);r[t]&&(o[t]=e?new e({type:"optional",innerType:n[t]}):n[t])}else for(const t in n)o[t]=e?new e({type:"optional",innerType:n[t]}):n[t];return Le(t,{...t._zod.def,shape:o,checks:[]})}(Fo,e,t[0]),e.required=(...t)=>function(e,t,r){const n=t._zod.def.shape,o={...n};if(r)for(const t in r){if(!(t in o))throw new Error(`Unrecognized key: "${t}"`);r[t]&&(o[t]=new e({type:"nonoptional",innerType:n[t]}))}else for(const t in n)o[t]=new e({type:"nonoptional",innerType:n[t]});return Le(t,{...t._zod.def,shape:o,checks:[]})}(Bo,e,t[0])});function So(e,t){const r={type:"object",get shape(){return ze(this,"shape",{...e}),this.shape},...Ke(t)};return new Po(r)}function To(e,t){return new Po({type:"object",get shape(){return ze(this,"shape",{...e}),this.shape},catchall:wo(),...Ke(t)})}const Io=Se("ZodUnion",(e,t)=>{Ur.init(e,t),Un.init(e,t),e.options=t.options});function xo(e,t){return new Io({type:"union",options:e,...Ke(t)})}const No=Se("ZodDiscriminatedUnion",(e,t)=>{Io.init(e,t),qr.init(e,t)});function Co(e,t,r){return new No({type:"union",options:t,discriminator:e,...Ke(r)})}const jo=Se("ZodIntersection",(e,t)=>{Vr.init(e,t),Un.init(e,t)});function Ro(e,t){return new jo({type:"intersection",left:e,right:t})}const Oo=Se("ZodRecord",(e,t)=>{Kr.init(e,t),Un.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function zo(e,t,r){return new Oo({type:"record",keyType:e,valueType:t,...Ke(r)})}const Ao=Se("ZodEnum",(e,t)=>{Hr.init(e,t),Un.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);const r=new Set(Object.keys(t.entries));e.extract=(e,n)=>{const o={};for(const n of e){if(!r.has(n))throw new Error(`Key ${n} not found in enum`);o[n]=t.entries[n]}return new Ao({...t,checks:[],...Ke(n),entries:o})},e.exclude=(e,n)=>{const o={...t.entries};for(const t of e){if(!r.has(t))throw new Error(`Key ${t} not found in enum`);delete o[t]}return new Ao({...t,checks:[],...Ke(n),entries:o})}});function Mo(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new Ao({type:"enum",entries:r,...Ke(t)})}const Do=Se("ZodLiteral",(e,t)=>{Zr.init(e,t),Un.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 Uo(e,t){return new Do({type:"literal",values:Array.isArray(e)?e:[e],...Ke(t)})}const qo=Se("ZodTransform",(e,t)=>{Gr.init(e,t),Un.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=n=>{if("string"==typeof n)r.issues.push(Qe(n,r.value,t));else{const t=n;t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=r.value),t.inst??(t.inst=e),t.continue??(t.continue=!0),r.issues.push(Qe(t))}};const o=t.transform(r.value,r);return o instanceof Promise?o.then(e=>(r.value=e,r)):(r.value=o,r)}});function Vo(e){return new qo({type:"transform",transform:e})}const Fo=Se("ZodOptional",(e,t)=>{Br.init(e,t),Un.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Lo(e){return new Fo({type:"optional",innerType:e})}const Ko=Se("ZodNullable",(e,t)=>{Jr.init(e,t),Un.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Ho(e){return new Ko({type:"nullable",innerType:e})}const Zo=Se("ZodDefault",(e,t)=>{Wr.init(e,t),Un.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});const Go=Se("ZodPrefault",(e,t)=>{Yr.init(e,t),Un.init(e,t),e.unwrap=()=>e._zod.def.innerType});const Bo=Se("ZodNonOptional",(e,t)=>{Xr.init(e,t),Un.init(e,t),e.unwrap=()=>e._zod.def.innerType});const Jo=Se("ZodCatch",(e,t)=>{tn.init(e,t),Un.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});const Wo=Se("ZodPipe",(e,t)=>{rn.init(e,t),Un.init(e,t),e.in=t.in,e.out=t.out});function Qo(e,t){return new Wo({type:"pipe",in:e,out:t})}const Yo=Se("ZodReadonly",(e,t)=>{on.init(e,t),Un.init(e,t)});const Xo=Se("ZodCustom",(e,t)=>{an.init(e,t),Un.init(e,t)});function es(e,t){return Qo(Vo(e),t)}const ts="custom";const rs="2025-11-25",ns=[rs,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],os="io.modelcontextprotocol/related-task",ss="2.0",as=function(e,t,r){const n=Ke(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}(Xo,(e=>null!==e&&("object"==typeof e||"function"==typeof e))??(()=>!0),is);var is;const cs=xo([Fn(),lo().int()]),us=Fn();To({ttl:xo([lo(),go()]).optional(),pollInterval:lo().optional()});const ls=So({ttl:lo().optional()}),ds=So({taskId:Fn()}),hs=To({progressToken:cs.optional(),[os]:ds.optional()}),ps=So({_meta:hs.optional()}),fs=ps.extend({task:ls.optional()}),ms=So({method:Fn(),params:ps.loose().optional()}),ys=So({_meta:hs.optional()}),gs=So({method:Fn(),params:ys.loose().optional()}),vs=To({_meta:hs.optional()}),_s=xo([Fn(),lo().int()]),ws=So({jsonrpc:Uo(ss),id:_s,...ms.shape}).strict(),$s=e=>ws.safeParse(e).success,bs=So({jsonrpc:Uo(ss),...gs.shape}).strict(),ks=So({jsonrpc:Uo(ss),id:_s,result:vs}).strict(),Es=e=>ks.safeParse(e).success;var Ps;!function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"}(Ps||(Ps={}));const Ss=So({jsonrpc:Uo(ss),id:_s.optional(),error:So({code:lo().int(),message:Fn(),data:wo().optional()})}).strict(),Ts=xo([ws,bs,ks,Ss]);xo([ks,Ss]);const Is=vs.strict(),xs=ys.extend({requestId:_s.optional(),reason:Fn().optional()}),Ns=gs.extend({method:Uo("notifications/cancelled"),params:xs}),Cs=So({src:Fn(),mimeType:Fn().optional(),sizes:Eo(Fn()).optional(),theme:Mo(["light","dark"]).optional()}),js=So({icons:Eo(Cs).optional()}),Rs=So({name:Fn(),title:Fn().optional()}),Os=Rs.extend({...Rs.shape,...js.shape,version:Fn(),websiteUrl:Fn().optional(),description:Fn().optional()}),zs=Ro(So({applyDefaults:mo().optional()}),zo(Fn(),wo())),As=es(e=>e&&"object"==typeof e&&!Array.isArray(e)&&0===Object.keys(e).length?{form:{}}:e,Ro(So({form:zs.optional(),url:as.optional()}),zo(Fn(),wo()).optional())),Ms=To({list:as.optional(),cancel:as.optional(),requests:To({sampling:To({createMessage:as.optional()}).optional(),elicitation:To({create:as.optional()}).optional()}).optional()}),Ds=To({list:as.optional(),cancel:as.optional(),requests:To({tools:To({call:as.optional()}).optional()}).optional()}),Us=So({experimental:zo(Fn(),as).optional(),sampling:So({context:as.optional(),tools:as.optional()}).optional(),elicitation:As.optional(),roots:So({listChanged:mo().optional()}).optional(),tasks:Ms.optional()}),qs=ps.extend({protocolVersion:Fn(),capabilities:Us,clientInfo:Os}),Vs=ms.extend({method:Uo("initialize"),params:qs}),Fs=So({experimental:zo(Fn(),as).optional(),logging:as.optional(),completions:as.optional(),prompts:So({listChanged:mo().optional()}).optional(),resources:So({subscribe:mo().optional(),listChanged:mo().optional()}).optional(),tools:So({listChanged:mo().optional()}).optional(),tasks:Ds.optional()}),Ls=vs.extend({protocolVersion:Fn(),capabilities:Fs,serverInfo:Os,instructions:Fn().optional()}),Ks=gs.extend({method:Uo("notifications/initialized"),params:ys.optional()}),Hs=ms.extend({method:Uo("ping"),params:ps.optional()}),Zs=So({progress:lo(),total:Lo(lo()),message:Lo(Fn())}),Gs=So({...ys.shape,...Zs.shape,progressToken:cs}),Bs=gs.extend({method:Uo("notifications/progress"),params:Gs}),Js=ps.extend({cursor:us.optional()}),Ws=ms.extend({params:Js.optional()}),Qs=vs.extend({nextCursor:us.optional()}),Ys=Mo(["working","input_required","completed","failed","cancelled"]),Xs=So({taskId:Fn(),status:Ys,ttl:xo([lo(),go()]),createdAt:Fn(),lastUpdatedAt:Fn(),pollInterval:Lo(lo()),statusMessage:Lo(Fn())}),ea=vs.extend({task:Xs}),ta=ys.merge(Xs),ra=gs.extend({method:Uo("notifications/tasks/status"),params:ta}),na=ms.extend({method:Uo("tasks/get"),params:ps.extend({taskId:Fn()})}),oa=vs.merge(Xs),sa=ms.extend({method:Uo("tasks/result"),params:ps.extend({taskId:Fn()})});vs.loose();const aa=Ws.extend({method:Uo("tasks/list")}),ia=Qs.extend({tasks:Eo(Xs)}),ca=ms.extend({method:Uo("tasks/cancel"),params:ps.extend({taskId:Fn()})}),ua=vs.merge(Xs),la=So({uri:Fn(),mimeType:Lo(Fn()),_meta:zo(Fn(),wo()).optional()}),da=la.extend({text:Fn()}),ha=Fn().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),pa=la.extend({blob:ha}),fa=Mo(["user","assistant"]),ma=So({audience:Eo(fa).optional(),priority:lo().min(0).max(1).optional(),lastModified:Tn({offset:!0}).optional()}),ya=So({...Rs.shape,...js.shape,uri:Fn(),description:Lo(Fn()),mimeType:Lo(Fn()),annotations:ma.optional(),_meta:Lo(To({}))}),ga=So({...Rs.shape,...js.shape,uriTemplate:Fn(),description:Lo(Fn()),mimeType:Lo(Fn()),annotations:ma.optional(),_meta:Lo(To({}))}),va=Ws.extend({method:Uo("resources/list")}),_a=Qs.extend({resources:Eo(ya)}),wa=Ws.extend({method:Uo("resources/templates/list")}),$a=Qs.extend({resourceTemplates:Eo(ga)}),ba=ps.extend({uri:Fn()}),ka=ba,Ea=ms.extend({method:Uo("resources/read"),params:ka}),Pa=vs.extend({contents:Eo(xo([da,pa]))}),Sa=gs.extend({method:Uo("notifications/resources/list_changed"),params:ys.optional()}),Ta=ba,Ia=ms.extend({method:Uo("resources/subscribe"),params:Ta}),xa=ba,Na=ms.extend({method:Uo("resources/unsubscribe"),params:xa}),Ca=ys.extend({uri:Fn()}),ja=gs.extend({method:Uo("notifications/resources/updated"),params:Ca}),Ra=So({name:Fn(),description:Lo(Fn()),required:Lo(mo())}),Oa=So({...Rs.shape,...js.shape,description:Lo(Fn()),arguments:Lo(Eo(Ra)),_meta:Lo(To({}))}),za=Ws.extend({method:Uo("prompts/list")}),Aa=Qs.extend({prompts:Eo(Oa)}),Ma=ps.extend({name:Fn(),arguments:zo(Fn(),Fn()).optional()}),Da=ms.extend({method:Uo("prompts/get"),params:Ma}),Ua=So({type:Uo("text"),text:Fn(),annotations:ma.optional(),_meta:zo(Fn(),wo()).optional()}),qa=So({type:Uo("image"),data:ha,mimeType:Fn(),annotations:ma.optional(),_meta:zo(Fn(),wo()).optional()}),Va=So({type:Uo("audio"),data:ha,mimeType:Fn(),annotations:ma.optional(),_meta:zo(Fn(),wo()).optional()}),Fa=So({type:Uo("tool_use"),name:Fn(),id:Fn(),input:zo(Fn(),wo()),_meta:zo(Fn(),wo()).optional()}),La=So({type:Uo("resource"),resource:xo([da,pa]),annotations:ma.optional(),_meta:zo(Fn(),wo()).optional()}),Ka=xo([Ua,qa,Va,ya.extend({type:Uo("resource_link")}),La]),Ha=So({role:fa,content:Ka}),Za=vs.extend({description:Fn().optional(),messages:Eo(Ha)}),Ga=gs.extend({method:Uo("notifications/prompts/list_changed"),params:ys.optional()}),Ba=So({title:Fn().optional(),readOnlyHint:mo().optional(),destructiveHint:mo().optional(),idempotentHint:mo().optional(),openWorldHint:mo().optional()}),Ja=So({taskSupport:Mo(["required","optional","forbidden"]).optional()}),Wa=So({...Rs.shape,...js.shape,description:Fn().optional(),inputSchema:So({type:Uo("object"),properties:zo(Fn(),as).optional(),required:Eo(Fn()).optional()}).catchall(wo()),outputSchema:So({type:Uo("object"),properties:zo(Fn(),as).optional(),required:Eo(Fn()).optional()}).catchall(wo()).optional(),annotations:Ba.optional(),execution:Ja.optional(),_meta:zo(Fn(),wo()).optional()}),Qa=Ws.extend({method:Uo("tools/list")}),Ya=Qs.extend({tools:Eo(Wa)}),Xa=vs.extend({content:Eo(Ka).default([]),structuredContent:zo(Fn(),wo()).optional(),isError:mo().optional()});Xa.or(vs.extend({toolResult:wo()}));const ei=fs.extend({name:Fn(),arguments:zo(Fn(),wo()).optional()}),ti=ms.extend({method:Uo("tools/call"),params:ei}),ri=gs.extend({method:Uo("notifications/tools/list_changed"),params:ys.optional()}),ni=So({autoRefresh:mo().default(!0),debounceMs:lo().int().nonnegative().default(300)}),oi=Mo(["debug","info","notice","warning","error","critical","alert","emergency"]),si=ps.extend({level:oi}),ai=ms.extend({method:Uo("logging/setLevel"),params:si}),ii=ys.extend({level:oi,logger:Fn().optional(),data:wo()}),ci=gs.extend({method:Uo("notifications/message"),params:ii}),ui=So({name:Fn().optional()}),li=So({hints:Eo(ui).optional(),costPriority:lo().min(0).max(1).optional(),speedPriority:lo().min(0).max(1).optional(),intelligencePriority:lo().min(0).max(1).optional()}),di=So({mode:Mo(["auto","required","none"]).optional()}),hi=So({type:Uo("tool_result"),toolUseId:Fn().describe("The unique identifier for the corresponding tool call."),content:Eo(Ka).default([]),structuredContent:So({}).loose().optional(),isError:mo().optional(),_meta:zo(Fn(),wo()).optional()}),pi=Co("type",[Ua,qa,Va]),fi=Co("type",[Ua,qa,Va,Fa,hi]),mi=So({role:fa,content:xo([fi,Eo(fi)]),_meta:zo(Fn(),wo()).optional()}),yi=fs.extend({messages:Eo(mi),modelPreferences:li.optional(),systemPrompt:Fn().optional(),includeContext:Mo(["none","thisServer","allServers"]).optional(),temperature:lo().optional(),maxTokens:lo().int(),stopSequences:Eo(Fn()).optional(),metadata:as.optional(),tools:Eo(Wa).optional(),toolChoice:di.optional()}),gi=ms.extend({method:Uo("sampling/createMessage"),params:yi}),vi=vs.extend({model:Fn(),stopReason:Lo(Mo(["endTurn","stopSequence","maxTokens"]).or(Fn())),role:fa,content:pi}),_i=vs.extend({model:Fn(),stopReason:Lo(Mo(["endTurn","stopSequence","maxTokens","toolUse"]).or(Fn())),role:fa,content:xo([fi,Eo(fi)])}),wi=So({type:Uo("boolean"),title:Fn().optional(),description:Fn().optional(),default:mo().optional()}),$i=So({type:Uo("string"),title:Fn().optional(),description:Fn().optional(),minLength:lo().optional(),maxLength:lo().optional(),format:Mo(["email","uri","date","date-time"]).optional(),default:Fn().optional()}),bi=So({type:Mo(["number","integer"]),title:Fn().optional(),description:Fn().optional(),minimum:lo().optional(),maximum:lo().optional(),default:lo().optional()}),ki=So({type:Uo("string"),title:Fn().optional(),description:Fn().optional(),enum:Eo(Fn()),default:Fn().optional()}),Ei=So({type:Uo("string"),title:Fn().optional(),description:Fn().optional(),oneOf:Eo(So({const:Fn(),title:Fn()})),default:Fn().optional()}),Pi=So({type:Uo("string"),title:Fn().optional(),description:Fn().optional(),enum:Eo(Fn()),enumNames:Eo(Fn()).optional(),default:Fn().optional()}),Si=xo([ki,Ei]),Ti=xo([So({type:Uo("array"),title:Fn().optional(),description:Fn().optional(),minItems:lo().optional(),maxItems:lo().optional(),items:So({type:Uo("string"),enum:Eo(Fn())}),default:Eo(Fn()).optional()}),So({type:Uo("array"),title:Fn().optional(),description:Fn().optional(),minItems:lo().optional(),maxItems:lo().optional(),items:So({anyOf:Eo(So({const:Fn(),title:Fn()}))}),default:Eo(Fn()).optional()})]),Ii=xo([Pi,Si,Ti]),xi=xo([Ii,wi,$i,bi]),Ni=xo([fs.extend({mode:Uo("form").optional(),message:Fn(),requestedSchema:So({type:Uo("object"),properties:zo(Fn(),xi),required:Eo(Fn()).optional()})}),fs.extend({mode:Uo("url"),message:Fn(),elicitationId:Fn(),url:Fn().url()})]),Ci=ms.extend({method:Uo("elicitation/create"),params:Ni}),ji=ys.extend({elicitationId:Fn()}),Ri=gs.extend({method:Uo("notifications/elicitation/complete"),params:ji}),Oi=vs.extend({action:Mo(["accept","decline","cancel"]),content:es(e=>null===e?void 0:e,zo(Fn(),xo([Fn(),lo(),mo(),Eo(Fn())])).optional())}),zi=So({type:Uo("ref/resource"),uri:Fn()}),Ai=So({type:Uo("ref/prompt"),name:Fn()}),Mi=ps.extend({ref:xo([Ai,zi]),argument:So({name:Fn(),value:Fn()}),context:So({arguments:zo(Fn(),Fn()).optional()}).optional()}),Di=ms.extend({method:Uo("completion/complete"),params:Mi}),Ui=vs.extend({completion:To({values:Eo(Fn()).max(100),total:Lo(lo().int()),hasMore:Lo(mo())})}),qi=So({uri:Fn().startsWith("file://"),name:Fn().optional(),_meta:zo(Fn(),wo()).optional()}),Vi=ms.extend({method:Uo("roots/list"),params:ps.optional()}),Fi=vs.extend({roots:Eo(qi)}),Li=gs.extend({method:Uo("notifications/roots/list_changed"),params:ys.optional()});xo([Hs,Vs,Di,ai,Da,za,va,wa,Ea,Ia,Na,ti,Qa,na,sa,aa,ca]),xo([Ns,Bs,Ks,Li,ra]),xo([Is,vi,_i,Oi,Fi,oa,ia,ea]),xo([Hs,gi,Ci,Vi,na,sa,aa,ca]),xo([Ns,Bs,ci,ja,Sa,ri,Ga,ra,Ri]),xo([Is,Ls,Ui,Za,Aa,_a,$a,Pa,Xa,Ya,oa,ia,ea]);class Ki extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`),this.code=e,this.data=r,this.name="McpError"}static fromError(e,t,r){if(e===Ps.UrlElicitationRequired&&r){const e=r;if(e.elicitations)return new Hi(e.elicitations,t)}return new Ki(e,t,r)}}class Hi extends Ki{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(Ps.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}function Zi(e){return"completed"===e||"failed"===e||"cancelled"===e}function Gi(e){const t=Pn(e),r=t?.method;if(!r)throw new Error("Schema is missing a method literal");const n=function(e){if(kn(e)){const t=e,r=t._zod?.def;if(r){if(void 0!==r.value)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}}const t=e._def;if(t){if(void 0!==t.value)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}const r=e.value;if(void 0!==r)return r}(r);if("string"!=typeof n)throw new Error("Schema method literal must be a string");return n}function Bi(e,t){const r=En(e,t);if(!r.success)throw r.error;return r.data}new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");class Ji{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Ns,e=>{this._oncancel(e)}),this.setNotificationHandler(Bs,e=>{this._onprogress(e)}),this.setRequestHandler(Hs,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(na,async(e,t)=>{const r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new Ki(Ps.InvalidParams,"Failed to retrieve task: Task not found");return{...r}}),this.setRequestHandler(sa,async(e,t)=>{const r=async()=>{const n=e.params.taskId;if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(n,t.sessionId);){if("response"===e.type||"error"===e.type){const t=e.message,r=t.id,n=this._requestResolvers.get(r);if(n)if(this._requestResolvers.delete(r),"response"===e.type)n(t);else{const e=t;n(new Ki(e.error.code,e.error.message,e.error.data))}else{const t="response"===e.type?"Response":"Error";this._onerror(new Error(`${t} handler missing for request ${r}`))}continue}await(this._transport?.send(e.message,{relatedRequestId:t.requestId}))}}const o=await this._taskStore.getTask(n,t.sessionId);if(!o)throw new Ki(Ps.InvalidParams,`Task not found: ${n}`);if(!Zi(o.status))return await this._waitForTaskUpdate(n,t.signal),await r();if(Zi(o.status)){const e=await this._taskStore.getTaskResult(n,t.sessionId);return this._clearTaskQueue(n),{...e,_meta:{...e._meta,[os]:{taskId:n}}}}return await r()};return await r()}),this.setRequestHandler(aa,async(e,t)=>{try{const{tasks:r,nextCursor:n}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:r,nextCursor:n,_meta:{}}}catch(e){throw new Ki(Ps.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(ca,async(e,t)=>{try{const r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new Ki(Ps.InvalidParams,`Task not found: ${e.params.taskId}`);if(Zi(r.status))throw new Ki(Ps.InvalidParams,`Cannot cancel task in terminal status: ${r.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,"cancelled","Client cancelled task execution.",t.sessionId),this._clearTaskQueue(e.params.taskId);const n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new Ki(Ps.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...n}}catch(e){if(e instanceof Ki)throw e;throw new Ki(Ps.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;const t=this._requestHandlerAbortControllers.get(e.params.requestId);t?.abort(e.params.reason)}_setupTimeout(e,t,r,n,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:o,onTimeout:n})}_resetTimeout(e){const t=this._timeoutInfo.get(e);if(!t)return!1;const r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),Ki.fromError(Ps.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){const t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;const t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};const r=this.transport?.onerror;this._transport.onerror=e=>{r?.(e),this._onerror(e)};const n=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{var r;n?.(e,t),Es(e)||(r=e,Ss.safeParse(r).success)?this._onresponse(e):$s(e)?this._onrequest(e,t):(e=>bs.safeParse(e).success)(e)?this._onnotification(e):this._onerror(new Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){const e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(const e of this._requestHandlerAbortControllers.values())e.abort();this._requestHandlerAbortControllers.clear();const t=Ki.fromError(Ps.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const r of e.values())r(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){const t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;void 0!==t&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(new Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){const r=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,n=this._transport,o=e.params?._meta?.[os]?.taskId;if(void 0===r){const t={jsonrpc:"2.0",id:e.id,error:{code:Ps.MethodNotFound,message:"Method not found"}};return void(o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:t,timestamp:Date.now()},n?.sessionId).catch(e=>this._onerror(new Error(`Failed to enqueue error response: ${e}`))):n?.send(t).catch(e=>this._onerror(new Error(`Failed to send an error response: ${e}`))))}const s=new AbortController;this._requestHandlerAbortControllers.set(e.id,s);const a=(i=e.params,fs.safeParse(i).success?e.params.task:void 0);var i;const c=this._taskStore?this.requestTaskStore(e,n?.sessionId):void 0,u={signal:s.signal,sessionId:n?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{if(s.signal.aborted)return;const r={relatedRequestId:e.id};o&&(r.relatedTask={taskId:o}),await this.notification(t,r)},sendRequest:async(t,r,n)=>{if(s.signal.aborted)throw new Ki(Ps.ConnectionClosed,"Request was cancelled");const a={...n,relatedRequestId:e.id};o&&!a.relatedTask&&(a.relatedTask={taskId:o});const i=a.relatedTask?.taskId??o;return i&&c&&await c.updateTaskStatus(i,"input_required"),await this.request(t,r,a)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:o,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>r(e,u)).then(async t=>{if(s.signal.aborted)return;const r={result:t,jsonrpc:"2.0",id:e.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:r,timestamp:Date.now()},n?.sessionId):await(n?.send(r))},async t=>{if(s.signal.aborted)return;const r={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:Ps.InternalError,message:t.message??"Internal error",...void 0!==t.data&&{data:t.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:r,timestamp:Date.now()},n?.sessionId):await(n?.send(r))}).catch(e=>this._onerror(new Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:t,...r}=e.params,n=Number(t),o=this._progressHandlers.get(n);if(!o)return void this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));const s=this._responseHandlers.get(n),a=this._timeoutInfo.get(n);if(a&&s&&a.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(e){return this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),void s(e)}o(r)}_onresponse(e){const t=Number(e.id),r=this._requestResolvers.get(t);if(r){if(this._requestResolvers.delete(t),Es(e))r(e);else{r(new Ki(e.error.code,e.error.message,e.error.data))}return}const n=this._responseHandlers.get(t);if(void 0===n)return void this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));this._responseHandlers.delete(t),this._cleanupTimeout(t);let o=!1;if(Es(e)&&e.result&&"object"==typeof e.result){const r=e.result;if(r.task&&"object"==typeof r.task){const e=r.task;"string"==typeof e.taskId&&(o=!0,this._taskProgressTokens.set(e.taskId,t))}}if(o||this._progressHandlers.delete(t),Es(e))n(e);else{n(Ki.fromError(e.error.code,e.error.message,e.error.data))}}get transport(){return this._transport}async close(){await(this._transport?.close())}async*requestStream(e,t,r){const{task:n}=r??{};if(!n){try{const n=await this.request(e,t,r);yield{type:"result",result:n}}catch(e){yield{type:"error",error:e instanceof Ki?e:new Ki(Ps.InternalError,String(e))}}return}let o;try{const n=await this.request(e,ea,r);if(!n.task)throw new Ki(Ps.InternalError,"Task creation did not return a task");for(o=n.task.taskId,yield{type:"taskCreated",task:n.task};;){const e=await this.getTask({taskId:o},r);if(yield{type:"taskStatus",task:e},Zi(e.status)){if("completed"===e.status){const e=await this.getTaskResult({taskId:o},t,r);yield{type:"result",result:e}}else"failed"===e.status?yield{type:"error",error:new Ki(Ps.InternalError,`Task ${o} failed`)}:"cancelled"===e.status&&(yield{type:"error",error:new Ki(Ps.InternalError,`Task ${o} was cancelled`)});return}if("input_required"===e.status){const e=await this.getTaskResult({taskId:o},t,r);return void(yield{type:"result",result:e})}const n=e.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,n)),r?.signal?.throwIfAborted()}}catch(e){yield{type:"error",error:e instanceof Ki?e:new Ki(Ps.InternalError,String(e))}}}request(e,t,r){const{relatedRequestId:n,resumptionToken:o,onresumptiontoken:s,task:a,relatedTask:i}=r??{};return new Promise((c,u)=>{const l=e=>{u(e)};if(!this._transport)return void l(new Error("Not connected"));if(!0===this._options?.enforceStrictCapabilities)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(e){return void l(e)}r?.signal?.throwIfAborted();const d=this._requestMessageId++,h={...e,jsonrpc:"2.0",id:d};r?.onprogress&&(this._progressHandlers.set(d,r.onprogress),h.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),a&&(h.params={...h.params,task:a}),i&&(h.params={...h.params,_meta:{...h.params?._meta||{},[os]:i}});const p=e=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:d,reason:String(e)}},{relatedRequestId:n,resumptionToken:o,onresumptiontoken:s}).catch(e=>this._onerror(new Error(`Failed to send cancellation: ${e}`)));const t=e instanceof Ki?e:new Ki(Ps.RequestTimeout,String(e));u(t)};this._responseHandlers.set(d,e=>{if(!r?.signal?.aborted){if(e instanceof Error)return u(e);try{const r=En(t,e.result);r.success?c(r.data):u(r.error)}catch(e){u(e)}}}),r?.signal?.addEventListener("abort",()=>{p(r?.signal?.reason)});const f=r?.timeout??6e4;this._setupTimeout(d,f,r?.maxTotalTimeout,()=>p(Ki.fromError(Ps.RequestTimeout,"Request timed out",{timeout:f})),r?.resetTimeoutOnProgress??!1);const m=i?.taskId;if(m){const e=e=>{const t=this._responseHandlers.get(d);t?t(e):this._onerror(new Error(`Response handler missing for side-channeled request ${d}`))};this._requestResolvers.set(d,e),this._enqueueTaskMessage(m,{type:"request",message:h,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(d),u(e)})}else this._transport.send(h,{relatedRequestId:n,resumptionToken:o,onresumptiontoken:s}).catch(e=>{this._cleanupTimeout(d),u(e)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},oa,t)}async getTaskResult(e,t,r){return this.request({method:"tasks/result",params:e},t,r)}async listTasks(e,t){return this.request({method:"tasks/list",params:e},ia,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},ua,t)}async notification(e,t){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);const r=t?.relatedTask?.taskId;if(r){const n={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[os]:t.relatedTask}}};return void await this._enqueueTaskMessage(r,{type:"notification",message:n,timestamp:Date.now()})}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;return this._pendingDebouncedNotifications.add(e.method),void Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let r={...e,jsonrpc:"2.0"};t?.relatedTask&&(r={...r,params:{...r.params,_meta:{...r.params?._meta||{},[os]:t.relatedTask}}}),this._transport?.send(r,t).catch(e=>this._onerror(e))})}let n={...e,jsonrpc:"2.0"};t?.relatedTask&&(n={...n,params:{...n.params,_meta:{...n.params?._meta||{},[os]:t.relatedTask}}}),await this._transport.send(n,t)}setRequestHandler(e,t){const r=Gi(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(r,n)=>{const o=Bi(e,r);return Promise.resolve(t(o,n))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){const r=Gi(e);this._notificationHandlers.set(r,r=>{const n=Bi(e,r);return Promise.resolve(t(n))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){const t=this._taskProgressTokens.get(e);void 0!==t&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,r){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const n=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,r,n)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){const r=await this._taskMessageQueue.dequeueAll(e,t);for(const t of r)if("request"===t.type&&$s(t.message)){const r=t.message.id,n=this._requestResolvers.get(r);n?(n(new Ki(Ps.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(r)):this._onerror(new Error(`Resolver missing for request ${r} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let r=this._options?.defaultTaskPollInterval??1e3;try{const t=await(this._taskStore?.getTask(e));t?.pollInterval&&(r=t.pollInterval)}catch{}return new Promise((e,n)=>{if(t.aborted)return void n(new Ki(Ps.InvalidRequest,"Request cancelled"));const o=setTimeout(e,r);t.addEventListener("abort",()=>{clearTimeout(o),n(new Ki(Ps.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,t){const r=this._taskStore;if(!r)throw new Error("No task store configured");return{createTask:async n=>{if(!e)throw new Error("No request provided");return await r.createTask(n,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{const n=await r.getTask(e,t);if(!n)throw new Ki(Ps.InvalidParams,"Failed to retrieve task: Task not found");return n},storeTaskResult:async(e,n,o)=>{await r.storeTaskResult(e,n,o,t);const s=await r.getTask(e,t);if(s){const t=ra.parse({method:"notifications/tasks/status",params:s});await this.notification(t),Zi(s.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>r.getTaskResult(e,t),updateTaskStatus:async(e,n,o)=>{const s=await r.getTask(e,t);if(!s)throw new Ki(Ps.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(Zi(s.status))throw new Ki(Ps.InvalidParams,`Cannot update task "${e}" from terminal status "${s.status}" to "${n}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(e,n,o,t);const a=await r.getTask(e,t);if(a){const t=ra.parse({method:"notifications/tasks/status",params:a});await this.notification(t),Zi(a.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>r.listTasks(e,t)}}}function Wi(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function Qi(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Yi,Xi={exports:{}},ec={},tc={},rc={},nc={},oc={},sc={};function ac(){return Yi||(Yi=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;class t{}e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw new Error("CodeGen: name must be a valid identifier");this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=r;class n extends t{constructor(e){super(),this._items="string"==typeof e?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const e=this._items[0];return""===e||'""'===e}get str(){var e;return null!==(e=this._str)&&void 0!==e?e:this._str=this._items.reduce((e,t)=>`${e}${t}`,"")}get names(){var e;return null!==(e=this._names)&&void 0!==e?e:this._names=this._items.reduce((e,t)=>(t instanceof r&&(e[t.str]=(e[t.str]||0)+1),e),{})}}function o(e,...t){const r=[e[0]];let o=0;for(;o<t.length;)i(r,t[o]),r.push(e[++o]);return new n(r)}e._Code=n,e.nil=new n(""),e._=o;const s=new n("+");function a(e,...t){const r=[u(e[0])];let o=0;for(;o<t.length;)r.push(s),i(r,t[o]),r.push(s,u(e[++o]));return function(e){let t=1;for(;t<e.length-1;){if(e[t]===s){const r=c(e[t-1],e[t+1]);if(void 0!==r){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}(r),new n(r)}function i(e,t){var o;t instanceof n?e.push(...t._items):t instanceof r?e.push(t):e.push("number"==typeof(o=t)||"boolean"==typeof o||null===o?o:u(Array.isArray(o)?o.join(","):o))}function c(e,t){if('""'===t)return e;if('""'===e)return t;if("string"==typeof e){if(t instanceof r||'"'!==e[e.length-1])return;return"string"!=typeof t?`${e.slice(0,-1)}${t}"`:'"'===t[0]?e.slice(0,-1)+t.slice(1):void 0}return"string"!=typeof t||'"'!==t[0]||e instanceof r?void 0:`"${e}${t.slice(1)}`}function u(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.str=a,e.addCodeArg=i,e.strConcat=function(e,t){return t.emptyStr()?e:e.emptyStr()?t:a`${e}${t}`},e.stringify=function(e){return new n(u(e))},e.safeStringify=u,e.getProperty=function(t){return"string"==typeof t&&e.IDENTIFIER.test(t)?new n(`.${t}`):o`[${t}]`},e.getEsmExportName=function(t){if("string"==typeof t&&e.IDENTIFIER.test(t))return new n(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)},e.regexpCode=function(e){return new n(e.toString())}}(sc)),sc}var ic,cc,uc={};function lc(){return ic||(ic=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=ac();class r extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}}var n;!function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"}(n||(e.UsedValueState=n={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};class o{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof t.Name?e:this.name(e)}name(e){return new t.Name(this._newName(e))}_newName(e){return`${e}${(this._names[e]||this._nameGroup(e)).index++}`}_nameGroup(e){var t,r;if((null===(r=null===(t=this._parent)||void 0===t?void 0:t._prefixes)||void 0===r?void 0:r.has(e))||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}}e.Scope=o;class s extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=t._`.${new t.Name(r)}[${n}]`}}e.ValueScopeName=s;const a=t._`\n`;e.ValueScope=class extends o{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?a:t.nil}}get(){return this._scope}name(e){return new s(e,this._newName(e))}value(e,t){var r;if(void 0===t.ref)throw new Error("CodeGen: ref must be passed in value");const n=this.toName(e),{prefix:o}=n,s=null!==(r=t.key)&&void 0!==r?r:t.ref;let a=this._values[o];if(a){const e=a.get(s);if(e)return e}else a=this._values[o]=new Map;a.set(s,n);const i=this._scope[o]||(this._scope[o]=[]),c=i.length;return i[c]=t.ref,n.setValue(t,{property:o,itemIndex:c}),n}getValue(e,t){const r=this._values[e];if(r)return r.get(t)}scopeRefs(e,r=this._values){return this._reduceValues(r,r=>{if(void 0===r.scopePath)throw new Error(`CodeGen: name "${r}" has no value`);return t._`${e}${r.scopePath}`})}scopeCode(e=this._values,t,r){return this._reduceValues(e,e=>{if(void 0===e.value)throw new Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,r)}_reduceValues(o,s,a={},i){let c=t.nil;for(const u in o){const l=o[u];if(!l)continue;const d=a[u]=a[u]||new Map;l.forEach(o=>{if(d.has(o))return;d.set(o,n.Started);let a=s(o);if(a){const r=this.opts.es5?e.varKinds.var:e.varKinds.const;c=t._`${c}${r} ${o} = ${a};${this.opts._n}`}else{if(!(a=null==i?void 0:i(o)))throw new r(o);c=t._`${c}${a}${this.opts._n}`}d.set(o,n.Completed)})}return c}}}(uc)),uc}function dc(){return cc||(cc=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;const t=ac(),r=lc();var n=ac();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return n.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return n.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return n.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}});var o=lc();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return o.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return o.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return o.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return o.varKinds}}),e.operators={GT:new t._Code(">"),GTE:new t._Code(">="),LT:new t._Code("<"),LTE:new t._Code("<="),EQ:new t._Code("==="),NEQ:new t._Code("!=="),NOT:new t._Code("!"),OR:new t._Code("||"),AND:new t._Code("&&"),ADD:new t._Code("+")};class s{optimizeNodes(){return this}optimizeNames(e,t){return this}}class a extends s{constructor(e,t,r){super(),this.varKind=e,this.name=t,this.rhs=r}render({es5:e,_n:t}){const n=e?r.varKinds.var:this.varKind,o=void 0===this.rhs?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&(this.rhs=x(this.rhs,e,t)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class i extends s{constructor(e,t,r){super(),this.lhs=e,this.rhs=t,this.sideEffects=r}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof t.Name)||e[this.lhs.str]||this.sideEffects)return this.rhs=x(this.rhs,e,r),this}get names(){return I(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}}class c extends i{constructor(e,t,r,n){super(e,r,n),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}}class u extends s{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}}class l extends s{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}}class d extends s{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}}class h extends s{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=x(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class p extends s{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,r)=>t+r.render(e),"")}optimizeNodes(){const{nodes:e}=this;let t=e.length;for(;t--;){const r=e[t].optimizeNodes();Array.isArray(r)?e.splice(t,1,...r):r?e[t]=r:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){const{nodes:r}=this;let n=r.length;for(;n--;){const o=r[n];o.optimizeNames(e,t)||(N(e,o.names),r.splice(n,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>T(e,t.names),{})}}class f extends p{render(e){return"{"+e._n+super.render(e)+"}"+e._n}}class m extends p{}class y extends f{}y.kind="else";class g extends f{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+="else "+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();const e=this.condition;if(!0===e)return this.nodes;let t=this.else;if(t){const e=t.optimizeNodes();t=this.else=Array.isArray(e)?new y(e):e}return t?!1===e?t instanceof g?t:t.nodes:this.nodes.length?this:new g(C(e),t instanceof g?[t]:t.nodes):!1!==e&&this.nodes.length?this:void 0}optimizeNames(e,t){var r;if(this.else=null===(r=this.else)||void 0===r?void 0:r.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=x(this.condition,e,t),this}get names(){const e=super.names;return I(e,this.condition),this.else&&T(e,this.else.names),e}}g.kind="if";class v extends f{}v.kind="for";class _ extends v{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=x(this.iteration,e,t),this}get names(){return T(super.names,this.iteration.names)}}class w extends v{constructor(e,t,r,n){super(),this.varKind=e,this.name=t,this.from=r,this.to=n}render(e){const t=e.es5?r.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${t} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){const e=I(super.names,this.from);return I(e,this.to)}}class $ extends v{constructor(e,t,r,n){super(),this.loop=e,this.varKind=t,this.name=r,this.iterable=n}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=x(this.iterable,e,t),this}get names(){return T(super.names,this.iterable.names)}}class b extends f{constructor(e,t,r){super(),this.name=e,this.args=t,this.async=r}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}}b.kind="func";class k extends p{render(e){return"return "+super.render(e)}}k.kind="return";class E extends f{render(e){let t="try"+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),null===(e=this.catch)||void 0===e||e.optimizeNodes(),null===(t=this.finally)||void 0===t||t.optimizeNodes(),this}optimizeNames(e,t){var r,n;return super.optimizeNames(e,t),null===(r=this.catch)||void 0===r||r.optimizeNames(e,t),null===(n=this.finally)||void 0===n||n.optimizeNames(e,t),this}get names(){const e=super.names;return this.catch&&T(e,this.catch.names),this.finally&&T(e,this.finally.names),e}}class P extends f{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}}P.kind="catch";class S extends f{render(e){return"finally"+super.render(e)}}S.kind="finally";function T(e,t){for(const r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function I(e,r){return r instanceof t._CodeOrName?T(e,r.names):e}function x(e,r,n){return e instanceof t.Name?s(e):(o=e)instanceof t._Code&&o._items.some(e=>e instanceof t.Name&&1===r[e.str]&&void 0!==n[e.str])?new t._Code(e._items.reduce((e,r)=>(r instanceof t.Name&&(r=s(r)),r instanceof t._Code?e.push(...r._items):e.push(r),e),[])):e;var o;function s(e){const t=n[e.str];return void 0===t||1!==r[e.str]?e:(delete r[e.str],t)}}function N(e,t){for(const r in t)e[r]=(e[r]||0)-(t[r]||0)}function C(e){return"boolean"==typeof e||"number"==typeof e||null===e?!e:t._`!${z(e)}`}e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?"\n":""},this._extScope=e,this._scope=new r.Scope({parent:e}),this._nodes=[new m]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){const r=this._extScope.value(e,t);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,r,n){const o=this._scope.toName(t);return void 0!==r&&n&&(this._constants[o.str]=r),this._leafNode(new a(e,o,r)),o}const(e,t,n){return this._def(r.varKinds.const,e,t,n)}let(e,t,n){return this._def(r.varKinds.let,e,t,n)}var(e,t,n){return this._def(r.varKinds.var,e,t,n)}assign(e,t,r){return this._leafNode(new i(e,t,r))}add(t,r){return this._leafNode(new c(t,e.operators.ADD,r))}code(e){return"function"==typeof e?e():e!==t.nil&&this._leafNode(new h(e)),this}object(...e){const r=["{"];for(const[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,t.addCodeArg)(r,o));return r.push("}"),new t._Code(r)}if(e,t,r){if(this._blockNode(new g(e)),t&&r)this.code(t).else().code(r).endIf();else if(t)this.code(t).endIf();else if(r)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new g(e))}else(){return this._elseNode(new y)}endIf(){return this._endBlockNode(g,y)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new _(e),t)}forRange(e,t,n,o,s=(this.opts.es5?r.varKinds.var:r.varKinds.let)){const a=this._scope.toName(e);return this._for(new w(s,a,t,n),()=>o(a))}forOf(e,n,o,s=r.varKinds.const){const a=this._scope.toName(e);if(this.opts.es5){const e=n instanceof t.Name?n:this.var("_arr",n);return this.forRange("_i",0,t._`${e}.length`,r=>{this.var(a,t._`${e}[${r}]`),o(a)})}return this._for(new $("of",s,a,n),()=>o(a))}forIn(e,n,o,s=(this.opts.es5?r.varKinds.var:r.varKinds.const)){if(this.opts.ownProperties)return this.forOf(e,t._`Object.keys(${n})`,o);const a=this._scope.toName(e);return this._for(new $("in",s,a,n),()=>o(a))}endFor(){return this._endBlockNode(v)}label(e){return this._leafNode(new u(e))}break(e){return this._leafNode(new l(e))}return(e){const t=new k;if(this._blockNode(t),this.code(e),1!==t.nodes.length)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(k)}try(e,t,r){if(!t&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');const n=new E;if(this._blockNode(n),this.code(e),t){const e=this.name("e");this._currNode=n.catch=new P(e),t(e)}return r&&(this._currNode=n.finally=new S,this.code(r)),this._endBlockNode(P,S)}throw(e){return this._leafNode(new d(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){const t=this._blockStarts.pop();if(void 0===t)throw new Error("CodeGen: not in self-balancing block");const r=this._nodes.length-t;if(r<0||void 0!==e&&r!==e)throw new Error(`CodeGen: wrong number of nodes: ${r} vs ${e} expected`);return this._nodes.length=t,this}func(e,r=t.nil,n,o){return this._blockNode(new b(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(b)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){const r=this._currNode;if(r instanceof e||t&&r instanceof t)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){const t=this._currNode;if(!(t instanceof g))throw new Error('CodeGen: "else" without "if"');return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){const e=this._nodes;return e[e.length-1]}set _currNode(e){const t=this._nodes;t[t.length-1]=e}},e.not=C;const j=O(e.operators.AND);e.and=function(...e){return e.reduce(j)};const R=O(e.operators.OR);function O(e){return(r,n)=>r===t.nil?n:n===t.nil?r:t._`${z(r)} ${e} ${z(n)}`}function z(e){return e instanceof t.Name?e:t._`(${e})`}e.or=function(...e){return e.reduce(R)}}(oc)),oc}var hc={};Object.defineProperty(hc,"__esModule",{value:!0}),hc.checkStrictMode=hc.getErrorPath=hc.Type=hc.useFunc=hc.setEvaluated=hc.evaluatedPropsToName=hc.mergeEvaluated=hc.eachItem=hc.unescapeJsonPointer=hc.escapeJsonPointer=hc.escapeFragment=hc.unescapeFragment=hc.schemaRefOrVal=hc.schemaHasRulesButRef=hc.schemaHasRules=hc.checkUnknownRules=hc.alwaysValidSchema=hc.toHash=void 0;const pc=dc(),fc=ac();function mc(e,t=e.schema){const{opts:r,self:n}=e;if(!r.strictSchema)return;if("boolean"==typeof t)return;const o=n.RULES.keywords;for(const r in t)o[r]||Ec(e,`unknown keyword: "${r}"`)}function yc(e,t){if("boolean"==typeof e)return!e;for(const r in e)if(t[r])return!0;return!1}function gc(e){return"number"==typeof e?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}function vc(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function _c({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(o,s,a,i)=>{const c=void 0===a?s:a instanceof pc.Name?(s instanceof pc.Name?e(o,s,a):t(o,s,a),a):s instanceof pc.Name?(t(o,a,s),s):r(s,a);return i!==pc.Name||c instanceof pc.Name?c:n(o,c)}}function wc(e,t){if(!0===t)return e.var("props",!0);const r=e.var("props",pc._`{}`);return void 0!==t&&$c(e,r,t),r}function $c(e,t,r){Object.keys(r).forEach(r=>e.assign(pc._`${t}${(0,pc.getProperty)(r)}`,!0))}hc.toHash=function(e){const t={};for(const r of e)t[r]=!0;return t},hc.alwaysValidSchema=function(e,t){return"boolean"==typeof t?t:0===Object.keys(t).length||(mc(e,t),!yc(t,e.self.RULES.all))},hc.checkUnknownRules=mc,hc.schemaHasRules=yc,hc.schemaHasRulesButRef=function(e,t){if("boolean"==typeof e)return!e;for(const r in e)if("$ref"!==r&&t.all[r])return!0;return!1},hc.schemaRefOrVal=function({topSchemaRef:e,schemaPath:t},r,n,o){if(!o){if("number"==typeof r||"boolean"==typeof r)return r;if("string"==typeof r)return pc._`${r}`}return pc._`${e}${t}${(0,pc.getProperty)(n)}`},hc.unescapeFragment=function(e){return vc(decodeURIComponent(e))},hc.escapeFragment=function(e){return encodeURIComponent(gc(e))},hc.escapeJsonPointer=gc,hc.unescapeJsonPointer=vc,hc.eachItem=function(e,t){if(Array.isArray(e))for(const r of e)t(r);else t(e)},hc.mergeEvaluated={props:_c({mergeNames:(e,t,r)=>e.if(pc._`${r} !== true && ${t} !== undefined`,()=>{e.if(pc._`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,pc._`${r} || {}`).code(pc._`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if(pc._`${r} !== true`,()=>{!0===t?e.assign(r,!0):(e.assign(r,pc._`${r} || {}`),$c(e,r,t))}),mergeValues:(e,t)=>!0===e||{...e,...t},resultToName:wc}),items:_c({mergeNames:(e,t,r)=>e.if(pc._`${r} !== true && ${t} !== undefined`,()=>e.assign(r,pc._`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if(pc._`${r} !== true`,()=>e.assign(r,!0===t||pc._`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>!0===e||Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})},hc.evaluatedPropsToName=wc,hc.setEvaluated=$c;const bc={};var kc;function Ec(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,!0===r)throw new Error(t);e.self.logger.warn(t)}}hc.useFunc=function(e,t){return e.scopeValue("func",{ref:t,code:bc[t.code]||(bc[t.code]=new fc._Code(t.code))})},function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"}(kc||(hc.Type=kc={})),hc.getErrorPath=function(e,t,r){if(e instanceof pc.Name){const n=t===kc.Num;return r?n?pc._`"[" + ${e} + "]"`:pc._`"['" + ${e} + "']"`:n?pc._`"/" + ${e}`:pc._`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,pc.getProperty)(e).toString():"/"+gc(e)},hc.checkStrictMode=Ec;var Pc,Sc,Tc,Ic={};function xc(){if(Pc)return Ic;Pc=1,Object.defineProperty(Ic,"__esModule",{value:!0});const e=dc(),t={data:new e.Name("data"),valCxt:new e.Name("valCxt"),instancePath:new e.Name("instancePath"),parentData:new e.Name("parentData"),parentDataProperty:new e.Name("parentDataProperty"),rootData:new e.Name("rootData"),dynamicAnchors:new e.Name("dynamicAnchors"),vErrors:new e.Name("vErrors"),errors:new e.Name("errors"),this:new e.Name("this"),self:new e.Name("self"),scope:new e.Name("scope"),json:new e.Name("json"),jsonPos:new e.Name("jsonPos"),jsonLen:new e.Name("jsonLen"),jsonPart:new e.Name("jsonPart")};return Ic.default=t,Ic}function Nc(){return Sc||(Sc=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;const t=dc(),r=hc,n=xc();function o(e,r){const o=e.const("err",r);e.if(t._`${n.default.vErrors} === null`,()=>e.assign(n.default.vErrors,t._`[${o}]`),t._`${n.default.vErrors}.push(${o})`),e.code(t._`${n.default.errors}++`)}function s(e,r){const{gen:n,validateName:o,schemaEnv:s}=e;s.$async?n.throw(t._`new ${e.ValidationError}(${r})`):(n.assign(t._`${o}.errors`,r),n.return(!1))}e.keywordError={message:({keyword:e})=>t.str`must pass "${e}" keyword validation`},e.keyword$DataError={message:({keyword:e,schemaType:r})=>r?t.str`"${e}" keyword must be ${r} ($data)`:t.str`"${e}" keyword is invalid ($data)`},e.reportError=function(r,n=e.keywordError,a,c){const{it:u}=r,{gen:l,compositeRule:d,allErrors:h}=u,p=i(r,n,a);(null!=c?c:d||h)?o(l,p):s(u,t._`[${p}]`)},e.reportExtraError=function(t,r=e.keywordError,a){const{it:c}=t,{gen:u,compositeRule:l,allErrors:d}=c;o(u,i(t,r,a)),l||d||s(c,n.default.vErrors)},e.resetErrorsCount=function(e,r){e.assign(n.default.errors,r),e.if(t._`${n.default.vErrors} !== null`,()=>e.if(r,()=>e.assign(t._`${n.default.vErrors}.length`,r),()=>e.assign(n.default.vErrors,null)))},e.extendErrors=function({gen:e,keyword:r,schemaValue:o,data:s,errsCount:a,it:i}){if(void 0===a)throw new Error("ajv implementation error");const c=e.name("err");e.forRange("i",a,n.default.errors,a=>{e.const(c,t._`${n.default.vErrors}[${a}]`),e.if(t._`${c}.instancePath === undefined`,()=>e.assign(t._`${c}.instancePath`,(0,t.strConcat)(n.default.instancePath,i.errorPath))),e.assign(t._`${c}.schemaPath`,t.str`${i.errSchemaPath}/${r}`),i.opts.verbose&&(e.assign(t._`${c}.schema`,o),e.assign(t._`${c}.data`,s))})};const a={keyword:new t.Name("keyword"),schemaPath:new t.Name("schemaPath"),params:new t.Name("params"),propertyName:new t.Name("propertyName"),message:new t.Name("message"),schema:new t.Name("schema"),parentSchema:new t.Name("parentSchema")};function i(e,r,o){const{createErrors:s}=e.it;return!1===s?t._`{}`:function(e,r,o={}){const{gen:s,it:i}=e,l=[c(i,o),u(e,o)];return function(e,{params:r,message:o},s){const{keyword:i,data:c,schemaValue:u,it:l}=e,{opts:d,propertyName:h,topSchemaRef:p,schemaPath:f}=l;s.push([a.keyword,i],[a.params,"function"==typeof r?r(e):r||t._`{}`]),d.messages&&s.push([a.message,"function"==typeof o?o(e):o]);d.verbose&&s.push([a.schema,u],[a.parentSchema,t._`${p}${f}`],[n.default.data,c]);h&&s.push([a.propertyName,h])}(e,r,l),s.object(...l)}(e,r,o)}function c({errorPath:e},{instancePath:o}){const s=o?t.str`${e}${(0,r.getErrorPath)(o,r.Type.Str)}`:e;return[n.default.instancePath,(0,t.strConcat)(n.default.instancePath,s)]}function u({keyword:e,it:{errSchemaPath:n}},{schemaPath:o,parentSchema:s}){let i=s?n:t.str`${n}/${e}`;return o&&(i=t.str`${i}${(0,r.getErrorPath)(o,r.Type.Str)}`),[a.schemaPath,i]}}(nc)),nc}var Cc={},jc={};Object.defineProperty(jc,"__esModule",{value:!0}),jc.getRules=jc.isJSONType=void 0;const Rc=new Set(["string","number","integer","boolean","null","object","array"]);jc.isJSONType=function(e){return"string"==typeof e&&Rc.has(e)},jc.getRules=function(){const e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}};var Oc,zc={};function Ac(){if(Oc)return zc;function e(e,r){return r.rules.some(r=>t(e,r))}function t(e,t){var r;return void 0!==e[t.keyword]||(null===(r=t.definition.implements)||void 0===r?void 0:r.some(t=>void 0!==e[t]))}return Oc=1,Object.defineProperty(zc,"__esModule",{value:!0}),zc.shouldUseRule=zc.shouldUseGroup=zc.schemaHasRulesForType=void 0,zc.schemaHasRulesForType=function({schema:t,self:r},n){const o=r.RULES.types[n];return o&&!0!==o&&e(t,o)},zc.shouldUseGroup=e,zc.shouldUseRule=t,zc}Object.defineProperty(Cc,"__esModule",{value:!0}),Cc.reportTypeError=Cc.checkDataTypes=Cc.checkDataType=Cc.coerceAndCheckDataType=Cc.getJSONTypes=Cc.getSchemaTypes=Cc.DataType=void 0;const Mc=jc,Dc=Ac(),Uc=Nc(),qc=dc(),Vc=hc;var Fc;function Lc(e){const t=Array.isArray(e)?e:e?[e]:[];if(t.every(Mc.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}!function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"}(Fc||(Cc.DataType=Fc={})),Cc.getSchemaTypes=function(e){const t=Lc(e.type);if(t.includes("null")){if(!1===e.nullable)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&void 0!==e.nullable)throw new Error('"nullable" cannot be used without "type"');!0===e.nullable&&t.push("null")}return t},Cc.getJSONTypes=Lc,Cc.coerceAndCheckDataType=function(e,t){const{gen:r,data:n,opts:o}=e,s=function(e,t){return t?e.filter(e=>Kc.has(e)||"array"===t&&"array"===e):[]}(t,o.coerceTypes),a=t.length>0&&!(0===s.length&&1===t.length&&(0,Dc.schemaHasRulesForType)(e,t[0]));if(a){const a=Zc(t,n,o.strictNumbers,Fc.Wrong);r.if(a,()=>{s.length?function(e,t,r){const{gen:n,data:o,opts:s}=e,a=n.let("dataType",qc._`typeof ${o}`),i=n.let("coerced",qc._`undefined`);"array"===s.coerceTypes&&n.if(qc._`${a} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,qc._`${o}[0]`).assign(a,qc._`typeof ${o}`).if(Zc(t,o,s.strictNumbers),()=>n.assign(i,o)));n.if(qc._`${i} !== undefined`);for(const e of r)(Kc.has(e)||"array"===e&&"array"===s.coerceTypes)&&c(e);function c(e){switch(e){case"string":return void n.elseIf(qc._`${a} == "number" || ${a} == "boolean"`).assign(i,qc._`"" + ${o}`).elseIf(qc._`${o} === null`).assign(i,qc._`""`);case"number":return void n.elseIf(qc._`${a} == "boolean" || ${o} === null
2
+ || (${a} == "string" && ${o} && ${o} == +${o})`).assign(i,qc._`+${o}`);case"integer":return void n.elseIf(qc._`${a} === "boolean" || ${o} === null
3
+ || (${a} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(i,qc._`+${o}`);case"boolean":return void n.elseIf(qc._`${o} === "false" || ${o} === 0 || ${o} === null`).assign(i,!1).elseIf(qc._`${o} === "true" || ${o} === 1`).assign(i,!0);case"null":return n.elseIf(qc._`${o} === "" || ${o} === 0 || ${o} === false`),void n.assign(i,null);case"array":n.elseIf(qc._`${a} === "string" || ${a} === "number"
4
+ || ${a} === "boolean" || ${o} === null`).assign(i,qc._`[${o}]`)}}n.else(),Bc(e),n.endIf(),n.if(qc._`${i} !== undefined`,()=>{n.assign(o,i),function({gen:e,parentData:t,parentDataProperty:r},n){e.if(qc._`${t} !== undefined`,()=>e.assign(qc._`${t}[${r}]`,n))}(e,i)})}(e,t,s):Bc(e)})}return a};const Kc=new Set(["string","number","integer","boolean","null"]);function Hc(e,t,r,n=Fc.Correct){const o=n===Fc.Correct?qc.operators.EQ:qc.operators.NEQ;let s;switch(e){case"null":return qc._`${t} ${o} null`;case"array":s=qc._`Array.isArray(${t})`;break;case"object":s=qc._`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":s=a(qc._`!(${t} % 1) && !isNaN(${t})`);break;case"number":s=a();break;default:return qc._`typeof ${t} ${o} ${e}`}return n===Fc.Correct?s:(0,qc.not)(s);function a(e=qc.nil){return(0,qc.and)(qc._`typeof ${t} == "number"`,e,r?qc._`isFinite(${t})`:qc.nil)}}function Zc(e,t,r,n){if(1===e.length)return Hc(e[0],t,r,n);let o;const s=(0,Vc.toHash)(e);if(s.array&&s.object){const e=qc._`typeof ${t} != "object"`;o=s.null?e:qc._`!${t} || ${e}`,delete s.null,delete s.array,delete s.object}else o=qc.nil;s.number&&delete s.integer;for(const e in s)o=(0,qc.and)(o,Hc(e,t,r,n));return o}Cc.checkDataType=Hc,Cc.checkDataTypes=Zc;const Gc={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>"string"==typeof e?qc._`{type: ${e}}`:qc._`{type: ${t}}`};function Bc(e){const t=function(e){const{gen:t,data:r,schema:n}=e,o=(0,Vc.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:e}}(e);(0,Uc.reportError)(t,Gc)}Cc.reportTypeError=Bc;var Jc,Wc={};var Qc,Yc,Xc={},eu={};function tu(){if(Qc)return eu;Qc=1,Object.defineProperty(eu,"__esModule",{value:!0}),eu.validateUnion=eu.validateArray=eu.usePattern=eu.callValidateCode=eu.schemaProperties=eu.allSchemaProperties=eu.noPropertyInData=eu.propertyInData=eu.isOwnProperty=eu.hasPropFunc=eu.reportMissingProp=eu.checkMissingProp=eu.checkReportMissingProp=void 0;const e=dc(),t=hc,r=xc(),n=hc;function o(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:e._`Object.prototype.hasOwnProperty`})}function s(t,r,n){return e._`${o(t)}.call(${r}, ${n})`}function a(t,r,n,o){const a=e._`${r}${(0,e.getProperty)(n)} === undefined`;return o?(0,e.or)(a,(0,e.not)(s(t,r,n))):a}function i(e){return e?Object.keys(e).filter(e=>"__proto__"!==e):[]}eu.checkReportMissingProp=function(t,r){const{gen:n,data:o,it:s}=t;n.if(a(n,o,r,s.opts.ownProperties),()=>{t.setParams({missingProperty:e._`${r}`},!0),t.error()})},eu.checkMissingProp=function({gen:t,data:r,it:{opts:n}},o,s){return(0,e.or)(...o.map(o=>(0,e.and)(a(t,r,o,n.ownProperties),e._`${s} = ${o}`)))},eu.reportMissingProp=function(e,t){e.setParams({missingProperty:t},!0),e.error()},eu.hasPropFunc=o,eu.isOwnProperty=s,eu.propertyInData=function(t,r,n,o){const a=e._`${r}${(0,e.getProperty)(n)} !== undefined`;return o?e._`${a} && ${s(t,r,n)}`:a},eu.noPropertyInData=a,eu.allSchemaProperties=i,eu.schemaProperties=function(e,r){return i(r).filter(n=>!(0,t.alwaysValidSchema)(e,r[n]))},eu.callValidateCode=function({schemaCode:t,data:n,it:{gen:o,topSchemaRef:s,schemaPath:a,errorPath:i},it:c},u,l,d){const h=d?e._`${t}, ${n}, ${s}${a}`:n,p=[[r.default.instancePath,(0,e.strConcat)(r.default.instancePath,i)],[r.default.parentData,c.parentData],[r.default.parentDataProperty,c.parentDataProperty],[r.default.rootData,r.default.rootData]];c.opts.dynamicRef&&p.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);const f=e._`${h}, ${o.object(...p)}`;return l!==e.nil?e._`${u}.call(${l}, ${f})`:e._`${u}(${f})`};const c=e._`new RegExp`;return eu.usePattern=function({gen:t,it:{opts:r}},o){const s=r.unicodeRegExp?"u":"",{regExp:a}=r.code,i=a(o,s);return t.scopeValue("pattern",{key:i.toString(),ref:i,code:e._`${"new RegExp"===a.code?c:(0,n.useFunc)(t,a)}(${o}, ${s})`})},eu.validateArray=function(r){const{gen:n,data:o,keyword:s,it:a}=r,i=n.name("valid");if(a.allErrors){const e=n.let("valid",!0);return c(()=>n.assign(e,!1)),e}return n.var(i,!0),c(()=>n.break()),i;function c(a){const c=n.const("len",e._`${o}.length`);n.forRange("i",0,c,o=>{r.subschema({keyword:s,dataProp:o,dataPropType:t.Type.Num},i),n.if((0,e.not)(i),a)})}},eu.validateUnion=function(r){const{gen:n,schema:o,keyword:s,it:a}=r;if(!Array.isArray(o))throw new Error("ajv implementation error");if(o.some(e=>(0,t.alwaysValidSchema)(a,e))&&!a.opts.unevaluated)return;const i=n.let("valid",!1),c=n.name("_valid");n.block(()=>o.forEach((t,o)=>{const a=r.subschema({keyword:s,schemaProp:o,compositeRule:!0},c);n.assign(i,e._`${i} || ${c}`);r.mergeValidEvaluated(a,c)||n.if((0,e.not)(i))})),r.result(i,()=>r.reset(),()=>r.error(!0))},eu}function ru(){if(Yc)return Xc;Yc=1,Object.defineProperty(Xc,"__esModule",{value:!0}),Xc.validateKeywordUsage=Xc.validSchemaType=Xc.funcKeywordCode=Xc.macroKeywordCode=void 0;const e=dc(),t=xc(),r=tu(),n=Nc();function o(t){const{gen:r,data:n,it:o}=t;r.if(o.parentData,()=>r.assign(n,e._`${o.parentData}[${o.parentDataProperty}]`))}function s(t,r,n){if(void 0===n)throw new Error(`keyword "${r}" failed to compile`);return t.scopeValue("keyword","function"==typeof n?{ref:n}:{ref:n,code:(0,e.stringify)(n)})}return Xc.macroKeywordCode=function(t,r){const{gen:n,keyword:o,schema:a,parentSchema:i,it:c}=t,u=r.macro.call(c.self,a,i,c),l=s(n,o,u);!1!==c.opts.validateSchema&&c.self.validateSchema(u,!0);const d=n.name("valid");t.subschema({schema:u,schemaPath:e.nil,errSchemaPath:`${c.errSchemaPath}/${o}`,topSchemaRef:l,compositeRule:!0},d),t.pass(d,()=>t.error(!0))},Xc.funcKeywordCode=function(a,i){var c;const{gen:u,keyword:l,schema:d,parentSchema:h,$data:p,it:f}=a;!function({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}(f,i);const m=!p&&i.compile?i.compile.call(f.self,d,h,f):i.validate,y=s(u,l,m),g=u.let("valid");function v(n=(i.async?e._`await `:e.nil)){const o=f.opts.passContext?t.default.this:t.default.self,s=!("compile"in i&&!p||!1===i.schema);u.assign(g,e._`${n}${(0,r.callValidateCode)(a,y,o,s)}`,i.modifying)}function _(t){var r;u.if((0,e.not)(null!==(r=i.valid)&&void 0!==r?r:g),t)}a.block$data(g,function(){if(!1===i.errors)v(),i.modifying&&o(a),_(()=>a.error());else{const r=i.async?function(){const t=u.let("ruleErrs",null);return u.try(()=>v(e._`await `),r=>u.assign(g,!1).if(e._`${r} instanceof ${f.ValidationError}`,()=>u.assign(t,e._`${r}.errors`),()=>u.throw(r))),t}():function(){const t=e._`${y}.errors`;return u.assign(t,null),v(e.nil),t}();i.modifying&&o(a),_(()=>function(r,o){const{gen:s}=r;s.if(e._`Array.isArray(${o})`,()=>{s.assign(t.default.vErrors,e._`${t.default.vErrors} === null ? ${o} : ${t.default.vErrors}.concat(${o})`).assign(t.default.errors,e._`${t.default.vErrors}.length`),(0,n.extendErrors)(r)},()=>r.error())}(a,r))}}),a.ok(null!==(c=i.valid)&&void 0!==c?c:g)},Xc.validSchemaType=function(e,t,r=!1){return!t.length||t.some(t=>"array"===t?Array.isArray(e):"object"===t?e&&"object"==typeof e&&!Array.isArray(e):typeof e==t||r&&void 0===e)},Xc.validateKeywordUsage=function({schema:e,opts:t,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");const a=o.dependencies;if(null==a?void 0:a.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw new Error(`parent schema must have dependencies of ${s}: ${a.join(",")}`);if(o.validateSchema){if(!o.validateSchema(e[s])){const e=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if("log"!==t.validateSchema)throw new Error(e);r.logger.error(e)}}},Xc}var nu,ou={};var su={},au=function e(t,r){if(t===r)return!0;if(t&&r&&"object"==typeof t&&"object"==typeof r){if(t.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(t)){if((n=t.length)!=r.length)return!1;for(o=n;0!==o--;)if(!e(t[o],r[o]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if((n=(s=Object.keys(t)).length)!==Object.keys(r).length)return!1;for(o=n;0!==o--;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;0!==o--;){var a=s[o];if(!e(t[a],r[a]))return!1}return!0}return t!=t&&r!=r},iu={exports:{}},cu=iu.exports=function(e,t,r){"function"==typeof t&&(r=t,t={}),uu(t,"function"==typeof(r=t.cb||r)?r:r.pre||function(){},r.post||function(){},e,"",e)};function uu(e,t,r,n,o,s,a,i,c,u){if(n&&"object"==typeof n&&!Array.isArray(n)){for(var l in t(n,o,s,a,i,c,u),n){var d=n[l];if(Array.isArray(d)){if(l in cu.arrayKeywords)for(var h=0;h<d.length;h++)uu(e,t,r,d[h],o+"/"+l+"/"+h,s,o,l,n,h)}else if(l in cu.propsKeywords){if(d&&"object"==typeof d)for(var p in d)uu(e,t,r,d[p],o+"/"+l+"/"+lu(p),s,o,l,n,p)}else(l in cu.keywords||e.allKeys&&!(l in cu.skipKeywords))&&uu(e,t,r,d,o+"/"+l,s,o,l,n)}r(n,o,s,a,i,c,u)}}function lu(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}cu.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},cu.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},cu.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},cu.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};var du=iu.exports;Object.defineProperty(su,"__esModule",{value:!0}),su.getSchemaRefs=su.resolveUrl=su.normalizeId=su._getFullPath=su.getFullPath=su.inlineRef=void 0;const hu=hc,pu=au,fu=du,mu=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);su.inlineRef=function(e,t=!0){return"boolean"==typeof e||(!0===t?!gu(e):!!t&&vu(e)<=t)};const yu=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function gu(e){for(const t in e){if(yu.has(t))return!0;const r=e[t];if(Array.isArray(r)&&r.some(gu))return!0;if("object"==typeof r&&gu(r))return!0}return!1}function vu(e){let t=0;for(const r in e){if("$ref"===r)return 1/0;if(t++,!mu.has(r)&&("object"==typeof e[r]&&(0,hu.eachItem)(e[r],e=>t+=vu(e)),t===1/0))return 1/0}return t}function _u(e,t="",r){!1!==r&&(t=bu(t));const n=e.parse(t);return wu(e,n)}function wu(e,t){return e.serialize(t).split("#")[0]+"#"}su.getFullPath=_u,su._getFullPath=wu;const $u=/#\/?$/;function bu(e){return e?e.replace($u,""):""}su.normalizeId=bu,su.resolveUrl=function(e,t,r){return r=bu(r),e.resolve(t,r)};const ku=/^[a-z_][-a-z0-9._]*$/i;var Eu;function Pu(){if(Eu)return tc;Eu=1,Object.defineProperty(tc,"__esModule",{value:!0}),tc.getData=tc.KeywordCxt=tc.validateFunctionCode=void 0;const e=function(){if(Tc)return rc;Tc=1,Object.defineProperty(rc,"__esModule",{value:!0}),rc.boolOrEmptySchema=rc.topBoolOrEmptySchema=void 0;const e=Nc(),t=dc(),r=xc(),n={message:"boolean schema is false"};function o(t,r){const{gen:o,data:s}=t,a={gen:o,keyword:"false schema",data:s,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,e.reportError)(a,n,void 0,r)}return rc.topBoolOrEmptySchema=function(e){const{gen:n,schema:s,validateName:a}=e;!1===s?o(e,!1):"object"==typeof s&&!0===s.$async?n.return(r.default.data):(n.assign(t._`${a}.errors`,null),n.return(!0))},rc.boolOrEmptySchema=function(e,t){const{gen:r,schema:n}=e;!1===n?(r.var(t,!1),o(e)):r.var(t,!0)},rc}(),t=Cc,r=Ac(),n=Cc,o=function(){if(Jc)return Wc;Jc=1,Object.defineProperty(Wc,"__esModule",{value:!0}),Wc.assignDefaults=void 0;const e=dc(),t=hc;function r(r,n,o){const{gen:s,compositeRule:a,data:i,opts:c}=r;if(void 0===o)return;const u=e._`${i}${(0,e.getProperty)(n)}`;if(a)return void(0,t.checkStrictMode)(r,`default is ignored for: ${u}`);let l=e._`${u} === undefined`;"empty"===c.useDefaults&&(l=e._`${l} || ${u} === null || ${u} === ""`),s.if(l,e._`${u} = ${(0,e.stringify)(o)}`)}return Wc.assignDefaults=function(e,t){const{properties:n,items:o}=e.schema;if("object"===t&&n)for(const t in n)r(e,t,n[t].default);else"array"===t&&Array.isArray(o)&&o.forEach((t,n)=>r(e,n,t.default))},Wc}(),s=ru(),a=function(){if(nu)return ou;nu=1,Object.defineProperty(ou,"__esModule",{value:!0}),ou.extendSubschemaMode=ou.extendSubschemaData=ou.getSubschema=void 0;const e=dc(),t=hc;return ou.getSubschema=function(r,{keyword:n,schemaProp:o,schema:s,schemaPath:a,errSchemaPath:i,topSchemaRef:c}){if(void 0!==n&&void 0!==s)throw new Error('both "keyword" and "schema" passed, only one allowed');if(void 0!==n){const s=r.schema[n];return void 0===o?{schema:s,schemaPath:e._`${r.schemaPath}${(0,e.getProperty)(n)}`,errSchemaPath:`${r.errSchemaPath}/${n}`}:{schema:s[o],schemaPath:e._`${r.schemaPath}${(0,e.getProperty)(n)}${(0,e.getProperty)(o)}`,errSchemaPath:`${r.errSchemaPath}/${n}/${(0,t.escapeFragment)(o)}`}}if(void 0!==s){if(void 0===a||void 0===i||void 0===c)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:s,schemaPath:a,topSchemaRef:c,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')},ou.extendSubschemaData=function(r,n,{dataProp:o,dataPropType:s,data:a,dataTypes:i,propertyName:c}){if(void 0!==a&&void 0!==o)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:u}=n;if(void 0!==o){const{errorPath:a,dataPathArr:i,opts:c}=n;l(u.let("data",e._`${n.data}${(0,e.getProperty)(o)}`,!0)),r.errorPath=e.str`${a}${(0,t.getErrorPath)(o,s,c.jsPropertySyntax)}`,r.parentDataProperty=e._`${o}`,r.dataPathArr=[...i,r.parentDataProperty]}function l(e){r.data=e,r.dataLevel=n.dataLevel+1,r.dataTypes=[],n.definedProperties=new Set,r.parentData=n.data,r.dataNames=[...n.dataNames,e]}void 0!==a&&(l(a instanceof e.Name?a:u.let("data",a,!0)),void 0!==c&&(r.propertyName=c)),i&&(r.dataTypes=i)},ou.extendSubschemaMode=function(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){void 0!==n&&(e.compositeRule=n),void 0!==o&&(e.createErrors=o),void 0!==s&&(e.allErrors=s),e.jtdDiscriminator=t,e.jtdMetadata=r},ou}(),i=dc(),c=xc(),u=su,l=hc,d=Nc();function h({gen:e,validateName:t,schema:r,schemaEnv:n,opts:o},s){o.code.es5?e.func(t,i._`${c.default.data}, ${c.default.valCxt}`,n.$async,()=>{e.code(i._`"use strict"; ${p(r,o)}`),function(e,t){e.if(c.default.valCxt,()=>{e.var(c.default.instancePath,i._`${c.default.valCxt}.${c.default.instancePath}`),e.var(c.default.parentData,i._`${c.default.valCxt}.${c.default.parentData}`),e.var(c.default.parentDataProperty,i._`${c.default.valCxt}.${c.default.parentDataProperty}`),e.var(c.default.rootData,i._`${c.default.valCxt}.${c.default.rootData}`),t.dynamicRef&&e.var(c.default.dynamicAnchors,i._`${c.default.valCxt}.${c.default.dynamicAnchors}`)},()=>{e.var(c.default.instancePath,i._`""`),e.var(c.default.parentData,i._`undefined`),e.var(c.default.parentDataProperty,i._`undefined`),e.var(c.default.rootData,c.default.data),t.dynamicRef&&e.var(c.default.dynamicAnchors,i._`{}`)})}(e,o),e.code(s)}):e.func(t,i._`${c.default.data}, ${function(e){return i._`{${c.default.instancePath}="", ${c.default.parentData}, ${c.default.parentDataProperty}, ${c.default.rootData}=${c.default.data}${e.dynamicRef?i._`, ${c.default.dynamicAnchors}={}`:i.nil}}={}`}(o)}`,n.$async,()=>e.code(p(r,o)).code(s))}function p(e,t){const r="object"==typeof e&&e[t.schemaId];return r&&(t.code.source||t.code.process)?i._`/*# sourceURL=${r} */`:i.nil}function f(t,r){y(t)&&(g(t),m(t))?function(e,t){const{schema:r,gen:n,opts:o}=e;o.$comment&&r.$comment&&_(e);(function(e){const t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,u.resolveUrl)(e.opts.uriResolver,e.baseId,t))})(e),function(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}(e);const s=n.const("_errs",c.default.errors);v(e,s),n.var(t,i._`${s} === ${c.default.errors}`)}(t,r):(0,e.boolOrEmptySchema)(t,r)}function m({schema:e,self:t}){if("boolean"==typeof e)return!e;for(const r in e)if(t.RULES.all[r])return!0;return!1}function y(e){return"boolean"!=typeof e.schema}function g(e){(0,l.checkUnknownRules)(e),function(e){const{schema:t,errSchemaPath:r,opts:n,self:o}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,l.schemaHasRulesButRef)(t,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}(e)}function v(e,r){if(e.opts.jtd)return w(e,[],!1,r);const n=(0,t.getSchemaTypes)(e.schema);w(e,n,!(0,t.coerceAndCheckDataType)(e,n),r)}function _({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:o}){const s=r.$comment;if(!0===o.$comment)e.code(i._`${c.default.self}.logger.log(${s})`);else if("function"==typeof o.$comment){const r=i.str`${n}/$comment`,o=e.scopeValue("root",{ref:t.root});e.code(i._`${c.default.self}.opts.$comment(${s}, ${r}, ${o}.schema)`)}}function w(e,t,o,s){const{gen:a,schema:u,data:d,allErrors:h,opts:p,self:f}=e,{RULES:m}=f;function y(l){(0,r.shouldUseGroup)(u,l)&&(l.type?(a.if((0,n.checkDataType)(l.type,d,p.strictNumbers)),$(e,l),1===t.length&&t[0]===l.type&&o&&(a.else(),(0,n.reportTypeError)(e)),a.endIf()):$(e,l),h||a.if(i._`${c.default.errors} === ${s||0}`))}!u.$ref||!p.ignoreKeywordsWithRef&&(0,l.schemaHasRulesButRef)(u,m)?(p.jtd||function(e,t){if(e.schemaEnv.meta||!e.opts.strictTypes)return;(function(e,t){if(!t.length)return;if(!e.dataTypes.length)return void(e.dataTypes=t);t.forEach(t=>{k(e.dataTypes,t)||E(e,`type "${t}" not allowed by context "${e.dataTypes.join(",")}"`)}),function(e,t){const r=[];for(const n of e.dataTypes)k(t,n)?r.push(n):t.includes("integer")&&"number"===n&&r.push("integer");e.dataTypes=r}(e,t)})(e,t),e.opts.allowUnionTypes||function(e,t){t.length>1&&(2!==t.length||!t.includes("null"))&&E(e,"use allowUnionTypes to allow union type keyword")}(e,t);!function(e,t){const n=e.self.RULES.all;for(const o in n){const s=n[o];if("object"==typeof s&&(0,r.shouldUseRule)(e.schema,s)){const{type:r}=s.definition;r.length&&!r.some(e=>b(t,e))&&E(e,`missing type "${r.join(",")}" for keyword "${o}"`)}}}(e,e.dataTypes)}(e,t),a.block(()=>{for(const e of m.rules)y(e);y(m.post)})):a.block(()=>S(e,"$ref",m.all.$ref.definition))}function $(e,t){const{gen:n,schema:s,opts:{useDefaults:a}}=e;a&&(0,o.assignDefaults)(e,t.type),n.block(()=>{for(const n of t.rules)(0,r.shouldUseRule)(s,n)&&S(e,n.keyword,n.definition,t.type)})}function b(e,t){return e.includes(t)||"number"===t&&e.includes("integer")}function k(e,t){return e.includes(t)||"integer"===t&&e.includes("number")}function E(e,t){t+=` at "${e.schemaEnv.baseId+e.errSchemaPath}" (strictTypes)`,(0,l.checkStrictMode)(e,t,e.opts.strictTypes)}tc.validateFunctionCode=function(t){y(t)&&(g(t),m(t))?function(e){const{schema:t,opts:r,gen:n}=e;h(e,()=>{r.$comment&&t.$comment&&_(e),function(e){const{schema:t,opts:r}=e;void 0!==t.default&&r.useDefaults&&r.strictSchema&&(0,l.checkStrictMode)(e,"default is ignored in the schema root")}(e),n.let(c.default.vErrors,null),n.let(c.default.errors,0),r.unevaluated&&function(e){const{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",i._`${r}.evaluated`),t.if(i._`${e.evaluated}.dynamicProps`,()=>t.assign(i._`${e.evaluated}.props`,i._`undefined`)),t.if(i._`${e.evaluated}.dynamicItems`,()=>t.assign(i._`${e.evaluated}.items`,i._`undefined`))}(e),v(e),function(e){const{gen:t,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=e;r.$async?t.if(i._`${c.default.errors} === 0`,()=>t.return(c.default.data),()=>t.throw(i._`new ${o}(${c.default.vErrors})`)):(t.assign(i._`${n}.errors`,c.default.vErrors),s.unevaluated&&function({gen:e,evaluated:t,props:r,items:n}){r instanceof i.Name&&e.assign(i._`${t}.props`,r);n instanceof i.Name&&e.assign(i._`${t}.items`,n)}(e),t.return(i._`${c.default.errors} === 0`))}(e)})}(t):h(t,()=>(0,e.topBoolOrEmptySchema)(t))};class P{constructor(e,t,r){if((0,s.validateKeywordUsage)(e,t,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,l.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const("vSchema",x(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,s.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw new Error(`${r} value must be ${JSON.stringify(t.schemaType)}`);("code"in t?t.trackErrors:!1!==t.errors)&&(this.errsCount=e.gen.const("_errs",c.default.errors))}result(e,t,r){this.failResult((0,i.not)(e),t,r)}failResult(e,t,r){this.gen.if(e),r?r():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,i.not)(e),void 0,t)}fail(e){if(void 0===e)return this.error(),void(this.allErrors||this.gen.if(!1));this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);const{schemaCode:t}=this;this.fail(i._`${t} !== undefined && (${(0,i.or)(this.invalid$data(),e)})`)}error(e,t,r){if(t)return this.setParams(t),this._error(e,r),void this.setParams({});this._error(e,r)}_error(e,t){(e?d.reportExtraError:d.reportError)(this,this.def.error,t)}$dataError(){(0,d.reportError)(this,this.def.$dataError||d.keyword$DataError)}reset(){if(void 0===this.errsCount)throw new Error('add "trackErrors" to keyword definition');(0,d.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,r=i.nil){this.gen.block(()=>{this.check$data(e,r),t()})}check$data(e=i.nil,t=i.nil){if(!this.$data)return;const{gen:r,schemaCode:n,schemaType:o,def:s}=this;r.if((0,i.or)(i._`${n} === undefined`,t)),e!==i.nil&&r.assign(e,!0),(o.length||s.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==i.nil&&r.assign(e,!1)),r.else()}invalid$data(){const{gen:e,schemaCode:t,schemaType:r,def:o,it:s}=this;return(0,i.or)(function(){if(r.length){if(!(t instanceof i.Name))throw new Error("ajv implementation error");const e=Array.isArray(r)?r:[r];return i._`${(0,n.checkDataTypes)(e,t,s.opts.strictNumbers,n.DataType.Wrong)}`}return i.nil}(),function(){if(o.validateSchema){const r=e.scopeValue("validate$data",{ref:o.validateSchema});return i._`!${r}(${t})`}return i.nil}())}subschema(e,t){const r=(0,a.getSubschema)(this.it,e);(0,a.extendSubschemaData)(r,this.it,e),(0,a.extendSubschemaMode)(r,e);const n={...this.it,...r,items:void 0,props:void 0};return f(n,t),n}mergeEvaluated(e,t){const{it:r,gen:n}=this;r.opts.unevaluated&&(!0!==r.props&&void 0!==e.props&&(r.props=l.mergeEvaluated.props(n,e.props,r.props,t)),!0!==r.items&&void 0!==e.items&&(r.items=l.mergeEvaluated.items(n,e.items,r.items,t)))}mergeValidEvaluated(e,t){const{it:r,gen:n}=this;if(r.opts.unevaluated&&(!0!==r.props||!0!==r.items))return n.if(t,()=>this.mergeEvaluated(e,i.Name)),!0}}function S(e,t,r,n){const o=new P(e,r,t);"code"in r?r.code(o,n):o.$data&&r.validate?(0,s.funcKeywordCode)(o,r):"macro"in r?(0,s.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,s.funcKeywordCode)(o,r)}tc.KeywordCxt=P;const T=/^\/(?:[^~]|~0|~1)*$/,I=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function x(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let o,s;if(""===e)return c.default.rootData;if("/"===e[0]){if(!T.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);o=e,s=c.default.rootData}else{const a=I.exec(e);if(!a)throw new Error(`Invalid JSON-pointer: ${e}`);const i=+a[1];if(o=a[2],"#"===o){if(i>=t)throw new Error(d("property/index",i));return n[t-i]}if(i>t)throw new Error(d("data",i));if(s=r[t-i],!o)return s}let a=s;const u=o.split("/");for(const e of u)e&&(s=i._`${s}${(0,i.getProperty)((0,l.unescapeJsonPointer)(e))}`,a=i._`${a} && ${s}`);return a;function d(e,r){return`Cannot access ${e} ${r} levels up, current level is ${t}`}}return tc.getData=x,tc}su.getSchemaRefs=function(e,t){if("boolean"==typeof e)return{};const{schemaId:r,uriResolver:n}=this.opts,o=bu(e[r]||t),s={"":o},a=_u(n,o,!1),i={},c=new Set;return fu(e,{allKeys:!0},(e,t,n,o)=>{if(void 0===o)return;const d=a+t;let h=s[o];function p(t){const r=this.opts.uriResolver.resolve;if(t=bu(h?r(h,t):t),c.has(t))throw l(t);c.add(t);let n=this.refs[t];return"string"==typeof n&&(n=this.refs[n]),"object"==typeof n?u(e,n.schema,t):t!==bu(d)&&("#"===t[0]?(u(e,i[t],t),i[t]=e):this.refs[t]=d),t}function f(e){if("string"==typeof e){if(!ku.test(e))throw new Error(`invalid anchor "${e}"`);p.call(this,`#${e}`)}}"string"==typeof e[r]&&(h=p.call(this,e[r])),f.call(this,e.$anchor),f.call(this,e.$dynamicAnchor),s[t]=h}),i;function u(e,t,r){if(void 0!==t&&!pu(e,t))throw l(r)}function l(e){return new Error(`reference "${e}" resolves to more than one schema`)}};var Su,Tu={};function Iu(){if(Su)return Tu;Su=1,Object.defineProperty(Tu,"__esModule",{value:!0});class e extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}}return Tu.default=e,Tu}var xu,Nu={};function Cu(){if(xu)return Nu;xu=1,Object.defineProperty(Nu,"__esModule",{value:!0});const e=su;class t extends Error{constructor(t,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,e.resolveUrl)(t,r,n),this.missingSchema=(0,e.normalizeId)((0,e.getFullPath)(t,this.missingRef))}}return Nu.default=t,Nu}var ju={};Object.defineProperty(ju,"__esModule",{value:!0}),ju.resolveSchema=ju.getCompilingSchema=ju.resolveRef=ju.compileSchema=ju.SchemaEnv=void 0;const Ru=dc(),Ou=Iu(),zu=xc(),Au=su,Mu=hc,Du=Pu();let Uu=class{constructor(e){var t;let r;this.refs={},this.dynamicAnchors={},"object"==typeof e.schema&&(r=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=null!==(t=e.baseId)&&void 0!==t?t:(0,Au.normalizeId)(null==r?void 0:r[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=null==r?void 0:r.$async,this.refs={}}};function qu(e){const t=Fu.call(this,e);if(t)return t;const r=(0,Au.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,a=new Ru.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s});let i;e.$async&&(i=a.scopeValue("Error",{ref:Ou.default,code:Ru._`require("ajv/dist/runtime/validation_error").default`}));const c=a.scopeName("validate");e.validateName=c;const u={gen:a,allErrors:this.opts.allErrors,data:zu.default.data,parentData:zu.default.parentData,parentDataProperty:zu.default.parentDataProperty,dataNames:[zu.default.data],dataPathArr:[Ru.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:a.scopeValue("schema",!0===this.opts.code.source?{ref:e.schema,code:(0,Ru.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:i,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:Ru.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:Ru._`""`,opts:this.opts,self:this};let l;try{this._compilations.add(e),(0,Du.validateFunctionCode)(u),a.optimize(this.opts.code.optimize);const t=a.toString();l=`${a.scopeRefs(zu.default.scope)}return ${t}`,this.opts.code.process&&(l=this.opts.code.process(l,e));const r=new Function(`${zu.default.self}`,`${zu.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:r}),r.errors=null,r.schema=e.schema,r.schemaEnv=e,e.$async&&(r.$async=!0),!0===this.opts.code.source&&(r.source={validateName:c,validateCode:t,scopeValues:a._values}),this.opts.unevaluated){const{props:e,items:t}=u;r.evaluated={props:e instanceof Ru.Name?void 0:e,items:t instanceof Ru.Name?void 0:t,dynamicProps:e instanceof Ru.Name,dynamicItems:t instanceof Ru.Name},r.source&&(r.source.evaluated=(0,Ru.stringify)(r.evaluated))}return e.validate=r,e}catch(t){throw delete e.validate,delete e.validateName,l&&this.logger.error("Error compiling schema, function code:",l),t}finally{this._compilations.delete(e)}}function Vu(e){return(0,Au.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:qu.call(this,e)}function Fu(e){for(const t of this._compilations)if(Lu(t,e))return t}function Lu(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function Ku(e,t){let r;for(;"string"==typeof(r=this.refs[t]);)t=r;return r||this.schemas[t]||Hu.call(this,e,t)}function Hu(e,t){const r=this.opts.uriResolver.parse(t),n=(0,Au._getFullPath)(this.opts.uriResolver,r);let o=(0,Au.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===o)return Gu.call(this,r,e);const s=(0,Au.normalizeId)(n),a=this.refs[s]||this.schemas[s];if("string"==typeof a){const t=Hu.call(this,e,a);if("object"!=typeof(null==t?void 0:t.schema))return;return Gu.call(this,r,t)}if("object"==typeof(null==a?void 0:a.schema)){if(a.validate||qu.call(this,a),s===(0,Au.normalizeId)(t)){const{schema:t}=a,{schemaId:r}=this.opts,n=t[r];return n&&(o=(0,Au.resolveUrl)(this.opts.uriResolver,o,n)),new Uu({schema:t,schemaId:r,root:e,baseId:o})}return Gu.call(this,r,a)}}ju.SchemaEnv=Uu,ju.compileSchema=qu,ju.resolveRef=function(e,t,r){var n;r=(0,Au.resolveUrl)(this.opts.uriResolver,t,r);const o=e.refs[r];if(o)return o;let s=Ku.call(this,e,r);if(void 0===s){const o=null===(n=e.localRefs)||void 0===n?void 0:n[r],{schemaId:a}=this.opts;o&&(s=new Uu({schema:o,schemaId:a,root:e,baseId:t}))}return void 0!==s?e.refs[r]=Vu.call(this,s):void 0},ju.getCompilingSchema=Fu,ju.resolveSchema=Hu;const Zu=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Gu(e,{baseId:t,schema:r,root:n}){var o;if("/"!==(null===(o=e.fragment)||void 0===o?void 0:o[0]))return;for(const n of e.fragment.slice(1).split("/")){if("boolean"==typeof r)return;const e=r[(0,Mu.unescapeFragment)(n)];if(void 0===e)return;const o="object"==typeof(r=e)&&r[this.opts.schemaId];!Zu.has(n)&&o&&(t=(0,Au.resolveUrl)(this.opts.uriResolver,t,o))}let s;if("boolean"!=typeof r&&r.$ref&&!(0,Mu.schemaHasRulesButRef)(r,this.RULES)){const e=(0,Au.resolveUrl)(this.opts.uriResolver,t,r.$ref);s=Hu.call(this,n,e)}const{schemaId:a}=this.opts;return s=s||new Uu({schema:r,schemaId:a,root:n,baseId:t}),s.schema!==s.root.schema?s:void 0}var Bu={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1},Ju={},Wu={exports:{}};const Qu=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Yu=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function Xu(e){let t="",r=0,n=0;for(n=0;n<e.length;n++)if(r=e[n].charCodeAt(0),48!==r){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n];break}for(n+=1;n<e.length;n++){if(r=e[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n]}return t}function el(e){return e.length=0,!0}function tl(e,t,r){if(e.length){const n=Xu(e);if(""===n)return r.error=!0,!1;t.push(n),e.length=0}return!0}function rl(e){if(function(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}(e,":")<2)return{host:e,isIPV6:!1};const t=function(e){let t=0;const r={error:!1,address:"",zone:""},n=[],o=[];let s=!1,a=!1,i=tl;for(let c=0;c<e.length;c++){const u=e[c];if("["!==u&&"]"!==u)if(":"!==u)if("%"===u){if(!i(o,n,r))break;i=el}else o.push(u);else{if(!0===s&&(a=!0),!i(o,n,r))break;if(++t>7){r.error=!0;break}c>0&&":"===e[c-1]&&(s=!0),n.push(":")}}return o.length&&(i===el?r.zone=o.join(""):a?n.push(o.join("")):n.push(Xu(o))),r.address=n.join(""),r}(e);if(t.error)return{host:e,isIPV6:!1};{let e=t.address,r=t.address;return t.zone&&(e+="%"+t.zone,r+="%25"+t.zone),{host:e,isIPV6:!0,escapedHost:r}}}var nl={nonSimpleDomain:RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u),recomposeAuthority:function(e){const t=[];if(void 0!==e.userinfo&&(t.push(e.userinfo),t.push("@")),void 0!==e.host){let r=unescape(e.host);if(!Yu(r)){const t=rl(r);r=!0===t.isIPV6?`[${t.escapedHost}]`:e.host}t.push(r)}return"number"!=typeof e.port&&"string"!=typeof e.port||(t.push(":"),t.push(String(e.port))),t.length?t.join(""):void 0},normalizeComponentEncoding:function(e,t){const r=!0!==t?escape:unescape;return void 0!==e.scheme&&(e.scheme=r(e.scheme)),void 0!==e.userinfo&&(e.userinfo=r(e.userinfo)),void 0!==e.host&&(e.host=r(e.host)),void 0!==e.path&&(e.path=r(e.path)),void 0!==e.query&&(e.query=r(e.query)),void 0!==e.fragment&&(e.fragment=r(e.fragment)),e},removeDotSegments:function(e){let t=e;const r=[];let n=-1,o=0;for(;o=t.length;){if(1===o){if("."===t)break;if("/"===t){r.push("/");break}r.push(t);break}if(2===o){if("."===t[0]){if("."===t[1])break;if("/"===t[1]){t=t.slice(2);continue}}else if("/"===t[0]&&("."===t[1]||"/"===t[1])){r.push("/");break}}else if(3===o&&"/.."===t){0!==r.length&&r.pop(),r.push("/");break}if("."===t[0]){if("."===t[1]){if("/"===t[2]){t=t.slice(3);continue}}else if("/"===t[1]){t=t.slice(2);continue}}else if("/"===t[0]&&"."===t[1]){if("/"===t[2]){t=t.slice(2);continue}if("."===t[2]&&"/"===t[3]){t=t.slice(3),0!==r.length&&r.pop();continue}}if(-1===(n=t.indexOf("/",1))){r.push(t);break}r.push(t.slice(0,n)),t=t.slice(n)}return r.join("")},isIPv4:Yu,isUUID:Qu,normalizeIPv6:rl,stringArrayToHexStripped:Xu};const{isUUID:ol}=nl,sl=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,al=["http","https","ws","wss","urn","urn:uuid"];function il(e){return!0===e.secure||!1!==e.secure&&(!!e.scheme&&!(3!==e.scheme.length||"w"!==e.scheme[0]&&"W"!==e.scheme[0]||"s"!==e.scheme[1]&&"S"!==e.scheme[1]||"s"!==e.scheme[2]&&"S"!==e.scheme[2]))}function cl(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function ul(e){const t="https"===String(e.scheme).toLowerCase();return e.port!==(t?443:80)&&""!==e.port||(e.port=void 0),e.path||(e.path="/"),e}const ll={scheme:"http",domainHost:!0,parse:cl,serialize:ul},dl={scheme:"ws",domainHost:!0,parse:function(e){return e.secure=il(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e},serialize:function(e){if(e.port!==(il(e)?443:80)&&""!==e.port||(e.port=void 0),"boolean"==typeof e.secure&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){const[t,r]=e.resourceName.split("?");e.path=t&&"/"!==t?t:void 0,e.query=r,e.resourceName=void 0}return e.fragment=void 0,e}},hl={http:ll,https:{scheme:"https",domainHost:ll.domainHost,parse:cl,serialize:ul},ws:dl,wss:{scheme:"wss",domainHost:dl.domainHost,parse:dl.parse,serialize:dl.serialize},urn:{scheme:"urn",parse:function(e,t){if(!e.path)return e.error="URN can not be parsed",e;const r=e.path.match(sl);if(r){const n=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];const o=pl(`${n}:${t.nid||e.nid}`);e.path=void 0,o&&(e=o.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e},serialize:function(e,t){if(void 0===e.nid)throw new Error("URN without nid cannot be serialized");const r=t.scheme||e.scheme||"urn",n=e.nid.toLowerCase(),o=pl(`${r}:${t.nid||n}`);o&&(e=o.serialize(e,t));const s=e,a=e.nss;return s.path=`${n||t.nid}:${a}`,t.skipEscape=!0,s},skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:function(e,t){const r=e;return r.uuid=r.nss,r.nss=void 0,t.tolerant||r.uuid&&ol(r.uuid)||(r.error=r.error||"UUID is not valid."),r},serialize:function(e){const t=e;return t.nss=(e.uuid||"").toLowerCase(),t},skipNormalize:!0}};function pl(e){return e&&(hl[e]||hl[e.toLowerCase()])||void 0}Object.setPrototypeOf(hl,null);var fl={wsIsSecure:il,SCHEMES:hl,isValidSchemeName:function(e){return-1!==al.indexOf(e)},getSchemeHandler:pl};const{normalizeIPv6:ml,removeDotSegments:yl,recomposeAuthority:gl,normalizeComponentEncoding:vl,isIPv4:_l,nonSimpleDomain:wl}=nl,{SCHEMES:$l,getSchemeHandler:bl}=fl;function kl(e,t,r,n){const o={};return n||(e=Sl(El(e,r),r),t=Sl(El(t,r),r)),!(r=r||{}).tolerant&&t.scheme?(o.scheme=t.scheme,o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=yl(t.path||""),o.query=t.query):(void 0!==t.userinfo||void 0!==t.host||void 0!==t.port?(o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=yl(t.path||""),o.query=t.query):(t.path?("/"===t.path[0]?o.path=yl(t.path):(void 0===e.userinfo&&void 0===e.host&&void 0===e.port||e.path?e.path?o.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:o.path=t.path:o.path="/"+t.path,o.path=yl(o.path)),o.query=t.query):(o.path=e.path,void 0!==t.query?o.query=t.query:o.query=e.query),o.userinfo=e.userinfo,o.host=e.host,o.port=e.port),o.scheme=e.scheme),o.fragment=t.fragment,o}function El(e,t){const r={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},n=Object.assign({},t),o=[],s=bl(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),void 0!==r.path&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),void 0!==r.scheme&&(r.path=r.path.split("%3A").join(":")))),"suffix"!==n.reference&&r.scheme&&o.push(r.scheme,":");const a=gl(r);if(void 0!==a&&("suffix"!==n.reference&&o.push("//"),o.push(a),r.path&&"/"!==r.path[0]&&o.push("/")),void 0!==r.path){let e=r.path;n.absolutePath||s&&s.absolutePath||(e=yl(e)),void 0===a&&"/"===e[0]&&"/"===e[1]&&(e="/%2F"+e.slice(2)),o.push(e)}return void 0!==r.query&&o.push("?",r.query),void 0!==r.fragment&&o.push("#",r.fragment),o.join("")}const Pl=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Sl(e,t){const r=Object.assign({},t),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let o=!1;"suffix"===r.reference&&(e=r.scheme?r.scheme+":"+e:"//"+e);const s=e.match(Pl);if(s){if(n.scheme=s[1],n.userinfo=s[3],n.host=s[4],n.port=parseInt(s[5],10),n.path=s[6]||"",n.query=s[7],n.fragment=s[8],isNaN(n.port)&&(n.port=s[5]),n.host){if(!1===_l(n.host)){const e=ml(n.host);n.host=e.host.toLowerCase(),o=e.isIPV6}else o=!0}void 0!==n.scheme||void 0!==n.userinfo||void 0!==n.host||void 0!==n.port||void 0!==n.query||n.path?void 0===n.scheme?n.reference="relative":void 0===n.fragment?n.reference="absolute":n.reference="uri":n.reference="same-document",r.reference&&"suffix"!==r.reference&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");const t=bl(r.scheme||n.scheme);if(!(r.unicodeSupport||t&&t.unicodeSupport)&&n.host&&(r.domainHost||t&&t.domainHost)&&!1===o&&wl(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(e){n.error=n.error||"Host's domain name can not be converted to ASCII: "+e}(!t||t&&!t.skipNormalize)&&(-1!==e.indexOf("%")&&(void 0!==n.scheme&&(n.scheme=unescape(n.scheme)),void 0!==n.host&&(n.host=unescape(n.host))),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),t&&t.parse&&t.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}const Tl={SCHEMES:$l,normalize:function(e,t){return"string"==typeof e?e=El(Sl(e,t),t):"object"==typeof e&&(e=Sl(El(e,t),t)),e},resolve:function(e,t,r){const n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=kl(Sl(e,n),Sl(t,n),n,!0);return n.skipEscape=!0,El(o,n)},resolveComponent:kl,equal:function(e,t,r){return"string"==typeof e?(e=unescape(e),e=El(vl(Sl(e,r),!0),{...r,skipEscape:!0})):"object"==typeof e&&(e=El(vl(e,!0),{...r,skipEscape:!0})),"string"==typeof t?(t=unescape(t),t=El(vl(Sl(t,r),!0),{...r,skipEscape:!0})):"object"==typeof t&&(t=El(vl(t,!0),{...r,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()},serialize:El,parse:Sl};Wu.exports=Tl,Wu.exports.default=Tl,Wu.exports.fastUri=Tl;var Il=Wu.exports;Object.defineProperty(Ju,"__esModule",{value:!0});const xl=Il;xl.code='require("ajv/dist/runtime/uri").default',Ju.default=xl,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=Pu();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var r=dc();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return r.CodeGen}});const n=Iu(),o=Cu(),s=jc,a=ju,i=dc(),c=su,u=Cc,l=hc,d=Bu,h=Ju,p=(e,t)=>new RegExp(e,t);p.code="new RegExp";const f=["removeAdditional","useDefaults","coerceTypes"],m=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),y={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},g={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'};function v(e){var t,r,n,o,s,a,i,c,u,l,d,f,m,y,g,v,_,w,$,b,k,E,P,S,T;const I=e.strict,x=null===(t=e.code)||void 0===t?void 0:t.optimize,N=!0===x||void 0===x?1:x||0,C=null!==(n=null===(r=e.code)||void 0===r?void 0:r.regExp)&&void 0!==n?n:p,j=null!==(o=e.uriResolver)&&void 0!==o?o:h.default;return{strictSchema:null===(a=null!==(s=e.strictSchema)&&void 0!==s?s:I)||void 0===a||a,strictNumbers:null===(c=null!==(i=e.strictNumbers)&&void 0!==i?i:I)||void 0===c||c,strictTypes:null!==(l=null!==(u=e.strictTypes)&&void 0!==u?u:I)&&void 0!==l?l:"log",strictTuples:null!==(f=null!==(d=e.strictTuples)&&void 0!==d?d:I)&&void 0!==f?f:"log",strictRequired:null!==(y=null!==(m=e.strictRequired)&&void 0!==m?m:I)&&void 0!==y&&y,code:e.code?{...e.code,optimize:N,regExp:C}:{optimize:N,regExp:C},loopRequired:null!==(g=e.loopRequired)&&void 0!==g?g:200,loopEnum:null!==(v=e.loopEnum)&&void 0!==v?v:200,meta:null===(_=e.meta)||void 0===_||_,messages:null===(w=e.messages)||void 0===w||w,inlineRefs:null===($=e.inlineRefs)||void 0===$||$,schemaId:null!==(b=e.schemaId)&&void 0!==b?b:"$id",addUsedSchema:null===(k=e.addUsedSchema)||void 0===k||k,validateSchema:null===(E=e.validateSchema)||void 0===E||E,validateFormats:null===(P=e.validateFormats)||void 0===P||P,unicodeRegExp:null===(S=e.unicodeRegExp)||void 0===S||S,int32range:null===(T=e.int32range)||void 0===T||T,uriResolver:j}}class _{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...v(e)};const{es5:t,lines:r}=this.opts.code;this.scope=new i.ValueScope({scope:{},prefixes:m,es5:t,lines:r}),this.logger=function(e){if(!1===e)return S;if(void 0===e)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}(e.logger);const n=e.validateFormats;e.validateFormats=!1,this.RULES=(0,s.getRules)(),w.call(this,y,e,"NOT SUPPORTED"),w.call(this,g,e,"DEPRECATED","warn"),this._metaOpts=P.call(this),e.formats&&k.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&E.call(this,e.keywords),"object"==typeof e.meta&&this.addMetaSchema(e.meta),b.call(this),e.validateFormats=n}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:e,meta:t,schemaId:r}=this.opts;let n=d;"id"===r&&(n={...d},n.id=n.$id,delete n.$id),t&&e&&this.addMetaSchema(n,n[r],!1)}defaultMeta(){const{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta="object"==typeof e?e[t]||e:void 0}validate(e,t){let r;if("string"==typeof e){if(r=this.getSchema(e),!r)throw new Error(`no schema with key or ref "${e}"`)}else r=this.compile(e);const n=r(t);return"$async"in r||(this.errors=r.errors),n}compile(e,t){const r=this._addSchema(e,t);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,t){if("function"!=typeof this.opts.loadSchema)throw new Error("options.loadSchema should be a function");const{loadSchema:r}=this.opts;return n.call(this,e,t);async function n(e,t){await s.call(this,e.$schema);const r=this._addSchema(e,t);return r.validate||a.call(this,r)}async function s(e){e&&!this.getSchema(e)&&await n.call(this,{$ref:e},!0)}async function a(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof o.default))throw t;return i.call(this,t),await c.call(this,t.missingSchema),a.call(this,e)}}function i({missingSchema:e,missingRef:t}){if(this.refs[e])throw new Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function c(e){const r=await u.call(this,e);this.refs[e]||await s.call(this,r.$schema),this.refs[e]||this.addSchema(r,e,t)}async function u(e){const t=this._loading[e];if(t)return t;try{return await(this._loading[e]=r(e))}finally{delete this._loading[e]}}}addSchema(e,t,r,n=this.opts.validateSchema){if(Array.isArray(e)){for(const t of e)this.addSchema(t,void 0,r,n);return this}let o;if("object"==typeof e){const{schemaId:t}=this.opts;if(o=e[t],void 0!==o&&"string"!=typeof o)throw new Error(`schema ${t} must be string`)}return t=(0,c.normalizeId)(t||o),this._checkUnique(t),this.schemas[t]=this._addSchema(e,r,t,n,!0),this}addMetaSchema(e,t,r=this.opts.validateSchema){return this.addSchema(e,t,!0,r),this}validateSchema(e,t){if("boolean"==typeof e)return!0;let r;if(r=e.$schema,void 0!==r&&"string"!=typeof r)throw new Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const n=this.validate(r,e);if(!n&&t){const e="schema is invalid: "+this.errorsText();if("log"!==this.opts.validateSchema)throw new Error(e);this.logger.error(e)}return n}getSchema(e){let t;for(;"string"==typeof(t=$.call(this,e));)e=t;if(void 0===t){const{schemaId:r}=this.opts,n=new a.SchemaEnv({schema:{},schemaId:r});if(t=a.resolveSchema.call(this,n,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const t=$.call(this,e);return"object"==typeof t&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{const t=e;this._cache.delete(t);let r=e[this.opts.schemaId];return r&&(r=(0,c.normalizeId)(r),delete this.schemas[r],delete this.refs[r]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(const t of e)this.addKeyword(t);return this}addKeyword(e,t){let r;if("string"==typeof e)r=e,"object"==typeof t&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=r);else{if("object"!=typeof e||void 0!==t)throw new Error("invalid addKeywords parameters");if(r=(t=e).keyword,Array.isArray(r)&&!r.length)throw new Error("addKeywords: keyword must be string or non-empty array")}if(I.call(this,r,t),!t)return(0,l.eachItem)(r,e=>x.call(this,e)),this;C.call(this,t);const n={...t,type:(0,u.getJSONTypes)(t.type),schemaType:(0,u.getJSONTypes)(t.schemaType)};return(0,l.eachItem)(r,0===n.type.length?e=>x.call(this,e,n):e=>n.type.forEach(t=>x.call(this,e,n,t))),this}getKeyword(e){const t=this.RULES.all[e];return"object"==typeof t?t.definition:!!t}removeKeyword(e){const{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(const r of t.rules){const t=r.rules.findIndex(t=>t.keyword===e);t>=0&&r.rules.splice(t,1)}return this}addFormat(e,t){return"string"==typeof t&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=", ",dataVar:r="data"}={}){return e&&0!==e.length?e.map(e=>`${r}${e.instancePath} ${e.message}`).reduce((e,r)=>e+t+r):"No errors"}$dataMetaSchema(e,t){const r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(const n of t){const t=n.split("/").slice(1);let o=e;for(const e of t)o=o[e];for(const e in r){const t=r[e];if("object"!=typeof t)continue;const{$data:n}=t.definition,s=o[e];n&&s&&(o[e]=R(s))}}return e}_removeAllSchemas(e,t){for(const r in e){const n=e[r];t&&!t.test(r)||("string"==typeof n?delete e[r]:n&&!n.meta&&(this._cache.delete(n.schema),delete e[r]))}}_addSchema(e,t,r,n=this.opts.validateSchema,o=this.opts.addUsedSchema){let s;const{schemaId:i}=this.opts;if("object"==typeof e)s=e[i];else{if(this.opts.jtd)throw new Error("schema must be object");if("boolean"!=typeof e)throw new Error("schema must be object or boolean")}let u=this._cache.get(e);if(void 0!==u)return u;r=(0,c.normalizeId)(s||r);const l=c.getSchemaRefs.call(this,e,r);return u=new a.SchemaEnv({schema:e,schemaId:i,meta:t,baseId:r,localRefs:l}),this._cache.set(u.schema,u),o&&!r.startsWith("#")&&(r&&this._checkUnique(r),this.refs[r]=u),n&&this.validateSchema(e,!0),u}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):a.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){const t=this.opts;this.opts=this._metaOpts;try{a.compileSchema.call(this,e)}finally{this.opts=t}}}function w(e,t,r,n="error"){for(const o in e){const s=o;s in t&&this.logger[n](`${r}: option ${o}. ${e[s]}`)}}function $(e){return e=(0,c.normalizeId)(e),this.schemas[e]||this.refs[e]}function b(){const e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(const t in e)this.addSchema(e[t],t)}function k(){for(const e in this.opts.formats){const t=this.opts.formats[e];t&&this.addFormat(e,t)}}function E(e){if(Array.isArray(e))this.addVocabulary(e);else{this.logger.warn("keywords option as map is deprecated, pass array");for(const t in e){const r=e[t];r.keyword||(r.keyword=t),this.addKeyword(r)}}}function P(){const e={...this.opts};for(const t of f)delete e[t];return e}_.ValidationError=n.default,_.MissingRefError=o.default,e.default=_;const S={log(){},warn(){},error(){}};const T=/^[a-z_$][a-z0-9_$:-]*$/i;function I(e,t){const{RULES:r}=this;if((0,l.eachItem)(e,e=>{if(r.keywords[e])throw new Error(`Keyword ${e} is already defined`);if(!T.test(e))throw new Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!("code"in t)&&!("validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}function x(e,t,r){var n;const o=null==t?void 0:t.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:s}=this;let a=o?s.post:s.rules.find(({type:e})=>e===r);if(a||(a={type:r,rules:[]},s.rules.push(a)),s.keywords[e]=!0,!t)return;const i={keyword:e,definition:{...t,type:(0,u.getJSONTypes)(t.type),schemaType:(0,u.getJSONTypes)(t.schemaType)}};t.before?N.call(this,a,i,t.before):a.rules.push(i),s.all[e]=i,null===(n=t.implements)||void 0===n||n.forEach(e=>this.addKeyword(e))}function N(e,t,r){const n=e.rules.findIndex(e=>e.keyword===r);n>=0?e.rules.splice(n,0,t):(e.rules.push(t),this.logger.warn(`rule ${r} is not defined`))}function C(e){let{metaSchema:t}=e;void 0!==t&&(e.$data&&this.opts.$data&&(t=R(t)),e.validateSchema=this.compile(t,!0))}const j={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function R(e){return{anyOf:[e,j]}}}(ec);var Nl={},Cl={},jl={};Object.defineProperty(jl,"__esModule",{value:!0});const Rl={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};jl.default=Rl;var Ol={};Object.defineProperty(Ol,"__esModule",{value:!0}),Ol.callRef=Ol.getValidate=void 0;const zl=Cu(),Al=tu(),Ml=dc(),Dl=xc(),Ul=ju,ql=hc,Vl={keyword:"$ref",schemaType:"string",code(e){const{gen:t,schema:r,it:n}=e,{baseId:o,schemaEnv:s,validateName:a,opts:i,self:c}=n,{root:u}=s;if(("#"===r||"#/"===r)&&o===u.baseId)return function(){if(s===u)return Ll(e,a,s,s.$async);const r=t.scopeValue("root",{ref:u});return Ll(e,Ml._`${r}.validate`,u,u.$async)}();const l=Ul.resolveRef.call(c,u,o,r);if(void 0===l)throw new zl.default(n.opts.uriResolver,o,r);return l instanceof Ul.SchemaEnv?function(t){const r=Fl(e,t);Ll(e,r,t,t.$async)}(l):function(n){const o=t.scopeValue("schema",!0===i.code.source?{ref:n,code:(0,Ml.stringify)(n)}:{ref:n}),s=t.name("valid"),a=e.subschema({schema:n,dataTypes:[],schemaPath:Ml.nil,topSchemaRef:o,errSchemaPath:r},s);e.mergeEvaluated(a),e.ok(s)}(l)}};function Fl(e,t){const{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):Ml._`${r.scopeValue("wrapper",{ref:t})}.validate`}function Ll(e,t,r,n){const{gen:o,it:s}=e,{allErrors:a,schemaEnv:i,opts:c}=s,u=c.passContext?Dl.default.this:Ml.nil;function l(e){const t=Ml._`${e}.errors`;o.assign(Dl.default.vErrors,Ml._`${Dl.default.vErrors} === null ? ${t} : ${Dl.default.vErrors}.concat(${t})`),o.assign(Dl.default.errors,Ml._`${Dl.default.vErrors}.length`)}function d(e){var t;if(!s.opts.unevaluated)return;const n=null===(t=null==r?void 0:r.validate)||void 0===t?void 0:t.evaluated;if(!0!==s.props)if(n&&!n.dynamicProps)void 0!==n.props&&(s.props=ql.mergeEvaluated.props(o,n.props,s.props));else{const t=o.var("props",Ml._`${e}.evaluated.props`);s.props=ql.mergeEvaluated.props(o,t,s.props,Ml.Name)}if(!0!==s.items)if(n&&!n.dynamicItems)void 0!==n.items&&(s.items=ql.mergeEvaluated.items(o,n.items,s.items));else{const t=o.var("items",Ml._`${e}.evaluated.items`);s.items=ql.mergeEvaluated.items(o,t,s.items,Ml.Name)}}n?function(){if(!i.$async)throw new Error("async schema referenced by sync schema");const r=o.let("valid");o.try(()=>{o.code(Ml._`await ${(0,Al.callValidateCode)(e,t,u)}`),d(t),a||o.assign(r,!0)},e=>{o.if(Ml._`!(${e} instanceof ${s.ValidationError})`,()=>o.throw(e)),l(e),a||o.assign(r,!1)}),e.ok(r)}():e.result((0,Al.callValidateCode)(e,t,u),()=>d(t),()=>l(t))}Ol.getValidate=Fl,Ol.callRef=Ll,Ol.default=Vl,Object.defineProperty(Cl,"__esModule",{value:!0});const Kl=Ol,Hl=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",jl.default,Kl.default];Cl.default=Hl;var Zl={},Gl={};Object.defineProperty(Gl,"__esModule",{value:!0});const Bl=dc(),Jl=Bl.operators,Wl={maximum:{okStr:"<=",ok:Jl.LTE,fail:Jl.GT},minimum:{okStr:">=",ok:Jl.GTE,fail:Jl.LT},exclusiveMaximum:{okStr:"<",ok:Jl.LT,fail:Jl.GTE},exclusiveMinimum:{okStr:">",ok:Jl.GT,fail:Jl.LTE}},Ql={message:({keyword:e,schemaCode:t})=>Bl.str`must be ${Wl[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>Bl._`{comparison: ${Wl[e].okStr}, limit: ${t}}`},Yl={keyword:Object.keys(Wl),type:"number",schemaType:"number",$data:!0,error:Ql,code(e){const{keyword:t,data:r,schemaCode:n}=e;e.fail$data(Bl._`${r} ${Wl[t].fail} ${n} || isNaN(${r})`)}};Gl.default=Yl;var Xl={};Object.defineProperty(Xl,"__esModule",{value:!0});const ed=dc(),td={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:e})=>ed.str`must be multiple of ${e}`,params:({schemaCode:e})=>ed._`{multipleOf: ${e}}`},code(e){const{gen:t,data:r,schemaCode:n,it:o}=e,s=o.opts.multipleOfPrecision,a=t.let("res"),i=s?ed._`Math.abs(Math.round(${a}) - ${a}) > 1e-${s}`:ed._`${a} !== parseInt(${a})`;e.fail$data(ed._`(${n} === 0 || (${a} = ${r}/${n}, ${i}))`)}};Xl.default=td;var rd={},nd={};function od(e){const t=e.length;let r,n=0,o=0;for(;o<t;)n++,r=e.charCodeAt(o++),r>=55296&&r<=56319&&o<t&&(r=e.charCodeAt(o),56320==(64512&r)&&o++);return n}Object.defineProperty(nd,"__esModule",{value:!0}),nd.default=od,od.code='require("ajv/dist/runtime/ucs2length").default',Object.defineProperty(rd,"__esModule",{value:!0});const sd=dc(),ad=hc,id=nd,cd={message({keyword:e,schemaCode:t}){const r="maxLength"===e?"more":"fewer";return sd.str`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>sd._`{limit: ${e}}`},ud={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:cd,code(e){const{keyword:t,data:r,schemaCode:n,it:o}=e,s="maxLength"===t?sd.operators.GT:sd.operators.LT,a=!1===o.opts.unicode?sd._`${r}.length`:sd._`${(0,ad.useFunc)(e.gen,id.default)}(${r})`;e.fail$data(sd._`${a} ${s} ${n}`)}};rd.default=ud;var ld={};Object.defineProperty(ld,"__esModule",{value:!0});const dd=tu(),hd=hc,pd=dc(),fd={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>pd.str`must match pattern "${e}"`,params:({schemaCode:e})=>pd._`{pattern: ${e}}`},code(e){const{gen:t,data:r,$data:n,schema:o,schemaCode:s,it:a}=e,i=a.opts.unicodeRegExp?"u":"";if(n){const{regExp:n}=a.opts.code,o="new RegExp"===n.code?pd._`new RegExp`:(0,hd.useFunc)(t,n),c=t.let("valid");t.try(()=>t.assign(c,pd._`${o}(${s}, ${i}).test(${r})`),()=>t.assign(c,!1)),e.fail$data(pd._`!${c}`)}else{const t=(0,dd.usePattern)(e,o);e.fail$data(pd._`!${t}.test(${r})`)}}};ld.default=fd;var md={};Object.defineProperty(md,"__esModule",{value:!0});const yd=dc(),gd={message({keyword:e,schemaCode:t}){const r="maxProperties"===e?"more":"fewer";return yd.str`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>yd._`{limit: ${e}}`},vd={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:gd,code(e){const{keyword:t,data:r,schemaCode:n}=e,o="maxProperties"===t?yd.operators.GT:yd.operators.LT;e.fail$data(yd._`Object.keys(${r}).length ${o} ${n}`)}};md.default=vd;var _d={};Object.defineProperty(_d,"__esModule",{value:!0});const wd=tu(),$d=dc(),bd=hc,kd={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:e}})=>$d.str`must have required property '${e}'`,params:({params:{missingProperty:e}})=>$d._`{missingProperty: ${e}}`},code(e){const{gen:t,schema:r,schemaCode:n,data:o,$data:s,it:a}=e,{opts:i}=a;if(!s&&0===r.length)return;const c=r.length>=i.loopRequired;if(a.allErrors?function(){if(c||s)e.block$data($d.nil,u);else for(const t of r)(0,wd.checkReportMissingProp)(e,t)}():function(){const a=t.let("missing");if(c||s){const r=t.let("valid",!0);e.block$data(r,()=>function(r,s){e.setParams({missingProperty:r}),t.forOf(r,n,()=>{t.assign(s,(0,wd.propertyInData)(t,o,r,i.ownProperties)),t.if((0,$d.not)(s),()=>{e.error(),t.break()})},$d.nil)}(a,r)),e.ok(r)}else t.if((0,wd.checkMissingProp)(e,r,a)),(0,wd.reportMissingProp)(e,a),t.else()}(),i.strictRequired){const t=e.parentSchema.properties,{definedProperties:n}=e.it;for(const e of r)if(void 0===(null==t?void 0:t[e])&&!n.has(e)){const t=`required property "${e}" is not defined at "${a.schemaEnv.baseId+a.errSchemaPath}" (strictRequired)`;(0,bd.checkStrictMode)(a,t,a.opts.strictRequired)}}function u(){t.forOf("prop",n,r=>{e.setParams({missingProperty:r}),t.if((0,wd.noPropertyInData)(t,o,r,i.ownProperties),()=>e.error())})}}};_d.default=kd;var Ed={};Object.defineProperty(Ed,"__esModule",{value:!0});const Pd=dc(),Sd={message({keyword:e,schemaCode:t}){const r="maxItems"===e?"more":"fewer";return Pd.str`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>Pd._`{limit: ${e}}`},Td={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Sd,code(e){const{keyword:t,data:r,schemaCode:n}=e,o="maxItems"===t?Pd.operators.GT:Pd.operators.LT;e.fail$data(Pd._`${r}.length ${o} ${n}`)}};Ed.default=Td;var Id={},xd={};Object.defineProperty(xd,"__esModule",{value:!0});const Nd=au;Nd.code='require("ajv/dist/runtime/equal").default',xd.default=Nd,Object.defineProperty(Id,"__esModule",{value:!0});const Cd=Cc,jd=dc(),Rd=hc,Od=xd,zd={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:e,j:t}})=>jd.str`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>jd._`{i: ${e}, j: ${t}}`},code(e){const{gen:t,data:r,$data:n,schema:o,parentSchema:s,schemaCode:a,it:i}=e;if(!n&&!o)return;const c=t.let("valid"),u=s.items?(0,Cd.getSchemaTypes)(s.items):[];function l(n,o){const s=t.name("item"),a=(0,Cd.checkDataTypes)(u,s,i.opts.strictNumbers,Cd.DataType.Wrong),l=t.const("indices",jd._`{}`);t.for(jd._`;${n}--;`,()=>{t.let(s,jd._`${r}[${n}]`),t.if(a,jd._`continue`),u.length>1&&t.if(jd._`typeof ${s} == "string"`,jd._`${s} += "_"`),t.if(jd._`typeof ${l}[${s}] == "number"`,()=>{t.assign(o,jd._`${l}[${s}]`),e.error(),t.assign(c,!1).break()}).code(jd._`${l}[${s}] = ${n}`)})}function d(n,o){const s=(0,Rd.useFunc)(t,Od.default),a=t.name("outer");t.label(a).for(jd._`;${n}--;`,()=>t.for(jd._`${o} = ${n}; ${o}--;`,()=>t.if(jd._`${s}(${r}[${n}], ${r}[${o}])`,()=>{e.error(),t.assign(c,!1).break(a)})))}e.block$data(c,function(){const n=t.let("i",jd._`${r}.length`),o=t.let("j");e.setParams({i:n,j:o}),t.assign(c,!0),t.if(jd._`${n} > 1`,()=>(u.length>0&&!u.some(e=>"object"===e||"array"===e)?l:d)(n,o))},jd._`${a} === false`),e.ok(c)}};Id.default=zd;var Ad={};Object.defineProperty(Ad,"__esModule",{value:!0});const Md=dc(),Dd=hc,Ud=xd,qd={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:e})=>Md._`{allowedValue: ${e}}`},code(e){const{gen:t,data:r,$data:n,schemaCode:o,schema:s}=e;n||s&&"object"==typeof s?e.fail$data(Md._`!${(0,Dd.useFunc)(t,Ud.default)}(${r}, ${o})`):e.fail(Md._`${s} !== ${r}`)}};Ad.default=qd;var Vd={};Object.defineProperty(Vd,"__esModule",{value:!0});const Fd=dc(),Ld=hc,Kd=xd,Hd={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:e})=>Fd._`{allowedValues: ${e}}`},code(e){const{gen:t,data:r,$data:n,schema:o,schemaCode:s,it:a}=e;if(!n&&0===o.length)throw new Error("enum must have non-empty array");const i=o.length>=a.opts.loopEnum;let c;const u=()=>null!=c?c:c=(0,Ld.useFunc)(t,Kd.default);let l;if(i||n)l=t.let("valid"),e.block$data(l,function(){t.assign(l,!1),t.forOf("v",s,e=>t.if(Fd._`${u()}(${r}, ${e})`,()=>t.assign(l,!0).break()))});else{if(!Array.isArray(o))throw new Error("ajv implementation error");const e=t.const("vSchema",s);l=(0,Fd.or)(...o.map((t,n)=>function(e,t){const n=o[t];return"object"==typeof n&&null!==n?Fd._`${u()}(${r}, ${e}[${t}])`:Fd._`${r} === ${n}`}(e,n)))}e.pass(l)}};Vd.default=Hd,Object.defineProperty(Zl,"__esModule",{value:!0});const Zd=Xl,Gd=rd,Bd=ld,Jd=md,Wd=_d,Qd=Ed,Yd=Id,Xd=Ad,eh=Vd,th=[Gl.default,Zd.default,Gd.default,Bd.default,Jd.default,Wd.default,Qd.default,Yd.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Xd.default,eh.default];Zl.default=th;var rh={},nh={};Object.defineProperty(nh,"__esModule",{value:!0}),nh.validateAdditionalItems=void 0;const oh=dc(),sh=hc,ah={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:e}})=>oh.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>oh._`{limit: ${e}}`},code(e){const{parentSchema:t,it:r}=e,{items:n}=t;Array.isArray(n)?ih(e,n):(0,sh.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas')}};function ih(e,t){const{gen:r,schema:n,data:o,keyword:s,it:a}=e;a.items=!0;const i=r.const("len",oh._`${o}.length`);if(!1===n)e.setParams({len:t.length}),e.pass(oh._`${i} <= ${t.length}`);else if("object"==typeof n&&!(0,sh.alwaysValidSchema)(a,n)){const n=r.var("valid",oh._`${i} <= ${t.length}`);r.if((0,oh.not)(n),()=>function(n){r.forRange("i",t.length,i,t=>{e.subschema({keyword:s,dataProp:t,dataPropType:sh.Type.Num},n),a.allErrors||r.if((0,oh.not)(n),()=>r.break())})}(n)),e.ok(n)}}nh.validateAdditionalItems=ih,nh.default=ah;var ch={},uh={};Object.defineProperty(uh,"__esModule",{value:!0}),uh.validateTuple=void 0;const lh=dc(),dh=hc,hh=tu(),ph={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){const{schema:t,it:r}=e;if(Array.isArray(t))return fh(e,"additionalItems",t);r.items=!0,(0,dh.alwaysValidSchema)(r,t)||e.ok((0,hh.validateArray)(e))}};function fh(e,t,r=e.schema){const{gen:n,parentSchema:o,data:s,keyword:a,it:i}=e;!function(e){const{opts:n,errSchemaPath:o}=i,s=r.length,c=s===e.minItems&&(s===e.maxItems||!1===e[t]);if(n.strictTuples&&!c){const e=`"${a}" is ${s}-tuple, but minItems or maxItems/${t} are not specified or different at path "${o}"`;(0,dh.checkStrictMode)(i,e,n.strictTuples)}}(o),i.opts.unevaluated&&r.length&&!0!==i.items&&(i.items=dh.mergeEvaluated.items(n,r.length,i.items));const c=n.name("valid"),u=n.const("len",lh._`${s}.length`);r.forEach((t,r)=>{(0,dh.alwaysValidSchema)(i,t)||(n.if(lh._`${u} > ${r}`,()=>e.subschema({keyword:a,schemaProp:r,dataProp:r},c)),e.ok(c))})}uh.validateTuple=fh,uh.default=ph,Object.defineProperty(ch,"__esModule",{value:!0});const mh=uh,yh={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,mh.validateTuple)(e,"items")};ch.default=yh;var gh={};Object.defineProperty(gh,"__esModule",{value:!0});const vh=dc(),_h=hc,wh=tu(),$h=nh,bh={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:e}})=>vh.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>vh._`{limit: ${e}}`},code(e){const{schema:t,parentSchema:r,it:n}=e,{prefixItems:o}=r;n.items=!0,(0,_h.alwaysValidSchema)(n,t)||(o?(0,$h.validateAdditionalItems)(e,o):e.ok((0,wh.validateArray)(e)))}};gh.default=bh;var kh={};Object.defineProperty(kh,"__esModule",{value:!0});const Eh=dc(),Ph=hc,Sh={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:e,max:t}})=>void 0===t?Eh.str`must contain at least ${e} valid item(s)`:Eh.str`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>void 0===t?Eh._`{minContains: ${e}}`:Eh._`{minContains: ${e}, maxContains: ${t}}`},code(e){const{gen:t,schema:r,parentSchema:n,data:o,it:s}=e;let a,i;const{minContains:c,maxContains:u}=n;s.opts.next?(a=void 0===c?1:c,i=u):a=1;const l=t.const("len",Eh._`${o}.length`);if(e.setParams({min:a,max:i}),void 0===i&&0===a)return void(0,Ph.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');if(void 0!==i&&a>i)return(0,Ph.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),void e.fail();if((0,Ph.alwaysValidSchema)(s,r)){let t=Eh._`${l} >= ${a}`;return void 0!==i&&(t=Eh._`${t} && ${l} <= ${i}`),void e.pass(t)}s.items=!0;const d=t.name("valid");function h(){const e=t.name("_valid"),r=t.let("count",0);p(e,()=>t.if(e,()=>function(e){t.code(Eh._`${e}++`),void 0===i?t.if(Eh._`${e} >= ${a}`,()=>t.assign(d,!0).break()):(t.if(Eh._`${e} > ${i}`,()=>t.assign(d,!1).break()),1===a?t.assign(d,!0):t.if(Eh._`${e} >= ${a}`,()=>t.assign(d,!0)))}(r)))}function p(r,n){t.forRange("i",0,l,t=>{e.subschema({keyword:"contains",dataProp:t,dataPropType:Ph.Type.Num,compositeRule:!0},r),n()})}void 0===i&&1===a?p(d,()=>t.if(d,()=>t.break())):0===a?(t.let(d,!0),void 0!==i&&t.if(Eh._`${o}.length > 0`,h)):(t.let(d,!1),h()),e.result(d,()=>e.reset())}};kh.default=Sh;var Th={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=dc(),r=hc,n=tu();e.error={message:({params:{property:e,depsCount:r,deps:n}})=>{const o=1===r?"property":"properties";return t.str`must have ${o} ${n} when property ${e} is present`},params:({params:{property:e,depsCount:r,deps:n,missingProperty:o}})=>t._`{property: ${e},
5
+ missingProperty: ${o},
6
6
  depsCount: ${r},
7
- deps: ${o}}`};const n={keyword:"dependencies",type:"object",schemaType:"object",error:e.error,code(e){const[t,r]=function({schema:e}){const t={},r={};for(const o in e){if("__proto__"===o)continue;(Array.isArray(e[o])?t:r)[o]=e[o]}return[t,r]}(e);s(e,t),a(e,r)}};function s(e,r=e.schema){const{gen:n,data:s,it:a}=e;if(0===Object.keys(r).length)return;const i=n.let("missing");for(const c in r){const u=r[c];if(0===u.length)continue;const l=(0,o.propertyInData)(n,s,c,a.opts.ownProperties);e.setParams({property:c,depsCount:u.length,deps:u.join(", ")}),a.allErrors?n.if(l,()=>{for(const t of u)(0,o.checkReportMissingProp)(e,t)}):(n.if(t._`${l} && (${(0,o.checkMissingProp)(e,u,i)})`),(0,o.reportMissingProp)(e,i),n.else())}}function a(e,t=e.schema){const{gen:n,data:s,keyword:a,it:i}=e,c=n.name("valid");for(const u in t)(0,r.alwaysValidSchema)(i,t[u])||(n.if((0,o.propertyInData)(n,s,u,i.opts.ownProperties),()=>{const t=e.subschema({keyword:a,schemaProp:u},c);e.mergeValidEvaluated(t,c)},()=>n.var(c,!0)),e.ok(c))}e.validatePropertyDeps=s,e.validateSchemaDeps=a,e.default=n}(Eh);var Sh={};Object.defineProperty(Sh,"__esModule",{value:!0});const Ph=uc(),Th=lc,Ih={message:"property name must be valid",params:({params:e})=>Ph._`{propertyName: ${e.propertyName}}`},xh={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Ih,code(e){const{gen:t,schema:r,data:o,it:n}=e;if((0,Th.alwaysValidSchema)(n,r))return;const s=t.name("valid");t.forIn("key",o,r=>{e.setParams({propertyName:r}),e.subschema({keyword:"propertyNames",data:r,dataTypes:["string"],propertyName:r,compositeRule:!0},s),t.if((0,Ph.not)(s),()=>{e.error(!0),n.allErrors||t.break()})}),e.ok(s)}};Sh.default=xh;var Nh={};Object.defineProperty(Nh,"__esModule",{value:!0});const Ch=Xc(),jh=uc(),Rh=Tc(),Oh=lc,zh={message:"must NOT have additional properties",params:({params:e})=>jh._`{additionalProperty: ${e.additionalProperty}}`},Ah={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:zh,code(e){const{gen:t,schema:r,parentSchema:o,data:n,errsCount:s,it:a}=e;if(!s)throw new Error("ajv implementation error");const{allErrors:i,opts:c}=a;if(a.props=!0,"all"!==c.removeAdditional&&(0,Oh.alwaysValidSchema)(a,r))return;const u=(0,Ch.allSchemaProperties)(o.properties),l=(0,Ch.allSchemaProperties)(o.patternProperties);function d(e){t.code(jh._`delete ${n}[${e}]`)}function h(o){if("all"===c.removeAdditional||c.removeAdditional&&!1===r)d(o);else{if(!1===r)return e.setParams({additionalProperty:o}),e.error(),void(i||t.break());if("object"==typeof r&&!(0,Oh.alwaysValidSchema)(a,r)){const r=t.name("valid");"failing"===c.removeAdditional?(p(o,r,!1),t.if((0,jh.not)(r),()=>{e.reset(),d(o)})):(p(o,r),i||t.if((0,jh.not)(r),()=>t.break()))}}}function p(t,r,o){const n={keyword:"additionalProperties",dataProp:t,dataPropType:Oh.Type.Str};!1===o&&Object.assign(n,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(n,r)}t.forIn("key",n,r=>{u.length||l.length?t.if(function(r){let n;if(u.length>8){const e=(0,Oh.schemaRefOrVal)(a,o.properties,"properties");n=(0,Ch.isOwnProperty)(t,e,r)}else n=u.length?(0,jh.or)(...u.map(e=>jh._`${r} === ${e}`)):jh.nil;return l.length&&(n=(0,jh.or)(n,...l.map(t=>jh._`${(0,Ch.usePattern)(e,t)}.test(${r})`))),(0,jh.not)(n)}(r),()=>h(r)):h(r)}),e.ok(jh._`${s} === ${Rh.default.errors}`)}};Nh.default=Ah;var Mh={};Object.defineProperty(Mh,"__esModule",{value:!0});const Dh=ku(),Uh=Xc(),qh=lc,Vh=Nh,Fh={keyword:"properties",type:"object",schemaType:"object",code(e){const{gen:t,schema:r,parentSchema:o,data:n,it:s}=e;"all"===s.opts.removeAdditional&&void 0===o.additionalProperties&&Vh.default.code(new Dh.KeywordCxt(s,Vh.default,"additionalProperties"));const a=(0,Uh.allSchemaProperties)(r);for(const e of a)s.definedProperties.add(e);s.opts.unevaluated&&a.length&&!0!==s.props&&(s.props=qh.mergeEvaluated.props(t,(0,qh.toHash)(a),s.props));const i=a.filter(e=>!(0,qh.alwaysValidSchema)(s,r[e]));if(0===i.length)return;const c=t.name("valid");for(const r of i)u(r)?l(r):(t.if((0,Uh.propertyInData)(t,n,r,s.opts.ownProperties)),l(r),s.allErrors||t.else().var(c,!0),t.endIf()),e.it.definedProperties.add(r),e.ok(c);function u(e){return s.opts.useDefaults&&!s.compositeRule&&void 0!==r[e].default}function l(t){e.subschema({keyword:"properties",schemaProp:t,dataProp:t},c)}}};Mh.default=Fh;var Lh={};Object.defineProperty(Lh,"__esModule",{value:!0});const Hh=Xc(),Kh=uc(),Zh=lc,Gh=lc,Bh={keyword:"patternProperties",type:"object",schemaType:"object",code(e){const{gen:t,schema:r,data:o,parentSchema:n,it:s}=e,{opts:a}=s,i=(0,Hh.allSchemaProperties)(r),c=i.filter(e=>(0,Zh.alwaysValidSchema)(s,r[e]));if(0===i.length||c.length===i.length&&(!s.opts.unevaluated||!0===s.props))return;const u=a.strictSchema&&!a.allowMatchingProperties&&n.properties,l=t.name("valid");!0===s.props||s.props instanceof Kh.Name||(s.props=(0,Gh.evaluatedPropsToName)(t,s.props));const{props:d}=s;function h(e){for(const t in u)new RegExp(e).test(t)&&(0,Zh.checkStrictMode)(s,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function p(r){t.forIn("key",o,o=>{t.if(Kh._`${(0,Hh.usePattern)(e,r)}.test(${o})`,()=>{const n=c.includes(r);n||e.subschema({keyword:"patternProperties",schemaProp:r,dataProp:o,dataPropType:Gh.Type.Str},l),s.opts.unevaluated&&!0!==d?t.assign(Kh._`${d}[${o}]`,!0):n||s.allErrors||t.if((0,Kh.not)(l),()=>t.break())})})}!function(){for(const e of i)u&&h(e),s.allErrors?p(e):(t.var(l,!0),p(e),t.if(l))}()}};Lh.default=Bh;var Jh={};Object.defineProperty(Jh,"__esModule",{value:!0});const Wh=lc,Qh={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){const{gen:t,schema:r,it:o}=e;if((0,Wh.alwaysValidSchema)(o,r))return void e.fail();const n=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},n),e.failResult(n,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};Jh.default=Qh;var Yh={};Object.defineProperty(Yh,"__esModule",{value:!0});const Xh={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Xc().validateUnion,error:{message:"must match a schema in anyOf"}};Yh.default=Xh;var ep={};Object.defineProperty(ep,"__esModule",{value:!0});const tp=uc(),rp=lc,op={message:"must match exactly one schema in oneOf",params:({params:e})=>tp._`{passingSchemas: ${e.passing}}`},np={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:op,code(e){const{gen:t,schema:r,parentSchema:o,it:n}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(n.opts.discriminator&&o.discriminator)return;const s=r,a=t.let("valid",!1),i=t.let("passing",null),c=t.name("_valid");e.setParams({passing:i}),t.block(function(){s.forEach((r,o)=>{let s;(0,rp.alwaysValidSchema)(n,r)?t.var(c,!0):s=e.subschema({keyword:"oneOf",schemaProp:o,compositeRule:!0},c),o>0&&t.if(tp._`${c} && ${a}`).assign(a,!1).assign(i,tp._`[${i}, ${o}]`).else(),t.if(c,()=>{t.assign(a,!0),t.assign(i,o),s&&e.mergeEvaluated(s,tp.Name)})})}),e.result(a,()=>e.reset(),()=>e.error(!0))}};ep.default=np;var sp={};Object.defineProperty(sp,"__esModule",{value:!0});const ap=lc,ip={keyword:"allOf",schemaType:"array",code(e){const{gen:t,schema:r,it:o}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");const n=t.name("valid");r.forEach((t,r)=>{if((0,ap.alwaysValidSchema)(o,t))return;const s=e.subschema({keyword:"allOf",schemaProp:r},n);e.ok(n),e.mergeEvaluated(s)})}};sp.default=ip;var cp={};Object.defineProperty(cp,"__esModule",{value:!0});const up=uc(),lp=lc,dp={message:({params:e})=>up.str`must match "${e.ifClause}" schema`,params:({params:e})=>up._`{failingKeyword: ${e.ifClause}}`},hp={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:dp,code(e){const{gen:t,parentSchema:r,it:o}=e;void 0===r.then&&void 0===r.else&&(0,lp.checkStrictMode)(o,'"if" without "then" and "else" is ignored');const n=pp(o,"then"),s=pp(o,"else");if(!n&&!s)return;const a=t.let("valid",!0),i=t.name("_valid");if(function(){const t=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},i);e.mergeEvaluated(t)}(),e.reset(),n&&s){const r=t.let("ifClause");e.setParams({ifClause:r}),t.if(i,c("then",r),c("else",r))}else n?t.if(i,c("then")):t.if((0,up.not)(i),c("else"));function c(r,o){return()=>{const n=e.subschema({keyword:r},i);t.assign(a,i),e.mergeValidEvaluated(n,a),o?t.assign(o,up._`${r}`):e.setParams({ifClause:r})}}e.pass(a,()=>e.error(!0))}};function pp(e,t){const r=e.schema[t];return void 0!==r&&!(0,lp.alwaysValidSchema)(e,r)}cp.default=hp;var fp={};Object.defineProperty(fp,"__esModule",{value:!0});const mp=lc,yp={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){void 0===t.if&&(0,mp.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};fp.default=yp,Object.defineProperty(Xd,"__esModule",{value:!0});const gp=eh,vp=sh,_p=ah,wp=fh,$p=wh,bp=Eh,kp=Sh,Ep=Nh,Sp=Mh,Pp=Lh,Tp=Jh,Ip=Yh,xp=ep,Np=sp,Cp=cp,jp=fp;Xd.default=function(e=!1){const t=[Tp.default,Ip.default,xp.default,Np.default,Cp.default,jp.default,kp.default,Ep.default,bp.default,Sp.default,Pp.default];return e?t.push(vp.default,wp.default):t.push(gp.default,_p.default),t.push($p.default),t};var Rp={},Op={};Object.defineProperty(Op,"__esModule",{value:!0});const zp=uc(),Ap={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>zp.str`must match format "${e}"`,params:({schemaCode:e})=>zp._`{format: ${e}}`},code(e,t){const{gen:r,data:o,$data:n,schema:s,schemaCode:a,it:i}=e,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=i;c.validateFormats&&(n?function(){const n=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),s=r.const("fDef",zp._`${n}[${a}]`),i=r.let("fType"),u=r.let("format");r.if(zp._`typeof ${s} == "object" && !(${s} instanceof RegExp)`,()=>r.assign(i,zp._`${s}.type || "string"`).assign(u,zp._`${s}.validate`),()=>r.assign(i,zp._`"string"`).assign(u,s)),e.fail$data((0,zp.or)(!1===c.strictSchema?zp.nil:zp._`${a} && !${u}`,function(){const e=l.$async?zp._`(${s}.async ? await ${u}(${o}) : ${u}(${o}))`:zp._`${u}(${o})`,r=zp._`(typeof ${u} == "function" ? ${e} : ${u}.test(${o}))`;return zp._`${u} && ${u} !== true && ${i} === ${t} && !${r}`}()))}():function(){const n=d.formats[s];if(!n)return void function(){if(!1===c.strictSchema)return void d.logger.warn(e());throw new Error(e());function e(){return`unknown format "${s}" ignored in schema at path "${u}"`}}();if(!0===n)return;const[a,i,h]=function(e){const t=e instanceof RegExp?(0,zp.regexpCode)(e):c.code.formats?zp._`${c.code.formats}${(0,zp.getProperty)(s)}`:void 0,o=r.scopeValue("formats",{key:s,ref:e,code:t});if("object"==typeof e&&!(e instanceof RegExp))return[e.type||"string",e.validate,zp._`${o}.validate`];return["string",e,o]}(n);a===t&&e.pass(function(){if("object"==typeof n&&!(n instanceof RegExp)&&n.async){if(!l.$async)throw new Error("async format in sync schema");return zp._`await ${h}(${o})`}return"function"==typeof i?zp._`${h}(${o})`:zp._`${h}.test(${o})`}())}())}};Op.default=Ap,Object.defineProperty(Rp,"__esModule",{value:!0});const Mp=[Op.default];Rp.default=Mp;var Dp={};Object.defineProperty(Dp,"__esModule",{value:!0}),Dp.contentVocabulary=Dp.metadataVocabulary=void 0,Dp.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],Dp.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"],Object.defineProperty(Il,"__esModule",{value:!0});const Up=Hl,qp=Xd,Vp=Rp,Fp=Dp,Lp=[xl.default,Up.default,(0,qp.default)(),Vp.default,Fp.metadataVocabulary,Fp.contentVocabulary];Il.default=Lp;var Hp,Kp={},Zp={};Object.defineProperty(Zp,"__esModule",{value:!0}),Zp.DiscrError=void 0,function(e){e.Tag="tag",e.Mapping="mapping"}(Hp||(Zp.DiscrError=Hp={})),Object.defineProperty(Kp,"__esModule",{value:!0});const Gp=uc(),Bp=Zp,Jp=Nu,Wp=xu(),Qp=lc,Yp={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:e,tagName:t}})=>e===Bp.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>Gp._`{error: ${e}, tag: ${r}, tagValue: ${t}}`},code(e){const{gen:t,data:r,schema:o,parentSchema:n,it:s}=e,{oneOf:a}=n;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");const i=o.propertyName;if("string"!=typeof i)throw new Error("discriminator: requires propertyName");if(o.mapping)throw new Error("discriminator: mapping is not supported");if(!a)throw new Error("discriminator: requires oneOf keyword");const c=t.let("valid",!1),u=t.const("tag",Gp._`${r}${(0,Gp.getProperty)(i)}`);function l(r){const o=t.name("valid"),n=e.subschema({keyword:"oneOf",schemaProp:r},o);return e.mergeEvaluated(n,Gp.Name),o}t.if(Gp._`typeof ${u} == "string"`,()=>function(){const r=function(){var e;const t={},r=c(n);let o=!0;for(let t=0;t<a.length;t++){let n=a[t];if((null==n?void 0:n.$ref)&&!(0,Qp.schemaHasRulesButRef)(n,s.self.RULES)){const e=n.$ref;if(n=Jp.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,e),n instanceof Jp.SchemaEnv&&(n=n.schema),void 0===n)throw new Wp.default(s.opts.uriResolver,s.baseId,e)}const l=null===(e=null==n?void 0:n.properties)||void 0===e?void 0:e[i];if("object"!=typeof l)throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${i}"`);o=o&&(r||c(n)),u(l,t)}if(!o)throw new Error(`discriminator: "${i}" must be required`);return t;function c({required:e}){return Array.isArray(e)&&e.includes(i)}function u(e,t){if(e.const)l(e.const,t);else{if(!e.enum)throw new Error(`discriminator: "properties/${i}" must have "const" or "enum"`);for(const r of e.enum)l(r,t)}}function l(e,r){if("string"!=typeof e||e in t)throw new Error(`discriminator: "${i}" values must be unique strings`);t[e]=r}}();t.if(!1);for(const e in r)t.elseIf(Gp._`${u} === ${e}`),t.assign(c,l(r[e]));t.else(),e.error(!1,{discrError:Bp.DiscrError.Mapping,tag:u,tagName:i}),t.endIf()}(),()=>e.error(!1,{discrError:Bp.DiscrError.Tag,tag:u,tagName:i})),e.ok(c)}};Kp.default=Yp;var Xp={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0};!function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.MissingRefError=t.ValidationError=t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=t.Ajv=void 0;const r=Yi,o=Il,n=Kp,s=Xp,a=["/properties"],i="http://json-schema.org/draft-07/schema";class c extends r.default{_addVocabularies(){super._addVocabularies(),o.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(n.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const e=this.opts.$data?this.$dataMetaSchema(s,a):s;this.addMetaSchema(e,i,!1),this.refs["http://json-schema.org/schema"]=i}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(i)?i:void 0)}}t.Ajv=c,e.exports=t=c,e.exports.Ajv=c,Object.defineProperty(t,"__esModule",{value:!0}),t.default=c;var u=ku();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return u.KeywordCxt}});var l=uc();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return l._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return l.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return l.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return l.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return l.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return l.CodeGen}});var d=Pu();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return d.default}});var h=xu();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return h.default}})}(Qi,Qi.exports);var ef=Ji(Qi.exports),tf={exports:{}},rf={};!function(e){function t(e,t){return{validate:e,compare:t}}Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0,e.fullFormats={date:t(n,s),time:t(i(!0),c),"date-time":t(d(!0),h),"iso-time":t(i(),u),"iso-date-time":t(d(),p),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:function(e){return f.test(e)&&m.test(e)},"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:function(e){if(w.test(e))return!1;try{return new RegExp(e),!0}catch(e){return!1}},uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:function(e){return y.lastIndex=0,y.test(e)},int32:{type:"number",validate:function(e){return Number.isInteger(e)&&e<=v&&e>=g}},int64:{type:"number",validate:function(e){return Number.isInteger(e)}},float:{type:"number",validate:_},double:{type:"number",validate:_},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,s),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,c),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,h),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,p),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);const r=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,o=[0,31,28,31,30,31,30,31,31,30,31,30,31];function n(e){const t=r.exec(e);if(!t)return!1;const n=+t[1],s=+t[2],a=+t[3];return s>=1&&s<=12&&a>=1&&a<=(2===s&&function(e){return e%4==0&&(e%100!=0||e%400==0)}(n)?29:o[s])}function s(e,t){if(e&&t)return e>t?1:e<t?-1:0}const a=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function i(e){return function(t){const r=a.exec(t);if(!r)return!1;const o=+r[1],n=+r[2],s=+r[3],i=r[4],c="-"===r[5]?-1:1,u=+(r[6]||0),l=+(r[7]||0);if(u>23||l>59||e&&!i)return!1;if(o<=23&&n<=59&&s<60)return!0;const d=n-l*c,h=o-u*c-(d<0?1:0);return(23===h||-1===h)&&(59===d||-1===d)&&s<61}}function c(e,t){if(!e||!t)return;const r=new Date("2020-01-01T"+e).valueOf(),o=new Date("2020-01-01T"+t).valueOf();return r&&o?r-o:void 0}function u(e,t){if(!e||!t)return;const r=a.exec(e),o=a.exec(t);return r&&o?(e=r[1]+r[2]+r[3])>(t=o[1]+o[2]+o[3])?1:e<t?-1:0:void 0}const l=/t|\s/i;function d(e){const t=i(e);return function(e){const r=e.split(l);return 2===r.length&&n(r[0])&&t(r[1])}}function h(e,t){if(!e||!t)return;const r=new Date(e).valueOf(),o=new Date(t).valueOf();return r&&o?r-o:void 0}function p(e,t){if(!e||!t)return;const[r,o]=e.split(l),[n,a]=t.split(l),i=s(r,n);return void 0!==i?i||c(o,a):void 0}const f=/\/|:/,m=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;const y=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;const g=-(2**31),v=2**31-1;function _(){return!0}const w=/[^\\]\\Z/}(rf);var of={},nf={exports:{}},sf={},af={},cf={},uf={},lf={},df={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;class t{}e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw new Error("CodeGen: name must be a valid identifier");this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=r;class o extends t{constructor(e){super(),this._items="string"==typeof e?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const e=this._items[0];return""===e||'""'===e}get str(){var e;return null!==(e=this._str)&&void 0!==e?e:this._str=this._items.reduce((e,t)=>`${e}${t}`,"")}get names(){var e;return null!==(e=this._names)&&void 0!==e?e:this._names=this._items.reduce((e,t)=>(t instanceof r&&(e[t.str]=(e[t.str]||0)+1),e),{})}}function n(e,...t){const r=[e[0]];let n=0;for(;n<t.length;)i(r,t[n]),r.push(e[++n]);return new o(r)}e._Code=o,e.nil=new o(""),e._=n;const s=new o("+");function a(e,...t){const r=[u(e[0])];let n=0;for(;n<t.length;)r.push(s),i(r,t[n]),r.push(s,u(e[++n]));return function(e){let t=1;for(;t<e.length-1;){if(e[t]===s){const r=c(e[t-1],e[t+1]);if(void 0!==r){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}(r),new o(r)}function i(e,t){var n;t instanceof o?e.push(...t._items):t instanceof r?e.push(t):e.push("number"==typeof(n=t)||"boolean"==typeof n||null===n?n:u(Array.isArray(n)?n.join(","):n))}function c(e,t){if('""'===t)return e;if('""'===e)return t;if("string"==typeof e){if(t instanceof r||'"'!==e[e.length-1])return;return"string"!=typeof t?`${e.slice(0,-1)}${t}"`:'"'===t[0]?e.slice(0,-1)+t.slice(1):void 0}return"string"!=typeof t||'"'!==t[0]||e instanceof r?void 0:`"${e}${t.slice(1)}`}function u(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.str=a,e.addCodeArg=i,e.strConcat=function(e,t){return t.emptyStr()?e:e.emptyStr()?t:a`${e}${t}`},e.stringify=function(e){return new o(u(e))},e.safeStringify=u,e.getProperty=function(t){return"string"==typeof t&&e.IDENTIFIER.test(t)?new o(`.${t}`):n`[${t}]`},e.getEsmExportName=function(t){if("string"==typeof t&&e.IDENTIFIER.test(t))return new o(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)},e.regexpCode=function(e){return new o(e.toString())}}(df);var hf={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=df;class r extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}}var o;!function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"}(o||(e.UsedValueState=o={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};class n{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof t.Name?e:this.name(e)}name(e){return new t.Name(this._newName(e))}_newName(e){return`${e}${(this._names[e]||this._nameGroup(e)).index++}`}_nameGroup(e){var t,r;if((null===(r=null===(t=this._parent)||void 0===t?void 0:t._prefixes)||void 0===r?void 0:r.has(e))||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}}e.Scope=n;class s extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:r,itemIndex:o}){this.value=e,this.scopePath=t._`.${new t.Name(r)}[${o}]`}}e.ValueScopeName=s;const a=t._`\n`;e.ValueScope=class extends n{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?a:t.nil}}get(){return this._scope}name(e){return new s(e,this._newName(e))}value(e,t){var r;if(void 0===t.ref)throw new Error("CodeGen: ref must be passed in value");const o=this.toName(e),{prefix:n}=o,s=null!==(r=t.key)&&void 0!==r?r:t.ref;let a=this._values[n];if(a){const e=a.get(s);if(e)return e}else a=this._values[n]=new Map;a.set(s,o);const i=this._scope[n]||(this._scope[n]=[]),c=i.length;return i[c]=t.ref,o.setValue(t,{property:n,itemIndex:c}),o}getValue(e,t){const r=this._values[e];if(r)return r.get(t)}scopeRefs(e,r=this._values){return this._reduceValues(r,r=>{if(void 0===r.scopePath)throw new Error(`CodeGen: name "${r}" has no value`);return t._`${e}${r.scopePath}`})}scopeCode(e=this._values,t,r){return this._reduceValues(e,e=>{if(void 0===e.value)throw new Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,r)}_reduceValues(n,s,a={},i){let c=t.nil;for(const u in n){const l=n[u];if(!l)continue;const d=a[u]=a[u]||new Map;l.forEach(n=>{if(d.has(n))return;d.set(n,o.Started);let a=s(n);if(a){const r=this.opts.es5?e.varKinds.var:e.varKinds.const;c=t._`${c}${r} ${n} = ${a};${this.opts._n}`}else{if(!(a=null==i?void 0:i(n)))throw new r(n);c=t._`${c}${a}${this.opts._n}`}d.set(n,o.Completed)})}return c}}}(hf),function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;const t=df,r=hf;var o=df;Object.defineProperty(e,"_",{enumerable:!0,get:function(){return o._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return o.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return o.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return o.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return o.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return o.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return o.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return o.Name}});var n=hf;Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return n.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return n.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return n.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return n.varKinds}}),e.operators={GT:new t._Code(">"),GTE:new t._Code(">="),LT:new t._Code("<"),LTE:new t._Code("<="),EQ:new t._Code("==="),NEQ:new t._Code("!=="),NOT:new t._Code("!"),OR:new t._Code("||"),AND:new t._Code("&&"),ADD:new t._Code("+")};class s{optimizeNodes(){return this}optimizeNames(e,t){return this}}class a extends s{constructor(e,t,r){super(),this.varKind=e,this.name=t,this.rhs=r}render({es5:e,_n:t}){const o=e?r.varKinds.var:this.varKind,n=void 0===this.rhs?"":` = ${this.rhs}`;return`${o} ${this.name}${n};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&(this.rhs=x(this.rhs,e,t)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class i extends s{constructor(e,t,r){super(),this.lhs=e,this.rhs=t,this.sideEffects=r}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof t.Name)||e[this.lhs.str]||this.sideEffects)return this.rhs=x(this.rhs,e,r),this}get names(){return I(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}}class c extends i{constructor(e,t,r,o){super(e,r,o),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}}class u extends s{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}}class l extends s{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}}class d extends s{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}}class h extends s{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=x(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class p extends s{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,r)=>t+r.render(e),"")}optimizeNodes(){const{nodes:e}=this;let t=e.length;for(;t--;){const r=e[t].optimizeNodes();Array.isArray(r)?e.splice(t,1,...r):r?e[t]=r:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){const{nodes:r}=this;let o=r.length;for(;o--;){const n=r[o];n.optimizeNames(e,t)||(N(e,n.names),r.splice(o,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>T(e,t.names),{})}}class f extends p{render(e){return"{"+e._n+super.render(e)+"}"+e._n}}class m extends p{}class y extends f{}y.kind="else";class g extends f{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+="else "+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();const e=this.condition;if(!0===e)return this.nodes;let t=this.else;if(t){const e=t.optimizeNodes();t=this.else=Array.isArray(e)?new y(e):e}return t?!1===e?t instanceof g?t:t.nodes:this.nodes.length?this:new g(C(e),t instanceof g?[t]:t.nodes):!1!==e&&this.nodes.length?this:void 0}optimizeNames(e,t){var r;if(this.else=null===(r=this.else)||void 0===r?void 0:r.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=x(this.condition,e,t),this}get names(){const e=super.names;return I(e,this.condition),this.else&&T(e,this.else.names),e}}g.kind="if";class v extends f{}v.kind="for";class _ extends v{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=x(this.iteration,e,t),this}get names(){return T(super.names,this.iteration.names)}}class w extends v{constructor(e,t,r,o){super(),this.varKind=e,this.name=t,this.from=r,this.to=o}render(e){const t=e.es5?r.varKinds.var:this.varKind,{name:o,from:n,to:s}=this;return`for(${t} ${o}=${n}; ${o}<${s}; ${o}++)`+super.render(e)}get names(){const e=I(super.names,this.from);return I(e,this.to)}}class $ extends v{constructor(e,t,r,o){super(),this.loop=e,this.varKind=t,this.name=r,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=x(this.iterable,e,t),this}get names(){return T(super.names,this.iterable.names)}}class b extends f{constructor(e,t,r){super(),this.name=e,this.args=t,this.async=r}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}}b.kind="func";class k extends p{render(e){return"return "+super.render(e)}}k.kind="return";class E extends f{render(e){let t="try"+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),null===(e=this.catch)||void 0===e||e.optimizeNodes(),null===(t=this.finally)||void 0===t||t.optimizeNodes(),this}optimizeNames(e,t){var r,o;return super.optimizeNames(e,t),null===(r=this.catch)||void 0===r||r.optimizeNames(e,t),null===(o=this.finally)||void 0===o||o.optimizeNames(e,t),this}get names(){const e=super.names;return this.catch&&T(e,this.catch.names),this.finally&&T(e,this.finally.names),e}}class S extends f{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}}S.kind="catch";class P extends f{render(e){return"finally"+super.render(e)}}P.kind="finally";function T(e,t){for(const r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function I(e,r){return r instanceof t._CodeOrName?T(e,r.names):e}function x(e,r,o){return e instanceof t.Name?s(e):(n=e)instanceof t._Code&&n._items.some(e=>e instanceof t.Name&&1===r[e.str]&&void 0!==o[e.str])?new t._Code(e._items.reduce((e,r)=>(r instanceof t.Name&&(r=s(r)),r instanceof t._Code?e.push(...r._items):e.push(r),e),[])):e;var n;function s(e){const t=o[e.str];return void 0===t||1!==r[e.str]?e:(delete r[e.str],t)}}function N(e,t){for(const r in t)e[r]=(e[r]||0)-(t[r]||0)}function C(e){return"boolean"==typeof e||"number"==typeof e||null===e?!e:t._`!${z(e)}`}e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?"\n":""},this._extScope=e,this._scope=new r.Scope({parent:e}),this._nodes=[new m]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){const r=this._extScope.value(e,t);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,r,o){const n=this._scope.toName(t);return void 0!==r&&o&&(this._constants[n.str]=r),this._leafNode(new a(e,n,r)),n}const(e,t,o){return this._def(r.varKinds.const,e,t,o)}let(e,t,o){return this._def(r.varKinds.let,e,t,o)}var(e,t,o){return this._def(r.varKinds.var,e,t,o)}assign(e,t,r){return this._leafNode(new i(e,t,r))}add(t,r){return this._leafNode(new c(t,e.operators.ADD,r))}code(e){return"function"==typeof e?e():e!==t.nil&&this._leafNode(new h(e)),this}object(...e){const r=["{"];for(const[o,n]of e)r.length>1&&r.push(","),r.push(o),(o!==n||this.opts.es5)&&(r.push(":"),(0,t.addCodeArg)(r,n));return r.push("}"),new t._Code(r)}if(e,t,r){if(this._blockNode(new g(e)),t&&r)this.code(t).else().code(r).endIf();else if(t)this.code(t).endIf();else if(r)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new g(e))}else(){return this._elseNode(new y)}endIf(){return this._endBlockNode(g,y)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new _(e),t)}forRange(e,t,o,n,s=(this.opts.es5?r.varKinds.var:r.varKinds.let)){const a=this._scope.toName(e);return this._for(new w(s,a,t,o),()=>n(a))}forOf(e,o,n,s=r.varKinds.const){const a=this._scope.toName(e);if(this.opts.es5){const e=o instanceof t.Name?o:this.var("_arr",o);return this.forRange("_i",0,t._`${e}.length`,r=>{this.var(a,t._`${e}[${r}]`),n(a)})}return this._for(new $("of",s,a,o),()=>n(a))}forIn(e,o,n,s=(this.opts.es5?r.varKinds.var:r.varKinds.const)){if(this.opts.ownProperties)return this.forOf(e,t._`Object.keys(${o})`,n);const a=this._scope.toName(e);return this._for(new $("in",s,a,o),()=>n(a))}endFor(){return this._endBlockNode(v)}label(e){return this._leafNode(new u(e))}break(e){return this._leafNode(new l(e))}return(e){const t=new k;if(this._blockNode(t),this.code(e),1!==t.nodes.length)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(k)}try(e,t,r){if(!t&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');const o=new E;if(this._blockNode(o),this.code(e),t){const e=this.name("e");this._currNode=o.catch=new S(e),t(e)}return r&&(this._currNode=o.finally=new P,this.code(r)),this._endBlockNode(S,P)}throw(e){return this._leafNode(new d(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){const t=this._blockStarts.pop();if(void 0===t)throw new Error("CodeGen: not in self-balancing block");const r=this._nodes.length-t;if(r<0||void 0!==e&&r!==e)throw new Error(`CodeGen: wrong number of nodes: ${r} vs ${e} expected`);return this._nodes.length=t,this}func(e,r=t.nil,o,n){return this._blockNode(new b(e,r,o)),n&&this.code(n).endFunc(),this}endFunc(){return this._endBlockNode(b)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){const r=this._currNode;if(r instanceof e||t&&r instanceof t)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){const t=this._currNode;if(!(t instanceof g))throw new Error('CodeGen: "else" without "if"');return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){const e=this._nodes;return e[e.length-1]}set _currNode(e){const t=this._nodes;t[t.length-1]=e}},e.not=C;const j=O(e.operators.AND);e.and=function(...e){return e.reduce(j)};const R=O(e.operators.OR);function O(e){return(r,o)=>r===t.nil?o:o===t.nil?r:t._`${z(r)} ${e} ${z(o)}`}function z(e){return e instanceof t.Name?e:t._`(${e})`}e.or=function(...e){return e.reduce(R)}}(lf);var pf={};Object.defineProperty(pf,"__esModule",{value:!0}),pf.checkStrictMode=pf.getErrorPath=pf.Type=pf.useFunc=pf.setEvaluated=pf.evaluatedPropsToName=pf.mergeEvaluated=pf.eachItem=pf.unescapeJsonPointer=pf.escapeJsonPointer=pf.escapeFragment=pf.unescapeFragment=pf.schemaRefOrVal=pf.schemaHasRulesButRef=pf.schemaHasRules=pf.checkUnknownRules=pf.alwaysValidSchema=pf.toHash=void 0;const ff=lf,mf=df;function yf(e,t=e.schema){const{opts:r,self:o}=e;if(!r.strictSchema)return;if("boolean"==typeof t)return;const n=o.RULES.keywords;for(const r in t)n[r]||Sf(e,`unknown keyword: "${r}"`)}function gf(e,t){if("boolean"==typeof e)return!e;for(const r in e)if(t[r])return!0;return!1}function vf(e){return"number"==typeof e?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}function _f(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function wf({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:o}){return(n,s,a,i)=>{const c=void 0===a?s:a instanceof ff.Name?(s instanceof ff.Name?e(n,s,a):t(n,s,a),a):s instanceof ff.Name?(t(n,a,s),s):r(s,a);return i!==ff.Name||c instanceof ff.Name?c:o(n,c)}}function $f(e,t){if(!0===t)return e.var("props",!0);const r=e.var("props",ff._`{}`);return void 0!==t&&bf(e,r,t),r}function bf(e,t,r){Object.keys(r).forEach(r=>e.assign(ff._`${t}${(0,ff.getProperty)(r)}`,!0))}pf.toHash=function(e){const t={};for(const r of e)t[r]=!0;return t},pf.alwaysValidSchema=function(e,t){return"boolean"==typeof t?t:0===Object.keys(t).length||(yf(e,t),!gf(t,e.self.RULES.all))},pf.checkUnknownRules=yf,pf.schemaHasRules=gf,pf.schemaHasRulesButRef=function(e,t){if("boolean"==typeof e)return!e;for(const r in e)if("$ref"!==r&&t.all[r])return!0;return!1},pf.schemaRefOrVal=function({topSchemaRef:e,schemaPath:t},r,o,n){if(!n){if("number"==typeof r||"boolean"==typeof r)return r;if("string"==typeof r)return ff._`${r}`}return ff._`${e}${t}${(0,ff.getProperty)(o)}`},pf.unescapeFragment=function(e){return _f(decodeURIComponent(e))},pf.escapeFragment=function(e){return encodeURIComponent(vf(e))},pf.escapeJsonPointer=vf,pf.unescapeJsonPointer=_f,pf.eachItem=function(e,t){if(Array.isArray(e))for(const r of e)t(r);else t(e)},pf.mergeEvaluated={props:wf({mergeNames:(e,t,r)=>e.if(ff._`${r} !== true && ${t} !== undefined`,()=>{e.if(ff._`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,ff._`${r} || {}`).code(ff._`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if(ff._`${r} !== true`,()=>{!0===t?e.assign(r,!0):(e.assign(r,ff._`${r} || {}`),bf(e,r,t))}),mergeValues:(e,t)=>!0===e||{...e,...t},resultToName:$f}),items:wf({mergeNames:(e,t,r)=>e.if(ff._`${r} !== true && ${t} !== undefined`,()=>e.assign(r,ff._`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if(ff._`${r} !== true`,()=>e.assign(r,!0===t||ff._`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>!0===e||Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})},pf.evaluatedPropsToName=$f,pf.setEvaluated=bf;const kf={};var Ef;function Sf(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,!0===r)throw new Error(t);e.self.logger.warn(t)}}pf.useFunc=function(e,t){return e.scopeValue("func",{ref:t,code:kf[t.code]||(kf[t.code]=new mf._Code(t.code))})},function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"}(Ef||(pf.Type=Ef={})),pf.getErrorPath=function(e,t,r){if(e instanceof ff.Name){const o=t===Ef.Num;return r?o?ff._`"[" + ${e} + "]"`:ff._`"['" + ${e} + "']"`:o?ff._`"/" + ${e}`:ff._`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,ff.getProperty)(e).toString():"/"+vf(e)},pf.checkStrictMode=Sf;var Pf,Tf,If,xf={};function Nf(){if(Pf)return xf;Pf=1,Object.defineProperty(xf,"__esModule",{value:!0});const e=lf,t={data:new e.Name("data"),valCxt:new e.Name("valCxt"),instancePath:new e.Name("instancePath"),parentData:new e.Name("parentData"),parentDataProperty:new e.Name("parentDataProperty"),rootData:new e.Name("rootData"),dynamicAnchors:new e.Name("dynamicAnchors"),vErrors:new e.Name("vErrors"),errors:new e.Name("errors"),this:new e.Name("this"),self:new e.Name("self"),scope:new e.Name("scope"),json:new e.Name("json"),jsonPos:new e.Name("jsonPos"),jsonLen:new e.Name("jsonLen"),jsonPart:new e.Name("jsonPart")};return xf.default=t,xf}function Cf(){return Tf||(Tf=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;const t=lf,r=pf,o=Nf();function n(e,r){const n=e.const("err",r);e.if(t._`${o.default.vErrors} === null`,()=>e.assign(o.default.vErrors,t._`[${n}]`),t._`${o.default.vErrors}.push(${n})`),e.code(t._`${o.default.errors}++`)}function s(e,r){const{gen:o,validateName:n,schemaEnv:s}=e;s.$async?o.throw(t._`new ${e.ValidationError}(${r})`):(o.assign(t._`${n}.errors`,r),o.return(!1))}e.keywordError={message:({keyword:e})=>t.str`must pass "${e}" keyword validation`},e.keyword$DataError={message:({keyword:e,schemaType:r})=>r?t.str`"${e}" keyword must be ${r} ($data)`:t.str`"${e}" keyword is invalid ($data)`},e.reportError=function(r,o=e.keywordError,a,c){const{it:u}=r,{gen:l,compositeRule:d,allErrors:h}=u,p=i(r,o,a);(null!=c?c:d||h)?n(l,p):s(u,t._`[${p}]`)},e.reportExtraError=function(t,r=e.keywordError,a){const{it:c}=t,{gen:u,compositeRule:l,allErrors:d}=c;n(u,i(t,r,a)),l||d||s(c,o.default.vErrors)},e.resetErrorsCount=function(e,r){e.assign(o.default.errors,r),e.if(t._`${o.default.vErrors} !== null`,()=>e.if(r,()=>e.assign(t._`${o.default.vErrors}.length`,r),()=>e.assign(o.default.vErrors,null)))},e.extendErrors=function({gen:e,keyword:r,schemaValue:n,data:s,errsCount:a,it:i}){if(void 0===a)throw new Error("ajv implementation error");const c=e.name("err");e.forRange("i",a,o.default.errors,a=>{e.const(c,t._`${o.default.vErrors}[${a}]`),e.if(t._`${c}.instancePath === undefined`,()=>e.assign(t._`${c}.instancePath`,(0,t.strConcat)(o.default.instancePath,i.errorPath))),e.assign(t._`${c}.schemaPath`,t.str`${i.errSchemaPath}/${r}`),i.opts.verbose&&(e.assign(t._`${c}.schema`,n),e.assign(t._`${c}.data`,s))})};const a={keyword:new t.Name("keyword"),schemaPath:new t.Name("schemaPath"),params:new t.Name("params"),propertyName:new t.Name("propertyName"),message:new t.Name("message"),schema:new t.Name("schema"),parentSchema:new t.Name("parentSchema")};function i(e,r,n){const{createErrors:s}=e.it;return!1===s?t._`{}`:function(e,r,n={}){const{gen:s,it:i}=e,l=[c(i,n),u(e,n)];return function(e,{params:r,message:n},s){const{keyword:i,data:c,schemaValue:u,it:l}=e,{opts:d,propertyName:h,topSchemaRef:p,schemaPath:f}=l;s.push([a.keyword,i],[a.params,"function"==typeof r?r(e):r||t._`{}`]),d.messages&&s.push([a.message,"function"==typeof n?n(e):n]);d.verbose&&s.push([a.schema,u],[a.parentSchema,t._`${p}${f}`],[o.default.data,c]);h&&s.push([a.propertyName,h])}(e,r,l),s.object(...l)}(e,r,n)}function c({errorPath:e},{instancePath:n}){const s=n?t.str`${e}${(0,r.getErrorPath)(n,r.Type.Str)}`:e;return[o.default.instancePath,(0,t.strConcat)(o.default.instancePath,s)]}function u({keyword:e,it:{errSchemaPath:o}},{schemaPath:n,parentSchema:s}){let i=s?o:t.str`${o}/${e}`;return n&&(i=t.str`${i}${(0,r.getErrorPath)(n,r.Type.Str)}`),[a.schemaPath,i]}}(uf)),uf}var jf={},Rf={};Object.defineProperty(Rf,"__esModule",{value:!0}),Rf.getRules=Rf.isJSONType=void 0;const Of=new Set(["string","number","integer","boolean","null","object","array"]);Rf.isJSONType=function(e){return"string"==typeof e&&Of.has(e)},Rf.getRules=function(){const e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}};var zf,Af={};function Mf(){if(zf)return Af;function e(e,r){return r.rules.some(r=>t(e,r))}function t(e,t){var r;return void 0!==e[t.keyword]||(null===(r=t.definition.implements)||void 0===r?void 0:r.some(t=>void 0!==e[t]))}return zf=1,Object.defineProperty(Af,"__esModule",{value:!0}),Af.shouldUseRule=Af.shouldUseGroup=Af.schemaHasRulesForType=void 0,Af.schemaHasRulesForType=function({schema:t,self:r},o){const n=r.RULES.types[o];return n&&!0!==n&&e(t,n)},Af.shouldUseGroup=e,Af.shouldUseRule=t,Af}Object.defineProperty(jf,"__esModule",{value:!0}),jf.reportTypeError=jf.checkDataTypes=jf.checkDataType=jf.coerceAndCheckDataType=jf.getJSONTypes=jf.getSchemaTypes=jf.DataType=void 0;const Df=Rf,Uf=Mf(),qf=Cf(),Vf=lf,Ff=pf;var Lf;function Hf(e){const t=Array.isArray(e)?e:e?[e]:[];if(t.every(Df.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}!function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"}(Lf||(jf.DataType=Lf={})),jf.getSchemaTypes=function(e){const t=Hf(e.type);if(t.includes("null")){if(!1===e.nullable)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&void 0!==e.nullable)throw new Error('"nullable" cannot be used without "type"');!0===e.nullable&&t.push("null")}return t},jf.getJSONTypes=Hf,jf.coerceAndCheckDataType=function(e,t){const{gen:r,data:o,opts:n}=e,s=function(e,t){return t?e.filter(e=>Kf.has(e)||"array"===t&&"array"===e):[]}(t,n.coerceTypes),a=t.length>0&&!(0===s.length&&1===t.length&&(0,Uf.schemaHasRulesForType)(e,t[0]));if(a){const a=Gf(t,o,n.strictNumbers,Lf.Wrong);r.if(a,()=>{s.length?function(e,t,r){const{gen:o,data:n,opts:s}=e,a=o.let("dataType",Vf._`typeof ${n}`),i=o.let("coerced",Vf._`undefined`);"array"===s.coerceTypes&&o.if(Vf._`${a} == 'object' && Array.isArray(${n}) && ${n}.length == 1`,()=>o.assign(n,Vf._`${n}[0]`).assign(a,Vf._`typeof ${n}`).if(Gf(t,n,s.strictNumbers),()=>o.assign(i,n)));o.if(Vf._`${i} !== undefined`);for(const e of r)(Kf.has(e)||"array"===e&&"array"===s.coerceTypes)&&c(e);function c(e){switch(e){case"string":return void o.elseIf(Vf._`${a} == "number" || ${a} == "boolean"`).assign(i,Vf._`"" + ${n}`).elseIf(Vf._`${n} === null`).assign(i,Vf._`""`);case"number":return void o.elseIf(Vf._`${a} == "boolean" || ${n} === null
8
- || (${a} == "string" && ${n} && ${n} == +${n})`).assign(i,Vf._`+${n}`);case"integer":return void o.elseIf(Vf._`${a} === "boolean" || ${n} === null
9
- || (${a} === "string" && ${n} && ${n} == +${n} && !(${n} % 1))`).assign(i,Vf._`+${n}`);case"boolean":return void o.elseIf(Vf._`${n} === "false" || ${n} === 0 || ${n} === null`).assign(i,!1).elseIf(Vf._`${n} === "true" || ${n} === 1`).assign(i,!0);case"null":return o.elseIf(Vf._`${n} === "" || ${n} === 0 || ${n} === false`),void o.assign(i,null);case"array":o.elseIf(Vf._`${a} === "string" || ${a} === "number"
10
- || ${a} === "boolean" || ${n} === null`).assign(i,Vf._`[${n}]`)}}o.else(),Jf(e),o.endIf(),o.if(Vf._`${i} !== undefined`,()=>{o.assign(n,i),function({gen:e,parentData:t,parentDataProperty:r},o){e.if(Vf._`${t} !== undefined`,()=>e.assign(Vf._`${t}[${r}]`,o))}(e,i)})}(e,t,s):Jf(e)})}return a};const Kf=new Set(["string","number","integer","boolean","null"]);function Zf(e,t,r,o=Lf.Correct){const n=o===Lf.Correct?Vf.operators.EQ:Vf.operators.NEQ;let s;switch(e){case"null":return Vf._`${t} ${n} null`;case"array":s=Vf._`Array.isArray(${t})`;break;case"object":s=Vf._`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":s=a(Vf._`!(${t} % 1) && !isNaN(${t})`);break;case"number":s=a();break;default:return Vf._`typeof ${t} ${n} ${e}`}return o===Lf.Correct?s:(0,Vf.not)(s);function a(e=Vf.nil){return(0,Vf.and)(Vf._`typeof ${t} == "number"`,e,r?Vf._`isFinite(${t})`:Vf.nil)}}function Gf(e,t,r,o){if(1===e.length)return Zf(e[0],t,r,o);let n;const s=(0,Ff.toHash)(e);if(s.array&&s.object){const e=Vf._`typeof ${t} != "object"`;n=s.null?e:Vf._`!${t} || ${e}`,delete s.null,delete s.array,delete s.object}else n=Vf.nil;s.number&&delete s.integer;for(const e in s)n=(0,Vf.and)(n,Zf(e,t,r,o));return n}jf.checkDataType=Zf,jf.checkDataTypes=Gf;const Bf={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>"string"==typeof e?Vf._`{type: ${e}}`:Vf._`{type: ${t}}`};function Jf(e){const t=function(e){const{gen:t,data:r,schema:o}=e,n=(0,Ff.schemaRefOrVal)(e,o,"type");return{gen:t,keyword:"type",data:r,schema:o.type,schemaCode:n,schemaValue:n,parentSchema:o,params:{},it:e}}(e);(0,qf.reportError)(t,Bf)}jf.reportTypeError=Jf;var Wf,Qf={};var Yf,Xf,em={},tm={};function rm(){if(Yf)return tm;Yf=1,Object.defineProperty(tm,"__esModule",{value:!0}),tm.validateUnion=tm.validateArray=tm.usePattern=tm.callValidateCode=tm.schemaProperties=tm.allSchemaProperties=tm.noPropertyInData=tm.propertyInData=tm.isOwnProperty=tm.hasPropFunc=tm.reportMissingProp=tm.checkMissingProp=tm.checkReportMissingProp=void 0;const e=lf,t=pf,r=Nf(),o=pf;function n(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:e._`Object.prototype.hasOwnProperty`})}function s(t,r,o){return e._`${n(t)}.call(${r}, ${o})`}function a(t,r,o,n){const a=e._`${r}${(0,e.getProperty)(o)} === undefined`;return n?(0,e.or)(a,(0,e.not)(s(t,r,o))):a}function i(e){return e?Object.keys(e).filter(e=>"__proto__"!==e):[]}tm.checkReportMissingProp=function(t,r){const{gen:o,data:n,it:s}=t;o.if(a(o,n,r,s.opts.ownProperties),()=>{t.setParams({missingProperty:e._`${r}`},!0),t.error()})},tm.checkMissingProp=function({gen:t,data:r,it:{opts:o}},n,s){return(0,e.or)(...n.map(n=>(0,e.and)(a(t,r,n,o.ownProperties),e._`${s} = ${n}`)))},tm.reportMissingProp=function(e,t){e.setParams({missingProperty:t},!0),e.error()},tm.hasPropFunc=n,tm.isOwnProperty=s,tm.propertyInData=function(t,r,o,n){const a=e._`${r}${(0,e.getProperty)(o)} !== undefined`;return n?e._`${a} && ${s(t,r,o)}`:a},tm.noPropertyInData=a,tm.allSchemaProperties=i,tm.schemaProperties=function(e,r){return i(r).filter(o=>!(0,t.alwaysValidSchema)(e,r[o]))},tm.callValidateCode=function({schemaCode:t,data:o,it:{gen:n,topSchemaRef:s,schemaPath:a,errorPath:i},it:c},u,l,d){const h=d?e._`${t}, ${o}, ${s}${a}`:o,p=[[r.default.instancePath,(0,e.strConcat)(r.default.instancePath,i)],[r.default.parentData,c.parentData],[r.default.parentDataProperty,c.parentDataProperty],[r.default.rootData,r.default.rootData]];c.opts.dynamicRef&&p.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);const f=e._`${h}, ${n.object(...p)}`;return l!==e.nil?e._`${u}.call(${l}, ${f})`:e._`${u}(${f})`};const c=e._`new RegExp`;return tm.usePattern=function({gen:t,it:{opts:r}},n){const s=r.unicodeRegExp?"u":"",{regExp:a}=r.code,i=a(n,s);return t.scopeValue("pattern",{key:i.toString(),ref:i,code:e._`${"new RegExp"===a.code?c:(0,o.useFunc)(t,a)}(${n}, ${s})`})},tm.validateArray=function(r){const{gen:o,data:n,keyword:s,it:a}=r,i=o.name("valid");if(a.allErrors){const e=o.let("valid",!0);return c(()=>o.assign(e,!1)),e}return o.var(i,!0),c(()=>o.break()),i;function c(a){const c=o.const("len",e._`${n}.length`);o.forRange("i",0,c,n=>{r.subschema({keyword:s,dataProp:n,dataPropType:t.Type.Num},i),o.if((0,e.not)(i),a)})}},tm.validateUnion=function(r){const{gen:o,schema:n,keyword:s,it:a}=r;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some(e=>(0,t.alwaysValidSchema)(a,e))&&!a.opts.unevaluated)return;const i=o.let("valid",!1),c=o.name("_valid");o.block(()=>n.forEach((t,n)=>{const a=r.subschema({keyword:s,schemaProp:n,compositeRule:!0},c);o.assign(i,e._`${i} || ${c}`);r.mergeValidEvaluated(a,c)||o.if((0,e.not)(i))})),r.result(i,()=>r.reset(),()=>r.error(!0))},tm}function om(){if(Xf)return em;Xf=1,Object.defineProperty(em,"__esModule",{value:!0}),em.validateKeywordUsage=em.validSchemaType=em.funcKeywordCode=em.macroKeywordCode=void 0;const e=lf,t=Nf(),r=rm(),o=Cf();function n(t){const{gen:r,data:o,it:n}=t;r.if(n.parentData,()=>r.assign(o,e._`${n.parentData}[${n.parentDataProperty}]`))}function s(t,r,o){if(void 0===o)throw new Error(`keyword "${r}" failed to compile`);return t.scopeValue("keyword","function"==typeof o?{ref:o}:{ref:o,code:(0,e.stringify)(o)})}return em.macroKeywordCode=function(t,r){const{gen:o,keyword:n,schema:a,parentSchema:i,it:c}=t,u=r.macro.call(c.self,a,i,c),l=s(o,n,u);!1!==c.opts.validateSchema&&c.self.validateSchema(u,!0);const d=o.name("valid");t.subschema({schema:u,schemaPath:e.nil,errSchemaPath:`${c.errSchemaPath}/${n}`,topSchemaRef:l,compositeRule:!0},d),t.pass(d,()=>t.error(!0))},em.funcKeywordCode=function(a,i){var c;const{gen:u,keyword:l,schema:d,parentSchema:h,$data:p,it:f}=a;!function({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}(f,i);const m=!p&&i.compile?i.compile.call(f.self,d,h,f):i.validate,y=s(u,l,m),g=u.let("valid");function v(o=(i.async?e._`await `:e.nil)){const n=f.opts.passContext?t.default.this:t.default.self,s=!("compile"in i&&!p||!1===i.schema);u.assign(g,e._`${o}${(0,r.callValidateCode)(a,y,n,s)}`,i.modifying)}function _(t){var r;u.if((0,e.not)(null!==(r=i.valid)&&void 0!==r?r:g),t)}a.block$data(g,function(){if(!1===i.errors)v(),i.modifying&&n(a),_(()=>a.error());else{const r=i.async?function(){const t=u.let("ruleErrs",null);return u.try(()=>v(e._`await `),r=>u.assign(g,!1).if(e._`${r} instanceof ${f.ValidationError}`,()=>u.assign(t,e._`${r}.errors`),()=>u.throw(r))),t}():function(){const t=e._`${y}.errors`;return u.assign(t,null),v(e.nil),t}();i.modifying&&n(a),_(()=>function(r,n){const{gen:s}=r;s.if(e._`Array.isArray(${n})`,()=>{s.assign(t.default.vErrors,e._`${t.default.vErrors} === null ? ${n} : ${t.default.vErrors}.concat(${n})`).assign(t.default.errors,e._`${t.default.vErrors}.length`),(0,o.extendErrors)(r)},()=>r.error())}(a,r))}}),a.ok(null!==(c=i.valid)&&void 0!==c?c:g)},em.validSchemaType=function(e,t,r=!1){return!t.length||t.some(t=>"array"===t?Array.isArray(e):"object"===t?e&&"object"==typeof e&&!Array.isArray(e):typeof e==t||r&&void 0===e)},em.validateKeywordUsage=function({schema:e,opts:t,self:r,errSchemaPath:o},n,s){if(Array.isArray(n.keyword)?!n.keyword.includes(s):n.keyword!==s)throw new Error("ajv implementation error");const a=n.dependencies;if(null==a?void 0:a.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw new Error(`parent schema must have dependencies of ${s}: ${a.join(",")}`);if(n.validateSchema){if(!n.validateSchema(e[s])){const e=`keyword "${s}" value is invalid at path "${o}": `+r.errorsText(n.validateSchema.errors);if("log"!==t.validateSchema)throw new Error(e);r.logger.error(e)}}},em}var nm,sm={};var am={},im={exports:{}},cm=im.exports=function(e,t,r){"function"==typeof t&&(r=t,t={}),um(t,"function"==typeof(r=t.cb||r)?r:r.pre||function(){},r.post||function(){},e,"",e)};function um(e,t,r,o,n,s,a,i,c,u){if(o&&"object"==typeof o&&!Array.isArray(o)){for(var l in t(o,n,s,a,i,c,u),o){var d=o[l];if(Array.isArray(d)){if(l in cm.arrayKeywords)for(var h=0;h<d.length;h++)um(e,t,r,d[h],n+"/"+l+"/"+h,s,n,l,o,h)}else if(l in cm.propsKeywords){if(d&&"object"==typeof d)for(var p in d)um(e,t,r,d[p],n+"/"+l+"/"+lm(p),s,n,l,o,p)}else(l in cm.keywords||e.allKeys&&!(l in cm.skipKeywords))&&um(e,t,r,d,n+"/"+l,s,n,l,o)}r(o,n,s,a,i,c,u)}}function lm(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}cm.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},cm.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},cm.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},cm.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};var dm=im.exports;Object.defineProperty(am,"__esModule",{value:!0}),am.getSchemaRefs=am.resolveUrl=am.normalizeId=am._getFullPath=am.getFullPath=am.inlineRef=void 0;const hm=pf,pm=nu,fm=dm,mm=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);am.inlineRef=function(e,t=!0){return"boolean"==typeof e||(!0===t?!gm(e):!!t&&vm(e)<=t)};const ym=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function gm(e){for(const t in e){if(ym.has(t))return!0;const r=e[t];if(Array.isArray(r)&&r.some(gm))return!0;if("object"==typeof r&&gm(r))return!0}return!1}function vm(e){let t=0;for(const r in e){if("$ref"===r)return 1/0;if(t++,!mm.has(r)&&("object"==typeof e[r]&&(0,hm.eachItem)(e[r],e=>t+=vm(e)),t===1/0))return 1/0}return t}function _m(e,t="",r){!1!==r&&(t=bm(t));const o=e.parse(t);return wm(e,o)}function wm(e,t){return e.serialize(t).split("#")[0]+"#"}am.getFullPath=_m,am._getFullPath=wm;const $m=/#\/?$/;function bm(e){return e?e.replace($m,""):""}am.normalizeId=bm,am.resolveUrl=function(e,t,r){return r=bm(r),e.resolve(t,r)};const km=/^[a-z_][-a-z0-9._]*$/i;var Em;function Sm(){if(Em)return af;Em=1,Object.defineProperty(af,"__esModule",{value:!0}),af.getData=af.KeywordCxt=af.validateFunctionCode=void 0;const e=function(){if(If)return cf;If=1,Object.defineProperty(cf,"__esModule",{value:!0}),cf.boolOrEmptySchema=cf.topBoolOrEmptySchema=void 0;const e=Cf(),t=lf,r=Nf(),o={message:"boolean schema is false"};function n(t,r){const{gen:n,data:s}=t,a={gen:n,keyword:"false schema",data:s,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,e.reportError)(a,o,void 0,r)}return cf.topBoolOrEmptySchema=function(e){const{gen:o,schema:s,validateName:a}=e;!1===s?n(e,!1):"object"==typeof s&&!0===s.$async?o.return(r.default.data):(o.assign(t._`${a}.errors`,null),o.return(!0))},cf.boolOrEmptySchema=function(e,t){const{gen:r,schema:o}=e;!1===o?(r.var(t,!1),n(e)):r.var(t,!0)},cf}(),t=jf,r=Mf(),o=jf,n=function(){if(Wf)return Qf;Wf=1,Object.defineProperty(Qf,"__esModule",{value:!0}),Qf.assignDefaults=void 0;const e=lf,t=pf;function r(r,o,n){const{gen:s,compositeRule:a,data:i,opts:c}=r;if(void 0===n)return;const u=e._`${i}${(0,e.getProperty)(o)}`;if(a)return void(0,t.checkStrictMode)(r,`default is ignored for: ${u}`);let l=e._`${u} === undefined`;"empty"===c.useDefaults&&(l=e._`${l} || ${u} === null || ${u} === ""`),s.if(l,e._`${u} = ${(0,e.stringify)(n)}`)}return Qf.assignDefaults=function(e,t){const{properties:o,items:n}=e.schema;if("object"===t&&o)for(const t in o)r(e,t,o[t].default);else"array"===t&&Array.isArray(n)&&n.forEach((t,o)=>r(e,o,t.default))},Qf}(),s=om(),a=function(){if(nm)return sm;nm=1,Object.defineProperty(sm,"__esModule",{value:!0}),sm.extendSubschemaMode=sm.extendSubschemaData=sm.getSubschema=void 0;const e=lf,t=pf;return sm.getSubschema=function(r,{keyword:o,schemaProp:n,schema:s,schemaPath:a,errSchemaPath:i,topSchemaRef:c}){if(void 0!==o&&void 0!==s)throw new Error('both "keyword" and "schema" passed, only one allowed');if(void 0!==o){const s=r.schema[o];return void 0===n?{schema:s,schemaPath:e._`${r.schemaPath}${(0,e.getProperty)(o)}`,errSchemaPath:`${r.errSchemaPath}/${o}`}:{schema:s[n],schemaPath:e._`${r.schemaPath}${(0,e.getProperty)(o)}${(0,e.getProperty)(n)}`,errSchemaPath:`${r.errSchemaPath}/${o}/${(0,t.escapeFragment)(n)}`}}if(void 0!==s){if(void 0===a||void 0===i||void 0===c)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:s,schemaPath:a,topSchemaRef:c,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')},sm.extendSubschemaData=function(r,o,{dataProp:n,dataPropType:s,data:a,dataTypes:i,propertyName:c}){if(void 0!==a&&void 0!==n)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:u}=o;if(void 0!==n){const{errorPath:a,dataPathArr:i,opts:c}=o;l(u.let("data",e._`${o.data}${(0,e.getProperty)(n)}`,!0)),r.errorPath=e.str`${a}${(0,t.getErrorPath)(n,s,c.jsPropertySyntax)}`,r.parentDataProperty=e._`${n}`,r.dataPathArr=[...i,r.parentDataProperty]}function l(e){r.data=e,r.dataLevel=o.dataLevel+1,r.dataTypes=[],o.definedProperties=new Set,r.parentData=o.data,r.dataNames=[...o.dataNames,e]}void 0!==a&&(l(a instanceof e.Name?a:u.let("data",a,!0)),void 0!==c&&(r.propertyName=c)),i&&(r.dataTypes=i)},sm.extendSubschemaMode=function(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:o,createErrors:n,allErrors:s}){void 0!==o&&(e.compositeRule=o),void 0!==n&&(e.createErrors=n),void 0!==s&&(e.allErrors=s),e.jtdDiscriminator=t,e.jtdMetadata=r},sm}(),i=lf,c=Nf(),u=am,l=pf,d=Cf();function h({gen:e,validateName:t,schema:r,schemaEnv:o,opts:n},s){n.code.es5?e.func(t,i._`${c.default.data}, ${c.default.valCxt}`,o.$async,()=>{e.code(i._`"use strict"; ${p(r,n)}`),function(e,t){e.if(c.default.valCxt,()=>{e.var(c.default.instancePath,i._`${c.default.valCxt}.${c.default.instancePath}`),e.var(c.default.parentData,i._`${c.default.valCxt}.${c.default.parentData}`),e.var(c.default.parentDataProperty,i._`${c.default.valCxt}.${c.default.parentDataProperty}`),e.var(c.default.rootData,i._`${c.default.valCxt}.${c.default.rootData}`),t.dynamicRef&&e.var(c.default.dynamicAnchors,i._`${c.default.valCxt}.${c.default.dynamicAnchors}`)},()=>{e.var(c.default.instancePath,i._`""`),e.var(c.default.parentData,i._`undefined`),e.var(c.default.parentDataProperty,i._`undefined`),e.var(c.default.rootData,c.default.data),t.dynamicRef&&e.var(c.default.dynamicAnchors,i._`{}`)})}(e,n),e.code(s)}):e.func(t,i._`${c.default.data}, ${function(e){return i._`{${c.default.instancePath}="", ${c.default.parentData}, ${c.default.parentDataProperty}, ${c.default.rootData}=${c.default.data}${e.dynamicRef?i._`, ${c.default.dynamicAnchors}={}`:i.nil}}={}`}(n)}`,o.$async,()=>e.code(p(r,n)).code(s))}function p(e,t){const r="object"==typeof e&&e[t.schemaId];return r&&(t.code.source||t.code.process)?i._`/*# sourceURL=${r} */`:i.nil}function f(t,r){y(t)&&(g(t),m(t))?function(e,t){const{schema:r,gen:o,opts:n}=e;n.$comment&&r.$comment&&_(e);(function(e){const t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,u.resolveUrl)(e.opts.uriResolver,e.baseId,t))})(e),function(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}(e);const s=o.const("_errs",c.default.errors);v(e,s),o.var(t,i._`${s} === ${c.default.errors}`)}(t,r):(0,e.boolOrEmptySchema)(t,r)}function m({schema:e,self:t}){if("boolean"==typeof e)return!e;for(const r in e)if(t.RULES.all[r])return!0;return!1}function y(e){return"boolean"!=typeof e.schema}function g(e){(0,l.checkUnknownRules)(e),function(e){const{schema:t,errSchemaPath:r,opts:o,self:n}=e;t.$ref&&o.ignoreKeywordsWithRef&&(0,l.schemaHasRulesButRef)(t,n.RULES)&&n.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}(e)}function v(e,r){if(e.opts.jtd)return w(e,[],!1,r);const o=(0,t.getSchemaTypes)(e.schema);w(e,o,!(0,t.coerceAndCheckDataType)(e,o),r)}function _({gen:e,schemaEnv:t,schema:r,errSchemaPath:o,opts:n}){const s=r.$comment;if(!0===n.$comment)e.code(i._`${c.default.self}.logger.log(${s})`);else if("function"==typeof n.$comment){const r=i.str`${o}/$comment`,n=e.scopeValue("root",{ref:t.root});e.code(i._`${c.default.self}.opts.$comment(${s}, ${r}, ${n}.schema)`)}}function w(e,t,n,s){const{gen:a,schema:u,data:d,allErrors:h,opts:p,self:f}=e,{RULES:m}=f;function y(l){(0,r.shouldUseGroup)(u,l)&&(l.type?(a.if((0,o.checkDataType)(l.type,d,p.strictNumbers)),$(e,l),1===t.length&&t[0]===l.type&&n&&(a.else(),(0,o.reportTypeError)(e)),a.endIf()):$(e,l),h||a.if(i._`${c.default.errors} === ${s||0}`))}!u.$ref||!p.ignoreKeywordsWithRef&&(0,l.schemaHasRulesButRef)(u,m)?(p.jtd||function(e,t){if(e.schemaEnv.meta||!e.opts.strictTypes)return;(function(e,t){if(!t.length)return;if(!e.dataTypes.length)return void(e.dataTypes=t);t.forEach(t=>{k(e.dataTypes,t)||E(e,`type "${t}" not allowed by context "${e.dataTypes.join(",")}"`)}),function(e,t){const r=[];for(const o of e.dataTypes)k(t,o)?r.push(o):t.includes("integer")&&"number"===o&&r.push("integer");e.dataTypes=r}(e,t)})(e,t),e.opts.allowUnionTypes||function(e,t){t.length>1&&(2!==t.length||!t.includes("null"))&&E(e,"use allowUnionTypes to allow union type keyword")}(e,t);!function(e,t){const o=e.self.RULES.all;for(const n in o){const s=o[n];if("object"==typeof s&&(0,r.shouldUseRule)(e.schema,s)){const{type:r}=s.definition;r.length&&!r.some(e=>b(t,e))&&E(e,`missing type "${r.join(",")}" for keyword "${n}"`)}}}(e,e.dataTypes)}(e,t),a.block(()=>{for(const e of m.rules)y(e);y(m.post)})):a.block(()=>P(e,"$ref",m.all.$ref.definition))}function $(e,t){const{gen:o,schema:s,opts:{useDefaults:a}}=e;a&&(0,n.assignDefaults)(e,t.type),o.block(()=>{for(const o of t.rules)(0,r.shouldUseRule)(s,o)&&P(e,o.keyword,o.definition,t.type)})}function b(e,t){return e.includes(t)||"number"===t&&e.includes("integer")}function k(e,t){return e.includes(t)||"integer"===t&&e.includes("number")}function E(e,t){t+=` at "${e.schemaEnv.baseId+e.errSchemaPath}" (strictTypes)`,(0,l.checkStrictMode)(e,t,e.opts.strictTypes)}af.validateFunctionCode=function(t){y(t)&&(g(t),m(t))?function(e){const{schema:t,opts:r,gen:o}=e;h(e,()=>{r.$comment&&t.$comment&&_(e),function(e){const{schema:t,opts:r}=e;void 0!==t.default&&r.useDefaults&&r.strictSchema&&(0,l.checkStrictMode)(e,"default is ignored in the schema root")}(e),o.let(c.default.vErrors,null),o.let(c.default.errors,0),r.unevaluated&&function(e){const{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",i._`${r}.evaluated`),t.if(i._`${e.evaluated}.dynamicProps`,()=>t.assign(i._`${e.evaluated}.props`,i._`undefined`)),t.if(i._`${e.evaluated}.dynamicItems`,()=>t.assign(i._`${e.evaluated}.items`,i._`undefined`))}(e),v(e),function(e){const{gen:t,schemaEnv:r,validateName:o,ValidationError:n,opts:s}=e;r.$async?t.if(i._`${c.default.errors} === 0`,()=>t.return(c.default.data),()=>t.throw(i._`new ${n}(${c.default.vErrors})`)):(t.assign(i._`${o}.errors`,c.default.vErrors),s.unevaluated&&function({gen:e,evaluated:t,props:r,items:o}){r instanceof i.Name&&e.assign(i._`${t}.props`,r);o instanceof i.Name&&e.assign(i._`${t}.items`,o)}(e),t.return(i._`${c.default.errors} === 0`))}(e)})}(t):h(t,()=>(0,e.topBoolOrEmptySchema)(t))};class S{constructor(e,t,r){if((0,s.validateKeywordUsage)(e,t,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,l.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const("vSchema",x(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,s.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw new Error(`${r} value must be ${JSON.stringify(t.schemaType)}`);("code"in t?t.trackErrors:!1!==t.errors)&&(this.errsCount=e.gen.const("_errs",c.default.errors))}result(e,t,r){this.failResult((0,i.not)(e),t,r)}failResult(e,t,r){this.gen.if(e),r?r():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,i.not)(e),void 0,t)}fail(e){if(void 0===e)return this.error(),void(this.allErrors||this.gen.if(!1));this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);const{schemaCode:t}=this;this.fail(i._`${t} !== undefined && (${(0,i.or)(this.invalid$data(),e)})`)}error(e,t,r){if(t)return this.setParams(t),this._error(e,r),void this.setParams({});this._error(e,r)}_error(e,t){(e?d.reportExtraError:d.reportError)(this,this.def.error,t)}$dataError(){(0,d.reportError)(this,this.def.$dataError||d.keyword$DataError)}reset(){if(void 0===this.errsCount)throw new Error('add "trackErrors" to keyword definition');(0,d.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,r=i.nil){this.gen.block(()=>{this.check$data(e,r),t()})}check$data(e=i.nil,t=i.nil){if(!this.$data)return;const{gen:r,schemaCode:o,schemaType:n,def:s}=this;r.if((0,i.or)(i._`${o} === undefined`,t)),e!==i.nil&&r.assign(e,!0),(n.length||s.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==i.nil&&r.assign(e,!1)),r.else()}invalid$data(){const{gen:e,schemaCode:t,schemaType:r,def:n,it:s}=this;return(0,i.or)(function(){if(r.length){if(!(t instanceof i.Name))throw new Error("ajv implementation error");const e=Array.isArray(r)?r:[r];return i._`${(0,o.checkDataTypes)(e,t,s.opts.strictNumbers,o.DataType.Wrong)}`}return i.nil}(),function(){if(n.validateSchema){const r=e.scopeValue("validate$data",{ref:n.validateSchema});return i._`!${r}(${t})`}return i.nil}())}subschema(e,t){const r=(0,a.getSubschema)(this.it,e);(0,a.extendSubschemaData)(r,this.it,e),(0,a.extendSubschemaMode)(r,e);const o={...this.it,...r,items:void 0,props:void 0};return f(o,t),o}mergeEvaluated(e,t){const{it:r,gen:o}=this;r.opts.unevaluated&&(!0!==r.props&&void 0!==e.props&&(r.props=l.mergeEvaluated.props(o,e.props,r.props,t)),!0!==r.items&&void 0!==e.items&&(r.items=l.mergeEvaluated.items(o,e.items,r.items,t)))}mergeValidEvaluated(e,t){const{it:r,gen:o}=this;if(r.opts.unevaluated&&(!0!==r.props||!0!==r.items))return o.if(t,()=>this.mergeEvaluated(e,i.Name)),!0}}function P(e,t,r,o){const n=new S(e,r,t);"code"in r?r.code(n,o):n.$data&&r.validate?(0,s.funcKeywordCode)(n,r):"macro"in r?(0,s.macroKeywordCode)(n,r):(r.compile||r.validate)&&(0,s.funcKeywordCode)(n,r)}af.KeywordCxt=S;const T=/^\/(?:[^~]|~0|~1)*$/,I=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function x(e,{dataLevel:t,dataNames:r,dataPathArr:o}){let n,s;if(""===e)return c.default.rootData;if("/"===e[0]){if(!T.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);n=e,s=c.default.rootData}else{const a=I.exec(e);if(!a)throw new Error(`Invalid JSON-pointer: ${e}`);const i=+a[1];if(n=a[2],"#"===n){if(i>=t)throw new Error(d("property/index",i));return o[t-i]}if(i>t)throw new Error(d("data",i));if(s=r[t-i],!n)return s}let a=s;const u=n.split("/");for(const e of u)e&&(s=i._`${s}${(0,i.getProperty)((0,l.unescapeJsonPointer)(e))}`,a=i._`${a} && ${s}`);return a;function d(e,r){return`Cannot access ${e} ${r} levels up, current level is ${t}`}}return af.getData=x,af}am.getSchemaRefs=function(e,t){if("boolean"==typeof e)return{};const{schemaId:r,uriResolver:o}=this.opts,n=bm(e[r]||t),s={"":n},a=_m(o,n,!1),i={},c=new Set;return fm(e,{allKeys:!0},(e,t,o,n)=>{if(void 0===n)return;const d=a+t;let h=s[n];function p(t){const r=this.opts.uriResolver.resolve;if(t=bm(h?r(h,t):t),c.has(t))throw l(t);c.add(t);let o=this.refs[t];return"string"==typeof o&&(o=this.refs[o]),"object"==typeof o?u(e,o.schema,t):t!==bm(d)&&("#"===t[0]?(u(e,i[t],t),i[t]=e):this.refs[t]=d),t}function f(e){if("string"==typeof e){if(!km.test(e))throw new Error(`invalid anchor "${e}"`);p.call(this,`#${e}`)}}"string"==typeof e[r]&&(h=p.call(this,e[r])),f.call(this,e.$anchor),f.call(this,e.$dynamicAnchor),s[t]=h}),i;function u(e,t,r){if(void 0!==t&&!pm(e,t))throw l(r)}function l(e){return new Error(`reference "${e}" resolves to more than one schema`)}};var Pm,Tm={};function Im(){if(Pm)return Tm;Pm=1,Object.defineProperty(Tm,"__esModule",{value:!0});class e extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}}return Tm.default=e,Tm}var xm,Nm={};function Cm(){if(xm)return Nm;xm=1,Object.defineProperty(Nm,"__esModule",{value:!0});const e=am;class t extends Error{constructor(t,r,o,n){super(n||`can't resolve reference ${o} from id ${r}`),this.missingRef=(0,e.resolveUrl)(t,r,o),this.missingSchema=(0,e.normalizeId)((0,e.getFullPath)(t,this.missingRef))}}return Nm.default=t,Nm}var jm={};Object.defineProperty(jm,"__esModule",{value:!0}),jm.resolveSchema=jm.getCompilingSchema=jm.resolveRef=jm.compileSchema=jm.SchemaEnv=void 0;const Rm=lf,Om=Im(),zm=Nf(),Am=am,Mm=pf,Dm=Sm();class Um{constructor(e){var t;let r;this.refs={},this.dynamicAnchors={},"object"==typeof e.schema&&(r=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=null!==(t=e.baseId)&&void 0!==t?t:(0,Am.normalizeId)(null==r?void 0:r[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=null==r?void 0:r.$async,this.refs={}}}function qm(e){const t=Fm.call(this,e);if(t)return t;const r=(0,Am.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:o,lines:n}=this.opts.code,{ownProperties:s}=this.opts,a=new Rm.CodeGen(this.scope,{es5:o,lines:n,ownProperties:s});let i;e.$async&&(i=a.scopeValue("Error",{ref:Om.default,code:Rm._`require("ajv/dist/runtime/validation_error").default`}));const c=a.scopeName("validate");e.validateName=c;const u={gen:a,allErrors:this.opts.allErrors,data:zm.default.data,parentData:zm.default.parentData,parentDataProperty:zm.default.parentDataProperty,dataNames:[zm.default.data],dataPathArr:[Rm.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:a.scopeValue("schema",!0===this.opts.code.source?{ref:e.schema,code:(0,Rm.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:i,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:Rm.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:Rm._`""`,opts:this.opts,self:this};let l;try{this._compilations.add(e),(0,Dm.validateFunctionCode)(u),a.optimize(this.opts.code.optimize);const t=a.toString();l=`${a.scopeRefs(zm.default.scope)}return ${t}`,this.opts.code.process&&(l=this.opts.code.process(l,e));const r=new Function(`${zm.default.self}`,`${zm.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:r}),r.errors=null,r.schema=e.schema,r.schemaEnv=e,e.$async&&(r.$async=!0),!0===this.opts.code.source&&(r.source={validateName:c,validateCode:t,scopeValues:a._values}),this.opts.unevaluated){const{props:e,items:t}=u;r.evaluated={props:e instanceof Rm.Name?void 0:e,items:t instanceof Rm.Name?void 0:t,dynamicProps:e instanceof Rm.Name,dynamicItems:t instanceof Rm.Name},r.source&&(r.source.evaluated=(0,Rm.stringify)(r.evaluated))}return e.validate=r,e}catch(t){throw delete e.validate,delete e.validateName,l&&this.logger.error("Error compiling schema, function code:",l),t}finally{this._compilations.delete(e)}}function Vm(e){return(0,Am.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:qm.call(this,e)}function Fm(e){for(const t of this._compilations)if(Lm(t,e))return t}function Lm(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function Hm(e,t){let r;for(;"string"==typeof(r=this.refs[t]);)t=r;return r||this.schemas[t]||Km.call(this,e,t)}function Km(e,t){const r=this.opts.uriResolver.parse(t),o=(0,Am._getFullPath)(this.opts.uriResolver,r);let n=(0,Am.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&o===n)return Gm.call(this,r,e);const s=(0,Am.normalizeId)(o),a=this.refs[s]||this.schemas[s];if("string"==typeof a){const t=Km.call(this,e,a);if("object"!=typeof(null==t?void 0:t.schema))return;return Gm.call(this,r,t)}if("object"==typeof(null==a?void 0:a.schema)){if(a.validate||qm.call(this,a),s===(0,Am.normalizeId)(t)){const{schema:t}=a,{schemaId:r}=this.opts,o=t[r];return o&&(n=(0,Am.resolveUrl)(this.opts.uriResolver,n,o)),new Um({schema:t,schemaId:r,root:e,baseId:n})}return Gm.call(this,r,a)}}jm.SchemaEnv=Um,jm.compileSchema=qm,jm.resolveRef=function(e,t,r){var o;r=(0,Am.resolveUrl)(this.opts.uriResolver,t,r);const n=e.refs[r];if(n)return n;let s=Hm.call(this,e,r);if(void 0===s){const n=null===(o=e.localRefs)||void 0===o?void 0:o[r],{schemaId:a}=this.opts;n&&(s=new Um({schema:n,schemaId:a,root:e,baseId:t}))}return void 0!==s?e.refs[r]=Vm.call(this,s):void 0},jm.getCompilingSchema=Fm,jm.resolveSchema=Km;const Zm=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Gm(e,{baseId:t,schema:r,root:o}){var n;if("/"!==(null===(n=e.fragment)||void 0===n?void 0:n[0]))return;for(const o of e.fragment.slice(1).split("/")){if("boolean"==typeof r)return;const e=r[(0,Mm.unescapeFragment)(o)];if(void 0===e)return;const n="object"==typeof(r=e)&&r[this.opts.schemaId];!Zm.has(o)&&n&&(t=(0,Am.resolveUrl)(this.opts.uriResolver,t,n))}let s;if("boolean"!=typeof r&&r.$ref&&!(0,Mm.schemaHasRulesButRef)(r,this.RULES)){const e=(0,Am.resolveUrl)(this.opts.uriResolver,t,r.$ref);s=Km.call(this,o,e)}const{schemaId:a}=this.opts;return s=s||new Um({schema:r,schemaId:a,root:o,baseId:t}),s.schema!==s.root.schema?s:void 0}var Bm={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1},Jm={};Object.defineProperty(Jm,"__esModule",{value:!0});const Wm=Pl;Wm.code='require("ajv/dist/runtime/uri").default',Jm.default=Wm,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=Sm();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var r=lf;Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return r.CodeGen}});const o=Im(),n=Cm(),s=Rf,a=jm,i=lf,c=am,u=jf,l=pf,d=Bm,h=Jm,p=(e,t)=>new RegExp(e,t);p.code="new RegExp";const f=["removeAdditional","useDefaults","coerceTypes"],m=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),y={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},g={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'};function v(e){var t,r,o,n,s,a,i,c,u,l,d,f,m,y,g,v,_,w,$,b,k,E,S,P,T;const I=e.strict,x=null===(t=e.code)||void 0===t?void 0:t.optimize,N=!0===x||void 0===x?1:x||0,C=null!==(o=null===(r=e.code)||void 0===r?void 0:r.regExp)&&void 0!==o?o:p,j=null!==(n=e.uriResolver)&&void 0!==n?n:h.default;return{strictSchema:null===(a=null!==(s=e.strictSchema)&&void 0!==s?s:I)||void 0===a||a,strictNumbers:null===(c=null!==(i=e.strictNumbers)&&void 0!==i?i:I)||void 0===c||c,strictTypes:null!==(l=null!==(u=e.strictTypes)&&void 0!==u?u:I)&&void 0!==l?l:"log",strictTuples:null!==(f=null!==(d=e.strictTuples)&&void 0!==d?d:I)&&void 0!==f?f:"log",strictRequired:null!==(y=null!==(m=e.strictRequired)&&void 0!==m?m:I)&&void 0!==y&&y,code:e.code?{...e.code,optimize:N,regExp:C}:{optimize:N,regExp:C},loopRequired:null!==(g=e.loopRequired)&&void 0!==g?g:200,loopEnum:null!==(v=e.loopEnum)&&void 0!==v?v:200,meta:null===(_=e.meta)||void 0===_||_,messages:null===(w=e.messages)||void 0===w||w,inlineRefs:null===($=e.inlineRefs)||void 0===$||$,schemaId:null!==(b=e.schemaId)&&void 0!==b?b:"$id",addUsedSchema:null===(k=e.addUsedSchema)||void 0===k||k,validateSchema:null===(E=e.validateSchema)||void 0===E||E,validateFormats:null===(S=e.validateFormats)||void 0===S||S,unicodeRegExp:null===(P=e.unicodeRegExp)||void 0===P||P,int32range:null===(T=e.int32range)||void 0===T||T,uriResolver:j}}class _{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...v(e)};const{es5:t,lines:r}=this.opts.code;this.scope=new i.ValueScope({scope:{},prefixes:m,es5:t,lines:r}),this.logger=function(e){if(!1===e)return P;if(void 0===e)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}(e.logger);const o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,s.getRules)(),w.call(this,y,e,"NOT SUPPORTED"),w.call(this,g,e,"DEPRECATED","warn"),this._metaOpts=S.call(this),e.formats&&k.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&E.call(this,e.keywords),"object"==typeof e.meta&&this.addMetaSchema(e.meta),b.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:e,meta:t,schemaId:r}=this.opts;let o=d;"id"===r&&(o={...d},o.id=o.$id,delete o.$id),t&&e&&this.addMetaSchema(o,o[r],!1)}defaultMeta(){const{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta="object"==typeof e?e[t]||e:void 0}validate(e,t){let r;if("string"==typeof e){if(r=this.getSchema(e),!r)throw new Error(`no schema with key or ref "${e}"`)}else r=this.compile(e);const o=r(t);return"$async"in r||(this.errors=r.errors),o}compile(e,t){const r=this._addSchema(e,t);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,t){if("function"!=typeof this.opts.loadSchema)throw new Error("options.loadSchema should be a function");const{loadSchema:r}=this.opts;return o.call(this,e,t);async function o(e,t){await s.call(this,e.$schema);const r=this._addSchema(e,t);return r.validate||a.call(this,r)}async function s(e){e&&!this.getSchema(e)&&await o.call(this,{$ref:e},!0)}async function a(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof n.default))throw t;return i.call(this,t),await c.call(this,t.missingSchema),a.call(this,e)}}function i({missingSchema:e,missingRef:t}){if(this.refs[e])throw new Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function c(e){const r=await u.call(this,e);this.refs[e]||await s.call(this,r.$schema),this.refs[e]||this.addSchema(r,e,t)}async function u(e){const t=this._loading[e];if(t)return t;try{return await(this._loading[e]=r(e))}finally{delete this._loading[e]}}}addSchema(e,t,r,o=this.opts.validateSchema){if(Array.isArray(e)){for(const t of e)this.addSchema(t,void 0,r,o);return this}let n;if("object"==typeof e){const{schemaId:t}=this.opts;if(n=e[t],void 0!==n&&"string"!=typeof n)throw new Error(`schema ${t} must be string`)}return t=(0,c.normalizeId)(t||n),this._checkUnique(t),this.schemas[t]=this._addSchema(e,r,t,o,!0),this}addMetaSchema(e,t,r=this.opts.validateSchema){return this.addSchema(e,t,!0,r),this}validateSchema(e,t){if("boolean"==typeof e)return!0;let r;if(r=e.$schema,void 0!==r&&"string"!=typeof r)throw new Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const o=this.validate(r,e);if(!o&&t){const e="schema is invalid: "+this.errorsText();if("log"!==this.opts.validateSchema)throw new Error(e);this.logger.error(e)}return o}getSchema(e){let t;for(;"string"==typeof(t=$.call(this,e));)e=t;if(void 0===t){const{schemaId:r}=this.opts,o=new a.SchemaEnv({schema:{},schemaId:r});if(t=a.resolveSchema.call(this,o,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const t=$.call(this,e);return"object"==typeof t&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{const t=e;this._cache.delete(t);let r=e[this.opts.schemaId];return r&&(r=(0,c.normalizeId)(r),delete this.schemas[r],delete this.refs[r]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(const t of e)this.addKeyword(t);return this}addKeyword(e,t){let r;if("string"==typeof e)r=e,"object"==typeof t&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=r);else{if("object"!=typeof e||void 0!==t)throw new Error("invalid addKeywords parameters");if(r=(t=e).keyword,Array.isArray(r)&&!r.length)throw new Error("addKeywords: keyword must be string or non-empty array")}if(I.call(this,r,t),!t)return(0,l.eachItem)(r,e=>x.call(this,e)),this;C.call(this,t);const o={...t,type:(0,u.getJSONTypes)(t.type),schemaType:(0,u.getJSONTypes)(t.schemaType)};return(0,l.eachItem)(r,0===o.type.length?e=>x.call(this,e,o):e=>o.type.forEach(t=>x.call(this,e,o,t))),this}getKeyword(e){const t=this.RULES.all[e];return"object"==typeof t?t.definition:!!t}removeKeyword(e){const{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(const r of t.rules){const t=r.rules.findIndex(t=>t.keyword===e);t>=0&&r.rules.splice(t,1)}return this}addFormat(e,t){return"string"==typeof t&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=", ",dataVar:r="data"}={}){return e&&0!==e.length?e.map(e=>`${r}${e.instancePath} ${e.message}`).reduce((e,r)=>e+t+r):"No errors"}$dataMetaSchema(e,t){const r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(const o of t){const t=o.split("/").slice(1);let n=e;for(const e of t)n=n[e];for(const e in r){const t=r[e];if("object"!=typeof t)continue;const{$data:o}=t.definition,s=n[e];o&&s&&(n[e]=R(s))}}return e}_removeAllSchemas(e,t){for(const r in e){const o=e[r];t&&!t.test(r)||("string"==typeof o?delete e[r]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[r]))}}_addSchema(e,t,r,o=this.opts.validateSchema,n=this.opts.addUsedSchema){let s;const{schemaId:i}=this.opts;if("object"==typeof e)s=e[i];else{if(this.opts.jtd)throw new Error("schema must be object");if("boolean"!=typeof e)throw new Error("schema must be object or boolean")}let u=this._cache.get(e);if(void 0!==u)return u;r=(0,c.normalizeId)(s||r);const l=c.getSchemaRefs.call(this,e,r);return u=new a.SchemaEnv({schema:e,schemaId:i,meta:t,baseId:r,localRefs:l}),this._cache.set(u.schema,u),n&&!r.startsWith("#")&&(r&&this._checkUnique(r),this.refs[r]=u),o&&this.validateSchema(e,!0),u}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):a.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){const t=this.opts;this.opts=this._metaOpts;try{a.compileSchema.call(this,e)}finally{this.opts=t}}}function w(e,t,r,o="error"){for(const n in e){const s=n;s in t&&this.logger[o](`${r}: option ${n}. ${e[s]}`)}}function $(e){return e=(0,c.normalizeId)(e),this.schemas[e]||this.refs[e]}function b(){const e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(const t in e)this.addSchema(e[t],t)}function k(){for(const e in this.opts.formats){const t=this.opts.formats[e];t&&this.addFormat(e,t)}}function E(e){if(Array.isArray(e))this.addVocabulary(e);else{this.logger.warn("keywords option as map is deprecated, pass array");for(const t in e){const r=e[t];r.keyword||(r.keyword=t),this.addKeyword(r)}}}function S(){const e={...this.opts};for(const t of f)delete e[t];return e}_.ValidationError=o.default,_.MissingRefError=n.default,e.default=_;const P={log(){},warn(){},error(){}};const T=/^[a-z_$][a-z0-9_$:-]*$/i;function I(e,t){const{RULES:r}=this;if((0,l.eachItem)(e,e=>{if(r.keywords[e])throw new Error(`Keyword ${e} is already defined`);if(!T.test(e))throw new Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!("code"in t)&&!("validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}function x(e,t,r){var o;const n=null==t?void 0:t.post;if(r&&n)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:s}=this;let a=n?s.post:s.rules.find(({type:e})=>e===r);if(a||(a={type:r,rules:[]},s.rules.push(a)),s.keywords[e]=!0,!t)return;const i={keyword:e,definition:{...t,type:(0,u.getJSONTypes)(t.type),schemaType:(0,u.getJSONTypes)(t.schemaType)}};t.before?N.call(this,a,i,t.before):a.rules.push(i),s.all[e]=i,null===(o=t.implements)||void 0===o||o.forEach(e=>this.addKeyword(e))}function N(e,t,r){const o=e.rules.findIndex(e=>e.keyword===r);o>=0?e.rules.splice(o,0,t):(e.rules.push(t),this.logger.warn(`rule ${r} is not defined`))}function C(e){let{metaSchema:t}=e;void 0!==t&&(e.$data&&this.opts.$data&&(t=R(t)),e.validateSchema=this.compile(t,!0))}const j={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function R(e){return{anyOf:[e,j]}}}(sf);var Qm={},Ym={},Xm={};Object.defineProperty(Xm,"__esModule",{value:!0});const ey={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Xm.default=ey;var ty={};Object.defineProperty(ty,"__esModule",{value:!0}),ty.callRef=ty.getValidate=void 0;const ry=Cm(),oy=rm(),ny=lf,sy=Nf(),ay=jm,iy=pf,cy={keyword:"$ref",schemaType:"string",code(e){const{gen:t,schema:r,it:o}=e,{baseId:n,schemaEnv:s,validateName:a,opts:i,self:c}=o,{root:u}=s;if(("#"===r||"#/"===r)&&n===u.baseId)return function(){if(s===u)return ly(e,a,s,s.$async);const r=t.scopeValue("root",{ref:u});return ly(e,ny._`${r}.validate`,u,u.$async)}();const l=ay.resolveRef.call(c,u,n,r);if(void 0===l)throw new ry.default(o.opts.uriResolver,n,r);return l instanceof ay.SchemaEnv?function(t){const r=uy(e,t);ly(e,r,t,t.$async)}(l):function(o){const n=t.scopeValue("schema",!0===i.code.source?{ref:o,code:(0,ny.stringify)(o)}:{ref:o}),s=t.name("valid"),a=e.subschema({schema:o,dataTypes:[],schemaPath:ny.nil,topSchemaRef:n,errSchemaPath:r},s);e.mergeEvaluated(a),e.ok(s)}(l)}};function uy(e,t){const{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):ny._`${r.scopeValue("wrapper",{ref:t})}.validate`}function ly(e,t,r,o){const{gen:n,it:s}=e,{allErrors:a,schemaEnv:i,opts:c}=s,u=c.passContext?sy.default.this:ny.nil;function l(e){const t=ny._`${e}.errors`;n.assign(sy.default.vErrors,ny._`${sy.default.vErrors} === null ? ${t} : ${sy.default.vErrors}.concat(${t})`),n.assign(sy.default.errors,ny._`${sy.default.vErrors}.length`)}function d(e){var t;if(!s.opts.unevaluated)return;const o=null===(t=null==r?void 0:r.validate)||void 0===t?void 0:t.evaluated;if(!0!==s.props)if(o&&!o.dynamicProps)void 0!==o.props&&(s.props=iy.mergeEvaluated.props(n,o.props,s.props));else{const t=n.var("props",ny._`${e}.evaluated.props`);s.props=iy.mergeEvaluated.props(n,t,s.props,ny.Name)}if(!0!==s.items)if(o&&!o.dynamicItems)void 0!==o.items&&(s.items=iy.mergeEvaluated.items(n,o.items,s.items));else{const t=n.var("items",ny._`${e}.evaluated.items`);s.items=iy.mergeEvaluated.items(n,t,s.items,ny.Name)}}o?function(){if(!i.$async)throw new Error("async schema referenced by sync schema");const r=n.let("valid");n.try(()=>{n.code(ny._`await ${(0,oy.callValidateCode)(e,t,u)}`),d(t),a||n.assign(r,!0)},e=>{n.if(ny._`!(${e} instanceof ${s.ValidationError})`,()=>n.throw(e)),l(e),a||n.assign(r,!1)}),e.ok(r)}():e.result((0,oy.callValidateCode)(e,t,u),()=>d(t),()=>l(t))}ty.getValidate=uy,ty.callRef=ly,ty.default=cy,Object.defineProperty(Ym,"__esModule",{value:!0});const dy=ty,hy=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Xm.default,dy.default];Ym.default=hy;var py={},fy={};Object.defineProperty(fy,"__esModule",{value:!0});const my=lf,yy=my.operators,gy={maximum:{okStr:"<=",ok:yy.LTE,fail:yy.GT},minimum:{okStr:">=",ok:yy.GTE,fail:yy.LT},exclusiveMaximum:{okStr:"<",ok:yy.LT,fail:yy.GTE},exclusiveMinimum:{okStr:">",ok:yy.GT,fail:yy.LTE}},vy={message:({keyword:e,schemaCode:t})=>my.str`must be ${gy[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>my._`{comparison: ${gy[e].okStr}, limit: ${t}}`},_y={keyword:Object.keys(gy),type:"number",schemaType:"number",$data:!0,error:vy,code(e){const{keyword:t,data:r,schemaCode:o}=e;e.fail$data(my._`${r} ${gy[t].fail} ${o} || isNaN(${r})`)}};fy.default=_y;var wy={};Object.defineProperty(wy,"__esModule",{value:!0});const $y=lf,by={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:e})=>$y.str`must be multiple of ${e}`,params:({schemaCode:e})=>$y._`{multipleOf: ${e}}`},code(e){const{gen:t,data:r,schemaCode:o,it:n}=e,s=n.opts.multipleOfPrecision,a=t.let("res"),i=s?$y._`Math.abs(Math.round(${a}) - ${a}) > 1e-${s}`:$y._`${a} !== parseInt(${a})`;e.fail$data($y._`(${o} === 0 || (${a} = ${r}/${o}, ${i}))`)}};wy.default=by;var ky={},Ey={};function Sy(e){const t=e.length;let r,o=0,n=0;for(;n<t;)o++,r=e.charCodeAt(n++),r>=55296&&r<=56319&&n<t&&(r=e.charCodeAt(n),56320==(64512&r)&&n++);return o}Object.defineProperty(Ey,"__esModule",{value:!0}),Ey.default=Sy,Sy.code='require("ajv/dist/runtime/ucs2length").default',Object.defineProperty(ky,"__esModule",{value:!0});const Py=lf,Ty=pf,Iy=Ey,xy={message:({keyword:e,schemaCode:t})=>Py.str`must NOT have ${"maxLength"===e?"more":"fewer"} than ${t} characters`,params:({schemaCode:e})=>Py._`{limit: ${e}}`},Ny={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:xy,code(e){const{keyword:t,data:r,schemaCode:o,it:n}=e,s="maxLength"===t?Py.operators.GT:Py.operators.LT,a=!1===n.opts.unicode?Py._`${r}.length`:Py._`${(0,Ty.useFunc)(e.gen,Iy.default)}(${r})`;e.fail$data(Py._`${a} ${s} ${o}`)}};ky.default=Ny;var Cy={};Object.defineProperty(Cy,"__esModule",{value:!0});const jy=rm(),Ry=lf,Oy={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>Ry.str`must match pattern "${e}"`,params:({schemaCode:e})=>Ry._`{pattern: ${e}}`},code(e){const{data:t,$data:r,schema:o,schemaCode:n,it:s}=e,a=s.opts.unicodeRegExp?"u":"",i=r?Ry._`(new RegExp(${n}, ${a}))`:(0,jy.usePattern)(e,o);e.fail$data(Ry._`!${i}.test(${t})`)}};Cy.default=Oy;var zy={};Object.defineProperty(zy,"__esModule",{value:!0});const Ay=lf,My={message:({keyword:e,schemaCode:t})=>Ay.str`must NOT have ${"maxProperties"===e?"more":"fewer"} than ${t} properties`,params:({schemaCode:e})=>Ay._`{limit: ${e}}`},Dy={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:My,code(e){const{keyword:t,data:r,schemaCode:o}=e,n="maxProperties"===t?Ay.operators.GT:Ay.operators.LT;e.fail$data(Ay._`Object.keys(${r}).length ${n} ${o}`)}};zy.default=Dy;var Uy={};Object.defineProperty(Uy,"__esModule",{value:!0});const qy=rm(),Vy=lf,Fy=pf,Ly={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:e}})=>Vy.str`must have required property '${e}'`,params:({params:{missingProperty:e}})=>Vy._`{missingProperty: ${e}}`},code(e){const{gen:t,schema:r,schemaCode:o,data:n,$data:s,it:a}=e,{opts:i}=a;if(!s&&0===r.length)return;const c=r.length>=i.loopRequired;if(a.allErrors?function(){if(c||s)e.block$data(Vy.nil,u);else for(const t of r)(0,qy.checkReportMissingProp)(e,t)}():function(){const a=t.let("missing");if(c||s){const r=t.let("valid",!0);e.block$data(r,()=>function(r,s){e.setParams({missingProperty:r}),t.forOf(r,o,()=>{t.assign(s,(0,qy.propertyInData)(t,n,r,i.ownProperties)),t.if((0,Vy.not)(s),()=>{e.error(),t.break()})},Vy.nil)}(a,r)),e.ok(r)}else t.if((0,qy.checkMissingProp)(e,r,a)),(0,qy.reportMissingProp)(e,a),t.else()}(),i.strictRequired){const t=e.parentSchema.properties,{definedProperties:o}=e.it;for(const e of r)if(void 0===(null==t?void 0:t[e])&&!o.has(e)){const t=`required property "${e}" is not defined at "${a.schemaEnv.baseId+a.errSchemaPath}" (strictRequired)`;(0,Fy.checkStrictMode)(a,t,a.opts.strictRequired)}}function u(){t.forOf("prop",o,r=>{e.setParams({missingProperty:r}),t.if((0,qy.noPropertyInData)(t,n,r,i.ownProperties),()=>e.error())})}}};Uy.default=Ly;var Hy={};Object.defineProperty(Hy,"__esModule",{value:!0});const Ky=lf,Zy={message:({keyword:e,schemaCode:t})=>Ky.str`must NOT have ${"maxItems"===e?"more":"fewer"} than ${t} items`,params:({schemaCode:e})=>Ky._`{limit: ${e}}`},Gy={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Zy,code(e){const{keyword:t,data:r,schemaCode:o}=e,n="maxItems"===t?Ky.operators.GT:Ky.operators.LT;e.fail$data(Ky._`${r}.length ${n} ${o}`)}};Hy.default=Gy;var By={},Jy={};Object.defineProperty(Jy,"__esModule",{value:!0});const Wy=nu;Wy.code='require("ajv/dist/runtime/equal").default',Jy.default=Wy,Object.defineProperty(By,"__esModule",{value:!0});const Qy=jf,Yy=lf,Xy=pf,eg=Jy,tg={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:e,j:t}})=>Yy.str`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>Yy._`{i: ${e}, j: ${t}}`},code(e){const{gen:t,data:r,$data:o,schema:n,parentSchema:s,schemaCode:a,it:i}=e;if(!o&&!n)return;const c=t.let("valid"),u=s.items?(0,Qy.getSchemaTypes)(s.items):[];function l(o,n){const s=t.name("item"),a=(0,Qy.checkDataTypes)(u,s,i.opts.strictNumbers,Qy.DataType.Wrong),l=t.const("indices",Yy._`{}`);t.for(Yy._`;${o}--;`,()=>{t.let(s,Yy._`${r}[${o}]`),t.if(a,Yy._`continue`),u.length>1&&t.if(Yy._`typeof ${s} == "string"`,Yy._`${s} += "_"`),t.if(Yy._`typeof ${l}[${s}] == "number"`,()=>{t.assign(n,Yy._`${l}[${s}]`),e.error(),t.assign(c,!1).break()}).code(Yy._`${l}[${s}] = ${o}`)})}function d(o,n){const s=(0,Xy.useFunc)(t,eg.default),a=t.name("outer");t.label(a).for(Yy._`;${o}--;`,()=>t.for(Yy._`${n} = ${o}; ${n}--;`,()=>t.if(Yy._`${s}(${r}[${o}], ${r}[${n}])`,()=>{e.error(),t.assign(c,!1).break(a)})))}e.block$data(c,function(){const o=t.let("i",Yy._`${r}.length`),n=t.let("j");e.setParams({i:o,j:n}),t.assign(c,!0),t.if(Yy._`${o} > 1`,()=>(u.length>0&&!u.some(e=>"object"===e||"array"===e)?l:d)(o,n))},Yy._`${a} === false`),e.ok(c)}};By.default=tg;var rg={};Object.defineProperty(rg,"__esModule",{value:!0});const og=lf,ng=pf,sg=Jy,ag={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:e})=>og._`{allowedValue: ${e}}`},code(e){const{gen:t,data:r,$data:o,schemaCode:n,schema:s}=e;o||s&&"object"==typeof s?e.fail$data(og._`!${(0,ng.useFunc)(t,sg.default)}(${r}, ${n})`):e.fail(og._`${s} !== ${r}`)}};rg.default=ag;var ig={};Object.defineProperty(ig,"__esModule",{value:!0});const cg=lf,ug=pf,lg=Jy,dg={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:e})=>cg._`{allowedValues: ${e}}`},code(e){const{gen:t,data:r,$data:o,schema:n,schemaCode:s,it:a}=e;if(!o&&0===n.length)throw new Error("enum must have non-empty array");const i=n.length>=a.opts.loopEnum;let c;const u=()=>null!=c?c:c=(0,ug.useFunc)(t,lg.default);let l;if(i||o)l=t.let("valid"),e.block$data(l,function(){t.assign(l,!1),t.forOf("v",s,e=>t.if(cg._`${u()}(${r}, ${e})`,()=>t.assign(l,!0).break()))});else{if(!Array.isArray(n))throw new Error("ajv implementation error");const e=t.const("vSchema",s);l=(0,cg.or)(...n.map((t,o)=>function(e,t){const o=n[t];return"object"==typeof o&&null!==o?cg._`${u()}(${r}, ${e}[${t}])`:cg._`${r} === ${o}`}(e,o)))}e.pass(l)}};ig.default=dg,Object.defineProperty(py,"__esModule",{value:!0});const hg=wy,pg=ky,fg=Cy,mg=zy,yg=Uy,gg=Hy,vg=By,_g=rg,wg=ig,$g=[fy.default,hg.default,pg.default,fg.default,mg.default,yg.default,gg.default,vg.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},_g.default,wg.default];py.default=$g;var bg={},kg={};Object.defineProperty(kg,"__esModule",{value:!0}),kg.validateAdditionalItems=void 0;const Eg=lf,Sg=pf,Pg={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:e}})=>Eg.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>Eg._`{limit: ${e}}`},code(e){const{parentSchema:t,it:r}=e,{items:o}=t;Array.isArray(o)?Tg(e,o):(0,Sg.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas')}};function Tg(e,t){const{gen:r,schema:o,data:n,keyword:s,it:a}=e;a.items=!0;const i=r.const("len",Eg._`${n}.length`);if(!1===o)e.setParams({len:t.length}),e.pass(Eg._`${i} <= ${t.length}`);else if("object"==typeof o&&!(0,Sg.alwaysValidSchema)(a,o)){const o=r.var("valid",Eg._`${i} <= ${t.length}`);r.if((0,Eg.not)(o),()=>function(o){r.forRange("i",t.length,i,t=>{e.subschema({keyword:s,dataProp:t,dataPropType:Sg.Type.Num},o),a.allErrors||r.if((0,Eg.not)(o),()=>r.break())})}(o)),e.ok(o)}}kg.validateAdditionalItems=Tg,kg.default=Pg;var Ig={},xg={};Object.defineProperty(xg,"__esModule",{value:!0}),xg.validateTuple=void 0;const Ng=lf,Cg=pf,jg=rm(),Rg={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){const{schema:t,it:r}=e;if(Array.isArray(t))return Og(e,"additionalItems",t);r.items=!0,(0,Cg.alwaysValidSchema)(r,t)||e.ok((0,jg.validateArray)(e))}};function Og(e,t,r=e.schema){const{gen:o,parentSchema:n,data:s,keyword:a,it:i}=e;!function(e){const{opts:o,errSchemaPath:n}=i,s=r.length,c=s===e.minItems&&(s===e.maxItems||!1===e[t]);if(o.strictTuples&&!c){const e=`"${a}" is ${s}-tuple, but minItems or maxItems/${t} are not specified or different at path "${n}"`;(0,Cg.checkStrictMode)(i,e,o.strictTuples)}}(n),i.opts.unevaluated&&r.length&&!0!==i.items&&(i.items=Cg.mergeEvaluated.items(o,r.length,i.items));const c=o.name("valid"),u=o.const("len",Ng._`${s}.length`);r.forEach((t,r)=>{(0,Cg.alwaysValidSchema)(i,t)||(o.if(Ng._`${u} > ${r}`,()=>e.subschema({keyword:a,schemaProp:r,dataProp:r},c)),e.ok(c))})}xg.validateTuple=Og,xg.default=Rg,Object.defineProperty(Ig,"__esModule",{value:!0});const zg=xg,Ag={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,zg.validateTuple)(e,"items")};Ig.default=Ag;var Mg={};Object.defineProperty(Mg,"__esModule",{value:!0});const Dg=lf,Ug=pf,qg=rm(),Vg=kg,Fg={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:e}})=>Dg.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>Dg._`{limit: ${e}}`},code(e){const{schema:t,parentSchema:r,it:o}=e,{prefixItems:n}=r;o.items=!0,(0,Ug.alwaysValidSchema)(o,t)||(n?(0,Vg.validateAdditionalItems)(e,n):e.ok((0,qg.validateArray)(e)))}};Mg.default=Fg;var Lg={};Object.defineProperty(Lg,"__esModule",{value:!0});const Hg=lf,Kg=pf,Zg={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:e,max:t}})=>void 0===t?Hg.str`must contain at least ${e} valid item(s)`:Hg.str`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>void 0===t?Hg._`{minContains: ${e}}`:Hg._`{minContains: ${e}, maxContains: ${t}}`},code(e){const{gen:t,schema:r,parentSchema:o,data:n,it:s}=e;let a,i;const{minContains:c,maxContains:u}=o;s.opts.next?(a=void 0===c?1:c,i=u):a=1;const l=t.const("len",Hg._`${n}.length`);if(e.setParams({min:a,max:i}),void 0===i&&0===a)return void(0,Kg.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');if(void 0!==i&&a>i)return(0,Kg.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),void e.fail();if((0,Kg.alwaysValidSchema)(s,r)){let t=Hg._`${l} >= ${a}`;return void 0!==i&&(t=Hg._`${t} && ${l} <= ${i}`),void e.pass(t)}s.items=!0;const d=t.name("valid");function h(){const e=t.name("_valid"),r=t.let("count",0);p(e,()=>t.if(e,()=>function(e){t.code(Hg._`${e}++`),void 0===i?t.if(Hg._`${e} >= ${a}`,()=>t.assign(d,!0).break()):(t.if(Hg._`${e} > ${i}`,()=>t.assign(d,!1).break()),1===a?t.assign(d,!0):t.if(Hg._`${e} >= ${a}`,()=>t.assign(d,!0)))}(r)))}function p(r,o){t.forRange("i",0,l,t=>{e.subschema({keyword:"contains",dataProp:t,dataPropType:Kg.Type.Num,compositeRule:!0},r),o()})}void 0===i&&1===a?p(d,()=>t.if(d,()=>t.break())):0===a?(t.let(d,!0),void 0!==i&&t.if(Hg._`${n}.length > 0`,h)):(t.let(d,!1),h()),e.result(d,()=>e.reset())}};Lg.default=Zg;var Gg={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=lf,r=pf,o=rm();e.error={message:({params:{property:e,depsCount:r,deps:o}})=>t.str`must have ${1===r?"property":"properties"} ${o} when property ${e} is present`,params:({params:{property:e,depsCount:r,deps:o,missingProperty:n}})=>t._`{property: ${e},
11
- missingProperty: ${n},
7
+ deps: ${n}}`};const o={keyword:"dependencies",type:"object",schemaType:"object",error:e.error,code(e){const[t,r]=function({schema:e}){const t={},r={};for(const n in e){if("__proto__"===n)continue;(Array.isArray(e[n])?t:r)[n]=e[n]}return[t,r]}(e);s(e,t),a(e,r)}};function s(e,r=e.schema){const{gen:o,data:s,it:a}=e;if(0===Object.keys(r).length)return;const i=o.let("missing");for(const c in r){const u=r[c];if(0===u.length)continue;const l=(0,n.propertyInData)(o,s,c,a.opts.ownProperties);e.setParams({property:c,depsCount:u.length,deps:u.join(", ")}),a.allErrors?o.if(l,()=>{for(const t of u)(0,n.checkReportMissingProp)(e,t)}):(o.if(t._`${l} && (${(0,n.checkMissingProp)(e,u,i)})`),(0,n.reportMissingProp)(e,i),o.else())}}function a(e,t=e.schema){const{gen:o,data:s,keyword:a,it:i}=e,c=o.name("valid");for(const u in t)(0,r.alwaysValidSchema)(i,t[u])||(o.if((0,n.propertyInData)(o,s,u,i.opts.ownProperties),()=>{const t=e.subschema({keyword:a,schemaProp:u},c);e.mergeValidEvaluated(t,c)},()=>o.var(c,!0)),e.ok(c))}e.validatePropertyDeps=s,e.validateSchemaDeps=a,e.default=o}(Th);var Ih={};Object.defineProperty(Ih,"__esModule",{value:!0});const xh=dc(),Nh=hc,Ch={message:"property name must be valid",params:({params:e})=>xh._`{propertyName: ${e.propertyName}}`},jh={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Ch,code(e){const{gen:t,schema:r,data:n,it:o}=e;if((0,Nh.alwaysValidSchema)(o,r))return;const s=t.name("valid");t.forIn("key",n,r=>{e.setParams({propertyName:r}),e.subschema({keyword:"propertyNames",data:r,dataTypes:["string"],propertyName:r,compositeRule:!0},s),t.if((0,xh.not)(s),()=>{e.error(!0),o.allErrors||t.break()})}),e.ok(s)}};Ih.default=jh;var Rh={};Object.defineProperty(Rh,"__esModule",{value:!0});const Oh=tu(),zh=dc(),Ah=xc(),Mh=hc,Dh={message:"must NOT have additional properties",params:({params:e})=>zh._`{additionalProperty: ${e.additionalProperty}}`},Uh={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Dh,code(e){const{gen:t,schema:r,parentSchema:n,data:o,errsCount:s,it:a}=e;if(!s)throw new Error("ajv implementation error");const{allErrors:i,opts:c}=a;if(a.props=!0,"all"!==c.removeAdditional&&(0,Mh.alwaysValidSchema)(a,r))return;const u=(0,Oh.allSchemaProperties)(n.properties),l=(0,Oh.allSchemaProperties)(n.patternProperties);function d(e){t.code(zh._`delete ${o}[${e}]`)}function h(n){if("all"===c.removeAdditional||c.removeAdditional&&!1===r)d(n);else{if(!1===r)return e.setParams({additionalProperty:n}),e.error(),void(i||t.break());if("object"==typeof r&&!(0,Mh.alwaysValidSchema)(a,r)){const r=t.name("valid");"failing"===c.removeAdditional?(p(n,r,!1),t.if((0,zh.not)(r),()=>{e.reset(),d(n)})):(p(n,r),i||t.if((0,zh.not)(r),()=>t.break()))}}}function p(t,r,n){const o={keyword:"additionalProperties",dataProp:t,dataPropType:Mh.Type.Str};!1===n&&Object.assign(o,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(o,r)}t.forIn("key",o,r=>{u.length||l.length?t.if(function(r){let o;if(u.length>8){const e=(0,Mh.schemaRefOrVal)(a,n.properties,"properties");o=(0,Oh.isOwnProperty)(t,e,r)}else o=u.length?(0,zh.or)(...u.map(e=>zh._`${r} === ${e}`)):zh.nil;return l.length&&(o=(0,zh.or)(o,...l.map(t=>zh._`${(0,Oh.usePattern)(e,t)}.test(${r})`))),(0,zh.not)(o)}(r),()=>h(r)):h(r)}),e.ok(zh._`${s} === ${Ah.default.errors}`)}};Rh.default=Uh;var qh={};Object.defineProperty(qh,"__esModule",{value:!0});const Vh=Pu(),Fh=tu(),Lh=hc,Kh=Rh,Hh={keyword:"properties",type:"object",schemaType:"object",code(e){const{gen:t,schema:r,parentSchema:n,data:o,it:s}=e;"all"===s.opts.removeAdditional&&void 0===n.additionalProperties&&Kh.default.code(new Vh.KeywordCxt(s,Kh.default,"additionalProperties"));const a=(0,Fh.allSchemaProperties)(r);for(const e of a)s.definedProperties.add(e);s.opts.unevaluated&&a.length&&!0!==s.props&&(s.props=Lh.mergeEvaluated.props(t,(0,Lh.toHash)(a),s.props));const i=a.filter(e=>!(0,Lh.alwaysValidSchema)(s,r[e]));if(0===i.length)return;const c=t.name("valid");for(const r of i)u(r)?l(r):(t.if((0,Fh.propertyInData)(t,o,r,s.opts.ownProperties)),l(r),s.allErrors||t.else().var(c,!0),t.endIf()),e.it.definedProperties.add(r),e.ok(c);function u(e){return s.opts.useDefaults&&!s.compositeRule&&void 0!==r[e].default}function l(t){e.subschema({keyword:"properties",schemaProp:t,dataProp:t},c)}}};qh.default=Hh;var Zh={};Object.defineProperty(Zh,"__esModule",{value:!0});const Gh=tu(),Bh=dc(),Jh=hc,Wh=hc,Qh={keyword:"patternProperties",type:"object",schemaType:"object",code(e){const{gen:t,schema:r,data:n,parentSchema:o,it:s}=e,{opts:a}=s,i=(0,Gh.allSchemaProperties)(r),c=i.filter(e=>(0,Jh.alwaysValidSchema)(s,r[e]));if(0===i.length||c.length===i.length&&(!s.opts.unevaluated||!0===s.props))return;const u=a.strictSchema&&!a.allowMatchingProperties&&o.properties,l=t.name("valid");!0===s.props||s.props instanceof Bh.Name||(s.props=(0,Wh.evaluatedPropsToName)(t,s.props));const{props:d}=s;function h(e){for(const t in u)new RegExp(e).test(t)&&(0,Jh.checkStrictMode)(s,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function p(r){t.forIn("key",n,n=>{t.if(Bh._`${(0,Gh.usePattern)(e,r)}.test(${n})`,()=>{const o=c.includes(r);o||e.subschema({keyword:"patternProperties",schemaProp:r,dataProp:n,dataPropType:Wh.Type.Str},l),s.opts.unevaluated&&!0!==d?t.assign(Bh._`${d}[${n}]`,!0):o||s.allErrors||t.if((0,Bh.not)(l),()=>t.break())})})}!function(){for(const e of i)u&&h(e),s.allErrors?p(e):(t.var(l,!0),p(e),t.if(l))}()}};Zh.default=Qh;var Yh={};Object.defineProperty(Yh,"__esModule",{value:!0});const Xh=hc,ep={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){const{gen:t,schema:r,it:n}=e;if((0,Xh.alwaysValidSchema)(n,r))return void e.fail();const o=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),e.failResult(o,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};Yh.default=ep;var tp={};Object.defineProperty(tp,"__esModule",{value:!0});const rp={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:tu().validateUnion,error:{message:"must match a schema in anyOf"}};tp.default=rp;var np={};Object.defineProperty(np,"__esModule",{value:!0});const op=dc(),sp=hc,ap={message:"must match exactly one schema in oneOf",params:({params:e})=>op._`{passingSchemas: ${e.passing}}`},ip={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:ap,code(e){const{gen:t,schema:r,parentSchema:n,it:o}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;const s=r,a=t.let("valid",!1),i=t.let("passing",null),c=t.name("_valid");e.setParams({passing:i}),t.block(function(){s.forEach((r,n)=>{let s;(0,sp.alwaysValidSchema)(o,r)?t.var(c,!0):s=e.subschema({keyword:"oneOf",schemaProp:n,compositeRule:!0},c),n>0&&t.if(op._`${c} && ${a}`).assign(a,!1).assign(i,op._`[${i}, ${n}]`).else(),t.if(c,()=>{t.assign(a,!0),t.assign(i,n),s&&e.mergeEvaluated(s,op.Name)})})}),e.result(a,()=>e.reset(),()=>e.error(!0))}};np.default=ip;var cp={};Object.defineProperty(cp,"__esModule",{value:!0});const up=hc,lp={keyword:"allOf",schemaType:"array",code(e){const{gen:t,schema:r,it:n}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");const o=t.name("valid");r.forEach((t,r)=>{if((0,up.alwaysValidSchema)(n,t))return;const s=e.subschema({keyword:"allOf",schemaProp:r},o);e.ok(o),e.mergeEvaluated(s)})}};cp.default=lp;var dp={};Object.defineProperty(dp,"__esModule",{value:!0});const hp=dc(),pp=hc,fp={message:({params:e})=>hp.str`must match "${e.ifClause}" schema`,params:({params:e})=>hp._`{failingKeyword: ${e.ifClause}}`},mp={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:fp,code(e){const{gen:t,parentSchema:r,it:n}=e;void 0===r.then&&void 0===r.else&&(0,pp.checkStrictMode)(n,'"if" without "then" and "else" is ignored');const o=yp(n,"then"),s=yp(n,"else");if(!o&&!s)return;const a=t.let("valid",!0),i=t.name("_valid");if(function(){const t=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},i);e.mergeEvaluated(t)}(),e.reset(),o&&s){const r=t.let("ifClause");e.setParams({ifClause:r}),t.if(i,c("then",r),c("else",r))}else o?t.if(i,c("then")):t.if((0,hp.not)(i),c("else"));function c(r,n){return()=>{const o=e.subschema({keyword:r},i);t.assign(a,i),e.mergeValidEvaluated(o,a),n?t.assign(n,hp._`${r}`):e.setParams({ifClause:r})}}e.pass(a,()=>e.error(!0))}};function yp(e,t){const r=e.schema[t];return void 0!==r&&!(0,pp.alwaysValidSchema)(e,r)}dp.default=mp;var gp={};Object.defineProperty(gp,"__esModule",{value:!0});const vp=hc,_p={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){void 0===t.if&&(0,vp.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};gp.default=_p,Object.defineProperty(rh,"__esModule",{value:!0});const wp=nh,$p=ch,bp=uh,kp=gh,Ep=kh,Pp=Th,Sp=Ih,Tp=Rh,Ip=qh,xp=Zh,Np=Yh,Cp=tp,jp=np,Rp=cp,Op=dp,zp=gp;rh.default=function(e=!1){const t=[Np.default,Cp.default,jp.default,Rp.default,Op.default,zp.default,Sp.default,Tp.default,Pp.default,Ip.default,xp.default];return e?t.push($p.default,kp.default):t.push(wp.default,bp.default),t.push(Ep.default),t};var Ap={},Mp={};Object.defineProperty(Mp,"__esModule",{value:!0});const Dp=dc(),Up={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>Dp.str`must match format "${e}"`,params:({schemaCode:e})=>Dp._`{format: ${e}}`},code(e,t){const{gen:r,data:n,$data:o,schema:s,schemaCode:a,it:i}=e,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=i;c.validateFormats&&(o?function(){const o=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),s=r.const("fDef",Dp._`${o}[${a}]`),i=r.let("fType"),u=r.let("format");r.if(Dp._`typeof ${s} == "object" && !(${s} instanceof RegExp)`,()=>r.assign(i,Dp._`${s}.type || "string"`).assign(u,Dp._`${s}.validate`),()=>r.assign(i,Dp._`"string"`).assign(u,s)),e.fail$data((0,Dp.or)(!1===c.strictSchema?Dp.nil:Dp._`${a} && !${u}`,function(){const e=l.$async?Dp._`(${s}.async ? await ${u}(${n}) : ${u}(${n}))`:Dp._`${u}(${n})`,r=Dp._`(typeof ${u} == "function" ? ${e} : ${u}.test(${n}))`;return Dp._`${u} && ${u} !== true && ${i} === ${t} && !${r}`}()))}():function(){const o=d.formats[s];if(!o)return void function(){if(!1===c.strictSchema)return void d.logger.warn(e());throw new Error(e());function e(){return`unknown format "${s}" ignored in schema at path "${u}"`}}();if(!0===o)return;const[a,i,h]=function(e){const t=e instanceof RegExp?(0,Dp.regexpCode)(e):c.code.formats?Dp._`${c.code.formats}${(0,Dp.getProperty)(s)}`:void 0,n=r.scopeValue("formats",{key:s,ref:e,code:t});if("object"==typeof e&&!(e instanceof RegExp))return[e.type||"string",e.validate,Dp._`${n}.validate`];return["string",e,n]}(o);a===t&&e.pass(function(){if("object"==typeof o&&!(o instanceof RegExp)&&o.async){if(!l.$async)throw new Error("async format in sync schema");return Dp._`await ${h}(${n})`}return"function"==typeof i?Dp._`${h}(${n})`:Dp._`${h}.test(${n})`}())}())}};Mp.default=Up,Object.defineProperty(Ap,"__esModule",{value:!0});const qp=[Mp.default];Ap.default=qp;var Vp={};Object.defineProperty(Vp,"__esModule",{value:!0}),Vp.contentVocabulary=Vp.metadataVocabulary=void 0,Vp.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],Vp.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"],Object.defineProperty(Nl,"__esModule",{value:!0});const Fp=Zl,Lp=rh,Kp=Ap,Hp=Vp,Zp=[Cl.default,Fp.default,(0,Lp.default)(),Kp.default,Hp.metadataVocabulary,Hp.contentVocabulary];Nl.default=Zp;var Gp,Bp={},Jp={};Object.defineProperty(Jp,"__esModule",{value:!0}),Jp.DiscrError=void 0,function(e){e.Tag="tag",e.Mapping="mapping"}(Gp||(Jp.DiscrError=Gp={})),Object.defineProperty(Bp,"__esModule",{value:!0});const Wp=dc(),Qp=Jp,Yp=ju,Xp=Cu(),ef=hc,tf={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:e,tagName:t}})=>e===Qp.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>Wp._`{error: ${e}, tag: ${r}, tagValue: ${t}}`},code(e){const{gen:t,data:r,schema:n,parentSchema:o,it:s}=e,{oneOf:a}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");const i=n.propertyName;if("string"!=typeof i)throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!a)throw new Error("discriminator: requires oneOf keyword");const c=t.let("valid",!1),u=t.const("tag",Wp._`${r}${(0,Wp.getProperty)(i)}`);function l(r){const n=t.name("valid"),o=e.subschema({keyword:"oneOf",schemaProp:r},n);return e.mergeEvaluated(o,Wp.Name),n}t.if(Wp._`typeof ${u} == "string"`,()=>function(){const r=function(){var e;const t={},r=c(o);let n=!0;for(let t=0;t<a.length;t++){let o=a[t];if((null==o?void 0:o.$ref)&&!(0,ef.schemaHasRulesButRef)(o,s.self.RULES)){const e=o.$ref;if(o=Yp.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,e),o instanceof Yp.SchemaEnv&&(o=o.schema),void 0===o)throw new Xp.default(s.opts.uriResolver,s.baseId,e)}const l=null===(e=null==o?void 0:o.properties)||void 0===e?void 0:e[i];if("object"!=typeof l)throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${i}"`);n=n&&(r||c(o)),u(l,t)}if(!n)throw new Error(`discriminator: "${i}" must be required`);return t;function c({required:e}){return Array.isArray(e)&&e.includes(i)}function u(e,t){if(e.const)l(e.const,t);else{if(!e.enum)throw new Error(`discriminator: "properties/${i}" must have "const" or "enum"`);for(const r of e.enum)l(r,t)}}function l(e,r){if("string"!=typeof e||e in t)throw new Error(`discriminator: "${i}" values must be unique strings`);t[e]=r}}();t.if(!1);for(const e in r)t.elseIf(Wp._`${u} === ${e}`),t.assign(c,l(r[e]));t.else(),e.error(!1,{discrError:Qp.DiscrError.Mapping,tag:u,tagName:i}),t.endIf()}(),()=>e.error(!1,{discrError:Qp.DiscrError.Tag,tag:u,tagName:i})),e.ok(c)}};Bp.default=tf;var rf={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0};!function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.MissingRefError=t.ValidationError=t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=t.Ajv=void 0;const r=ec,n=Nl,o=Bp,s=rf,a=["/properties"],i="http://json-schema.org/draft-07/schema";class c extends r.default{_addVocabularies(){super._addVocabularies(),n.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(o.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const e=this.opts.$data?this.$dataMetaSchema(s,a):s;this.addMetaSchema(e,i,!1),this.refs["http://json-schema.org/schema"]=i}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(i)?i:void 0)}}t.Ajv=c,e.exports=t=c,e.exports.Ajv=c,Object.defineProperty(t,"__esModule",{value:!0}),t.default=c;var u=Pu();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return u.KeywordCxt}});var l=dc();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return l._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return l.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return l.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return l.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return l.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return l.CodeGen}});var d=Iu();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return d.default}});var h=Cu();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return h.default}})}(Xi,Xi.exports);var nf=Qi(Xi.exports),of={exports:{}},sf={};!function(e){function t(e,t){return{validate:e,compare:t}}Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0,e.fullFormats={date:t(o,s),time:t(i(!0),c),"date-time":t(d(!0),h),"iso-time":t(i(),u),"iso-date-time":t(d(),p),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:function(e){return f.test(e)&&m.test(e)},"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:function(e){if(w.test(e))return!1;try{return new RegExp(e),!0}catch(e){return!1}},uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:function(e){return y.lastIndex=0,y.test(e)},int32:{type:"number",validate:function(e){return Number.isInteger(e)&&e<=v&&e>=g}},int64:{type:"number",validate:function(e){return Number.isInteger(e)}},float:{type:"number",validate:_},double:{type:"number",validate:_},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,s),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,c),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,h),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,p),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);const r=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,n=[0,31,28,31,30,31,30,31,31,30,31,30,31];function o(e){const t=r.exec(e);if(!t)return!1;const o=+t[1],s=+t[2],a=+t[3];return s>=1&&s<=12&&a>=1&&a<=(2===s&&function(e){return e%4==0&&(e%100!=0||e%400==0)}(o)?29:n[s])}function s(e,t){if(e&&t)return e>t?1:e<t?-1:0}const a=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function i(e){return function(t){const r=a.exec(t);if(!r)return!1;const n=+r[1],o=+r[2],s=+r[3],i=r[4],c="-"===r[5]?-1:1,u=+(r[6]||0),l=+(r[7]||0);if(u>23||l>59||e&&!i)return!1;if(n<=23&&o<=59&&s<60)return!0;const d=o-l*c,h=n-u*c-(d<0?1:0);return(23===h||-1===h)&&(59===d||-1===d)&&s<61}}function c(e,t){if(!e||!t)return;const r=new Date("2020-01-01T"+e).valueOf(),n=new Date("2020-01-01T"+t).valueOf();return r&&n?r-n:void 0}function u(e,t){if(!e||!t)return;const r=a.exec(e),n=a.exec(t);return r&&n?(e=r[1]+r[2]+r[3])>(t=n[1]+n[2]+n[3])?1:e<t?-1:0:void 0}const l=/t|\s/i;function d(e){const t=i(e);return function(e){const r=e.split(l);return 2===r.length&&o(r[0])&&t(r[1])}}function h(e,t){if(!e||!t)return;const r=new Date(e).valueOf(),n=new Date(t).valueOf();return r&&n?r-n:void 0}function p(e,t){if(!e||!t)return;const[r,n]=e.split(l),[o,a]=t.split(l),i=s(r,o);return void 0!==i?i||c(n,a):void 0}const f=/\/|:/,m=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;const y=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;const g=-(2**31),v=2**31-1;function _(){return!0}const w=/[^\\]\\Z/}(sf);var af={},cf={exports:{}},uf={},lf={},df={},hf={},pf={},ff={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;class t{}e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw new Error("CodeGen: name must be a valid identifier");this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=r;class n extends t{constructor(e){super(),this._items="string"==typeof e?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const e=this._items[0];return""===e||'""'===e}get str(){var e;return null!==(e=this._str)&&void 0!==e?e:this._str=this._items.reduce((e,t)=>`${e}${t}`,"")}get names(){var e;return null!==(e=this._names)&&void 0!==e?e:this._names=this._items.reduce((e,t)=>(t instanceof r&&(e[t.str]=(e[t.str]||0)+1),e),{})}}function o(e,...t){const r=[e[0]];let o=0;for(;o<t.length;)i(r,t[o]),r.push(e[++o]);return new n(r)}e._Code=n,e.nil=new n(""),e._=o;const s=new n("+");function a(e,...t){const r=[u(e[0])];let o=0;for(;o<t.length;)r.push(s),i(r,t[o]),r.push(s,u(e[++o]));return function(e){let t=1;for(;t<e.length-1;){if(e[t]===s){const r=c(e[t-1],e[t+1]);if(void 0!==r){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}(r),new n(r)}function i(e,t){var o;t instanceof n?e.push(...t._items):t instanceof r?e.push(t):e.push("number"==typeof(o=t)||"boolean"==typeof o||null===o?o:u(Array.isArray(o)?o.join(","):o))}function c(e,t){if('""'===t)return e;if('""'===e)return t;if("string"==typeof e){if(t instanceof r||'"'!==e[e.length-1])return;return"string"!=typeof t?`${e.slice(0,-1)}${t}"`:'"'===t[0]?e.slice(0,-1)+t.slice(1):void 0}return"string"!=typeof t||'"'!==t[0]||e instanceof r?void 0:`"${e}${t.slice(1)}`}function u(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.str=a,e.addCodeArg=i,e.strConcat=function(e,t){return t.emptyStr()?e:e.emptyStr()?t:a`${e}${t}`},e.stringify=function(e){return new n(u(e))},e.safeStringify=u,e.getProperty=function(t){return"string"==typeof t&&e.IDENTIFIER.test(t)?new n(`.${t}`):o`[${t}]`},e.getEsmExportName=function(t){if("string"==typeof t&&e.IDENTIFIER.test(t))return new n(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)},e.regexpCode=function(e){return new n(e.toString())}}(ff);var mf={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=ff;class r extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}}var n;!function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"}(n||(e.UsedValueState=n={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};class o{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof t.Name?e:this.name(e)}name(e){return new t.Name(this._newName(e))}_newName(e){return`${e}${(this._names[e]||this._nameGroup(e)).index++}`}_nameGroup(e){var t,r;if((null===(r=null===(t=this._parent)||void 0===t?void 0:t._prefixes)||void 0===r?void 0:r.has(e))||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}}e.Scope=o;class s extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=t._`.${new t.Name(r)}[${n}]`}}e.ValueScopeName=s;const a=t._`\n`;e.ValueScope=class extends o{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?a:t.nil}}get(){return this._scope}name(e){return new s(e,this._newName(e))}value(e,t){var r;if(void 0===t.ref)throw new Error("CodeGen: ref must be passed in value");const n=this.toName(e),{prefix:o}=n,s=null!==(r=t.key)&&void 0!==r?r:t.ref;let a=this._values[o];if(a){const e=a.get(s);if(e)return e}else a=this._values[o]=new Map;a.set(s,n);const i=this._scope[o]||(this._scope[o]=[]),c=i.length;return i[c]=t.ref,n.setValue(t,{property:o,itemIndex:c}),n}getValue(e,t){const r=this._values[e];if(r)return r.get(t)}scopeRefs(e,r=this._values){return this._reduceValues(r,r=>{if(void 0===r.scopePath)throw new Error(`CodeGen: name "${r}" has no value`);return t._`${e}${r.scopePath}`})}scopeCode(e=this._values,t,r){return this._reduceValues(e,e=>{if(void 0===e.value)throw new Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,r)}_reduceValues(o,s,a={},i){let c=t.nil;for(const u in o){const l=o[u];if(!l)continue;const d=a[u]=a[u]||new Map;l.forEach(o=>{if(d.has(o))return;d.set(o,n.Started);let a=s(o);if(a){const r=this.opts.es5?e.varKinds.var:e.varKinds.const;c=t._`${c}${r} ${o} = ${a};${this.opts._n}`}else{if(!(a=null==i?void 0:i(o)))throw new r(o);c=t._`${c}${a}${this.opts._n}`}d.set(o,n.Completed)})}return c}}}(mf),function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;const t=ff,r=mf;var n=ff;Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return n.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return n.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return n.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}});var o=mf;Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return o.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return o.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return o.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return o.varKinds}}),e.operators={GT:new t._Code(">"),GTE:new t._Code(">="),LT:new t._Code("<"),LTE:new t._Code("<="),EQ:new t._Code("==="),NEQ:new t._Code("!=="),NOT:new t._Code("!"),OR:new t._Code("||"),AND:new t._Code("&&"),ADD:new t._Code("+")};class s{optimizeNodes(){return this}optimizeNames(e,t){return this}}class a extends s{constructor(e,t,r){super(),this.varKind=e,this.name=t,this.rhs=r}render({es5:e,_n:t}){const n=e?r.varKinds.var:this.varKind,o=void 0===this.rhs?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&(this.rhs=x(this.rhs,e,t)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class i extends s{constructor(e,t,r){super(),this.lhs=e,this.rhs=t,this.sideEffects=r}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof t.Name)||e[this.lhs.str]||this.sideEffects)return this.rhs=x(this.rhs,e,r),this}get names(){return I(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}}class c extends i{constructor(e,t,r,n){super(e,r,n),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}}class u extends s{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}}class l extends s{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}}class d extends s{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}}class h extends s{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=x(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class p extends s{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,r)=>t+r.render(e),"")}optimizeNodes(){const{nodes:e}=this;let t=e.length;for(;t--;){const r=e[t].optimizeNodes();Array.isArray(r)?e.splice(t,1,...r):r?e[t]=r:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){const{nodes:r}=this;let n=r.length;for(;n--;){const o=r[n];o.optimizeNames(e,t)||(N(e,o.names),r.splice(n,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>T(e,t.names),{})}}class f extends p{render(e){return"{"+e._n+super.render(e)+"}"+e._n}}class m extends p{}class y extends f{}y.kind="else";class g extends f{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+="else "+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();const e=this.condition;if(!0===e)return this.nodes;let t=this.else;if(t){const e=t.optimizeNodes();t=this.else=Array.isArray(e)?new y(e):e}return t?!1===e?t instanceof g?t:t.nodes:this.nodes.length?this:new g(C(e),t instanceof g?[t]:t.nodes):!1!==e&&this.nodes.length?this:void 0}optimizeNames(e,t){var r;if(this.else=null===(r=this.else)||void 0===r?void 0:r.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=x(this.condition,e,t),this}get names(){const e=super.names;return I(e,this.condition),this.else&&T(e,this.else.names),e}}g.kind="if";class v extends f{}v.kind="for";class _ extends v{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=x(this.iteration,e,t),this}get names(){return T(super.names,this.iteration.names)}}class w extends v{constructor(e,t,r,n){super(),this.varKind=e,this.name=t,this.from=r,this.to=n}render(e){const t=e.es5?r.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${t} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){const e=I(super.names,this.from);return I(e,this.to)}}class $ extends v{constructor(e,t,r,n){super(),this.loop=e,this.varKind=t,this.name=r,this.iterable=n}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=x(this.iterable,e,t),this}get names(){return T(super.names,this.iterable.names)}}class b extends f{constructor(e,t,r){super(),this.name=e,this.args=t,this.async=r}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}}b.kind="func";class k extends p{render(e){return"return "+super.render(e)}}k.kind="return";class E extends f{render(e){let t="try"+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),null===(e=this.catch)||void 0===e||e.optimizeNodes(),null===(t=this.finally)||void 0===t||t.optimizeNodes(),this}optimizeNames(e,t){var r,n;return super.optimizeNames(e,t),null===(r=this.catch)||void 0===r||r.optimizeNames(e,t),null===(n=this.finally)||void 0===n||n.optimizeNames(e,t),this}get names(){const e=super.names;return this.catch&&T(e,this.catch.names),this.finally&&T(e,this.finally.names),e}}class P extends f{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}}P.kind="catch";class S extends f{render(e){return"finally"+super.render(e)}}S.kind="finally";function T(e,t){for(const r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function I(e,r){return r instanceof t._CodeOrName?T(e,r.names):e}function x(e,r,n){return e instanceof t.Name?s(e):(o=e)instanceof t._Code&&o._items.some(e=>e instanceof t.Name&&1===r[e.str]&&void 0!==n[e.str])?new t._Code(e._items.reduce((e,r)=>(r instanceof t.Name&&(r=s(r)),r instanceof t._Code?e.push(...r._items):e.push(r),e),[])):e;var o;function s(e){const t=n[e.str];return void 0===t||1!==r[e.str]?e:(delete r[e.str],t)}}function N(e,t){for(const r in t)e[r]=(e[r]||0)-(t[r]||0)}function C(e){return"boolean"==typeof e||"number"==typeof e||null===e?!e:t._`!${z(e)}`}e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?"\n":""},this._extScope=e,this._scope=new r.Scope({parent:e}),this._nodes=[new m]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){const r=this._extScope.value(e,t);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,r,n){const o=this._scope.toName(t);return void 0!==r&&n&&(this._constants[o.str]=r),this._leafNode(new a(e,o,r)),o}const(e,t,n){return this._def(r.varKinds.const,e,t,n)}let(e,t,n){return this._def(r.varKinds.let,e,t,n)}var(e,t,n){return this._def(r.varKinds.var,e,t,n)}assign(e,t,r){return this._leafNode(new i(e,t,r))}add(t,r){return this._leafNode(new c(t,e.operators.ADD,r))}code(e){return"function"==typeof e?e():e!==t.nil&&this._leafNode(new h(e)),this}object(...e){const r=["{"];for(const[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,t.addCodeArg)(r,o));return r.push("}"),new t._Code(r)}if(e,t,r){if(this._blockNode(new g(e)),t&&r)this.code(t).else().code(r).endIf();else if(t)this.code(t).endIf();else if(r)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new g(e))}else(){return this._elseNode(new y)}endIf(){return this._endBlockNode(g,y)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new _(e),t)}forRange(e,t,n,o,s=(this.opts.es5?r.varKinds.var:r.varKinds.let)){const a=this._scope.toName(e);return this._for(new w(s,a,t,n),()=>o(a))}forOf(e,n,o,s=r.varKinds.const){const a=this._scope.toName(e);if(this.opts.es5){const e=n instanceof t.Name?n:this.var("_arr",n);return this.forRange("_i",0,t._`${e}.length`,r=>{this.var(a,t._`${e}[${r}]`),o(a)})}return this._for(new $("of",s,a,n),()=>o(a))}forIn(e,n,o,s=(this.opts.es5?r.varKinds.var:r.varKinds.const)){if(this.opts.ownProperties)return this.forOf(e,t._`Object.keys(${n})`,o);const a=this._scope.toName(e);return this._for(new $("in",s,a,n),()=>o(a))}endFor(){return this._endBlockNode(v)}label(e){return this._leafNode(new u(e))}break(e){return this._leafNode(new l(e))}return(e){const t=new k;if(this._blockNode(t),this.code(e),1!==t.nodes.length)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(k)}try(e,t,r){if(!t&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');const n=new E;if(this._blockNode(n),this.code(e),t){const e=this.name("e");this._currNode=n.catch=new P(e),t(e)}return r&&(this._currNode=n.finally=new S,this.code(r)),this._endBlockNode(P,S)}throw(e){return this._leafNode(new d(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){const t=this._blockStarts.pop();if(void 0===t)throw new Error("CodeGen: not in self-balancing block");const r=this._nodes.length-t;if(r<0||void 0!==e&&r!==e)throw new Error(`CodeGen: wrong number of nodes: ${r} vs ${e} expected`);return this._nodes.length=t,this}func(e,r=t.nil,n,o){return this._blockNode(new b(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(b)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){const r=this._currNode;if(r instanceof e||t&&r instanceof t)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){const t=this._currNode;if(!(t instanceof g))throw new Error('CodeGen: "else" without "if"');return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){const e=this._nodes;return e[e.length-1]}set _currNode(e){const t=this._nodes;t[t.length-1]=e}},e.not=C;const j=O(e.operators.AND);e.and=function(...e){return e.reduce(j)};const R=O(e.operators.OR);function O(e){return(r,n)=>r===t.nil?n:n===t.nil?r:t._`${z(r)} ${e} ${z(n)}`}function z(e){return e instanceof t.Name?e:t._`(${e})`}e.or=function(...e){return e.reduce(R)}}(pf);var yf={};Object.defineProperty(yf,"__esModule",{value:!0}),yf.checkStrictMode=yf.getErrorPath=yf.Type=yf.useFunc=yf.setEvaluated=yf.evaluatedPropsToName=yf.mergeEvaluated=yf.eachItem=yf.unescapeJsonPointer=yf.escapeJsonPointer=yf.escapeFragment=yf.unescapeFragment=yf.schemaRefOrVal=yf.schemaHasRulesButRef=yf.schemaHasRules=yf.checkUnknownRules=yf.alwaysValidSchema=yf.toHash=void 0;const gf=pf,vf=ff;function _f(e,t=e.schema){const{opts:r,self:n}=e;if(!r.strictSchema)return;if("boolean"==typeof t)return;const o=n.RULES.keywords;for(const r in t)o[r]||If(e,`unknown keyword: "${r}"`)}function wf(e,t){if("boolean"==typeof e)return!e;for(const r in e)if(t[r])return!0;return!1}function $f(e){return"number"==typeof e?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}function bf(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function kf({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(o,s,a,i)=>{const c=void 0===a?s:a instanceof gf.Name?(s instanceof gf.Name?e(o,s,a):t(o,s,a),a):s instanceof gf.Name?(t(o,a,s),s):r(s,a);return i!==gf.Name||c instanceof gf.Name?c:n(o,c)}}function Ef(e,t){if(!0===t)return e.var("props",!0);const r=e.var("props",gf._`{}`);return void 0!==t&&Pf(e,r,t),r}function Pf(e,t,r){Object.keys(r).forEach(r=>e.assign(gf._`${t}${(0,gf.getProperty)(r)}`,!0))}yf.toHash=function(e){const t={};for(const r of e)t[r]=!0;return t},yf.alwaysValidSchema=function(e,t){return"boolean"==typeof t?t:0===Object.keys(t).length||(_f(e,t),!wf(t,e.self.RULES.all))},yf.checkUnknownRules=_f,yf.schemaHasRules=wf,yf.schemaHasRulesButRef=function(e,t){if("boolean"==typeof e)return!e;for(const r in e)if("$ref"!==r&&t.all[r])return!0;return!1},yf.schemaRefOrVal=function({topSchemaRef:e,schemaPath:t},r,n,o){if(!o){if("number"==typeof r||"boolean"==typeof r)return r;if("string"==typeof r)return gf._`${r}`}return gf._`${e}${t}${(0,gf.getProperty)(n)}`},yf.unescapeFragment=function(e){return bf(decodeURIComponent(e))},yf.escapeFragment=function(e){return encodeURIComponent($f(e))},yf.escapeJsonPointer=$f,yf.unescapeJsonPointer=bf,yf.eachItem=function(e,t){if(Array.isArray(e))for(const r of e)t(r);else t(e)},yf.mergeEvaluated={props:kf({mergeNames:(e,t,r)=>e.if(gf._`${r} !== true && ${t} !== undefined`,()=>{e.if(gf._`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,gf._`${r} || {}`).code(gf._`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if(gf._`${r} !== true`,()=>{!0===t?e.assign(r,!0):(e.assign(r,gf._`${r} || {}`),Pf(e,r,t))}),mergeValues:(e,t)=>!0===e||{...e,...t},resultToName:Ef}),items:kf({mergeNames:(e,t,r)=>e.if(gf._`${r} !== true && ${t} !== undefined`,()=>e.assign(r,gf._`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if(gf._`${r} !== true`,()=>e.assign(r,!0===t||gf._`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>!0===e||Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})},yf.evaluatedPropsToName=Ef,yf.setEvaluated=Pf;const Sf={};var Tf;function If(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,!0===r)throw new Error(t);e.self.logger.warn(t)}}yf.useFunc=function(e,t){return e.scopeValue("func",{ref:t,code:Sf[t.code]||(Sf[t.code]=new vf._Code(t.code))})},function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"}(Tf||(yf.Type=Tf={})),yf.getErrorPath=function(e,t,r){if(e instanceof gf.Name){const n=t===Tf.Num;return r?n?gf._`"[" + ${e} + "]"`:gf._`"['" + ${e} + "']"`:n?gf._`"/" + ${e}`:gf._`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,gf.getProperty)(e).toString():"/"+$f(e)},yf.checkStrictMode=If;var xf,Nf,Cf,jf={};function Rf(){if(xf)return jf;xf=1,Object.defineProperty(jf,"__esModule",{value:!0});const e=pf,t={data:new e.Name("data"),valCxt:new e.Name("valCxt"),instancePath:new e.Name("instancePath"),parentData:new e.Name("parentData"),parentDataProperty:new e.Name("parentDataProperty"),rootData:new e.Name("rootData"),dynamicAnchors:new e.Name("dynamicAnchors"),vErrors:new e.Name("vErrors"),errors:new e.Name("errors"),this:new e.Name("this"),self:new e.Name("self"),scope:new e.Name("scope"),json:new e.Name("json"),jsonPos:new e.Name("jsonPos"),jsonLen:new e.Name("jsonLen"),jsonPart:new e.Name("jsonPart")};return jf.default=t,jf}function Of(){return Nf||(Nf=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;const t=pf,r=yf,n=Rf();function o(e,r){const o=e.const("err",r);e.if(t._`${n.default.vErrors} === null`,()=>e.assign(n.default.vErrors,t._`[${o}]`),t._`${n.default.vErrors}.push(${o})`),e.code(t._`${n.default.errors}++`)}function s(e,r){const{gen:n,validateName:o,schemaEnv:s}=e;s.$async?n.throw(t._`new ${e.ValidationError}(${r})`):(n.assign(t._`${o}.errors`,r),n.return(!1))}e.keywordError={message:({keyword:e})=>t.str`must pass "${e}" keyword validation`},e.keyword$DataError={message:({keyword:e,schemaType:r})=>r?t.str`"${e}" keyword must be ${r} ($data)`:t.str`"${e}" keyword is invalid ($data)`},e.reportError=function(r,n=e.keywordError,a,c){const{it:u}=r,{gen:l,compositeRule:d,allErrors:h}=u,p=i(r,n,a);(null!=c?c:d||h)?o(l,p):s(u,t._`[${p}]`)},e.reportExtraError=function(t,r=e.keywordError,a){const{it:c}=t,{gen:u,compositeRule:l,allErrors:d}=c;o(u,i(t,r,a)),l||d||s(c,n.default.vErrors)},e.resetErrorsCount=function(e,r){e.assign(n.default.errors,r),e.if(t._`${n.default.vErrors} !== null`,()=>e.if(r,()=>e.assign(t._`${n.default.vErrors}.length`,r),()=>e.assign(n.default.vErrors,null)))},e.extendErrors=function({gen:e,keyword:r,schemaValue:o,data:s,errsCount:a,it:i}){if(void 0===a)throw new Error("ajv implementation error");const c=e.name("err");e.forRange("i",a,n.default.errors,a=>{e.const(c,t._`${n.default.vErrors}[${a}]`),e.if(t._`${c}.instancePath === undefined`,()=>e.assign(t._`${c}.instancePath`,(0,t.strConcat)(n.default.instancePath,i.errorPath))),e.assign(t._`${c}.schemaPath`,t.str`${i.errSchemaPath}/${r}`),i.opts.verbose&&(e.assign(t._`${c}.schema`,o),e.assign(t._`${c}.data`,s))})};const a={keyword:new t.Name("keyword"),schemaPath:new t.Name("schemaPath"),params:new t.Name("params"),propertyName:new t.Name("propertyName"),message:new t.Name("message"),schema:new t.Name("schema"),parentSchema:new t.Name("parentSchema")};function i(e,r,o){const{createErrors:s}=e.it;return!1===s?t._`{}`:function(e,r,o={}){const{gen:s,it:i}=e,l=[c(i,o),u(e,o)];return function(e,{params:r,message:o},s){const{keyword:i,data:c,schemaValue:u,it:l}=e,{opts:d,propertyName:h,topSchemaRef:p,schemaPath:f}=l;s.push([a.keyword,i],[a.params,"function"==typeof r?r(e):r||t._`{}`]),d.messages&&s.push([a.message,"function"==typeof o?o(e):o]);d.verbose&&s.push([a.schema,u],[a.parentSchema,t._`${p}${f}`],[n.default.data,c]);h&&s.push([a.propertyName,h])}(e,r,l),s.object(...l)}(e,r,o)}function c({errorPath:e},{instancePath:o}){const s=o?t.str`${e}${(0,r.getErrorPath)(o,r.Type.Str)}`:e;return[n.default.instancePath,(0,t.strConcat)(n.default.instancePath,s)]}function u({keyword:e,it:{errSchemaPath:n}},{schemaPath:o,parentSchema:s}){let i=s?n:t.str`${n}/${e}`;return o&&(i=t.str`${i}${(0,r.getErrorPath)(o,r.Type.Str)}`),[a.schemaPath,i]}}(hf)),hf}var zf={},Af={};Object.defineProperty(Af,"__esModule",{value:!0}),Af.getRules=Af.isJSONType=void 0;const Mf=new Set(["string","number","integer","boolean","null","object","array"]);Af.isJSONType=function(e){return"string"==typeof e&&Mf.has(e)},Af.getRules=function(){const e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}};var Df,Uf={};function qf(){if(Df)return Uf;function e(e,r){return r.rules.some(r=>t(e,r))}function t(e,t){var r;return void 0!==e[t.keyword]||(null===(r=t.definition.implements)||void 0===r?void 0:r.some(t=>void 0!==e[t]))}return Df=1,Object.defineProperty(Uf,"__esModule",{value:!0}),Uf.shouldUseRule=Uf.shouldUseGroup=Uf.schemaHasRulesForType=void 0,Uf.schemaHasRulesForType=function({schema:t,self:r},n){const o=r.RULES.types[n];return o&&!0!==o&&e(t,o)},Uf.shouldUseGroup=e,Uf.shouldUseRule=t,Uf}Object.defineProperty(zf,"__esModule",{value:!0}),zf.reportTypeError=zf.checkDataTypes=zf.checkDataType=zf.coerceAndCheckDataType=zf.getJSONTypes=zf.getSchemaTypes=zf.DataType=void 0;const Vf=Af,Ff=qf(),Lf=Of(),Kf=pf,Hf=yf;var Zf;function Gf(e){const t=Array.isArray(e)?e:e?[e]:[];if(t.every(Vf.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}!function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"}(Zf||(zf.DataType=Zf={})),zf.getSchemaTypes=function(e){const t=Gf(e.type);if(t.includes("null")){if(!1===e.nullable)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&void 0!==e.nullable)throw new Error('"nullable" cannot be used without "type"');!0===e.nullable&&t.push("null")}return t},zf.getJSONTypes=Gf,zf.coerceAndCheckDataType=function(e,t){const{gen:r,data:n,opts:o}=e,s=function(e,t){return t?e.filter(e=>Bf.has(e)||"array"===t&&"array"===e):[]}(t,o.coerceTypes),a=t.length>0&&!(0===s.length&&1===t.length&&(0,Ff.schemaHasRulesForType)(e,t[0]));if(a){const a=Wf(t,n,o.strictNumbers,Zf.Wrong);r.if(a,()=>{s.length?function(e,t,r){const{gen:n,data:o,opts:s}=e,a=n.let("dataType",Kf._`typeof ${o}`),i=n.let("coerced",Kf._`undefined`);"array"===s.coerceTypes&&n.if(Kf._`${a} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,Kf._`${o}[0]`).assign(a,Kf._`typeof ${o}`).if(Wf(t,o,s.strictNumbers),()=>n.assign(i,o)));n.if(Kf._`${i} !== undefined`);for(const e of r)(Bf.has(e)||"array"===e&&"array"===s.coerceTypes)&&c(e);function c(e){switch(e){case"string":return void n.elseIf(Kf._`${a} == "number" || ${a} == "boolean"`).assign(i,Kf._`"" + ${o}`).elseIf(Kf._`${o} === null`).assign(i,Kf._`""`);case"number":return void n.elseIf(Kf._`${a} == "boolean" || ${o} === null
8
+ || (${a} == "string" && ${o} && ${o} == +${o})`).assign(i,Kf._`+${o}`);case"integer":return void n.elseIf(Kf._`${a} === "boolean" || ${o} === null
9
+ || (${a} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(i,Kf._`+${o}`);case"boolean":return void n.elseIf(Kf._`${o} === "false" || ${o} === 0 || ${o} === null`).assign(i,!1).elseIf(Kf._`${o} === "true" || ${o} === 1`).assign(i,!0);case"null":return n.elseIf(Kf._`${o} === "" || ${o} === 0 || ${o} === false`),void n.assign(i,null);case"array":n.elseIf(Kf._`${a} === "string" || ${a} === "number"
10
+ || ${a} === "boolean" || ${o} === null`).assign(i,Kf._`[${o}]`)}}n.else(),Yf(e),n.endIf(),n.if(Kf._`${i} !== undefined`,()=>{n.assign(o,i),function({gen:e,parentData:t,parentDataProperty:r},n){e.if(Kf._`${t} !== undefined`,()=>e.assign(Kf._`${t}[${r}]`,n))}(e,i)})}(e,t,s):Yf(e)})}return a};const Bf=new Set(["string","number","integer","boolean","null"]);function Jf(e,t,r,n=Zf.Correct){const o=n===Zf.Correct?Kf.operators.EQ:Kf.operators.NEQ;let s;switch(e){case"null":return Kf._`${t} ${o} null`;case"array":s=Kf._`Array.isArray(${t})`;break;case"object":s=Kf._`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":s=a(Kf._`!(${t} % 1) && !isNaN(${t})`);break;case"number":s=a();break;default:return Kf._`typeof ${t} ${o} ${e}`}return n===Zf.Correct?s:(0,Kf.not)(s);function a(e=Kf.nil){return(0,Kf.and)(Kf._`typeof ${t} == "number"`,e,r?Kf._`isFinite(${t})`:Kf.nil)}}function Wf(e,t,r,n){if(1===e.length)return Jf(e[0],t,r,n);let o;const s=(0,Hf.toHash)(e);if(s.array&&s.object){const e=Kf._`typeof ${t} != "object"`;o=s.null?e:Kf._`!${t} || ${e}`,delete s.null,delete s.array,delete s.object}else o=Kf.nil;s.number&&delete s.integer;for(const e in s)o=(0,Kf.and)(o,Jf(e,t,r,n));return o}zf.checkDataType=Jf,zf.checkDataTypes=Wf;const Qf={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>"string"==typeof e?Kf._`{type: ${e}}`:Kf._`{type: ${t}}`};function Yf(e){const t=function(e){const{gen:t,data:r,schema:n}=e,o=(0,Hf.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:e}}(e);(0,Lf.reportError)(t,Qf)}zf.reportTypeError=Yf;var Xf,em={};var tm,rm,nm={},om={};function sm(){if(tm)return om;tm=1,Object.defineProperty(om,"__esModule",{value:!0}),om.validateUnion=om.validateArray=om.usePattern=om.callValidateCode=om.schemaProperties=om.allSchemaProperties=om.noPropertyInData=om.propertyInData=om.isOwnProperty=om.hasPropFunc=om.reportMissingProp=om.checkMissingProp=om.checkReportMissingProp=void 0;const e=pf,t=yf,r=Rf(),n=yf;function o(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:e._`Object.prototype.hasOwnProperty`})}function s(t,r,n){return e._`${o(t)}.call(${r}, ${n})`}function a(t,r,n,o){const a=e._`${r}${(0,e.getProperty)(n)} === undefined`;return o?(0,e.or)(a,(0,e.not)(s(t,r,n))):a}function i(e){return e?Object.keys(e).filter(e=>"__proto__"!==e):[]}om.checkReportMissingProp=function(t,r){const{gen:n,data:o,it:s}=t;n.if(a(n,o,r,s.opts.ownProperties),()=>{t.setParams({missingProperty:e._`${r}`},!0),t.error()})},om.checkMissingProp=function({gen:t,data:r,it:{opts:n}},o,s){return(0,e.or)(...o.map(o=>(0,e.and)(a(t,r,o,n.ownProperties),e._`${s} = ${o}`)))},om.reportMissingProp=function(e,t){e.setParams({missingProperty:t},!0),e.error()},om.hasPropFunc=o,om.isOwnProperty=s,om.propertyInData=function(t,r,n,o){const a=e._`${r}${(0,e.getProperty)(n)} !== undefined`;return o?e._`${a} && ${s(t,r,n)}`:a},om.noPropertyInData=a,om.allSchemaProperties=i,om.schemaProperties=function(e,r){return i(r).filter(n=>!(0,t.alwaysValidSchema)(e,r[n]))},om.callValidateCode=function({schemaCode:t,data:n,it:{gen:o,topSchemaRef:s,schemaPath:a,errorPath:i},it:c},u,l,d){const h=d?e._`${t}, ${n}, ${s}${a}`:n,p=[[r.default.instancePath,(0,e.strConcat)(r.default.instancePath,i)],[r.default.parentData,c.parentData],[r.default.parentDataProperty,c.parentDataProperty],[r.default.rootData,r.default.rootData]];c.opts.dynamicRef&&p.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);const f=e._`${h}, ${o.object(...p)}`;return l!==e.nil?e._`${u}.call(${l}, ${f})`:e._`${u}(${f})`};const c=e._`new RegExp`;return om.usePattern=function({gen:t,it:{opts:r}},o){const s=r.unicodeRegExp?"u":"",{regExp:a}=r.code,i=a(o,s);return t.scopeValue("pattern",{key:i.toString(),ref:i,code:e._`${"new RegExp"===a.code?c:(0,n.useFunc)(t,a)}(${o}, ${s})`})},om.validateArray=function(r){const{gen:n,data:o,keyword:s,it:a}=r,i=n.name("valid");if(a.allErrors){const e=n.let("valid",!0);return c(()=>n.assign(e,!1)),e}return n.var(i,!0),c(()=>n.break()),i;function c(a){const c=n.const("len",e._`${o}.length`);n.forRange("i",0,c,o=>{r.subschema({keyword:s,dataProp:o,dataPropType:t.Type.Num},i),n.if((0,e.not)(i),a)})}},om.validateUnion=function(r){const{gen:n,schema:o,keyword:s,it:a}=r;if(!Array.isArray(o))throw new Error("ajv implementation error");if(o.some(e=>(0,t.alwaysValidSchema)(a,e))&&!a.opts.unevaluated)return;const i=n.let("valid",!1),c=n.name("_valid");n.block(()=>o.forEach((t,o)=>{const a=r.subschema({keyword:s,schemaProp:o,compositeRule:!0},c);n.assign(i,e._`${i} || ${c}`);r.mergeValidEvaluated(a,c)||n.if((0,e.not)(i))})),r.result(i,()=>r.reset(),()=>r.error(!0))},om}function am(){if(rm)return nm;rm=1,Object.defineProperty(nm,"__esModule",{value:!0}),nm.validateKeywordUsage=nm.validSchemaType=nm.funcKeywordCode=nm.macroKeywordCode=void 0;const e=pf,t=Rf(),r=sm(),n=Of();function o(t){const{gen:r,data:n,it:o}=t;r.if(o.parentData,()=>r.assign(n,e._`${o.parentData}[${o.parentDataProperty}]`))}function s(t,r,n){if(void 0===n)throw new Error(`keyword "${r}" failed to compile`);return t.scopeValue("keyword","function"==typeof n?{ref:n}:{ref:n,code:(0,e.stringify)(n)})}return nm.macroKeywordCode=function(t,r){const{gen:n,keyword:o,schema:a,parentSchema:i,it:c}=t,u=r.macro.call(c.self,a,i,c),l=s(n,o,u);!1!==c.opts.validateSchema&&c.self.validateSchema(u,!0);const d=n.name("valid");t.subschema({schema:u,schemaPath:e.nil,errSchemaPath:`${c.errSchemaPath}/${o}`,topSchemaRef:l,compositeRule:!0},d),t.pass(d,()=>t.error(!0))},nm.funcKeywordCode=function(a,i){var c;const{gen:u,keyword:l,schema:d,parentSchema:h,$data:p,it:f}=a;!function({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}(f,i);const m=!p&&i.compile?i.compile.call(f.self,d,h,f):i.validate,y=s(u,l,m),g=u.let("valid");function v(n=(i.async?e._`await `:e.nil)){const o=f.opts.passContext?t.default.this:t.default.self,s=!("compile"in i&&!p||!1===i.schema);u.assign(g,e._`${n}${(0,r.callValidateCode)(a,y,o,s)}`,i.modifying)}function _(t){var r;u.if((0,e.not)(null!==(r=i.valid)&&void 0!==r?r:g),t)}a.block$data(g,function(){if(!1===i.errors)v(),i.modifying&&o(a),_(()=>a.error());else{const r=i.async?function(){const t=u.let("ruleErrs",null);return u.try(()=>v(e._`await `),r=>u.assign(g,!1).if(e._`${r} instanceof ${f.ValidationError}`,()=>u.assign(t,e._`${r}.errors`),()=>u.throw(r))),t}():function(){const t=e._`${y}.errors`;return u.assign(t,null),v(e.nil),t}();i.modifying&&o(a),_(()=>function(r,o){const{gen:s}=r;s.if(e._`Array.isArray(${o})`,()=>{s.assign(t.default.vErrors,e._`${t.default.vErrors} === null ? ${o} : ${t.default.vErrors}.concat(${o})`).assign(t.default.errors,e._`${t.default.vErrors}.length`),(0,n.extendErrors)(r)},()=>r.error())}(a,r))}}),a.ok(null!==(c=i.valid)&&void 0!==c?c:g)},nm.validSchemaType=function(e,t,r=!1){return!t.length||t.some(t=>"array"===t?Array.isArray(e):"object"===t?e&&"object"==typeof e&&!Array.isArray(e):typeof e==t||r&&void 0===e)},nm.validateKeywordUsage=function({schema:e,opts:t,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");const a=o.dependencies;if(null==a?void 0:a.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw new Error(`parent schema must have dependencies of ${s}: ${a.join(",")}`);if(o.validateSchema){if(!o.validateSchema(e[s])){const e=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if("log"!==t.validateSchema)throw new Error(e);r.logger.error(e)}}},nm}var im,cm={};var um={},lm={exports:{}},dm=lm.exports=function(e,t,r){"function"==typeof t&&(r=t,t={}),hm(t,"function"==typeof(r=t.cb||r)?r:r.pre||function(){},r.post||function(){},e,"",e)};function hm(e,t,r,n,o,s,a,i,c,u){if(n&&"object"==typeof n&&!Array.isArray(n)){for(var l in t(n,o,s,a,i,c,u),n){var d=n[l];if(Array.isArray(d)){if(l in dm.arrayKeywords)for(var h=0;h<d.length;h++)hm(e,t,r,d[h],o+"/"+l+"/"+h,s,o,l,n,h)}else if(l in dm.propsKeywords){if(d&&"object"==typeof d)for(var p in d)hm(e,t,r,d[p],o+"/"+l+"/"+pm(p),s,o,l,n,p)}else(l in dm.keywords||e.allKeys&&!(l in dm.skipKeywords))&&hm(e,t,r,d,o+"/"+l,s,o,l,n)}r(n,o,s,a,i,c,u)}}function pm(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}dm.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},dm.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},dm.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},dm.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};var fm=lm.exports;Object.defineProperty(um,"__esModule",{value:!0}),um.getSchemaRefs=um.resolveUrl=um.normalizeId=um._getFullPath=um.getFullPath=um.inlineRef=void 0;const mm=yf,ym=au,gm=fm,vm=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);um.inlineRef=function(e,t=!0){return"boolean"==typeof e||(!0===t?!wm(e):!!t&&$m(e)<=t)};const _m=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function wm(e){for(const t in e){if(_m.has(t))return!0;const r=e[t];if(Array.isArray(r)&&r.some(wm))return!0;if("object"==typeof r&&wm(r))return!0}return!1}function $m(e){let t=0;for(const r in e){if("$ref"===r)return 1/0;if(t++,!vm.has(r)&&("object"==typeof e[r]&&(0,mm.eachItem)(e[r],e=>t+=$m(e)),t===1/0))return 1/0}return t}function bm(e,t="",r){!1!==r&&(t=Pm(t));const n=e.parse(t);return km(e,n)}function km(e,t){return e.serialize(t).split("#")[0]+"#"}um.getFullPath=bm,um._getFullPath=km;const Em=/#\/?$/;function Pm(e){return e?e.replace(Em,""):""}um.normalizeId=Pm,um.resolveUrl=function(e,t,r){return r=Pm(r),e.resolve(t,r)};const Sm=/^[a-z_][-a-z0-9._]*$/i;var Tm;function Im(){if(Tm)return lf;Tm=1,Object.defineProperty(lf,"__esModule",{value:!0}),lf.getData=lf.KeywordCxt=lf.validateFunctionCode=void 0;const e=function(){if(Cf)return df;Cf=1,Object.defineProperty(df,"__esModule",{value:!0}),df.boolOrEmptySchema=df.topBoolOrEmptySchema=void 0;const e=Of(),t=pf,r=Rf(),n={message:"boolean schema is false"};function o(t,r){const{gen:o,data:s}=t,a={gen:o,keyword:"false schema",data:s,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,e.reportError)(a,n,void 0,r)}return df.topBoolOrEmptySchema=function(e){const{gen:n,schema:s,validateName:a}=e;!1===s?o(e,!1):"object"==typeof s&&!0===s.$async?n.return(r.default.data):(n.assign(t._`${a}.errors`,null),n.return(!0))},df.boolOrEmptySchema=function(e,t){const{gen:r,schema:n}=e;!1===n?(r.var(t,!1),o(e)):r.var(t,!0)},df}(),t=zf,r=qf(),n=zf,o=function(){if(Xf)return em;Xf=1,Object.defineProperty(em,"__esModule",{value:!0}),em.assignDefaults=void 0;const e=pf,t=yf;function r(r,n,o){const{gen:s,compositeRule:a,data:i,opts:c}=r;if(void 0===o)return;const u=e._`${i}${(0,e.getProperty)(n)}`;if(a)return void(0,t.checkStrictMode)(r,`default is ignored for: ${u}`);let l=e._`${u} === undefined`;"empty"===c.useDefaults&&(l=e._`${l} || ${u} === null || ${u} === ""`),s.if(l,e._`${u} = ${(0,e.stringify)(o)}`)}return em.assignDefaults=function(e,t){const{properties:n,items:o}=e.schema;if("object"===t&&n)for(const t in n)r(e,t,n[t].default);else"array"===t&&Array.isArray(o)&&o.forEach((t,n)=>r(e,n,t.default))},em}(),s=am(),a=function(){if(im)return cm;im=1,Object.defineProperty(cm,"__esModule",{value:!0}),cm.extendSubschemaMode=cm.extendSubschemaData=cm.getSubschema=void 0;const e=pf,t=yf;return cm.getSubschema=function(r,{keyword:n,schemaProp:o,schema:s,schemaPath:a,errSchemaPath:i,topSchemaRef:c}){if(void 0!==n&&void 0!==s)throw new Error('both "keyword" and "schema" passed, only one allowed');if(void 0!==n){const s=r.schema[n];return void 0===o?{schema:s,schemaPath:e._`${r.schemaPath}${(0,e.getProperty)(n)}`,errSchemaPath:`${r.errSchemaPath}/${n}`}:{schema:s[o],schemaPath:e._`${r.schemaPath}${(0,e.getProperty)(n)}${(0,e.getProperty)(o)}`,errSchemaPath:`${r.errSchemaPath}/${n}/${(0,t.escapeFragment)(o)}`}}if(void 0!==s){if(void 0===a||void 0===i||void 0===c)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:s,schemaPath:a,topSchemaRef:c,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')},cm.extendSubschemaData=function(r,n,{dataProp:o,dataPropType:s,data:a,dataTypes:i,propertyName:c}){if(void 0!==a&&void 0!==o)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:u}=n;if(void 0!==o){const{errorPath:a,dataPathArr:i,opts:c}=n;l(u.let("data",e._`${n.data}${(0,e.getProperty)(o)}`,!0)),r.errorPath=e.str`${a}${(0,t.getErrorPath)(o,s,c.jsPropertySyntax)}`,r.parentDataProperty=e._`${o}`,r.dataPathArr=[...i,r.parentDataProperty]}function l(e){r.data=e,r.dataLevel=n.dataLevel+1,r.dataTypes=[],n.definedProperties=new Set,r.parentData=n.data,r.dataNames=[...n.dataNames,e]}void 0!==a&&(l(a instanceof e.Name?a:u.let("data",a,!0)),void 0!==c&&(r.propertyName=c)),i&&(r.dataTypes=i)},cm.extendSubschemaMode=function(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){void 0!==n&&(e.compositeRule=n),void 0!==o&&(e.createErrors=o),void 0!==s&&(e.allErrors=s),e.jtdDiscriminator=t,e.jtdMetadata=r},cm}(),i=pf,c=Rf(),u=um,l=yf,d=Of();function h({gen:e,validateName:t,schema:r,schemaEnv:n,opts:o},s){o.code.es5?e.func(t,i._`${c.default.data}, ${c.default.valCxt}`,n.$async,()=>{e.code(i._`"use strict"; ${p(r,o)}`),function(e,t){e.if(c.default.valCxt,()=>{e.var(c.default.instancePath,i._`${c.default.valCxt}.${c.default.instancePath}`),e.var(c.default.parentData,i._`${c.default.valCxt}.${c.default.parentData}`),e.var(c.default.parentDataProperty,i._`${c.default.valCxt}.${c.default.parentDataProperty}`),e.var(c.default.rootData,i._`${c.default.valCxt}.${c.default.rootData}`),t.dynamicRef&&e.var(c.default.dynamicAnchors,i._`${c.default.valCxt}.${c.default.dynamicAnchors}`)},()=>{e.var(c.default.instancePath,i._`""`),e.var(c.default.parentData,i._`undefined`),e.var(c.default.parentDataProperty,i._`undefined`),e.var(c.default.rootData,c.default.data),t.dynamicRef&&e.var(c.default.dynamicAnchors,i._`{}`)})}(e,o),e.code(s)}):e.func(t,i._`${c.default.data}, ${function(e){return i._`{${c.default.instancePath}="", ${c.default.parentData}, ${c.default.parentDataProperty}, ${c.default.rootData}=${c.default.data}${e.dynamicRef?i._`, ${c.default.dynamicAnchors}={}`:i.nil}}={}`}(o)}`,n.$async,()=>e.code(p(r,o)).code(s))}function p(e,t){const r="object"==typeof e&&e[t.schemaId];return r&&(t.code.source||t.code.process)?i._`/*# sourceURL=${r} */`:i.nil}function f(t,r){y(t)&&(g(t),m(t))?function(e,t){const{schema:r,gen:n,opts:o}=e;o.$comment&&r.$comment&&_(e);(function(e){const t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,u.resolveUrl)(e.opts.uriResolver,e.baseId,t))})(e),function(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}(e);const s=n.const("_errs",c.default.errors);v(e,s),n.var(t,i._`${s} === ${c.default.errors}`)}(t,r):(0,e.boolOrEmptySchema)(t,r)}function m({schema:e,self:t}){if("boolean"==typeof e)return!e;for(const r in e)if(t.RULES.all[r])return!0;return!1}function y(e){return"boolean"!=typeof e.schema}function g(e){(0,l.checkUnknownRules)(e),function(e){const{schema:t,errSchemaPath:r,opts:n,self:o}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,l.schemaHasRulesButRef)(t,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}(e)}function v(e,r){if(e.opts.jtd)return w(e,[],!1,r);const n=(0,t.getSchemaTypes)(e.schema);w(e,n,!(0,t.coerceAndCheckDataType)(e,n),r)}function _({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:o}){const s=r.$comment;if(!0===o.$comment)e.code(i._`${c.default.self}.logger.log(${s})`);else if("function"==typeof o.$comment){const r=i.str`${n}/$comment`,o=e.scopeValue("root",{ref:t.root});e.code(i._`${c.default.self}.opts.$comment(${s}, ${r}, ${o}.schema)`)}}function w(e,t,o,s){const{gen:a,schema:u,data:d,allErrors:h,opts:p,self:f}=e,{RULES:m}=f;function y(l){(0,r.shouldUseGroup)(u,l)&&(l.type?(a.if((0,n.checkDataType)(l.type,d,p.strictNumbers)),$(e,l),1===t.length&&t[0]===l.type&&o&&(a.else(),(0,n.reportTypeError)(e)),a.endIf()):$(e,l),h||a.if(i._`${c.default.errors} === ${s||0}`))}!u.$ref||!p.ignoreKeywordsWithRef&&(0,l.schemaHasRulesButRef)(u,m)?(p.jtd||function(e,t){if(e.schemaEnv.meta||!e.opts.strictTypes)return;(function(e,t){if(!t.length)return;if(!e.dataTypes.length)return void(e.dataTypes=t);t.forEach(t=>{k(e.dataTypes,t)||E(e,`type "${t}" not allowed by context "${e.dataTypes.join(",")}"`)}),function(e,t){const r=[];for(const n of e.dataTypes)k(t,n)?r.push(n):t.includes("integer")&&"number"===n&&r.push("integer");e.dataTypes=r}(e,t)})(e,t),e.opts.allowUnionTypes||function(e,t){t.length>1&&(2!==t.length||!t.includes("null"))&&E(e,"use allowUnionTypes to allow union type keyword")}(e,t);!function(e,t){const n=e.self.RULES.all;for(const o in n){const s=n[o];if("object"==typeof s&&(0,r.shouldUseRule)(e.schema,s)){const{type:r}=s.definition;r.length&&!r.some(e=>b(t,e))&&E(e,`missing type "${r.join(",")}" for keyword "${o}"`)}}}(e,e.dataTypes)}(e,t),a.block(()=>{for(const e of m.rules)y(e);y(m.post)})):a.block(()=>S(e,"$ref",m.all.$ref.definition))}function $(e,t){const{gen:n,schema:s,opts:{useDefaults:a}}=e;a&&(0,o.assignDefaults)(e,t.type),n.block(()=>{for(const n of t.rules)(0,r.shouldUseRule)(s,n)&&S(e,n.keyword,n.definition,t.type)})}function b(e,t){return e.includes(t)||"number"===t&&e.includes("integer")}function k(e,t){return e.includes(t)||"integer"===t&&e.includes("number")}function E(e,t){t+=` at "${e.schemaEnv.baseId+e.errSchemaPath}" (strictTypes)`,(0,l.checkStrictMode)(e,t,e.opts.strictTypes)}lf.validateFunctionCode=function(t){y(t)&&(g(t),m(t))?function(e){const{schema:t,opts:r,gen:n}=e;h(e,()=>{r.$comment&&t.$comment&&_(e),function(e){const{schema:t,opts:r}=e;void 0!==t.default&&r.useDefaults&&r.strictSchema&&(0,l.checkStrictMode)(e,"default is ignored in the schema root")}(e),n.let(c.default.vErrors,null),n.let(c.default.errors,0),r.unevaluated&&function(e){const{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",i._`${r}.evaluated`),t.if(i._`${e.evaluated}.dynamicProps`,()=>t.assign(i._`${e.evaluated}.props`,i._`undefined`)),t.if(i._`${e.evaluated}.dynamicItems`,()=>t.assign(i._`${e.evaluated}.items`,i._`undefined`))}(e),v(e),function(e){const{gen:t,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=e;r.$async?t.if(i._`${c.default.errors} === 0`,()=>t.return(c.default.data),()=>t.throw(i._`new ${o}(${c.default.vErrors})`)):(t.assign(i._`${n}.errors`,c.default.vErrors),s.unevaluated&&function({gen:e,evaluated:t,props:r,items:n}){r instanceof i.Name&&e.assign(i._`${t}.props`,r);n instanceof i.Name&&e.assign(i._`${t}.items`,n)}(e),t.return(i._`${c.default.errors} === 0`))}(e)})}(t):h(t,()=>(0,e.topBoolOrEmptySchema)(t))};class P{constructor(e,t,r){if((0,s.validateKeywordUsage)(e,t,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,l.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const("vSchema",x(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,s.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw new Error(`${r} value must be ${JSON.stringify(t.schemaType)}`);("code"in t?t.trackErrors:!1!==t.errors)&&(this.errsCount=e.gen.const("_errs",c.default.errors))}result(e,t,r){this.failResult((0,i.not)(e),t,r)}failResult(e,t,r){this.gen.if(e),r?r():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,i.not)(e),void 0,t)}fail(e){if(void 0===e)return this.error(),void(this.allErrors||this.gen.if(!1));this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);const{schemaCode:t}=this;this.fail(i._`${t} !== undefined && (${(0,i.or)(this.invalid$data(),e)})`)}error(e,t,r){if(t)return this.setParams(t),this._error(e,r),void this.setParams({});this._error(e,r)}_error(e,t){(e?d.reportExtraError:d.reportError)(this,this.def.error,t)}$dataError(){(0,d.reportError)(this,this.def.$dataError||d.keyword$DataError)}reset(){if(void 0===this.errsCount)throw new Error('add "trackErrors" to keyword definition');(0,d.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,r=i.nil){this.gen.block(()=>{this.check$data(e,r),t()})}check$data(e=i.nil,t=i.nil){if(!this.$data)return;const{gen:r,schemaCode:n,schemaType:o,def:s}=this;r.if((0,i.or)(i._`${n} === undefined`,t)),e!==i.nil&&r.assign(e,!0),(o.length||s.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==i.nil&&r.assign(e,!1)),r.else()}invalid$data(){const{gen:e,schemaCode:t,schemaType:r,def:o,it:s}=this;return(0,i.or)(function(){if(r.length){if(!(t instanceof i.Name))throw new Error("ajv implementation error");const e=Array.isArray(r)?r:[r];return i._`${(0,n.checkDataTypes)(e,t,s.opts.strictNumbers,n.DataType.Wrong)}`}return i.nil}(),function(){if(o.validateSchema){const r=e.scopeValue("validate$data",{ref:o.validateSchema});return i._`!${r}(${t})`}return i.nil}())}subschema(e,t){const r=(0,a.getSubschema)(this.it,e);(0,a.extendSubschemaData)(r,this.it,e),(0,a.extendSubschemaMode)(r,e);const n={...this.it,...r,items:void 0,props:void 0};return f(n,t),n}mergeEvaluated(e,t){const{it:r,gen:n}=this;r.opts.unevaluated&&(!0!==r.props&&void 0!==e.props&&(r.props=l.mergeEvaluated.props(n,e.props,r.props,t)),!0!==r.items&&void 0!==e.items&&(r.items=l.mergeEvaluated.items(n,e.items,r.items,t)))}mergeValidEvaluated(e,t){const{it:r,gen:n}=this;if(r.opts.unevaluated&&(!0!==r.props||!0!==r.items))return n.if(t,()=>this.mergeEvaluated(e,i.Name)),!0}}function S(e,t,r,n){const o=new P(e,r,t);"code"in r?r.code(o,n):o.$data&&r.validate?(0,s.funcKeywordCode)(o,r):"macro"in r?(0,s.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,s.funcKeywordCode)(o,r)}lf.KeywordCxt=P;const T=/^\/(?:[^~]|~0|~1)*$/,I=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function x(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let o,s;if(""===e)return c.default.rootData;if("/"===e[0]){if(!T.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);o=e,s=c.default.rootData}else{const a=I.exec(e);if(!a)throw new Error(`Invalid JSON-pointer: ${e}`);const i=+a[1];if(o=a[2],"#"===o){if(i>=t)throw new Error(d("property/index",i));return n[t-i]}if(i>t)throw new Error(d("data",i));if(s=r[t-i],!o)return s}let a=s;const u=o.split("/");for(const e of u)e&&(s=i._`${s}${(0,i.getProperty)((0,l.unescapeJsonPointer)(e))}`,a=i._`${a} && ${s}`);return a;function d(e,r){return`Cannot access ${e} ${r} levels up, current level is ${t}`}}return lf.getData=x,lf}um.getSchemaRefs=function(e,t){if("boolean"==typeof e)return{};const{schemaId:r,uriResolver:n}=this.opts,o=Pm(e[r]||t),s={"":o},a=bm(n,o,!1),i={},c=new Set;return gm(e,{allKeys:!0},(e,t,n,o)=>{if(void 0===o)return;const d=a+t;let h=s[o];function p(t){const r=this.opts.uriResolver.resolve;if(t=Pm(h?r(h,t):t),c.has(t))throw l(t);c.add(t);let n=this.refs[t];return"string"==typeof n&&(n=this.refs[n]),"object"==typeof n?u(e,n.schema,t):t!==Pm(d)&&("#"===t[0]?(u(e,i[t],t),i[t]=e):this.refs[t]=d),t}function f(e){if("string"==typeof e){if(!Sm.test(e))throw new Error(`invalid anchor "${e}"`);p.call(this,`#${e}`)}}"string"==typeof e[r]&&(h=p.call(this,e[r])),f.call(this,e.$anchor),f.call(this,e.$dynamicAnchor),s[t]=h}),i;function u(e,t,r){if(void 0!==t&&!ym(e,t))throw l(r)}function l(e){return new Error(`reference "${e}" resolves to more than one schema`)}};var xm,Nm={};function Cm(){if(xm)return Nm;xm=1,Object.defineProperty(Nm,"__esModule",{value:!0});class e extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}}return Nm.default=e,Nm}var jm,Rm={};function Om(){if(jm)return Rm;jm=1,Object.defineProperty(Rm,"__esModule",{value:!0});const e=um;class t extends Error{constructor(t,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,e.resolveUrl)(t,r,n),this.missingSchema=(0,e.normalizeId)((0,e.getFullPath)(t,this.missingRef))}}return Rm.default=t,Rm}var zm={};Object.defineProperty(zm,"__esModule",{value:!0}),zm.resolveSchema=zm.getCompilingSchema=zm.resolveRef=zm.compileSchema=zm.SchemaEnv=void 0;const Am=pf,Mm=Cm(),Dm=Rf(),Um=um,qm=yf,Vm=Im();class Fm{constructor(e){var t;let r;this.refs={},this.dynamicAnchors={},"object"==typeof e.schema&&(r=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=null!==(t=e.baseId)&&void 0!==t?t:(0,Um.normalizeId)(null==r?void 0:r[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=null==r?void 0:r.$async,this.refs={}}}function Lm(e){const t=Hm.call(this,e);if(t)return t;const r=(0,Um.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,a=new Am.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s});let i;e.$async&&(i=a.scopeValue("Error",{ref:Mm.default,code:Am._`require("ajv/dist/runtime/validation_error").default`}));const c=a.scopeName("validate");e.validateName=c;const u={gen:a,allErrors:this.opts.allErrors,data:Dm.default.data,parentData:Dm.default.parentData,parentDataProperty:Dm.default.parentDataProperty,dataNames:[Dm.default.data],dataPathArr:[Am.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:a.scopeValue("schema",!0===this.opts.code.source?{ref:e.schema,code:(0,Am.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:i,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:Am.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:Am._`""`,opts:this.opts,self:this};let l;try{this._compilations.add(e),(0,Vm.validateFunctionCode)(u),a.optimize(this.opts.code.optimize);const t=a.toString();l=`${a.scopeRefs(Dm.default.scope)}return ${t}`,this.opts.code.process&&(l=this.opts.code.process(l,e));const r=new Function(`${Dm.default.self}`,`${Dm.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:r}),r.errors=null,r.schema=e.schema,r.schemaEnv=e,e.$async&&(r.$async=!0),!0===this.opts.code.source&&(r.source={validateName:c,validateCode:t,scopeValues:a._values}),this.opts.unevaluated){const{props:e,items:t}=u;r.evaluated={props:e instanceof Am.Name?void 0:e,items:t instanceof Am.Name?void 0:t,dynamicProps:e instanceof Am.Name,dynamicItems:t instanceof Am.Name},r.source&&(r.source.evaluated=(0,Am.stringify)(r.evaluated))}return e.validate=r,e}catch(t){throw delete e.validate,delete e.validateName,l&&this.logger.error("Error compiling schema, function code:",l),t}finally{this._compilations.delete(e)}}function Km(e){return(0,Um.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:Lm.call(this,e)}function Hm(e){for(const t of this._compilations)if(Zm(t,e))return t}function Zm(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function Gm(e,t){let r;for(;"string"==typeof(r=this.refs[t]);)t=r;return r||this.schemas[t]||Bm.call(this,e,t)}function Bm(e,t){const r=this.opts.uriResolver.parse(t),n=(0,Um._getFullPath)(this.opts.uriResolver,r);let o=(0,Um.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===o)return Wm.call(this,r,e);const s=(0,Um.normalizeId)(n),a=this.refs[s]||this.schemas[s];if("string"==typeof a){const t=Bm.call(this,e,a);if("object"!=typeof(null==t?void 0:t.schema))return;return Wm.call(this,r,t)}if("object"==typeof(null==a?void 0:a.schema)){if(a.validate||Lm.call(this,a),s===(0,Um.normalizeId)(t)){const{schema:t}=a,{schemaId:r}=this.opts,n=t[r];return n&&(o=(0,Um.resolveUrl)(this.opts.uriResolver,o,n)),new Fm({schema:t,schemaId:r,root:e,baseId:o})}return Wm.call(this,r,a)}}zm.SchemaEnv=Fm,zm.compileSchema=Lm,zm.resolveRef=function(e,t,r){var n;r=(0,Um.resolveUrl)(this.opts.uriResolver,t,r);const o=e.refs[r];if(o)return o;let s=Gm.call(this,e,r);if(void 0===s){const o=null===(n=e.localRefs)||void 0===n?void 0:n[r],{schemaId:a}=this.opts;o&&(s=new Fm({schema:o,schemaId:a,root:e,baseId:t}))}return void 0!==s?e.refs[r]=Km.call(this,s):void 0},zm.getCompilingSchema=Hm,zm.resolveSchema=Bm;const Jm=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Wm(e,{baseId:t,schema:r,root:n}){var o;if("/"!==(null===(o=e.fragment)||void 0===o?void 0:o[0]))return;for(const n of e.fragment.slice(1).split("/")){if("boolean"==typeof r)return;const e=r[(0,qm.unescapeFragment)(n)];if(void 0===e)return;const o="object"==typeof(r=e)&&r[this.opts.schemaId];!Jm.has(n)&&o&&(t=(0,Um.resolveUrl)(this.opts.uriResolver,t,o))}let s;if("boolean"!=typeof r&&r.$ref&&!(0,qm.schemaHasRulesButRef)(r,this.RULES)){const e=(0,Um.resolveUrl)(this.opts.uriResolver,t,r.$ref);s=Bm.call(this,n,e)}const{schemaId:a}=this.opts;return s=s||new Fm({schema:r,schemaId:a,root:n,baseId:t}),s.schema!==s.root.schema?s:void 0}var Qm={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1},Ym={};Object.defineProperty(Ym,"__esModule",{value:!0});const Xm=Il;Xm.code='require("ajv/dist/runtime/uri").default',Ym.default=Xm,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=Im();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var r=pf;Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return r.CodeGen}});const n=Cm(),o=Om(),s=Af,a=zm,i=pf,c=um,u=zf,l=yf,d=Qm,h=Ym,p=(e,t)=>new RegExp(e,t);p.code="new RegExp";const f=["removeAdditional","useDefaults","coerceTypes"],m=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),y={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},g={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'};function v(e){var t,r,n,o,s,a,i,c,u,l,d,f,m,y,g,v,_,w,$,b,k,E,P,S,T;const I=e.strict,x=null===(t=e.code)||void 0===t?void 0:t.optimize,N=!0===x||void 0===x?1:x||0,C=null!==(n=null===(r=e.code)||void 0===r?void 0:r.regExp)&&void 0!==n?n:p,j=null!==(o=e.uriResolver)&&void 0!==o?o:h.default;return{strictSchema:null===(a=null!==(s=e.strictSchema)&&void 0!==s?s:I)||void 0===a||a,strictNumbers:null===(c=null!==(i=e.strictNumbers)&&void 0!==i?i:I)||void 0===c||c,strictTypes:null!==(l=null!==(u=e.strictTypes)&&void 0!==u?u:I)&&void 0!==l?l:"log",strictTuples:null!==(f=null!==(d=e.strictTuples)&&void 0!==d?d:I)&&void 0!==f?f:"log",strictRequired:null!==(y=null!==(m=e.strictRequired)&&void 0!==m?m:I)&&void 0!==y&&y,code:e.code?{...e.code,optimize:N,regExp:C}:{optimize:N,regExp:C},loopRequired:null!==(g=e.loopRequired)&&void 0!==g?g:200,loopEnum:null!==(v=e.loopEnum)&&void 0!==v?v:200,meta:null===(_=e.meta)||void 0===_||_,messages:null===(w=e.messages)||void 0===w||w,inlineRefs:null===($=e.inlineRefs)||void 0===$||$,schemaId:null!==(b=e.schemaId)&&void 0!==b?b:"$id",addUsedSchema:null===(k=e.addUsedSchema)||void 0===k||k,validateSchema:null===(E=e.validateSchema)||void 0===E||E,validateFormats:null===(P=e.validateFormats)||void 0===P||P,unicodeRegExp:null===(S=e.unicodeRegExp)||void 0===S||S,int32range:null===(T=e.int32range)||void 0===T||T,uriResolver:j}}class _{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...v(e)};const{es5:t,lines:r}=this.opts.code;this.scope=new i.ValueScope({scope:{},prefixes:m,es5:t,lines:r}),this.logger=function(e){if(!1===e)return S;if(void 0===e)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}(e.logger);const n=e.validateFormats;e.validateFormats=!1,this.RULES=(0,s.getRules)(),w.call(this,y,e,"NOT SUPPORTED"),w.call(this,g,e,"DEPRECATED","warn"),this._metaOpts=P.call(this),e.formats&&k.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&E.call(this,e.keywords),"object"==typeof e.meta&&this.addMetaSchema(e.meta),b.call(this),e.validateFormats=n}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:e,meta:t,schemaId:r}=this.opts;let n=d;"id"===r&&(n={...d},n.id=n.$id,delete n.$id),t&&e&&this.addMetaSchema(n,n[r],!1)}defaultMeta(){const{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta="object"==typeof e?e[t]||e:void 0}validate(e,t){let r;if("string"==typeof e){if(r=this.getSchema(e),!r)throw new Error(`no schema with key or ref "${e}"`)}else r=this.compile(e);const n=r(t);return"$async"in r||(this.errors=r.errors),n}compile(e,t){const r=this._addSchema(e,t);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,t){if("function"!=typeof this.opts.loadSchema)throw new Error("options.loadSchema should be a function");const{loadSchema:r}=this.opts;return n.call(this,e,t);async function n(e,t){await s.call(this,e.$schema);const r=this._addSchema(e,t);return r.validate||a.call(this,r)}async function s(e){e&&!this.getSchema(e)&&await n.call(this,{$ref:e},!0)}async function a(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof o.default))throw t;return i.call(this,t),await c.call(this,t.missingSchema),a.call(this,e)}}function i({missingSchema:e,missingRef:t}){if(this.refs[e])throw new Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function c(e){const r=await u.call(this,e);this.refs[e]||await s.call(this,r.$schema),this.refs[e]||this.addSchema(r,e,t)}async function u(e){const t=this._loading[e];if(t)return t;try{return await(this._loading[e]=r(e))}finally{delete this._loading[e]}}}addSchema(e,t,r,n=this.opts.validateSchema){if(Array.isArray(e)){for(const t of e)this.addSchema(t,void 0,r,n);return this}let o;if("object"==typeof e){const{schemaId:t}=this.opts;if(o=e[t],void 0!==o&&"string"!=typeof o)throw new Error(`schema ${t} must be string`)}return t=(0,c.normalizeId)(t||o),this._checkUnique(t),this.schemas[t]=this._addSchema(e,r,t,n,!0),this}addMetaSchema(e,t,r=this.opts.validateSchema){return this.addSchema(e,t,!0,r),this}validateSchema(e,t){if("boolean"==typeof e)return!0;let r;if(r=e.$schema,void 0!==r&&"string"!=typeof r)throw new Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const n=this.validate(r,e);if(!n&&t){const e="schema is invalid: "+this.errorsText();if("log"!==this.opts.validateSchema)throw new Error(e);this.logger.error(e)}return n}getSchema(e){let t;for(;"string"==typeof(t=$.call(this,e));)e=t;if(void 0===t){const{schemaId:r}=this.opts,n=new a.SchemaEnv({schema:{},schemaId:r});if(t=a.resolveSchema.call(this,n,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const t=$.call(this,e);return"object"==typeof t&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{const t=e;this._cache.delete(t);let r=e[this.opts.schemaId];return r&&(r=(0,c.normalizeId)(r),delete this.schemas[r],delete this.refs[r]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(const t of e)this.addKeyword(t);return this}addKeyword(e,t){let r;if("string"==typeof e)r=e,"object"==typeof t&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=r);else{if("object"!=typeof e||void 0!==t)throw new Error("invalid addKeywords parameters");if(r=(t=e).keyword,Array.isArray(r)&&!r.length)throw new Error("addKeywords: keyword must be string or non-empty array")}if(I.call(this,r,t),!t)return(0,l.eachItem)(r,e=>x.call(this,e)),this;C.call(this,t);const n={...t,type:(0,u.getJSONTypes)(t.type),schemaType:(0,u.getJSONTypes)(t.schemaType)};return(0,l.eachItem)(r,0===n.type.length?e=>x.call(this,e,n):e=>n.type.forEach(t=>x.call(this,e,n,t))),this}getKeyword(e){const t=this.RULES.all[e];return"object"==typeof t?t.definition:!!t}removeKeyword(e){const{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(const r of t.rules){const t=r.rules.findIndex(t=>t.keyword===e);t>=0&&r.rules.splice(t,1)}return this}addFormat(e,t){return"string"==typeof t&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=", ",dataVar:r="data"}={}){return e&&0!==e.length?e.map(e=>`${r}${e.instancePath} ${e.message}`).reduce((e,r)=>e+t+r):"No errors"}$dataMetaSchema(e,t){const r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(const n of t){const t=n.split("/").slice(1);let o=e;for(const e of t)o=o[e];for(const e in r){const t=r[e];if("object"!=typeof t)continue;const{$data:n}=t.definition,s=o[e];n&&s&&(o[e]=R(s))}}return e}_removeAllSchemas(e,t){for(const r in e){const n=e[r];t&&!t.test(r)||("string"==typeof n?delete e[r]:n&&!n.meta&&(this._cache.delete(n.schema),delete e[r]))}}_addSchema(e,t,r,n=this.opts.validateSchema,o=this.opts.addUsedSchema){let s;const{schemaId:i}=this.opts;if("object"==typeof e)s=e[i];else{if(this.opts.jtd)throw new Error("schema must be object");if("boolean"!=typeof e)throw new Error("schema must be object or boolean")}let u=this._cache.get(e);if(void 0!==u)return u;r=(0,c.normalizeId)(s||r);const l=c.getSchemaRefs.call(this,e,r);return u=new a.SchemaEnv({schema:e,schemaId:i,meta:t,baseId:r,localRefs:l}),this._cache.set(u.schema,u),o&&!r.startsWith("#")&&(r&&this._checkUnique(r),this.refs[r]=u),n&&this.validateSchema(e,!0),u}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):a.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){const t=this.opts;this.opts=this._metaOpts;try{a.compileSchema.call(this,e)}finally{this.opts=t}}}function w(e,t,r,n="error"){for(const o in e){const s=o;s in t&&this.logger[n](`${r}: option ${o}. ${e[s]}`)}}function $(e){return e=(0,c.normalizeId)(e),this.schemas[e]||this.refs[e]}function b(){const e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(const t in e)this.addSchema(e[t],t)}function k(){for(const e in this.opts.formats){const t=this.opts.formats[e];t&&this.addFormat(e,t)}}function E(e){if(Array.isArray(e))this.addVocabulary(e);else{this.logger.warn("keywords option as map is deprecated, pass array");for(const t in e){const r=e[t];r.keyword||(r.keyword=t),this.addKeyword(r)}}}function P(){const e={...this.opts};for(const t of f)delete e[t];return e}_.ValidationError=n.default,_.MissingRefError=o.default,e.default=_;const S={log(){},warn(){},error(){}};const T=/^[a-z_$][a-z0-9_$:-]*$/i;function I(e,t){const{RULES:r}=this;if((0,l.eachItem)(e,e=>{if(r.keywords[e])throw new Error(`Keyword ${e} is already defined`);if(!T.test(e))throw new Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!("code"in t)&&!("validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}function x(e,t,r){var n;const o=null==t?void 0:t.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:s}=this;let a=o?s.post:s.rules.find(({type:e})=>e===r);if(a||(a={type:r,rules:[]},s.rules.push(a)),s.keywords[e]=!0,!t)return;const i={keyword:e,definition:{...t,type:(0,u.getJSONTypes)(t.type),schemaType:(0,u.getJSONTypes)(t.schemaType)}};t.before?N.call(this,a,i,t.before):a.rules.push(i),s.all[e]=i,null===(n=t.implements)||void 0===n||n.forEach(e=>this.addKeyword(e))}function N(e,t,r){const n=e.rules.findIndex(e=>e.keyword===r);n>=0?e.rules.splice(n,0,t):(e.rules.push(t),this.logger.warn(`rule ${r} is not defined`))}function C(e){let{metaSchema:t}=e;void 0!==t&&(e.$data&&this.opts.$data&&(t=R(t)),e.validateSchema=this.compile(t,!0))}const j={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function R(e){return{anyOf:[e,j]}}}(uf);var ey={},ty={},ry={};Object.defineProperty(ry,"__esModule",{value:!0});const ny={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};ry.default=ny;var oy={};Object.defineProperty(oy,"__esModule",{value:!0}),oy.callRef=oy.getValidate=void 0;const sy=Om(),ay=sm(),iy=pf,cy=Rf(),uy=zm,ly=yf,dy={keyword:"$ref",schemaType:"string",code(e){const{gen:t,schema:r,it:n}=e,{baseId:o,schemaEnv:s,validateName:a,opts:i,self:c}=n,{root:u}=s;if(("#"===r||"#/"===r)&&o===u.baseId)return function(){if(s===u)return py(e,a,s,s.$async);const r=t.scopeValue("root",{ref:u});return py(e,iy._`${r}.validate`,u,u.$async)}();const l=uy.resolveRef.call(c,u,o,r);if(void 0===l)throw new sy.default(n.opts.uriResolver,o,r);return l instanceof uy.SchemaEnv?function(t){const r=hy(e,t);py(e,r,t,t.$async)}(l):function(n){const o=t.scopeValue("schema",!0===i.code.source?{ref:n,code:(0,iy.stringify)(n)}:{ref:n}),s=t.name("valid"),a=e.subschema({schema:n,dataTypes:[],schemaPath:iy.nil,topSchemaRef:o,errSchemaPath:r},s);e.mergeEvaluated(a),e.ok(s)}(l)}};function hy(e,t){const{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):iy._`${r.scopeValue("wrapper",{ref:t})}.validate`}function py(e,t,r,n){const{gen:o,it:s}=e,{allErrors:a,schemaEnv:i,opts:c}=s,u=c.passContext?cy.default.this:iy.nil;function l(e){const t=iy._`${e}.errors`;o.assign(cy.default.vErrors,iy._`${cy.default.vErrors} === null ? ${t} : ${cy.default.vErrors}.concat(${t})`),o.assign(cy.default.errors,iy._`${cy.default.vErrors}.length`)}function d(e){var t;if(!s.opts.unevaluated)return;const n=null===(t=null==r?void 0:r.validate)||void 0===t?void 0:t.evaluated;if(!0!==s.props)if(n&&!n.dynamicProps)void 0!==n.props&&(s.props=ly.mergeEvaluated.props(o,n.props,s.props));else{const t=o.var("props",iy._`${e}.evaluated.props`);s.props=ly.mergeEvaluated.props(o,t,s.props,iy.Name)}if(!0!==s.items)if(n&&!n.dynamicItems)void 0!==n.items&&(s.items=ly.mergeEvaluated.items(o,n.items,s.items));else{const t=o.var("items",iy._`${e}.evaluated.items`);s.items=ly.mergeEvaluated.items(o,t,s.items,iy.Name)}}n?function(){if(!i.$async)throw new Error("async schema referenced by sync schema");const r=o.let("valid");o.try(()=>{o.code(iy._`await ${(0,ay.callValidateCode)(e,t,u)}`),d(t),a||o.assign(r,!0)},e=>{o.if(iy._`!(${e} instanceof ${s.ValidationError})`,()=>o.throw(e)),l(e),a||o.assign(r,!1)}),e.ok(r)}():e.result((0,ay.callValidateCode)(e,t,u),()=>d(t),()=>l(t))}oy.getValidate=hy,oy.callRef=py,oy.default=dy,Object.defineProperty(ty,"__esModule",{value:!0});const fy=oy,my=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",ry.default,fy.default];ty.default=my;var yy={},gy={};Object.defineProperty(gy,"__esModule",{value:!0});const vy=pf,_y=vy.operators,wy={maximum:{okStr:"<=",ok:_y.LTE,fail:_y.GT},minimum:{okStr:">=",ok:_y.GTE,fail:_y.LT},exclusiveMaximum:{okStr:"<",ok:_y.LT,fail:_y.GTE},exclusiveMinimum:{okStr:">",ok:_y.GT,fail:_y.LTE}},$y={message:({keyword:e,schemaCode:t})=>vy.str`must be ${wy[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>vy._`{comparison: ${wy[e].okStr}, limit: ${t}}`},by={keyword:Object.keys(wy),type:"number",schemaType:"number",$data:!0,error:$y,code(e){const{keyword:t,data:r,schemaCode:n}=e;e.fail$data(vy._`${r} ${wy[t].fail} ${n} || isNaN(${r})`)}};gy.default=by;var ky={};Object.defineProperty(ky,"__esModule",{value:!0});const Ey=pf,Py={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:e})=>Ey.str`must be multiple of ${e}`,params:({schemaCode:e})=>Ey._`{multipleOf: ${e}}`},code(e){const{gen:t,data:r,schemaCode:n,it:o}=e,s=o.opts.multipleOfPrecision,a=t.let("res"),i=s?Ey._`Math.abs(Math.round(${a}) - ${a}) > 1e-${s}`:Ey._`${a} !== parseInt(${a})`;e.fail$data(Ey._`(${n} === 0 || (${a} = ${r}/${n}, ${i}))`)}};ky.default=Py;var Sy={},Ty={};function Iy(e){const t=e.length;let r,n=0,o=0;for(;o<t;)n++,r=e.charCodeAt(o++),r>=55296&&r<=56319&&o<t&&(r=e.charCodeAt(o),56320==(64512&r)&&o++);return n}Object.defineProperty(Ty,"__esModule",{value:!0}),Ty.default=Iy,Iy.code='require("ajv/dist/runtime/ucs2length").default',Object.defineProperty(Sy,"__esModule",{value:!0});const xy=pf,Ny=yf,Cy=Ty,jy={message:({keyword:e,schemaCode:t})=>xy.str`must NOT have ${"maxLength"===e?"more":"fewer"} than ${t} characters`,params:({schemaCode:e})=>xy._`{limit: ${e}}`},Ry={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:jy,code(e){const{keyword:t,data:r,schemaCode:n,it:o}=e,s="maxLength"===t?xy.operators.GT:xy.operators.LT,a=!1===o.opts.unicode?xy._`${r}.length`:xy._`${(0,Ny.useFunc)(e.gen,Cy.default)}(${r})`;e.fail$data(xy._`${a} ${s} ${n}`)}};Sy.default=Ry;var Oy={};Object.defineProperty(Oy,"__esModule",{value:!0});const zy=sm(),Ay=yf,My=pf,Dy={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>My.str`must match pattern "${e}"`,params:({schemaCode:e})=>My._`{pattern: ${e}}`},code(e){const{gen:t,data:r,$data:n,schema:o,schemaCode:s,it:a}=e,i=a.opts.unicodeRegExp?"u":"";if(n){const{regExp:n}=a.opts.code,o="new RegExp"===n.code?My._`new RegExp`:(0,Ay.useFunc)(t,n),c=t.let("valid");t.try(()=>t.assign(c,My._`${o}(${s}, ${i}).test(${r})`),()=>t.assign(c,!1)),e.fail$data(My._`!${c}`)}else{const t=(0,zy.usePattern)(e,o);e.fail$data(My._`!${t}.test(${r})`)}}};Oy.default=Dy;var Uy={};Object.defineProperty(Uy,"__esModule",{value:!0});const qy=pf,Vy={message:({keyword:e,schemaCode:t})=>qy.str`must NOT have ${"maxProperties"===e?"more":"fewer"} than ${t} properties`,params:({schemaCode:e})=>qy._`{limit: ${e}}`},Fy={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:Vy,code(e){const{keyword:t,data:r,schemaCode:n}=e,o="maxProperties"===t?qy.operators.GT:qy.operators.LT;e.fail$data(qy._`Object.keys(${r}).length ${o} ${n}`)}};Uy.default=Fy;var Ly={};Object.defineProperty(Ly,"__esModule",{value:!0});const Ky=sm(),Hy=pf,Zy=yf,Gy={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:e}})=>Hy.str`must have required property '${e}'`,params:({params:{missingProperty:e}})=>Hy._`{missingProperty: ${e}}`},code(e){const{gen:t,schema:r,schemaCode:n,data:o,$data:s,it:a}=e,{opts:i}=a;if(!s&&0===r.length)return;const c=r.length>=i.loopRequired;if(a.allErrors?function(){if(c||s)e.block$data(Hy.nil,u);else for(const t of r)(0,Ky.checkReportMissingProp)(e,t)}():function(){const a=t.let("missing");if(c||s){const r=t.let("valid",!0);e.block$data(r,()=>function(r,s){e.setParams({missingProperty:r}),t.forOf(r,n,()=>{t.assign(s,(0,Ky.propertyInData)(t,o,r,i.ownProperties)),t.if((0,Hy.not)(s),()=>{e.error(),t.break()})},Hy.nil)}(a,r)),e.ok(r)}else t.if((0,Ky.checkMissingProp)(e,r,a)),(0,Ky.reportMissingProp)(e,a),t.else()}(),i.strictRequired){const t=e.parentSchema.properties,{definedProperties:n}=e.it;for(const e of r)if(void 0===(null==t?void 0:t[e])&&!n.has(e)){const t=`required property "${e}" is not defined at "${a.schemaEnv.baseId+a.errSchemaPath}" (strictRequired)`;(0,Zy.checkStrictMode)(a,t,a.opts.strictRequired)}}function u(){t.forOf("prop",n,r=>{e.setParams({missingProperty:r}),t.if((0,Ky.noPropertyInData)(t,o,r,i.ownProperties),()=>e.error())})}}};Ly.default=Gy;var By={};Object.defineProperty(By,"__esModule",{value:!0});const Jy=pf,Wy={message:({keyword:e,schemaCode:t})=>Jy.str`must NOT have ${"maxItems"===e?"more":"fewer"} than ${t} items`,params:({schemaCode:e})=>Jy._`{limit: ${e}}`},Qy={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Wy,code(e){const{keyword:t,data:r,schemaCode:n}=e,o="maxItems"===t?Jy.operators.GT:Jy.operators.LT;e.fail$data(Jy._`${r}.length ${o} ${n}`)}};By.default=Qy;var Yy={},Xy={};Object.defineProperty(Xy,"__esModule",{value:!0});const eg=au;eg.code='require("ajv/dist/runtime/equal").default',Xy.default=eg,Object.defineProperty(Yy,"__esModule",{value:!0});const tg=zf,rg=pf,ng=yf,og=Xy,sg={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:e,j:t}})=>rg.str`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>rg._`{i: ${e}, j: ${t}}`},code(e){const{gen:t,data:r,$data:n,schema:o,parentSchema:s,schemaCode:a,it:i}=e;if(!n&&!o)return;const c=t.let("valid"),u=s.items?(0,tg.getSchemaTypes)(s.items):[];function l(n,o){const s=t.name("item"),a=(0,tg.checkDataTypes)(u,s,i.opts.strictNumbers,tg.DataType.Wrong),l=t.const("indices",rg._`{}`);t.for(rg._`;${n}--;`,()=>{t.let(s,rg._`${r}[${n}]`),t.if(a,rg._`continue`),u.length>1&&t.if(rg._`typeof ${s} == "string"`,rg._`${s} += "_"`),t.if(rg._`typeof ${l}[${s}] == "number"`,()=>{t.assign(o,rg._`${l}[${s}]`),e.error(),t.assign(c,!1).break()}).code(rg._`${l}[${s}] = ${n}`)})}function d(n,o){const s=(0,ng.useFunc)(t,og.default),a=t.name("outer");t.label(a).for(rg._`;${n}--;`,()=>t.for(rg._`${o} = ${n}; ${o}--;`,()=>t.if(rg._`${s}(${r}[${n}], ${r}[${o}])`,()=>{e.error(),t.assign(c,!1).break(a)})))}e.block$data(c,function(){const n=t.let("i",rg._`${r}.length`),o=t.let("j");e.setParams({i:n,j:o}),t.assign(c,!0),t.if(rg._`${n} > 1`,()=>(u.length>0&&!u.some(e=>"object"===e||"array"===e)?l:d)(n,o))},rg._`${a} === false`),e.ok(c)}};Yy.default=sg;var ag={};Object.defineProperty(ag,"__esModule",{value:!0});const ig=pf,cg=yf,ug=Xy,lg={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:e})=>ig._`{allowedValue: ${e}}`},code(e){const{gen:t,data:r,$data:n,schemaCode:o,schema:s}=e;n||s&&"object"==typeof s?e.fail$data(ig._`!${(0,cg.useFunc)(t,ug.default)}(${r}, ${o})`):e.fail(ig._`${s} !== ${r}`)}};ag.default=lg;var dg={};Object.defineProperty(dg,"__esModule",{value:!0});const hg=pf,pg=yf,fg=Xy,mg={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:e})=>hg._`{allowedValues: ${e}}`},code(e){const{gen:t,data:r,$data:n,schema:o,schemaCode:s,it:a}=e;if(!n&&0===o.length)throw new Error("enum must have non-empty array");const i=o.length>=a.opts.loopEnum;let c;const u=()=>null!=c?c:c=(0,pg.useFunc)(t,fg.default);let l;if(i||n)l=t.let("valid"),e.block$data(l,function(){t.assign(l,!1),t.forOf("v",s,e=>t.if(hg._`${u()}(${r}, ${e})`,()=>t.assign(l,!0).break()))});else{if(!Array.isArray(o))throw new Error("ajv implementation error");const e=t.const("vSchema",s);l=(0,hg.or)(...o.map((t,n)=>function(e,t){const n=o[t];return"object"==typeof n&&null!==n?hg._`${u()}(${r}, ${e}[${t}])`:hg._`${r} === ${n}`}(e,n)))}e.pass(l)}};dg.default=mg,Object.defineProperty(yy,"__esModule",{value:!0});const yg=ky,gg=Sy,vg=Oy,_g=Uy,wg=Ly,$g=By,bg=Yy,kg=ag,Eg=dg,Pg=[gy.default,yg.default,gg.default,vg.default,_g.default,wg.default,$g.default,bg.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},kg.default,Eg.default];yy.default=Pg;var Sg={},Tg={};Object.defineProperty(Tg,"__esModule",{value:!0}),Tg.validateAdditionalItems=void 0;const Ig=pf,xg=yf,Ng={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:e}})=>Ig.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>Ig._`{limit: ${e}}`},code(e){const{parentSchema:t,it:r}=e,{items:n}=t;Array.isArray(n)?Cg(e,n):(0,xg.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas')}};function Cg(e,t){const{gen:r,schema:n,data:o,keyword:s,it:a}=e;a.items=!0;const i=r.const("len",Ig._`${o}.length`);if(!1===n)e.setParams({len:t.length}),e.pass(Ig._`${i} <= ${t.length}`);else if("object"==typeof n&&!(0,xg.alwaysValidSchema)(a,n)){const n=r.var("valid",Ig._`${i} <= ${t.length}`);r.if((0,Ig.not)(n),()=>function(n){r.forRange("i",t.length,i,t=>{e.subschema({keyword:s,dataProp:t,dataPropType:xg.Type.Num},n),a.allErrors||r.if((0,Ig.not)(n),()=>r.break())})}(n)),e.ok(n)}}Tg.validateAdditionalItems=Cg,Tg.default=Ng;var jg={},Rg={};Object.defineProperty(Rg,"__esModule",{value:!0}),Rg.validateTuple=void 0;const Og=pf,zg=yf,Ag=sm(),Mg={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){const{schema:t,it:r}=e;if(Array.isArray(t))return Dg(e,"additionalItems",t);r.items=!0,(0,zg.alwaysValidSchema)(r,t)||e.ok((0,Ag.validateArray)(e))}};function Dg(e,t,r=e.schema){const{gen:n,parentSchema:o,data:s,keyword:a,it:i}=e;!function(e){const{opts:n,errSchemaPath:o}=i,s=r.length,c=s===e.minItems&&(s===e.maxItems||!1===e[t]);if(n.strictTuples&&!c){const e=`"${a}" is ${s}-tuple, but minItems or maxItems/${t} are not specified or different at path "${o}"`;(0,zg.checkStrictMode)(i,e,n.strictTuples)}}(o),i.opts.unevaluated&&r.length&&!0!==i.items&&(i.items=zg.mergeEvaluated.items(n,r.length,i.items));const c=n.name("valid"),u=n.const("len",Og._`${s}.length`);r.forEach((t,r)=>{(0,zg.alwaysValidSchema)(i,t)||(n.if(Og._`${u} > ${r}`,()=>e.subschema({keyword:a,schemaProp:r,dataProp:r},c)),e.ok(c))})}Rg.validateTuple=Dg,Rg.default=Mg,Object.defineProperty(jg,"__esModule",{value:!0});const Ug=Rg,qg={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,Ug.validateTuple)(e,"items")};jg.default=qg;var Vg={};Object.defineProperty(Vg,"__esModule",{value:!0});const Fg=pf,Lg=yf,Kg=sm(),Hg=Tg,Zg={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:e}})=>Fg.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>Fg._`{limit: ${e}}`},code(e){const{schema:t,parentSchema:r,it:n}=e,{prefixItems:o}=r;n.items=!0,(0,Lg.alwaysValidSchema)(n,t)||(o?(0,Hg.validateAdditionalItems)(e,o):e.ok((0,Kg.validateArray)(e)))}};Vg.default=Zg;var Gg={};Object.defineProperty(Gg,"__esModule",{value:!0});const Bg=pf,Jg=yf,Wg={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:e,max:t}})=>void 0===t?Bg.str`must contain at least ${e} valid item(s)`:Bg.str`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>void 0===t?Bg._`{minContains: ${e}}`:Bg._`{minContains: ${e}, maxContains: ${t}}`},code(e){const{gen:t,schema:r,parentSchema:n,data:o,it:s}=e;let a,i;const{minContains:c,maxContains:u}=n;s.opts.next?(a=void 0===c?1:c,i=u):a=1;const l=t.const("len",Bg._`${o}.length`);if(e.setParams({min:a,max:i}),void 0===i&&0===a)return void(0,Jg.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');if(void 0!==i&&a>i)return(0,Jg.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),void e.fail();if((0,Jg.alwaysValidSchema)(s,r)){let t=Bg._`${l} >= ${a}`;return void 0!==i&&(t=Bg._`${t} && ${l} <= ${i}`),void e.pass(t)}s.items=!0;const d=t.name("valid");function h(){const e=t.name("_valid"),r=t.let("count",0);p(e,()=>t.if(e,()=>function(e){t.code(Bg._`${e}++`),void 0===i?t.if(Bg._`${e} >= ${a}`,()=>t.assign(d,!0).break()):(t.if(Bg._`${e} > ${i}`,()=>t.assign(d,!1).break()),1===a?t.assign(d,!0):t.if(Bg._`${e} >= ${a}`,()=>t.assign(d,!0)))}(r)))}function p(r,n){t.forRange("i",0,l,t=>{e.subschema({keyword:"contains",dataProp:t,dataPropType:Jg.Type.Num,compositeRule:!0},r),n()})}void 0===i&&1===a?p(d,()=>t.if(d,()=>t.break())):0===a?(t.let(d,!0),void 0!==i&&t.if(Bg._`${o}.length > 0`,h)):(t.let(d,!1),h()),e.result(d,()=>e.reset())}};Gg.default=Wg;var Qg={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=pf,r=yf,n=sm();e.error={message:({params:{property:e,depsCount:r,deps:n}})=>t.str`must have ${1===r?"property":"properties"} ${n} when property ${e} is present`,params:({params:{property:e,depsCount:r,deps:n,missingProperty:o}})=>t._`{property: ${e},
11
+ missingProperty: ${o},
12
12
  depsCount: ${r},
13
- deps: ${o}}`};const n={keyword:"dependencies",type:"object",schemaType:"object",error:e.error,code(e){const[t,r]=function({schema:e}){const t={},r={};for(const o in e){if("__proto__"===o)continue;(Array.isArray(e[o])?t:r)[o]=e[o]}return[t,r]}(e);s(e,t),a(e,r)}};function s(e,r=e.schema){const{gen:n,data:s,it:a}=e;if(0===Object.keys(r).length)return;const i=n.let("missing");for(const c in r){const u=r[c];if(0===u.length)continue;const l=(0,o.propertyInData)(n,s,c,a.opts.ownProperties);e.setParams({property:c,depsCount:u.length,deps:u.join(", ")}),a.allErrors?n.if(l,()=>{for(const t of u)(0,o.checkReportMissingProp)(e,t)}):(n.if(t._`${l} && (${(0,o.checkMissingProp)(e,u,i)})`),(0,o.reportMissingProp)(e,i),n.else())}}function a(e,t=e.schema){const{gen:n,data:s,keyword:a,it:i}=e,c=n.name("valid");for(const u in t)(0,r.alwaysValidSchema)(i,t[u])||(n.if((0,o.propertyInData)(n,s,u,i.opts.ownProperties),()=>{const t=e.subschema({keyword:a,schemaProp:u},c);e.mergeValidEvaluated(t,c)},()=>n.var(c,!0)),e.ok(c))}e.validatePropertyDeps=s,e.validateSchemaDeps=a,e.default=n}(Gg);var Bg={};Object.defineProperty(Bg,"__esModule",{value:!0});const Jg=lf,Wg=pf,Qg={message:"property name must be valid",params:({params:e})=>Jg._`{propertyName: ${e.propertyName}}`},Yg={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Qg,code(e){const{gen:t,schema:r,data:o,it:n}=e;if((0,Wg.alwaysValidSchema)(n,r))return;const s=t.name("valid");t.forIn("key",o,r=>{e.setParams({propertyName:r}),e.subschema({keyword:"propertyNames",data:r,dataTypes:["string"],propertyName:r,compositeRule:!0},s),t.if((0,Jg.not)(s),()=>{e.error(!0),n.allErrors||t.break()})}),e.ok(s)}};Bg.default=Yg;var Xg={};Object.defineProperty(Xg,"__esModule",{value:!0});const ev=rm(),tv=lf,rv=Nf(),ov=pf,nv={message:"must NOT have additional properties",params:({params:e})=>tv._`{additionalProperty: ${e.additionalProperty}}`},sv={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:nv,code(e){const{gen:t,schema:r,parentSchema:o,data:n,errsCount:s,it:a}=e;if(!s)throw new Error("ajv implementation error");const{allErrors:i,opts:c}=a;if(a.props=!0,"all"!==c.removeAdditional&&(0,ov.alwaysValidSchema)(a,r))return;const u=(0,ev.allSchemaProperties)(o.properties),l=(0,ev.allSchemaProperties)(o.patternProperties);function d(e){t.code(tv._`delete ${n}[${e}]`)}function h(o){if("all"===c.removeAdditional||c.removeAdditional&&!1===r)d(o);else{if(!1===r)return e.setParams({additionalProperty:o}),e.error(),void(i||t.break());if("object"==typeof r&&!(0,ov.alwaysValidSchema)(a,r)){const r=t.name("valid");"failing"===c.removeAdditional?(p(o,r,!1),t.if((0,tv.not)(r),()=>{e.reset(),d(o)})):(p(o,r),i||t.if((0,tv.not)(r),()=>t.break()))}}}function p(t,r,o){const n={keyword:"additionalProperties",dataProp:t,dataPropType:ov.Type.Str};!1===o&&Object.assign(n,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(n,r)}t.forIn("key",n,r=>{u.length||l.length?t.if(function(r){let n;if(u.length>8){const e=(0,ov.schemaRefOrVal)(a,o.properties,"properties");n=(0,ev.isOwnProperty)(t,e,r)}else n=u.length?(0,tv.or)(...u.map(e=>tv._`${r} === ${e}`)):tv.nil;return l.length&&(n=(0,tv.or)(n,...l.map(t=>tv._`${(0,ev.usePattern)(e,t)}.test(${r})`))),(0,tv.not)(n)}(r),()=>h(r)):h(r)}),e.ok(tv._`${s} === ${rv.default.errors}`)}};Xg.default=sv;var av={};Object.defineProperty(av,"__esModule",{value:!0});const iv=Sm(),cv=rm(),uv=pf,lv=Xg,dv={keyword:"properties",type:"object",schemaType:"object",code(e){const{gen:t,schema:r,parentSchema:o,data:n,it:s}=e;"all"===s.opts.removeAdditional&&void 0===o.additionalProperties&&lv.default.code(new iv.KeywordCxt(s,lv.default,"additionalProperties"));const a=(0,cv.allSchemaProperties)(r);for(const e of a)s.definedProperties.add(e);s.opts.unevaluated&&a.length&&!0!==s.props&&(s.props=uv.mergeEvaluated.props(t,(0,uv.toHash)(a),s.props));const i=a.filter(e=>!(0,uv.alwaysValidSchema)(s,r[e]));if(0===i.length)return;const c=t.name("valid");for(const r of i)u(r)?l(r):(t.if((0,cv.propertyInData)(t,n,r,s.opts.ownProperties)),l(r),s.allErrors||t.else().var(c,!0),t.endIf()),e.it.definedProperties.add(r),e.ok(c);function u(e){return s.opts.useDefaults&&!s.compositeRule&&void 0!==r[e].default}function l(t){e.subschema({keyword:"properties",schemaProp:t,dataProp:t},c)}}};av.default=dv;var hv={};Object.defineProperty(hv,"__esModule",{value:!0});const pv=rm(),fv=lf,mv=pf,yv=pf,gv={keyword:"patternProperties",type:"object",schemaType:"object",code(e){const{gen:t,schema:r,data:o,parentSchema:n,it:s}=e,{opts:a}=s,i=(0,pv.allSchemaProperties)(r),c=i.filter(e=>(0,mv.alwaysValidSchema)(s,r[e]));if(0===i.length||c.length===i.length&&(!s.opts.unevaluated||!0===s.props))return;const u=a.strictSchema&&!a.allowMatchingProperties&&n.properties,l=t.name("valid");!0===s.props||s.props instanceof fv.Name||(s.props=(0,yv.evaluatedPropsToName)(t,s.props));const{props:d}=s;function h(e){for(const t in u)new RegExp(e).test(t)&&(0,mv.checkStrictMode)(s,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function p(r){t.forIn("key",o,o=>{t.if(fv._`${(0,pv.usePattern)(e,r)}.test(${o})`,()=>{const n=c.includes(r);n||e.subschema({keyword:"patternProperties",schemaProp:r,dataProp:o,dataPropType:yv.Type.Str},l),s.opts.unevaluated&&!0!==d?t.assign(fv._`${d}[${o}]`,!0):n||s.allErrors||t.if((0,fv.not)(l),()=>t.break())})})}!function(){for(const e of i)u&&h(e),s.allErrors?p(e):(t.var(l,!0),p(e),t.if(l))}()}};hv.default=gv;var vv={};Object.defineProperty(vv,"__esModule",{value:!0});const _v=pf,wv={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){const{gen:t,schema:r,it:o}=e;if((0,_v.alwaysValidSchema)(o,r))return void e.fail();const n=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},n),e.failResult(n,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};vv.default=wv;var $v={};Object.defineProperty($v,"__esModule",{value:!0});const bv={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:rm().validateUnion,error:{message:"must match a schema in anyOf"}};$v.default=bv;var kv={};Object.defineProperty(kv,"__esModule",{value:!0});const Ev=lf,Sv=pf,Pv={message:"must match exactly one schema in oneOf",params:({params:e})=>Ev._`{passingSchemas: ${e.passing}}`},Tv={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Pv,code(e){const{gen:t,schema:r,parentSchema:o,it:n}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(n.opts.discriminator&&o.discriminator)return;const s=r,a=t.let("valid",!1),i=t.let("passing",null),c=t.name("_valid");e.setParams({passing:i}),t.block(function(){s.forEach((r,o)=>{let s;(0,Sv.alwaysValidSchema)(n,r)?t.var(c,!0):s=e.subschema({keyword:"oneOf",schemaProp:o,compositeRule:!0},c),o>0&&t.if(Ev._`${c} && ${a}`).assign(a,!1).assign(i,Ev._`[${i}, ${o}]`).else(),t.if(c,()=>{t.assign(a,!0),t.assign(i,o),s&&e.mergeEvaluated(s,Ev.Name)})})}),e.result(a,()=>e.reset(),()=>e.error(!0))}};kv.default=Tv;var Iv={};Object.defineProperty(Iv,"__esModule",{value:!0});const xv=pf,Nv={keyword:"allOf",schemaType:"array",code(e){const{gen:t,schema:r,it:o}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");const n=t.name("valid");r.forEach((t,r)=>{if((0,xv.alwaysValidSchema)(o,t))return;const s=e.subschema({keyword:"allOf",schemaProp:r},n);e.ok(n),e.mergeEvaluated(s)})}};Iv.default=Nv;var Cv={};Object.defineProperty(Cv,"__esModule",{value:!0});const jv=lf,Rv=pf,Ov={message:({params:e})=>jv.str`must match "${e.ifClause}" schema`,params:({params:e})=>jv._`{failingKeyword: ${e.ifClause}}`},zv={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:Ov,code(e){const{gen:t,parentSchema:r,it:o}=e;void 0===r.then&&void 0===r.else&&(0,Rv.checkStrictMode)(o,'"if" without "then" and "else" is ignored');const n=Av(o,"then"),s=Av(o,"else");if(!n&&!s)return;const a=t.let("valid",!0),i=t.name("_valid");if(function(){const t=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},i);e.mergeEvaluated(t)}(),e.reset(),n&&s){const r=t.let("ifClause");e.setParams({ifClause:r}),t.if(i,c("then",r),c("else",r))}else n?t.if(i,c("then")):t.if((0,jv.not)(i),c("else"));function c(r,o){return()=>{const n=e.subschema({keyword:r},i);t.assign(a,i),e.mergeValidEvaluated(n,a),o?t.assign(o,jv._`${r}`):e.setParams({ifClause:r})}}e.pass(a,()=>e.error(!0))}};function Av(e,t){const r=e.schema[t];return void 0!==r&&!(0,Rv.alwaysValidSchema)(e,r)}Cv.default=zv;var Mv={};Object.defineProperty(Mv,"__esModule",{value:!0});const Dv=pf,Uv={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){void 0===t.if&&(0,Dv.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};Mv.default=Uv,Object.defineProperty(bg,"__esModule",{value:!0});const qv=kg,Vv=Ig,Fv=xg,Lv=Mg,Hv=Lg,Kv=Gg,Zv=Bg,Gv=Xg,Bv=av,Jv=hv,Wv=vv,Qv=$v,Yv=kv,Xv=Iv,e_=Cv,t_=Mv;bg.default=function(e=!1){const t=[Wv.default,Qv.default,Yv.default,Xv.default,e_.default,t_.default,Zv.default,Gv.default,Kv.default,Bv.default,Jv.default];return e?t.push(Vv.default,Lv.default):t.push(qv.default,Fv.default),t.push(Hv.default),t};var r_={},o_={};Object.defineProperty(o_,"__esModule",{value:!0});const n_=lf,s_={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>n_.str`must match format "${e}"`,params:({schemaCode:e})=>n_._`{format: ${e}}`},code(e,t){const{gen:r,data:o,$data:n,schema:s,schemaCode:a,it:i}=e,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=i;c.validateFormats&&(n?function(){const n=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),s=r.const("fDef",n_._`${n}[${a}]`),i=r.let("fType"),u=r.let("format");r.if(n_._`typeof ${s} == "object" && !(${s} instanceof RegExp)`,()=>r.assign(i,n_._`${s}.type || "string"`).assign(u,n_._`${s}.validate`),()=>r.assign(i,n_._`"string"`).assign(u,s)),e.fail$data((0,n_.or)(!1===c.strictSchema?n_.nil:n_._`${a} && !${u}`,function(){const e=l.$async?n_._`(${s}.async ? await ${u}(${o}) : ${u}(${o}))`:n_._`${u}(${o})`,r=n_._`(typeof ${u} == "function" ? ${e} : ${u}.test(${o}))`;return n_._`${u} && ${u} !== true && ${i} === ${t} && !${r}`}()))}():function(){const n=d.formats[s];if(!n)return void function(){if(!1===c.strictSchema)return void d.logger.warn(e());throw new Error(e());function e(){return`unknown format "${s}" ignored in schema at path "${u}"`}}();if(!0===n)return;const[a,i,h]=function(e){const t=e instanceof RegExp?(0,n_.regexpCode)(e):c.code.formats?n_._`${c.code.formats}${(0,n_.getProperty)(s)}`:void 0,o=r.scopeValue("formats",{key:s,ref:e,code:t});if("object"==typeof e&&!(e instanceof RegExp))return[e.type||"string",e.validate,n_._`${o}.validate`];return["string",e,o]}(n);a===t&&e.pass(function(){if("object"==typeof n&&!(n instanceof RegExp)&&n.async){if(!l.$async)throw new Error("async format in sync schema");return n_._`await ${h}(${o})`}return"function"==typeof i?n_._`${h}(${o})`:n_._`${h}.test(${o})`}())}())}};o_.default=s_,Object.defineProperty(r_,"__esModule",{value:!0});const a_=[o_.default];r_.default=a_;var i_={};Object.defineProperty(i_,"__esModule",{value:!0}),i_.contentVocabulary=i_.metadataVocabulary=void 0,i_.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],i_.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"],Object.defineProperty(Qm,"__esModule",{value:!0});const c_=py,u_=bg,l_=r_,d_=i_,h_=[Ym.default,c_.default,(0,u_.default)(),l_.default,d_.metadataVocabulary,d_.contentVocabulary];Qm.default=h_;var p_,f_={},m_={};Object.defineProperty(m_,"__esModule",{value:!0}),m_.DiscrError=void 0,function(e){e.Tag="tag",e.Mapping="mapping"}(p_||(m_.DiscrError=p_={})),Object.defineProperty(f_,"__esModule",{value:!0});const y_=lf,g_=m_,v_=jm,__=Cm(),w_=pf,$_={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:e,tagName:t}})=>e===g_.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>y_._`{error: ${e}, tag: ${r}, tagValue: ${t}}`},code(e){const{gen:t,data:r,schema:o,parentSchema:n,it:s}=e,{oneOf:a}=n;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");const i=o.propertyName;if("string"!=typeof i)throw new Error("discriminator: requires propertyName");if(o.mapping)throw new Error("discriminator: mapping is not supported");if(!a)throw new Error("discriminator: requires oneOf keyword");const c=t.let("valid",!1),u=t.const("tag",y_._`${r}${(0,y_.getProperty)(i)}`);function l(r){const o=t.name("valid"),n=e.subschema({keyword:"oneOf",schemaProp:r},o);return e.mergeEvaluated(n,y_.Name),o}t.if(y_._`typeof ${u} == "string"`,()=>function(){const r=function(){var e;const t={},r=c(n);let o=!0;for(let t=0;t<a.length;t++){let n=a[t];if((null==n?void 0:n.$ref)&&!(0,w_.schemaHasRulesButRef)(n,s.self.RULES)){const e=n.$ref;if(n=v_.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,e),n instanceof v_.SchemaEnv&&(n=n.schema),void 0===n)throw new __.default(s.opts.uriResolver,s.baseId,e)}const l=null===(e=null==n?void 0:n.properties)||void 0===e?void 0:e[i];if("object"!=typeof l)throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${i}"`);o=o&&(r||c(n)),u(l,t)}if(!o)throw new Error(`discriminator: "${i}" must be required`);return t;function c({required:e}){return Array.isArray(e)&&e.includes(i)}function u(e,t){if(e.const)l(e.const,t);else{if(!e.enum)throw new Error(`discriminator: "properties/${i}" must have "const" or "enum"`);for(const r of e.enum)l(r,t)}}function l(e,r){if("string"!=typeof e||e in t)throw new Error(`discriminator: "${i}" values must be unique strings`);t[e]=r}}();t.if(!1);for(const e in r)t.elseIf(y_._`${u} === ${e}`),t.assign(c,l(r[e]));t.else(),e.error(!1,{discrError:g_.DiscrError.Mapping,tag:u,tagName:i}),t.endIf()}(),()=>e.error(!1,{discrError:g_.DiscrError.Tag,tag:u,tagName:i})),e.ok(c)}};f_.default=$_;var b_={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0};!function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.MissingRefError=t.ValidationError=t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=t.Ajv=void 0;const r=sf,o=Qm,n=f_,s=b_,a=["/properties"],i="http://json-schema.org/draft-07/schema";class c extends r.default{_addVocabularies(){super._addVocabularies(),o.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(n.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const e=this.opts.$data?this.$dataMetaSchema(s,a):s;this.addMetaSchema(e,i,!1),this.refs["http://json-schema.org/schema"]=i}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(i)?i:void 0)}}t.Ajv=c,e.exports=t=c,e.exports.Ajv=c,Object.defineProperty(t,"__esModule",{value:!0}),t.default=c;var u=Sm();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return u.KeywordCxt}});var l=lf;Object.defineProperty(t,"_",{enumerable:!0,get:function(){return l._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return l.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return l.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return l.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return l.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return l.CodeGen}});var d=Im();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return d.default}});var h=Cm();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return h.default}})}(nf,nf.exports);var k_=nf.exports;!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;const t=k_,r=lf,o=r.operators,n={formatMaximum:{okStr:"<=",ok:o.LTE,fail:o.GT},formatMinimum:{okStr:">=",ok:o.GTE,fail:o.LT},formatExclusiveMaximum:{okStr:"<",ok:o.LT,fail:o.GTE},formatExclusiveMinimum:{okStr:">",ok:o.GT,fail:o.LTE}},s={message:({keyword:e,schemaCode:t})=>r.str`should be ${n[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>r._`{comparison: ${n[e].okStr}, limit: ${t}}`};e.formatLimitDefinition={keyword:Object.keys(n),type:"string",schemaType:"string",$data:!0,error:s,code(e){const{gen:o,data:s,schemaCode:a,keyword:i,it:c}=e,{opts:u,self:l}=c;if(!u.validateFormats)return;const d=new t.KeywordCxt(c,l.RULES.all.format.definition,"format");function h(e){return r._`${e}.compare(${s}, ${a}) ${n[i].fail} 0`}d.$data?function(){const t=o.scopeValue("formats",{ref:l.formats,code:u.code.formats}),n=o.const("fmt",r._`${t}[${d.schemaCode}]`);e.fail$data((0,r.or)(r._`typeof ${n} != "object"`,r._`${n} instanceof RegExp`,r._`typeof ${n}.compare != "function"`,h(n)))}():function(){const t=d.schema,n=l.formats[t];if(!n||!0===n)return;if("object"!=typeof n||n instanceof RegExp||"function"!=typeof n.compare)throw new Error(`"${i}": format "${t}" does not define "compare" function`);const s=o.scopeValue("formats",{key:t,ref:n,code:u.code.formats?r._`${u.code.formats}${(0,r.getProperty)(t)}`:void 0});e.fail$data(h(s))}()},dependencies:["format"]};e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)}(of),function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r=rf,o=of,n=lf,s=new n.Name("fullFormats"),a=new n.Name("fastFormats"),i=(e,t={keywords:!0})=>{if(Array.isArray(t))return c(e,t,r.fullFormats,s),e;const[n,i]="fast"===t.mode?[r.fastFormats,a]:[r.fullFormats,s];return c(e,t.formats||r.formatNames,n,i),t.keywords&&(0,o.default)(e),e};function c(e,t,r,o){var s,a;null!==(s=(a=e.opts.code).formats)&&void 0!==s||(a.formats=n._`require("ajv-formats/dist/formats").${o}`);for(const o of t)e.addFormat(o,r[o])}i.get=(e,t="full")=>{const o=("fast"===t?r.fastFormats:r.fullFormats)[e];if(!o)throw new Error(`Unknown format "${e}"`);return o},e.exports=t=i,Object.defineProperty(t,"__esModule",{value:!0}),t.default=i}(tf,tf.exports);var E_=Ji(tf.exports);class S_{constructor(e){this._ajv=e??function(){const e=new ef({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return E_(e),e}()}getValidator(e){const t="$id"in e&&"string"==typeof e.$id?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}}class P_{constructor(e){this._client=e}async*callToolStream(e,t=Qa,r){const o=this._client,n={...r,task:r?.task??(o.isToolTask(e.name)?{}:void 0)},s=o.requestStream({method:"tools/call",params:e},t,n),a=o.getToolOutputValidator(e.name);for await(const t of s){if("result"===t.type&&a){const r=t.result;if(!r.structuredContent&&!r.isError)return void(yield{type:"error",error:new Fi(ks.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)});if(r.structuredContent)try{const e=a(r.structuredContent);if(!e.valid)return void(yield{type:"error",error:new Fi(ks.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)})}catch(e){return e instanceof Fi?void(yield{type:"error",error:e}):void(yield{type:"error",error:new Fi(ks.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)})}}yield t}}async getTask(e,t){return this._client.getTask({taskId:e},t)}async getTaskResult(e,t,r){return this._client.getTaskResult({taskId:e},t,r)}async listTasks(e,t){return this._client.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._client.cancelTask({taskId:e},t)}requestStream(e,t,r){return this._client.requestStream(e,t,r)}}function T_(e,t){if(e&&null!==t&&"object"==typeof t){if("object"===e.type&&e.properties&&"object"==typeof e.properties){const r=t,o=e.properties;for(const e of Object.keys(o)){const t=o[e];void 0===r[e]&&Object.prototype.hasOwnProperty.call(t,"default")&&(r[e]=t.default),void 0!==r[e]&&T_(t,r[e])}}if(Array.isArray(e.anyOf))for(const r of e.anyOf)"boolean"!=typeof r&&T_(r,t);if(Array.isArray(e.oneOf))for(const r of e.oneOf)"boolean"!=typeof r&&T_(r,t)}}class I_ extends Gi{constructor(e,t){super(t),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=t?.capabilities??{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new S_,t?.listChanged&&(this._pendingListChangedConfig=t.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",ei,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Ka,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Ea,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new P_(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=function(e,t){const r={...e};for(const e in t){const o=e,n=t[o];if(void 0===n)continue;const s=r[o];Bi(s)&&Bi(n)?r[o]={...s,...n}:r[o]=n}return r}(this._capabilities,e)}setRequestHandler(e,t){const r=ko(e),o=r?.method;if(!o)throw new Error("Schema is missing a method literal");let n;if($o(o)){const e=o,t=e._zod?.def;n=t?.value??e.value}else{const e=o,t=e._def;n=t?.value??e.value}if("string"!=typeof n)throw new Error("Schema method literal must be a string");const s=n;if("elicitation/create"===s){const r=async(e,r)=>{const o=bo(xi,e);if(!o.success){const e=o.error instanceof Error?o.error.message:String(o.error);throw new Fi(ks.InvalidParams,`Invalid elicitation request: ${e}`)}const{params:n}=o.data;n.mode=n.mode??"form";const{supportsFormMode:s,supportsUrlMode:a}=function(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};const t=void 0!==e.form,r=void 0!==e.url;return{supportsFormMode:t||!t&&!r,supportsUrlMode:r}}(this._capabilities.elicitation);if("form"===n.mode&&!s)throw new Fi(ks.InvalidParams,"Client does not support form-mode elicitation requests");if("url"===n.mode&&!a)throw new Fi(ks.InvalidParams,"Client does not support URL-mode elicitation requests");const i=await Promise.resolve(t(e,r));if(n.task){const e=bo(Ys,i);if(!e.success){const t=e.error instanceof Error?e.error.message:String(e.error);throw new Fi(ks.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}const c=bo(ji,i);if(!c.success){const e=c.error instanceof Error?c.error.message:String(c.error);throw new Fi(ks.InvalidParams,`Invalid elicitation result: ${e}`)}const u=c.data,l="form"===n.mode?n.requestedSchema:void 0;if("form"===n.mode&&"accept"===u.action&&u.content&&l&&this._capabilities.elicitation?.form?.applyDefaults)try{T_(l,u.content)}catch{}return u};return super.setRequestHandler(e,r)}if("sampling/createMessage"===s){const r=async(e,r)=>{const o=bo(mi,e);if(!o.success){const e=o.error instanceof Error?o.error.message:String(o.error);throw new Fi(ks.InvalidParams,`Invalid sampling request: ${e}`)}const{params:n}=o.data,s=await Promise.resolve(t(e,r));if(n.task){const e=bo(Ys,s);if(!e.success){const t=e.error instanceof Error?e.error.message:String(e.error);throw new Fi(ks.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}const a=bo(n.tools||n.toolChoice?gi:yi,s);if(!a.success){const e=a.error instanceof Error?a.error.message:String(a.error);throw new Fi(ks.InvalidParams,`Invalid sampling result: ${e}`)}return a.data};return super.setRequestHandler(e,r)}return super.setRequestHandler(e,t)}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw new Error(`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(await super.connect(e),void 0===e.sessionId)try{const r=await this.request({method:"initialize",params:{protocolVersion:es,capabilities:this._capabilities,clientInfo:this._clientInfo}},Vs,t);if(void 0===r)throw new Error(`Server sent invalid initialize result: ${r}`);if(!ts.includes(r.protocolVersion))throw new Error(`Server's protocol version is not supported: ${r.protocolVersion}`);this._serverCapabilities=r.capabilities,this._serverVersion=r.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(r.protocolVersion),this._instructions=r.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(e){throw this.close(),e}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${e})`);if("resources/subscribe"===e&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${e})`)}}assertNotificationCapability(e){if("notifications/roots/list_changed"===e)if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${e})`)}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${e})`)}}assertTaskCapability(e){!function(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);if("tools/call"===t&&!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`)}(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&function(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`)}}(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},Ps,e)}async complete(e,t){return this.request({method:"completion/complete",params:e},Mi,t)}async setLoggingLevel(e,t){return this.request({method:"logging/setLevel",params:{level:e}},Ps,t)}async getPrompt(e,t){return this.request({method:"prompts/get",params:e},Ha,t)}async listPrompts(e,t){return this.request({method:"prompts/list",params:e},Oa,t)}async listResources(e,t){return this.request({method:"resources/list",params:e},ga,t)}async listResourceTemplates(e,t){return this.request({method:"resources/templates/list",params:e},_a,t)}async readResource(e,t){return this.request({method:"resources/read",params:e},ka,t)}async subscribeResource(e,t){return this.request({method:"resources/subscribe",params:e},Ps,t)}async unsubscribeResource(e,t){return this.request({method:"resources/unsubscribe",params:e},Ps,t)}async callTool(e,t=Qa,r){if(this.isToolTaskRequired(e.name))throw new Fi(ks.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);const o=await this.request({method:"tools/call",params:e},t,r),n=this.getToolOutputValidator(e.name);if(n){if(!o.structuredContent&&!o.isError)throw new Fi(ks.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(o.structuredContent)try{const e=n(o.structuredContent);if(!e.valid)throw new Fi(ks.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)}catch(e){if(e instanceof Fi)throw e;throw new Fi(ks.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)}}return o}isToolTask(e){return!!this._serverCapabilities?.tasks?.requests?.tools?.call&&this._cachedKnownTaskTools.has(e)}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(const t of e){if(t.outputSchema){const e=this._jsonSchemaValidator.getValidator(t.outputSchema);this._cachedToolOutputValidators.set(t.name,e)}const e=t.execution?.taskSupport;"required"!==e&&"optional"!==e||this._cachedKnownTaskTools.add(t.name),"required"===e&&this._cachedRequiredTaskTools.add(t.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,t){const r=await this.request({method:"tools/list",params:e},Wa,t);return this.cacheToolMetadata(r.tools),r}_setupListChangedHandler(e,t,r,o){const n=ti.safeParse(r);if(!n.success)throw new Error(`Invalid ${e} listChanged options: ${n.error.message}`);if("function"!=typeof r.onChanged)throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);const{autoRefresh:s,debounceMs:a}=n.data,{onChanged:i}=r,c=async()=>{if(s)try{const e=await o();i(null,e)}catch(e){const t=e instanceof Error?e:new Error(String(e));i(t,null)}else i(null,null)};this.setNotificationHandler(t,()=>{if(a){const t=this._listChangedDebounceTimers.get(e);t&&clearTimeout(t);const r=setTimeout(c,a);this._listChangedDebounceTimers.set(e,r)}else c()})}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}function x_(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}const N_=lo(Ko,C_).superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Xn,message:"URL must be parseable",fatal:!0}),ke}).refine(e=>{const t=new URL(e);return"javascript:"!==t.protocol&&"data:"!==t.protocol&&"vbscript:"!==t.protocol},{message:"URL cannot use javascript:, data:, or vbscript: scheme"});var C_;const j_=Sn({resource:qo().url(),authorization_servers:bn(N_).optional(),jwks_uri:qo().url().optional(),scopes_supported:bn(qo()).optional(),bearer_methods_supported:bn(qo()).optional(),resource_signing_alg_values_supported:bn(qo()).optional(),resource_name:qo().optional(),resource_documentation:qo().optional(),resource_policy_uri:qo().url().optional(),resource_tos_uri:qo().url().optional(),tls_client_certificate_bound_access_tokens:pn().optional(),authorization_details_types_supported:bn(qo()).optional(),dpop_signing_alg_values_supported:bn(qo()).optional(),dpop_bound_access_tokens_required:pn().optional()}),R_=Sn({issuer:qo(),authorization_endpoint:N_,token_endpoint:N_,registration_endpoint:N_.optional(),scopes_supported:bn(qo()).optional(),response_types_supported:bn(qo()),response_modes_supported:bn(qo()).optional(),grant_types_supported:bn(qo()).optional(),token_endpoint_auth_methods_supported:bn(qo()).optional(),token_endpoint_auth_signing_alg_values_supported:bn(qo()).optional(),service_documentation:N_.optional(),revocation_endpoint:N_.optional(),revocation_endpoint_auth_methods_supported:bn(qo()).optional(),revocation_endpoint_auth_signing_alg_values_supported:bn(qo()).optional(),introspection_endpoint:qo().optional(),introspection_endpoint_auth_methods_supported:bn(qo()).optional(),introspection_endpoint_auth_signing_alg_values_supported:bn(qo()).optional(),code_challenge_methods_supported:bn(qo()).optional(),client_id_metadata_document_supported:pn().optional()}),O_=En({...Sn({issuer:qo(),authorization_endpoint:N_,token_endpoint:N_,userinfo_endpoint:N_.optional(),jwks_uri:N_,registration_endpoint:N_.optional(),scopes_supported:bn(qo()).optional(),response_types_supported:bn(qo()),response_modes_supported:bn(qo()).optional(),grant_types_supported:bn(qo()).optional(),acr_values_supported:bn(qo()).optional(),subject_types_supported:bn(qo()),id_token_signing_alg_values_supported:bn(qo()),id_token_encryption_alg_values_supported:bn(qo()).optional(),id_token_encryption_enc_values_supported:bn(qo()).optional(),userinfo_signing_alg_values_supported:bn(qo()).optional(),userinfo_encryption_alg_values_supported:bn(qo()).optional(),userinfo_encryption_enc_values_supported:bn(qo()).optional(),request_object_signing_alg_values_supported:bn(qo()).optional(),request_object_encryption_alg_values_supported:bn(qo()).optional(),request_object_encryption_enc_values_supported:bn(qo()).optional(),token_endpoint_auth_methods_supported:bn(qo()).optional(),token_endpoint_auth_signing_alg_values_supported:bn(qo()).optional(),display_values_supported:bn(qo()).optional(),claim_types_supported:bn(qo()).optional(),claims_supported:bn(qo()).optional(),service_documentation:qo().optional(),claims_locales_supported:bn(qo()).optional(),ui_locales_supported:bn(qo()).optional(),claims_parameter_supported:pn().optional(),request_parameter_supported:pn().optional(),request_uri_parameter_supported:pn().optional(),require_request_uri_registration:pn().optional(),op_policy_uri:N_.optional(),op_tos_uri:N_.optional(),client_id_metadata_document_supported:pn().optional()}).shape,...R_.pick({code_challenge_methods_supported:!0}).shape}),z_=En({access_token:qo(),id_token:qo().optional(),token_type:qo(),expires_in:function(e){return function(e,t){return new e({type:"number",coerce:!0,checks:[],...Fe(t)})}(cn,e)}().optional(),scope:qo().optional(),refresh_token:qo().optional()}).strip(),A_=En({error:qo(),error_description:qo().optional(),error_uri:qo().optional()}),M_=N_.optional().or(Mn("").transform(()=>{})),D_=En({redirect_uris:bn(N_),token_endpoint_auth_method:qo().optional(),grant_types:bn(qo()).optional(),response_types:bn(qo()).optional(),client_name:qo().optional(),client_uri:N_.optional(),logo_uri:M_,scope:qo().optional(),contacts:bn(qo()).optional(),tos_uri:M_,policy_uri:qo().optional(),jwks_uri:N_.optional(),jwks:new yn({type:"any"}).optional(),software_id:qo().optional(),software_version:qo().optional(),software_statement:qo().optional()}).strip(),U_=En({client_id:qo(),client_secret:qo().optional(),client_id_issued_at:un().optional(),client_secret_expires_at:un().optional()}).strip(),q_=D_.merge(U_);En({error:qo(),error_description:qo().optional()}).strip(),En({token:qo(),token_type_hint:qo().optional()}).strip();class V_ extends Error{constructor(e,t){super(e),this.errorUri=t,this.name=this.constructor.name}toResponseObject(){const e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}}class F_ extends V_{}F_.errorCode="invalid_request";class L_ extends V_{}L_.errorCode="invalid_client";class H_ extends V_{}H_.errorCode="invalid_grant";class K_ extends V_{}K_.errorCode="unauthorized_client";class Z_ extends V_{}Z_.errorCode="unsupported_grant_type";class G_ extends V_{}G_.errorCode="invalid_scope";class B_ extends V_{}B_.errorCode="access_denied";class J_ extends V_{}J_.errorCode="server_error";class W_ extends V_{}W_.errorCode="temporarily_unavailable";class Q_ extends V_{}Q_.errorCode="unsupported_response_type";class Y_ extends V_{}Y_.errorCode="unsupported_token_type";class X_ extends V_{}X_.errorCode="invalid_token";class ew extends V_{}ew.errorCode="method_not_allowed";class tw extends V_{}tw.errorCode="too_many_requests";class rw extends V_{}rw.errorCode="invalid_client_metadata";class ow extends V_{}ow.errorCode="insufficient_scope";class nw extends V_{}nw.errorCode="invalid_target";const sw={[F_.errorCode]:F_,[L_.errorCode]:L_,[H_.errorCode]:H_,[K_.errorCode]:K_,[Z_.errorCode]:Z_,[G_.errorCode]:G_,[B_.errorCode]:B_,[J_.errorCode]:J_,[W_.errorCode]:W_,[Q_.errorCode]:Q_,[Y_.errorCode]:Y_,[X_.errorCode]:X_,[ew.errorCode]:ew,[tw.errorCode]:tw,[rw.errorCode]:rw,[ow.errorCode]:ow,[nw.errorCode]:nw};class aw extends Error{constructor(e){super(e??"Unauthorized")}}const iw="code",cw="S256";function uw(e,t,r,o){const{client_id:n,client_secret:s}=t;switch(e){case"client_secret_basic":return void function(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const o=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${o}`)}(n,s,r);case"client_secret_post":return void function(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}(n,s,o);case"none":return void function(e,t){t.set("client_id",e)}(n,o);default:throw new Error(`Unsupported client authentication method: ${e}`)}}async function lw(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const e=A_.parse(JSON.parse(r)),{error:t,error_description:o,error_uri:n}=e;return new(sw[t]||J_)(o||"",n)}catch(e){return new J_(`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${e}. Raw body: ${r}`)}}async function dw(e,t){try{return await hw(e,t)}catch(r){if(r instanceof L_||r instanceof K_)return await(e.invalidateCredentials?.("all")),await hw(e,t);if(r instanceof H_)return await(e.invalidateCredentials?.("tokens")),await hw(e,t);throw r}}async function hw(e,{serverUrl:t,authorizationCode:r,scope:o,resourceMetadataUrl:n,fetchFn:s}){let a,i;try{a=await async function(e,t,r=fetch){const o=await async function(e,t,r,o){const n=new URL(e),s=o?.protocolVersion??es;let a;if(o?.metadataUrl)a=new URL(o.metadataUrl);else{const e=function(e,t="",r={}){t.endsWith("/")&&(t=t.slice(0,-1));return r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}(t,n.pathname);a=new URL(e,o?.metadataServerUrl??n),a.search=n.search}let i=await yw(a,s,r);if(!o?.metadataUrl&&function(e,t){return!e||e.status>=400&&e.status<500&&"/"!==t}(i,n.pathname)){const e=new URL(`/.well-known/${t}`,n);i=await yw(e,s,r)}return i}(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!o||404===o.status)throw await(o?.body?.cancel()),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!o.ok)throw await(o.body?.cancel()),new Error(`HTTP ${o.status} trying to load well-known OAuth protected resource metadata.`);return j_.parse(await o.json())}(t,{resourceMetadataUrl:n},s),a.authorization_servers&&a.authorization_servers.length>0&&(i=a.authorization_servers[0])}catch{}i||(i=new URL("/",t));const c=await async function(e,t,r){const o=function(e){const t="string"==typeof e?new URL(e):new URL(e.href);return t.hash="",t}(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(!r)return;if(!function({requestedResource:e,configuredResource:t}){const r="string"==typeof e?new URL(e):new URL(e.href),o="string"==typeof t?new URL(t):new URL(t.href);if(r.origin!==o.origin)return!1;if(r.pathname.length<o.pathname.length)return!1;const n=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return n.startsWith(s)}({requestedResource:o,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${o} (or origin)`);return new URL(r.resource)}(t,e,a),u=await async function(e,{fetchFn:t=fetch,protocolVersion:r=es}={}){const o={"MCP-Protocol-Version":r,Accept:"application/json"},n=function(e){const t="string"==typeof e?new URL(e):e,r="/"!==t.pathname,o=[];if(!r)return o.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),o.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),o;let n=t.pathname;n.endsWith("/")&&(n=n.slice(0,-1));return o.push({url:new URL(`/.well-known/oauth-authorization-server${n}`,t.origin),type:"oauth"}),o.push({url:new URL(`/.well-known/openid-configuration${n}`,t.origin),type:"oidc"}),o.push({url:new URL(`${n}/.well-known/openid-configuration`,t.origin),type:"oidc"}),o}(e);for(const{url:e,type:r}of n){const n=await mw(e,o,t);if(n){if(!n.ok){if(await(n.body?.cancel()),n.status>=400&&n.status<500)continue;throw new Error(`HTTP ${n.status} trying to load ${"oauth"===r?"OAuth":"OpenID provider"} metadata from ${e}`)}return"oauth"===r?R_.parse(await n.json()):O_.parse(await n.json())}}return}(i,{fetchFn:s});let l=await Promise.resolve(e.clientInformation());if(!l){if(void 0!==r)throw new Error("Existing OAuth client information is required when exchanging an authorization code");const t=!0===u?.client_id_metadata_document_supported,o=e.clientMetadataUrl;if(o&&!function(e){if(!e)return!1;try{const t=new URL(e);return"https:"===t.protocol&&"/"!==t.pathname}catch{return!1}}(o))throw new rw(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${o}`);if(t&&o)l={client_id:o},await(e.saveClientInformation?.(l));else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const t=await async function(e,{metadata:t,clientMetadata:r,fetchFn:o}){let n;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");n=new URL(t.registration_endpoint)}else n=new URL("/register",e);const s=await(o??fetch)(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok)throw await lw(s);return q_.parse(await s.json())}(i,{metadata:u,clientMetadata:e.clientMetadata,fetchFn:s});await e.saveClientInformation(t),l=t}}const d=!e.redirectUrl;if(void 0!==r||d){const t=await async function(e,t,{metadata:r,resource:o,authorizationCode:n,fetchFn:s}={}){const a=e.clientMetadata.scope;let i;e.prepareTokenRequest&&(i=await e.prepareTokenRequest(a));if(!i){if(!n)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");i=function(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}(n,await e.codeVerifier(),e.redirectUrl)}const c=await e.clientInformation();return gw(t,{metadata:r,tokenRequestParams:i,clientInformation:c??void 0,addClientAuthentication:e.addClientAuthentication,resource:o,fetchFn:s})}(e,i,{metadata:u,resource:c,authorizationCode:r,fetchFn:s});return await e.saveTokens(t),"AUTHORIZED"}const h=await e.tokens();if(h?.refresh_token)try{const t=await async function(e,{metadata:t,clientInformation:r,refreshToken:o,resource:n,addClientAuthentication:s,fetchFn:a}){const i=new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),c=await gw(e,{metadata:t,tokenRequestParams:i,clientInformation:r,addClientAuthentication:s,resource:n,fetchFn:a});return{refresh_token:o,...c}}(i,{metadata:u,clientInformation:l,refreshToken:h.refresh_token,resource:c,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(t),"AUTHORIZED"}catch(e){if(e instanceof V_&&!(e instanceof J_))throw e}const f=e.state?await e.state():void 0,{authorizationUrl:m,codeVerifier:y}=await async function(e,{metadata:t,clientInformation:r,redirectUrl:o,scope:n,state:s,resource:a}){let i;if(t){if(i=new URL(t.authorization_endpoint),!t.response_types_supported.includes(iw))throw new Error(`Incompatible auth server: does not support response type ${iw}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(cw))throw new Error(`Incompatible auth server: does not support code challenge method ${cw}`)}else i=new URL("/authorize",e);const c=await p(),u=c.code_verifier,l=c.code_challenge;i.searchParams.set("response_type",iw),i.searchParams.set("client_id",r.client_id),i.searchParams.set("code_challenge",l),i.searchParams.set("code_challenge_method",cw),i.searchParams.set("redirect_uri",String(o)),s&&i.searchParams.set("state",s);n&&i.searchParams.set("scope",n);n?.includes("offline_access")&&i.searchParams.append("prompt","consent");a&&i.searchParams.set("resource",a.href);return{authorizationUrl:i,codeVerifier:u}}(i,{metadata:u,clientInformation:l,state:f,redirectUrl:e.redirectUrl,scope:o||a?.scopes_supported?.join(" ")||e.clientMetadata.scope,resource:c});return await e.saveCodeVerifier(y),await e.redirectToAuthorization(m),"REDIRECT"}function pw(e){const t=e.headers.get("WWW-Authenticate");if(!t)return{};const[r,o]=t.split(" ");if("bearer"!==r.toLowerCase()||!o)return{};const n=fw(e,"resource_metadata")||void 0;let s;if(n)try{s=new URL(n)}catch{}return{resourceMetadataUrl:s,scope:fw(e,"scope")||void 0,error:fw(e,"error")||void 0}}function fw(e,t){const r=e.headers.get("WWW-Authenticate");if(!r)return null;const o=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),n=r.match(o);return n?n[1]||n[2]:null}async function mw(e,t,r=fetch){try{return await r(e,{headers:t})}catch(o){if(o instanceof TypeError)return t?mw(e,void 0,r):void 0;throw o}}async function yw(e,t,r=fetch){const o={"MCP-Protocol-Version":t};return await mw(e,o,r)}async function gw(e,{metadata:t,tokenRequestParams:r,clientInformation:o,addClientAuthentication:n,resource:s,fetchFn:a}){const i=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),c=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(s&&r.set("resource",s.href),n)await n(c,r,i,t);else if(o){const e=function(e,t){const r=void 0!==e.client_secret;return 0===t.length?r?"client_secret_post":"none":"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&(o=e.token_endpoint_auth_method,["client_secret_basic","client_secret_post","none"].includes(o))&&t.includes(e.token_endpoint_auth_method)?e.token_endpoint_auth_method:r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none";var o}(o,t?.token_endpoint_auth_methods_supported??[]);uw(e,o,c,r)}const u=await(a??fetch)(i,{method:"POST",headers:c,body:r});if(!u.ok)throw await lw(u);return z_.parse(await u.json())}class vw 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 _w(e){}function ww(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=_w,onError:r=_w,onRetry:o=_w,onComment:n}=e;let s,a="",i=!0,c="",u="";function l(e){if(""===e)return c.length>0&&t({id:s,event:u||void 0,data:c.endsWith("\n")?c.slice(0,-1):c}),s=void 0,c="",void(u="");if(e.startsWith(":"))return void(n&&n(e.slice(e.startsWith(": ")?2:1)));const r=e.indexOf(":");if(-1!==r){const t=e.slice(0,r),o=" "===e[r+1]?2:1;return void d(t,e.slice(r+o),e)}d(e,"",e)}function d(e,t,n){switch(e){case"event":u=t;break;case"data":c=`${c}${t}\n`;break;case"id":s=t.includes("\0")?void 0:t;break;case"retry":/^\d+$/.test(t)?o(parseInt(t,10)):r(new vw(`Invalid \`retry\` value: "${t}"`,{type:"invalid-retry",value:t,line:n}));break;default:r(new vw(`Unknown field "${e.length>20?`${e.slice(0,20)}…`:e}"`,{type:"unknown-field",field:e,value:t,line:n}))}}return{feed:function(e){const t=i?e.replace(/^\xEF\xBB\xBF/,""):e,[r,o]=function(e){const t=[];let r="",o=0;for(;o<e.length;){const n=e.indexOf("\r",o),s=e.indexOf("\n",o);let a=-1;if(-1!==n&&-1!==s?a=Math.min(n,s):-1!==n?a=n:-1!==s&&(a=s),-1===a){r=e.slice(o);break}{const r=e.slice(o,a);t.push(r),o=a+1,"\r"===e[o-1]&&"\n"===e[o]&&o++}}return[t,r]}(`${a}${t}`);for(const e of r)l(e);a=o,i=!1},reset:function(e={}){a&&e.consume&&l(a),i=!0,s=void 0,c="",u="",a=""}}}class $w extends TransformStream{constructor({onError:e,onRetry:t,onComment:r}={}){let o;super({start(n){o=ww({onEvent:e=>{n.enqueue(e)},onError(t){"terminate"===e?n.error(t):"function"==typeof e&&e(t)},onRetry:t,onComment:r})},transform(e){o.feed(e)}})}}const bw={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class kw extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}}class Ew{constructor(e,t){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=function(e=fetch,t){return t?async(r,o)=>{const n={...t,...o,headers:o?.headers?{...x_(t.headers),...x_(o.headers)}:t.headers};return e(r,n)}:e}(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??bw}async _authThenStart(){if(!this._authProvider)throw new aw("No auth provider");let e;try{e=await dw(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(e){throw this.onerror?.(e),e}if("AUTHORIZED"!==e)throw new aw;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){const e={};if(this._authProvider){const t=await this._authProvider.tokens();t&&(e.Authorization=`Bearer ${t.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);const t=x_(this._requestInit?.headers);return new Headers({...e,...t})}async _startOrAuthSse(e){const{resumptionToken:t}=e;try{const r=await this._commonHeaders();r.set("Accept","text/event-stream"),t&&r.set("last-event-id",t);const o=await(this._fetch??fetch)(this._url,{method:"GET",headers:r,signal:this._abortController?.signal});if(!o.ok){if(await(o.body?.cancel()),401===o.status&&this._authProvider)return await this._authThenStart();if(405===o.status)return;throw new kw(o.status,`Failed to open SSE stream: ${o.statusText}`)}this._handleSseStream(o.body,e,!0)}catch(e){throw this.onerror?.(e),e}}_getNextReconnectionDelay(e){if(void 0!==this._serverRetryMs)return this._serverRetryMs;const t=this._reconnectionOptions.initialReconnectionDelay,r=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*Math.pow(r,e),o)}_scheduleReconnection(e,t=0){const r=this._reconnectionOptions.maxRetries;if(t>=r)return void this.onerror?.(new Error(`Maximum reconnection attempts (${r}) exceeded.`));const o=this._getNextReconnectionDelay(t);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(r=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${r instanceof Error?r.message:String(r)}`)),this._scheduleReconnection(e,t+1)})},o)}_handleSseStream(e,t,r){if(!e)return;const{onresumptiontoken:o,replayMessageId:n}=t;let s,a=!1,i=!1;(async()=>{try{const t=e.pipeThrough(new TextDecoderStream).pipeThrough(new $w({onRetry:e=>{this._serverRetryMs=e}})).getReader();for(;;){const{value:e,done:r}=await t.read();if(r)break;if(e.id&&(s=e.id,a=!0,o?.(e.id)),e.data&&(!e.event||"message"===e.event))try{const t=Ss.parse(JSON.parse(e.data));bs(t)&&(i=!0,void 0!==n&&(t.id=n)),this.onmessage?.(t)}catch(e){this.onerror?.(e)}}(r||a)&&!i&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:s,onresumptiontoken:o,replayMessageId:n},0)}catch(e){this.onerror?.(new Error(`SSE stream disconnected: ${e}`));if((r||a)&&!i&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:o,replayMessageId:n},0)}catch(e){this.onerror?.(new Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new aw("No auth provider");if("AUTHORIZED"!==await dw(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit}))throw new aw("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,t){try{const{resumptionToken:o,onresumptiontoken:n}=t||{};if(o)return void this._startOrAuthSse({resumptionToken:o,replayMessageId:_s(e)?e.id:void 0}).catch(e=>this.onerror?.(e));const s=await this._commonHeaders();s.set("content-type","application/json"),s.set("accept","application/json, text/event-stream");const a={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:this._abortController?.signal},i=await(this._fetch??fetch)(this._url,a),c=i.headers.get("mcp-session-id");if(c&&(this._sessionId=c),!i.ok){const t=await i.text().catch(()=>null);if(401===i.status&&this._authProvider){if(this._hasCompletedAuthFlow)throw new kw(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:t,scope:r}=pw(i);this._resourceMetadataUrl=t,this._scope=r;if("AUTHORIZED"!==await dw(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit}))throw new aw;return this._hasCompletedAuthFlow=!0,this.send(e)}if(403===i.status&&this._authProvider){const{resourceMetadataUrl:t,scope:r,error:o}=pw(i);if("insufficient_scope"===o){const o=i.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===o)throw new kw(403,"Server returned 403 after trying upscoping");r&&(this._scope=r),t&&(this._resourceMetadataUrl=t),this._lastUpscopingHeader=o??void 0;if("AUTHORIZED"!==await dw(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch}))throw new aw;return this.send(e)}}throw new kw(i.status,`Error POSTing to endpoint: ${t}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,202===i.status)return await(i.body?.cancel()),r=e,void(Fs.safeParse(r).success&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>this.onerror?.(e)));const u=(Array.isArray(e)?e:[e]).filter(e=>"method"in e&&"id"in e&&void 0!==e.id).length>0,l=i.headers.get("content-type");if(u)if(l?.includes("text/event-stream"))this._handleSseStream(i.body,{onresumptiontoken:n},!1);else{if(!l?.includes("application/json"))throw await(i.body?.cancel()),new kw(-1,`Unexpected content type: ${l}`);{const e=await i.json(),t=Array.isArray(e)?e.map(e=>Ss.parse(e)):[Ss.parse(e)];for(const e of t)this.onmessage?.(e)}}else await(i.body?.cancel())}catch(e){throw this.onerror?.(e),e}var r}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{const e=await this._commonHeaders(),t={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},r=await(this._fetch??fetch)(this._url,t);if(await(r.body?.cancel()),!r.ok&&405!==r.status)throw new kw(r.status,`Failed to terminate session: ${r.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}}const Sw=H("quickstart");async function Pw(t={}){if(!R)throw new Error("Interactive login is only available in Node.js environment");Sw.info("Starting interactive login flow");const r=M();let o;o=t.authIssuer?t.authIssuer:t.authDomain?t.authDomain.startsWith("http")?t.authDomain:`https://${t.authDomain}`:r.authIssuer;const{clientId:n=r.clientId,clientSecret:s=r.clientSecret,audience:a=r.apiAudience,baseUrl:i,port:c=52765}=t;if(!n||!s)throw new Error("AGENT_CLIENT_ID / AGENT_CLIENT_SECRET not set – create a .env file or export in the shell");const u=await he();if(u)try{let e;q(u)?e=D(u):(Sw.warn("Cached token has no organization information, using static config"),e=M());const t=new be(e.baseUrl,{token:u});return await t.validateCachedToken(),Sw.info("Using cached valid token"),t}catch(e){Sw.info("Cached token invalid, starting OAuth flow")}else Sw.info("No cached token, starting OAuth flow");const l="undefined"!=typeof process&&!(!process.env||"1"!==process.env.BARNDOOR_MANUAL_CODE&&"true"!==process.env.BARNDOOR_MANUAL_CODE);let p,f=null;if(l){const e=process.env&&process.env.BARNDOOR_REDIRECT_HOST||"127.0.0.1";p=e.startsWith("http")?`${e}:${c}/cb`:`http://${e}:${c}/cb`}else{const e=$e(c);p=e[0],f=e[1]}const m=new ve,y=await m.buildAuthorizationUrl({clientId:n,redirectUri:p,audience:a,issuer:o});Sw.info(`Auth URL: ${y}`);const g=e.platform();let v,_;try{v=new URL(y)}catch{throw new Error("Invalid auth URL")}if("https:"!==v.protocol&&("http:"!==v.protocol||"localhost"!==v.hostname&&"127.0.0.1"!==v.hostname))throw new Error("Auth URL must use HTTPS (http allowed only for localhost)");try{"darwin"===g?d("open",[y],{detached:!0,stdio:"ignore"}).unref():"win32"===g?d("powershell",["-NoProfile","Start-Process",y],{detached:!0,stdio:"ignore"}).unref():d("xdg-open",[y],{detached:!0,stdio:"ignore"}).unref(),Sw.info("Please complete login in your browser…")}catch(e){Sw.warn("Failed to open browser automatically. Please visit:",y)}if(l){const e=await new Promise(e=>{const t=h.createInterface({input:process.stdin,output:process.stdout});t.question("Paste the full redirected URL (or just the code= value): ",r=>{t.close(),e(r.trim())})});try{const t=new URL(e);_=t.searchParams.get("code")||e}catch{_=e}}else{const e=new Promise((e,t)=>{setTimeout(()=>{t(new Error(`OAuth callback timeout after 2 minutes. This usually means the callback URL is not registered in Auth0. Please add "${p}" to Allowed Callback URLs in your Auth0 application settings.`))},12e4)});_=(await Promise.race([f,e]))[0]}const w=await m.exchangeCodeForToken({clientId:n,clientSecret:s,code:_,redirectUri:p,issuer:o});let $;if(await pe(w),i)$=i;else if(q(w.access_token)){$=D(w.access_token).baseUrl}else Sw.warn("New token has no organization information, using static config"),$=M().baseUrl;return new be($,{token:w.access_token})}async function Tw(e,t,r={}){const{timeout:o=90}=r;Sw.info(`Ensuring ${t} server is connected`);try{await e.ensureServerConnected(t,{pollSeconds:o}),Sw.info(`Server ${t} connected successfully`)}catch(e){throw e instanceof b?Sw.error(`Server '${t}' not found`):Sw.error(`Failed to connect to ${t}:`,e),e}}async function Iw(e,t,r={}){const{serverId:o,serverSlug:n,proxyBaseUrl:s="http://proxy-ingress:8080",transport:a="streamable-http"}=r,i=o||n||t;let c;try{c=await e.getServer(i)}catch(e){if(e instanceof $&&404===e.statusCode)throw new b(i);throw e}const u=c.slug||i;let l;if(q(e.token)){l=`${D(e.token).baseUrl}/mcp/${u}`}else{Sw.warn("Token has no organization information, using static config for MCP connection");l=`${M().baseUrl}/mcp/${u}`}return[{url:l,transport:a,headers:{Accept:"application/json, text/event-stream",Authorization:`Bearer ${e.token}`,"x-barndoor-session-id":Nw()}},l]}async function xw(e,t,r={}){const[o]=await Iw(e,t,r),n=o,s=new I_({name:"barndoor-js-sdk",version:"0.1.0"}),a=new Ew(new URL(n.url),{requestInit:{headers:n.headers}});return await s.connect(a),s}function Nw(){if(R&&"function"==typeof i.randomUUID)return i.randomUUID();if("undefined"!=typeof globalThis&&globalThis.crypto?.randomUUID)return globalThis.crypto.randomUUID();let e;if(R&&"function"==typeof i.randomBytes)e=i.randomBytes(16);else{if("undefined"==typeof globalThis||!globalThis.crypto?.getRandomValues)throw new Error("Secure random generator not available for UUID.");e=new Uint8Array(16),globalThis.crypto.getRandomValues(e)}const t=e??new Uint8Array(0);if(t.length<16)throw new Error("Secure random generator not available for UUID.");const r=t[6],o=t[8];t[6]=15&r|64,t[8]=63&o|128;const n=Array.from(t,e=>e.toString(16).padStart(2,"0")).join("");return`${n.substring(0,8)}-${n.substring(8,12)}-${n.substring(12,16)}-${n.substring(16,20)}-${n.substring(20)}`}const Cw=function(){try{if("undefined"!=typeof process&&process.versions?.node){const e=l(import.meta.url),t=r(e),n=o(t,"..","package.json");return JSON.parse(f(n,"utf8")).version}return'"1.0.2"'}catch(e){return console.warn("Could not read version from package.json:",e),"0.1.0"}}();export{C as AUTH_CONFIG,N as AgentToken,y as AuthenticationError,z as BarndoorConfig,m as BarndoorError,be as BarndoorSDK,E as ConfigurationError,w as ConnectionError,$ as HTTPError,re as JWTVerificationResult,k as OAuthError,ve as PKCEManager,x as ServerDetail,b as ServerNotFoundError,I as ServerSummary,S as TimeoutError,g as TokenError,v as TokenExpiredError,de as TokenManager,_ as TokenValidationError,U as checkTokenOrganization,fe as clearCachedToken,Y as clearOidcConfigCache,H as createScopedLogger,K as debug,Tw as ensureServerConnected,B as error,D as getDynamicConfig,L as getLogger,Q as getOidcConfig,M as getStaticConfig,q as hasOrganizationInfo,Z as info,j as isBrowser,R as isNode,me as isTokenActive,ye as isTokenActiveWithRefresh,he as loadUserToken,Pw as loginInteractive,xw as makeMcpClient,Iw as makeMcpConnectionParams,pe as saveUserToken,F as setLogger,X as setTokenLogger,$e as startLocalCallbackServer,ge as validateToken,ue as verifyJWTLocal,Cw as version,G as warn};
13
+ deps: ${n}}`};const o={keyword:"dependencies",type:"object",schemaType:"object",error:e.error,code(e){const[t,r]=function({schema:e}){const t={},r={};for(const n in e){if("__proto__"===n)continue;(Array.isArray(e[n])?t:r)[n]=e[n]}return[t,r]}(e);s(e,t),a(e,r)}};function s(e,r=e.schema){const{gen:o,data:s,it:a}=e;if(0===Object.keys(r).length)return;const i=o.let("missing");for(const c in r){const u=r[c];if(0===u.length)continue;const l=(0,n.propertyInData)(o,s,c,a.opts.ownProperties);e.setParams({property:c,depsCount:u.length,deps:u.join(", ")}),a.allErrors?o.if(l,()=>{for(const t of u)(0,n.checkReportMissingProp)(e,t)}):(o.if(t._`${l} && (${(0,n.checkMissingProp)(e,u,i)})`),(0,n.reportMissingProp)(e,i),o.else())}}function a(e,t=e.schema){const{gen:o,data:s,keyword:a,it:i}=e,c=o.name("valid");for(const u in t)(0,r.alwaysValidSchema)(i,t[u])||(o.if((0,n.propertyInData)(o,s,u,i.opts.ownProperties),()=>{const t=e.subschema({keyword:a,schemaProp:u},c);e.mergeValidEvaluated(t,c)},()=>o.var(c,!0)),e.ok(c))}e.validatePropertyDeps=s,e.validateSchemaDeps=a,e.default=o}(Qg);var Yg={};Object.defineProperty(Yg,"__esModule",{value:!0});const Xg=pf,ev=yf,tv={message:"property name must be valid",params:({params:e})=>Xg._`{propertyName: ${e.propertyName}}`},rv={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:tv,code(e){const{gen:t,schema:r,data:n,it:o}=e;if((0,ev.alwaysValidSchema)(o,r))return;const s=t.name("valid");t.forIn("key",n,r=>{e.setParams({propertyName:r}),e.subschema({keyword:"propertyNames",data:r,dataTypes:["string"],propertyName:r,compositeRule:!0},s),t.if((0,Xg.not)(s),()=>{e.error(!0),o.allErrors||t.break()})}),e.ok(s)}};Yg.default=rv;var nv={};Object.defineProperty(nv,"__esModule",{value:!0});const ov=sm(),sv=pf,av=Rf(),iv=yf,cv={message:"must NOT have additional properties",params:({params:e})=>sv._`{additionalProperty: ${e.additionalProperty}}`},uv={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:cv,code(e){const{gen:t,schema:r,parentSchema:n,data:o,errsCount:s,it:a}=e;if(!s)throw new Error("ajv implementation error");const{allErrors:i,opts:c}=a;if(a.props=!0,"all"!==c.removeAdditional&&(0,iv.alwaysValidSchema)(a,r))return;const u=(0,ov.allSchemaProperties)(n.properties),l=(0,ov.allSchemaProperties)(n.patternProperties);function d(e){t.code(sv._`delete ${o}[${e}]`)}function h(n){if("all"===c.removeAdditional||c.removeAdditional&&!1===r)d(n);else{if(!1===r)return e.setParams({additionalProperty:n}),e.error(),void(i||t.break());if("object"==typeof r&&!(0,iv.alwaysValidSchema)(a,r)){const r=t.name("valid");"failing"===c.removeAdditional?(p(n,r,!1),t.if((0,sv.not)(r),()=>{e.reset(),d(n)})):(p(n,r),i||t.if((0,sv.not)(r),()=>t.break()))}}}function p(t,r,n){const o={keyword:"additionalProperties",dataProp:t,dataPropType:iv.Type.Str};!1===n&&Object.assign(o,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(o,r)}t.forIn("key",o,r=>{u.length||l.length?t.if(function(r){let o;if(u.length>8){const e=(0,iv.schemaRefOrVal)(a,n.properties,"properties");o=(0,ov.isOwnProperty)(t,e,r)}else o=u.length?(0,sv.or)(...u.map(e=>sv._`${r} === ${e}`)):sv.nil;return l.length&&(o=(0,sv.or)(o,...l.map(t=>sv._`${(0,ov.usePattern)(e,t)}.test(${r})`))),(0,sv.not)(o)}(r),()=>h(r)):h(r)}),e.ok(sv._`${s} === ${av.default.errors}`)}};nv.default=uv;var lv={};Object.defineProperty(lv,"__esModule",{value:!0});const dv=Im(),hv=sm(),pv=yf,fv=nv,mv={keyword:"properties",type:"object",schemaType:"object",code(e){const{gen:t,schema:r,parentSchema:n,data:o,it:s}=e;"all"===s.opts.removeAdditional&&void 0===n.additionalProperties&&fv.default.code(new dv.KeywordCxt(s,fv.default,"additionalProperties"));const a=(0,hv.allSchemaProperties)(r);for(const e of a)s.definedProperties.add(e);s.opts.unevaluated&&a.length&&!0!==s.props&&(s.props=pv.mergeEvaluated.props(t,(0,pv.toHash)(a),s.props));const i=a.filter(e=>!(0,pv.alwaysValidSchema)(s,r[e]));if(0===i.length)return;const c=t.name("valid");for(const r of i)u(r)?l(r):(t.if((0,hv.propertyInData)(t,o,r,s.opts.ownProperties)),l(r),s.allErrors||t.else().var(c,!0),t.endIf()),e.it.definedProperties.add(r),e.ok(c);function u(e){return s.opts.useDefaults&&!s.compositeRule&&void 0!==r[e].default}function l(t){e.subschema({keyword:"properties",schemaProp:t,dataProp:t},c)}}};lv.default=mv;var yv={};Object.defineProperty(yv,"__esModule",{value:!0});const gv=sm(),vv=pf,_v=yf,wv=yf,$v={keyword:"patternProperties",type:"object",schemaType:"object",code(e){const{gen:t,schema:r,data:n,parentSchema:o,it:s}=e,{opts:a}=s,i=(0,gv.allSchemaProperties)(r),c=i.filter(e=>(0,_v.alwaysValidSchema)(s,r[e]));if(0===i.length||c.length===i.length&&(!s.opts.unevaluated||!0===s.props))return;const u=a.strictSchema&&!a.allowMatchingProperties&&o.properties,l=t.name("valid");!0===s.props||s.props instanceof vv.Name||(s.props=(0,wv.evaluatedPropsToName)(t,s.props));const{props:d}=s;function h(e){for(const t in u)new RegExp(e).test(t)&&(0,_v.checkStrictMode)(s,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function p(r){t.forIn("key",n,n=>{t.if(vv._`${(0,gv.usePattern)(e,r)}.test(${n})`,()=>{const o=c.includes(r);o||e.subschema({keyword:"patternProperties",schemaProp:r,dataProp:n,dataPropType:wv.Type.Str},l),s.opts.unevaluated&&!0!==d?t.assign(vv._`${d}[${n}]`,!0):o||s.allErrors||t.if((0,vv.not)(l),()=>t.break())})})}!function(){for(const e of i)u&&h(e),s.allErrors?p(e):(t.var(l,!0),p(e),t.if(l))}()}};yv.default=$v;var bv={};Object.defineProperty(bv,"__esModule",{value:!0});const kv=yf,Ev={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){const{gen:t,schema:r,it:n}=e;if((0,kv.alwaysValidSchema)(n,r))return void e.fail();const o=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),e.failResult(o,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};bv.default=Ev;var Pv={};Object.defineProperty(Pv,"__esModule",{value:!0});const Sv={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:sm().validateUnion,error:{message:"must match a schema in anyOf"}};Pv.default=Sv;var Tv={};Object.defineProperty(Tv,"__esModule",{value:!0});const Iv=pf,xv=yf,Nv={message:"must match exactly one schema in oneOf",params:({params:e})=>Iv._`{passingSchemas: ${e.passing}}`},Cv={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Nv,code(e){const{gen:t,schema:r,parentSchema:n,it:o}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;const s=r,a=t.let("valid",!1),i=t.let("passing",null),c=t.name("_valid");e.setParams({passing:i}),t.block(function(){s.forEach((r,n)=>{let s;(0,xv.alwaysValidSchema)(o,r)?t.var(c,!0):s=e.subschema({keyword:"oneOf",schemaProp:n,compositeRule:!0},c),n>0&&t.if(Iv._`${c} && ${a}`).assign(a,!1).assign(i,Iv._`[${i}, ${n}]`).else(),t.if(c,()=>{t.assign(a,!0),t.assign(i,n),s&&e.mergeEvaluated(s,Iv.Name)})})}),e.result(a,()=>e.reset(),()=>e.error(!0))}};Tv.default=Cv;var jv={};Object.defineProperty(jv,"__esModule",{value:!0});const Rv=yf,Ov={keyword:"allOf",schemaType:"array",code(e){const{gen:t,schema:r,it:n}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");const o=t.name("valid");r.forEach((t,r)=>{if((0,Rv.alwaysValidSchema)(n,t))return;const s=e.subschema({keyword:"allOf",schemaProp:r},o);e.ok(o),e.mergeEvaluated(s)})}};jv.default=Ov;var zv={};Object.defineProperty(zv,"__esModule",{value:!0});const Av=pf,Mv=yf,Dv={message:({params:e})=>Av.str`must match "${e.ifClause}" schema`,params:({params:e})=>Av._`{failingKeyword: ${e.ifClause}}`},Uv={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:Dv,code(e){const{gen:t,parentSchema:r,it:n}=e;void 0===r.then&&void 0===r.else&&(0,Mv.checkStrictMode)(n,'"if" without "then" and "else" is ignored');const o=qv(n,"then"),s=qv(n,"else");if(!o&&!s)return;const a=t.let("valid",!0),i=t.name("_valid");if(function(){const t=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},i);e.mergeEvaluated(t)}(),e.reset(),o&&s){const r=t.let("ifClause");e.setParams({ifClause:r}),t.if(i,c("then",r),c("else",r))}else o?t.if(i,c("then")):t.if((0,Av.not)(i),c("else"));function c(r,n){return()=>{const o=e.subschema({keyword:r},i);t.assign(a,i),e.mergeValidEvaluated(o,a),n?t.assign(n,Av._`${r}`):e.setParams({ifClause:r})}}e.pass(a,()=>e.error(!0))}};function qv(e,t){const r=e.schema[t];return void 0!==r&&!(0,Mv.alwaysValidSchema)(e,r)}zv.default=Uv;var Vv={};Object.defineProperty(Vv,"__esModule",{value:!0});const Fv=yf,Lv={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){void 0===t.if&&(0,Fv.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};Vv.default=Lv,Object.defineProperty(Sg,"__esModule",{value:!0});const Kv=Tg,Hv=jg,Zv=Rg,Gv=Vg,Bv=Gg,Jv=Qg,Wv=Yg,Qv=nv,Yv=lv,Xv=yv,e_=bv,t_=Pv,r_=Tv,n_=jv,o_=zv,s_=Vv;Sg.default=function(e=!1){const t=[e_.default,t_.default,r_.default,n_.default,o_.default,s_.default,Wv.default,Qv.default,Jv.default,Yv.default,Xv.default];return e?t.push(Hv.default,Gv.default):t.push(Kv.default,Zv.default),t.push(Bv.default),t};var a_={},i_={};Object.defineProperty(i_,"__esModule",{value:!0});const c_=pf,u_={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>c_.str`must match format "${e}"`,params:({schemaCode:e})=>c_._`{format: ${e}}`},code(e,t){const{gen:r,data:n,$data:o,schema:s,schemaCode:a,it:i}=e,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=i;c.validateFormats&&(o?function(){const o=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),s=r.const("fDef",c_._`${o}[${a}]`),i=r.let("fType"),u=r.let("format");r.if(c_._`typeof ${s} == "object" && !(${s} instanceof RegExp)`,()=>r.assign(i,c_._`${s}.type || "string"`).assign(u,c_._`${s}.validate`),()=>r.assign(i,c_._`"string"`).assign(u,s)),e.fail$data((0,c_.or)(!1===c.strictSchema?c_.nil:c_._`${a} && !${u}`,function(){const e=l.$async?c_._`(${s}.async ? await ${u}(${n}) : ${u}(${n}))`:c_._`${u}(${n})`,r=c_._`(typeof ${u} == "function" ? ${e} : ${u}.test(${n}))`;return c_._`${u} && ${u} !== true && ${i} === ${t} && !${r}`}()))}():function(){const o=d.formats[s];if(!o)return void function(){if(!1===c.strictSchema)return void d.logger.warn(e());throw new Error(e());function e(){return`unknown format "${s}" ignored in schema at path "${u}"`}}();if(!0===o)return;const[a,i,h]=function(e){const t=e instanceof RegExp?(0,c_.regexpCode)(e):c.code.formats?c_._`${c.code.formats}${(0,c_.getProperty)(s)}`:void 0,n=r.scopeValue("formats",{key:s,ref:e,code:t});if("object"==typeof e&&!(e instanceof RegExp))return[e.type||"string",e.validate,c_._`${n}.validate`];return["string",e,n]}(o);a===t&&e.pass(function(){if("object"==typeof o&&!(o instanceof RegExp)&&o.async){if(!l.$async)throw new Error("async format in sync schema");return c_._`await ${h}(${n})`}return"function"==typeof i?c_._`${h}(${n})`:c_._`${h}.test(${n})`}())}())}};i_.default=u_,Object.defineProperty(a_,"__esModule",{value:!0});const l_=[i_.default];a_.default=l_;var d_={};Object.defineProperty(d_,"__esModule",{value:!0}),d_.contentVocabulary=d_.metadataVocabulary=void 0,d_.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],d_.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"],Object.defineProperty(ey,"__esModule",{value:!0});const h_=yy,p_=Sg,f_=a_,m_=d_,y_=[ty.default,h_.default,(0,p_.default)(),f_.default,m_.metadataVocabulary,m_.contentVocabulary];ey.default=y_;var g_,v_={},__={};Object.defineProperty(__,"__esModule",{value:!0}),__.DiscrError=void 0,function(e){e.Tag="tag",e.Mapping="mapping"}(g_||(__.DiscrError=g_={})),Object.defineProperty(v_,"__esModule",{value:!0});const w_=pf,$_=__,b_=zm,k_=Om(),E_=yf,P_={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:e,tagName:t}})=>e===$_.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>w_._`{error: ${e}, tag: ${r}, tagValue: ${t}}`},code(e){const{gen:t,data:r,schema:n,parentSchema:o,it:s}=e,{oneOf:a}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");const i=n.propertyName;if("string"!=typeof i)throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!a)throw new Error("discriminator: requires oneOf keyword");const c=t.let("valid",!1),u=t.const("tag",w_._`${r}${(0,w_.getProperty)(i)}`);function l(r){const n=t.name("valid"),o=e.subschema({keyword:"oneOf",schemaProp:r},n);return e.mergeEvaluated(o,w_.Name),n}t.if(w_._`typeof ${u} == "string"`,()=>function(){const r=function(){var e;const t={},r=c(o);let n=!0;for(let t=0;t<a.length;t++){let o=a[t];if((null==o?void 0:o.$ref)&&!(0,E_.schemaHasRulesButRef)(o,s.self.RULES)){const e=o.$ref;if(o=b_.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,e),o instanceof b_.SchemaEnv&&(o=o.schema),void 0===o)throw new k_.default(s.opts.uriResolver,s.baseId,e)}const l=null===(e=null==o?void 0:o.properties)||void 0===e?void 0:e[i];if("object"!=typeof l)throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${i}"`);n=n&&(r||c(o)),u(l,t)}if(!n)throw new Error(`discriminator: "${i}" must be required`);return t;function c({required:e}){return Array.isArray(e)&&e.includes(i)}function u(e,t){if(e.const)l(e.const,t);else{if(!e.enum)throw new Error(`discriminator: "properties/${i}" must have "const" or "enum"`);for(const r of e.enum)l(r,t)}}function l(e,r){if("string"!=typeof e||e in t)throw new Error(`discriminator: "${i}" values must be unique strings`);t[e]=r}}();t.if(!1);for(const e in r)t.elseIf(w_._`${u} === ${e}`),t.assign(c,l(r[e]));t.else(),e.error(!1,{discrError:$_.DiscrError.Mapping,tag:u,tagName:i}),t.endIf()}(),()=>e.error(!1,{discrError:$_.DiscrError.Tag,tag:u,tagName:i})),e.ok(c)}};v_.default=P_;var S_={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0};!function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.MissingRefError=t.ValidationError=t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=t.Ajv=void 0;const r=uf,n=ey,o=v_,s=S_,a=["/properties"],i="http://json-schema.org/draft-07/schema";class c extends r.default{_addVocabularies(){super._addVocabularies(),n.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(o.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const e=this.opts.$data?this.$dataMetaSchema(s,a):s;this.addMetaSchema(e,i,!1),this.refs["http://json-schema.org/schema"]=i}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(i)?i:void 0)}}t.Ajv=c,e.exports=t=c,e.exports.Ajv=c,Object.defineProperty(t,"__esModule",{value:!0}),t.default=c;var u=Im();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return u.KeywordCxt}});var l=pf;Object.defineProperty(t,"_",{enumerable:!0,get:function(){return l._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return l.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return l.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return l.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return l.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return l.CodeGen}});var d=Cm();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return d.default}});var h=Om();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return h.default}})}(cf,cf.exports);var T_=cf.exports;!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;const t=T_,r=pf,n=r.operators,o={formatMaximum:{okStr:"<=",ok:n.LTE,fail:n.GT},formatMinimum:{okStr:">=",ok:n.GTE,fail:n.LT},formatExclusiveMaximum:{okStr:"<",ok:n.LT,fail:n.GTE},formatExclusiveMinimum:{okStr:">",ok:n.GT,fail:n.LTE}},s={message:({keyword:e,schemaCode:t})=>r.str`should be ${o[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>r._`{comparison: ${o[e].okStr}, limit: ${t}}`};e.formatLimitDefinition={keyword:Object.keys(o),type:"string",schemaType:"string",$data:!0,error:s,code(e){const{gen:n,data:s,schemaCode:a,keyword:i,it:c}=e,{opts:u,self:l}=c;if(!u.validateFormats)return;const d=new t.KeywordCxt(c,l.RULES.all.format.definition,"format");function h(e){return r._`${e}.compare(${s}, ${a}) ${o[i].fail} 0`}d.$data?function(){const t=n.scopeValue("formats",{ref:l.formats,code:u.code.formats}),o=n.const("fmt",r._`${t}[${d.schemaCode}]`);e.fail$data((0,r.or)(r._`typeof ${o} != "object"`,r._`${o} instanceof RegExp`,r._`typeof ${o}.compare != "function"`,h(o)))}():function(){const t=d.schema,o=l.formats[t];if(!o||!0===o)return;if("object"!=typeof o||o instanceof RegExp||"function"!=typeof o.compare)throw new Error(`"${i}": format "${t}" does not define "compare" function`);const s=n.scopeValue("formats",{key:t,ref:o,code:u.code.formats?r._`${u.code.formats}${(0,r.getProperty)(t)}`:void 0});e.fail$data(h(s))}()},dependencies:["format"]};e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)}(af),function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r=sf,n=af,o=pf,s=new o.Name("fullFormats"),a=new o.Name("fastFormats"),i=(e,t={keywords:!0})=>{if(Array.isArray(t))return c(e,t,r.fullFormats,s),e;const[o,i]="fast"===t.mode?[r.fastFormats,a]:[r.fullFormats,s];return c(e,t.formats||r.formatNames,o,i),t.keywords&&(0,n.default)(e),e};function c(e,t,r,n){var s,a;null!==(s=(a=e.opts.code).formats)&&void 0!==s||(a.formats=o._`require("ajv-formats/dist/formats").${n}`);for(const n of t)e.addFormat(n,r[n])}i.get=(e,t="full")=>{const n=("fast"===t?r.fastFormats:r.fullFormats)[e];if(!n)throw new Error(`Unknown format "${e}"`);return n},e.exports=t=i,Object.defineProperty(t,"__esModule",{value:!0}),t.default=i}(of,of.exports);var I_=Qi(of.exports);class x_{constructor(e){this._ajv=e??function(){const e=new nf({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return I_(e),e}()}getValidator(e){const t="$id"in e&&"string"==typeof e.$id?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}}class N_{constructor(e){this._client=e}async*callToolStream(e,t=Xa,r){const n=this._client,o={...r,task:r?.task??(n.isToolTask(e.name)?{}:void 0)},s=n.requestStream({method:"tools/call",params:e},t,o),a=n.getToolOutputValidator(e.name);for await(const t of s){if("result"===t.type&&a){const r=t.result;if(!r.structuredContent&&!r.isError)return void(yield{type:"error",error:new Ki(Ps.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)});if(r.structuredContent)try{const e=a(r.structuredContent);if(!e.valid)return void(yield{type:"error",error:new Ki(Ps.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)})}catch(e){return e instanceof Ki?void(yield{type:"error",error:e}):void(yield{type:"error",error:new Ki(Ps.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)})}}yield t}}async getTask(e,t){return this._client.getTask({taskId:e},t)}async getTaskResult(e,t,r){return this._client.getTaskResult({taskId:e},t,r)}async listTasks(e,t){return this._client.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._client.cancelTask({taskId:e},t)}requestStream(e,t,r){return this._client.requestStream(e,t,r)}}function C_(e,t){if(e&&null!==t&&"object"==typeof t){if("object"===e.type&&e.properties&&"object"==typeof e.properties){const r=t,n=e.properties;for(const e of Object.keys(n)){const t=n[e];void 0===r[e]&&Object.prototype.hasOwnProperty.call(t,"default")&&(r[e]=t.default),void 0!==r[e]&&C_(t,r[e])}}if(Array.isArray(e.anyOf))for(const r of e.anyOf)"boolean"!=typeof r&&C_(r,t);if(Array.isArray(e.oneOf))for(const r of e.oneOf)"boolean"!=typeof r&&C_(r,t)}}class j_ extends Ji{constructor(e,t){super(t),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=t?.capabilities??{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new x_,t?.listChanged&&(this._pendingListChangedConfig=t.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",ri,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Ga,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Sa,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new N_(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=function(e,t){const r={...e};for(const e in t){const n=e,o=t[n];if(void 0===o)continue;const s=r[n];Wi(s)&&Wi(o)?r[n]={...s,...o}:r[n]=o}return r}(this._capabilities,e)}setRequestHandler(e,t){const r=Pn(e),n=r?.method;if(!n)throw new Error("Schema is missing a method literal");let o;if(kn(n)){const e=n,t=e._zod?.def;o=t?.value??e.value}else{const e=n,t=e._def;o=t?.value??e.value}if("string"!=typeof o)throw new Error("Schema method literal must be a string");const s=o;if("elicitation/create"===s){const r=async(e,r)=>{const n=En(Ci,e);if(!n.success){const e=n.error instanceof Error?n.error.message:String(n.error);throw new Ki(Ps.InvalidParams,`Invalid elicitation request: ${e}`)}const{params:o}=n.data;o.mode=o.mode??"form";const{supportsFormMode:s,supportsUrlMode:a}=function(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};const t=void 0!==e.form,r=void 0!==e.url;return{supportsFormMode:t||!t&&!r,supportsUrlMode:r}}(this._capabilities.elicitation);if("form"===o.mode&&!s)throw new Ki(Ps.InvalidParams,"Client does not support form-mode elicitation requests");if("url"===o.mode&&!a)throw new Ki(Ps.InvalidParams,"Client does not support URL-mode elicitation requests");const i=await Promise.resolve(t(e,r));if(o.task){const e=En(ea,i);if(!e.success){const t=e.error instanceof Error?e.error.message:String(e.error);throw new Ki(Ps.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}const c=En(Oi,i);if(!c.success){const e=c.error instanceof Error?c.error.message:String(c.error);throw new Ki(Ps.InvalidParams,`Invalid elicitation result: ${e}`)}const u=c.data,l="form"===o.mode?o.requestedSchema:void 0;if("form"===o.mode&&"accept"===u.action&&u.content&&l&&this._capabilities.elicitation?.form?.applyDefaults)try{C_(l,u.content)}catch{}return u};return super.setRequestHandler(e,r)}if("sampling/createMessage"===s){const r=async(e,r)=>{const n=En(gi,e);if(!n.success){const e=n.error instanceof Error?n.error.message:String(n.error);throw new Ki(Ps.InvalidParams,`Invalid sampling request: ${e}`)}const{params:o}=n.data,s=await Promise.resolve(t(e,r));if(o.task){const e=En(ea,s);if(!e.success){const t=e.error instanceof Error?e.error.message:String(e.error);throw new Ki(Ps.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}const a=En(o.tools||o.toolChoice?_i:vi,s);if(!a.success){const e=a.error instanceof Error?a.error.message:String(a.error);throw new Ki(Ps.InvalidParams,`Invalid sampling result: ${e}`)}return a.data};return super.setRequestHandler(e,r)}return super.setRequestHandler(e,t)}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw new Error(`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(await super.connect(e),void 0===e.sessionId)try{const r=await this.request({method:"initialize",params:{protocolVersion:rs,capabilities:this._capabilities,clientInfo:this._clientInfo}},Ls,t);if(void 0===r)throw new Error(`Server sent invalid initialize result: ${r}`);if(!ns.includes(r.protocolVersion))throw new Error(`Server's protocol version is not supported: ${r.protocolVersion}`);this._serverCapabilities=r.capabilities,this._serverVersion=r.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(r.protocolVersion),this._instructions=r.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(e){throw this.close(),e}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${e})`);if("resources/subscribe"===e&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${e})`)}}assertNotificationCapability(e){if("notifications/roots/list_changed"===e)if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${e})`)}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${e})`)}}assertTaskCapability(e){!function(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);if("tools/call"===t&&!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`)}(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&function(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`)}}(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},Is,e)}async complete(e,t){return this.request({method:"completion/complete",params:e},Ui,t)}async setLoggingLevel(e,t){return this.request({method:"logging/setLevel",params:{level:e}},Is,t)}async getPrompt(e,t){return this.request({method:"prompts/get",params:e},Za,t)}async listPrompts(e,t){return this.request({method:"prompts/list",params:e},Aa,t)}async listResources(e,t){return this.request({method:"resources/list",params:e},_a,t)}async listResourceTemplates(e,t){return this.request({method:"resources/templates/list",params:e},$a,t)}async readResource(e,t){return this.request({method:"resources/read",params:e},Pa,t)}async subscribeResource(e,t){return this.request({method:"resources/subscribe",params:e},Is,t)}async unsubscribeResource(e,t){return this.request({method:"resources/unsubscribe",params:e},Is,t)}async callTool(e,t=Xa,r){if(this.isToolTaskRequired(e.name))throw new Ki(Ps.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);const n=await this.request({method:"tools/call",params:e},t,r),o=this.getToolOutputValidator(e.name);if(o){if(!n.structuredContent&&!n.isError)throw new Ki(Ps.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(n.structuredContent)try{const e=o(n.structuredContent);if(!e.valid)throw new Ki(Ps.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)}catch(e){if(e instanceof Ki)throw e;throw new Ki(Ps.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)}}return n}isToolTask(e){return!!this._serverCapabilities?.tasks?.requests?.tools?.call&&this._cachedKnownTaskTools.has(e)}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(const t of e){if(t.outputSchema){const e=this._jsonSchemaValidator.getValidator(t.outputSchema);this._cachedToolOutputValidators.set(t.name,e)}const e=t.execution?.taskSupport;"required"!==e&&"optional"!==e||this._cachedKnownTaskTools.add(t.name),"required"===e&&this._cachedRequiredTaskTools.add(t.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,t){const r=await this.request({method:"tools/list",params:e},Ya,t);return this.cacheToolMetadata(r.tools),r}_setupListChangedHandler(e,t,r,n){const o=ni.safeParse(r);if(!o.success)throw new Error(`Invalid ${e} listChanged options: ${o.error.message}`);if("function"!=typeof r.onChanged)throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);const{autoRefresh:s,debounceMs:a}=o.data,{onChanged:i}=r,c=async()=>{if(s)try{const e=await n();i(null,e)}catch(e){const t=e instanceof Error?e:new Error(String(e));i(t,null)}else i(null,null)};this.setNotificationHandler(t,()=>{if(a){const t=this._listChangedDebounceTimers.get(e);t&&clearTimeout(t);const r=setTimeout(c,a);this._listChangedDebounceTimers.set(e,r)}else c()})}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}function R_(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}const O_=pn(Gn,z_).superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:ts,message:"URL must be parseable",fatal:!0}),Pe}).refine(e=>{const t=new URL(e);return"javascript:"!==t.protocol&&"data:"!==t.protocol&&"vbscript:"!==t.protocol},{message:"URL cannot use javascript:, data:, or vbscript: scheme"});var z_;const A_=To({resource:Fn().url(),authorization_servers:Eo(O_).optional(),jwks_uri:Fn().url().optional(),scopes_supported:Eo(Fn()).optional(),bearer_methods_supported:Eo(Fn()).optional(),resource_signing_alg_values_supported:Eo(Fn()).optional(),resource_name:Fn().optional(),resource_documentation:Fn().optional(),resource_policy_uri:Fn().url().optional(),resource_tos_uri:Fn().url().optional(),tls_client_certificate_bound_access_tokens:mo().optional(),authorization_details_types_supported:Eo(Fn()).optional(),dpop_signing_alg_values_supported:Eo(Fn()).optional(),dpop_bound_access_tokens_required:mo().optional()}),M_=To({issuer:Fn(),authorization_endpoint:O_,token_endpoint:O_,registration_endpoint:O_.optional(),scopes_supported:Eo(Fn()).optional(),response_types_supported:Eo(Fn()),response_modes_supported:Eo(Fn()).optional(),grant_types_supported:Eo(Fn()).optional(),token_endpoint_auth_methods_supported:Eo(Fn()).optional(),token_endpoint_auth_signing_alg_values_supported:Eo(Fn()).optional(),service_documentation:O_.optional(),revocation_endpoint:O_.optional(),revocation_endpoint_auth_methods_supported:Eo(Fn()).optional(),revocation_endpoint_auth_signing_alg_values_supported:Eo(Fn()).optional(),introspection_endpoint:Fn().optional(),introspection_endpoint_auth_methods_supported:Eo(Fn()).optional(),introspection_endpoint_auth_signing_alg_values_supported:Eo(Fn()).optional(),code_challenge_methods_supported:Eo(Fn()).optional(),client_id_metadata_document_supported:mo().optional()}),D_=So({...To({issuer:Fn(),authorization_endpoint:O_,token_endpoint:O_,userinfo_endpoint:O_.optional(),jwks_uri:O_,registration_endpoint:O_.optional(),scopes_supported:Eo(Fn()).optional(),response_types_supported:Eo(Fn()),response_modes_supported:Eo(Fn()).optional(),grant_types_supported:Eo(Fn()).optional(),acr_values_supported:Eo(Fn()).optional(),subject_types_supported:Eo(Fn()),id_token_signing_alg_values_supported:Eo(Fn()),id_token_encryption_alg_values_supported:Eo(Fn()).optional(),id_token_encryption_enc_values_supported:Eo(Fn()).optional(),userinfo_signing_alg_values_supported:Eo(Fn()).optional(),userinfo_encryption_alg_values_supported:Eo(Fn()).optional(),userinfo_encryption_enc_values_supported:Eo(Fn()).optional(),request_object_signing_alg_values_supported:Eo(Fn()).optional(),request_object_encryption_alg_values_supported:Eo(Fn()).optional(),request_object_encryption_enc_values_supported:Eo(Fn()).optional(),token_endpoint_auth_methods_supported:Eo(Fn()).optional(),token_endpoint_auth_signing_alg_values_supported:Eo(Fn()).optional(),display_values_supported:Eo(Fn()).optional(),claim_types_supported:Eo(Fn()).optional(),claims_supported:Eo(Fn()).optional(),service_documentation:Fn().optional(),claims_locales_supported:Eo(Fn()).optional(),ui_locales_supported:Eo(Fn()).optional(),claims_parameter_supported:mo().optional(),request_parameter_supported:mo().optional(),request_uri_parameter_supported:mo().optional(),require_request_uri_registration:mo().optional(),op_policy_uri:O_.optional(),op_tos_uri:O_.optional(),client_id_metadata_document_supported:mo().optional()}).shape,...M_.pick({code_challenge_methods_supported:!0}).shape}),U_=So({access_token:Fn(),id_token:Fn().optional(),token_type:Fn(),expires_in:function(e){return function(e,t){return new e({type:"number",coerce:!0,checks:[],...Ke(t)})}(uo,e)}().optional(),scope:Fn().optional(),refresh_token:Fn().optional()}).strip(),q_=So({error:Fn(),error_description:Fn().optional(),error_uri:Fn().optional()}),V_=O_.optional().or(Uo("").transform(()=>{})),F_=So({redirect_uris:Eo(O_),token_endpoint_auth_method:Fn().optional(),grant_types:Eo(Fn()).optional(),response_types:Eo(Fn()).optional(),client_name:Fn().optional(),client_uri:O_.optional(),logo_uri:V_,scope:Fn().optional(),contacts:Eo(Fn()).optional(),tos_uri:V_,policy_uri:Fn().optional(),jwks_uri:O_.optional(),jwks:new vo({type:"any"}).optional(),software_id:Fn().optional(),software_version:Fn().optional(),software_statement:Fn().optional()}).strip(),L_=So({client_id:Fn(),client_secret:Fn().optional(),client_id_issued_at:lo().optional(),client_secret_expires_at:lo().optional()}).strip(),K_=F_.merge(L_);So({error:Fn(),error_description:Fn().optional()}).strip(),So({token:Fn(),token_type_hint:Fn().optional()}).strip();class H_ extends Error{constructor(e,t){super(e),this.errorUri=t,this.name=this.constructor.name}toResponseObject(){const e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}}class Z_ extends H_{}Z_.errorCode="invalid_request";class G_ extends H_{}G_.errorCode="invalid_client";class B_ extends H_{}B_.errorCode="invalid_grant";class J_ extends H_{}J_.errorCode="unauthorized_client";class W_ extends H_{}W_.errorCode="unsupported_grant_type";class Q_ extends H_{}Q_.errorCode="invalid_scope";class Y_ extends H_{}Y_.errorCode="access_denied";class X_ extends H_{}X_.errorCode="server_error";class ew extends H_{}ew.errorCode="temporarily_unavailable";class tw extends H_{}tw.errorCode="unsupported_response_type";class rw extends H_{}rw.errorCode="unsupported_token_type";class nw extends H_{}nw.errorCode="invalid_token";class ow extends H_{}ow.errorCode="method_not_allowed";class sw extends H_{}sw.errorCode="too_many_requests";class aw extends H_{}aw.errorCode="invalid_client_metadata";class iw extends H_{}iw.errorCode="insufficient_scope";class cw extends H_{}cw.errorCode="invalid_target";const uw={[Z_.errorCode]:Z_,[G_.errorCode]:G_,[B_.errorCode]:B_,[J_.errorCode]:J_,[W_.errorCode]:W_,[Q_.errorCode]:Q_,[Y_.errorCode]:Y_,[X_.errorCode]:X_,[ew.errorCode]:ew,[tw.errorCode]:tw,[rw.errorCode]:rw,[nw.errorCode]:nw,[ow.errorCode]:ow,[sw.errorCode]:sw,[aw.errorCode]:aw,[iw.errorCode]:iw,[cw.errorCode]:cw};class lw extends Error{constructor(e){super(e??"Unauthorized")}}const dw="code",hw="S256";function pw(e,t,r,n){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":return void function(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const n=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${n}`)}(o,s,r);case"client_secret_post":return void function(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}(o,s,n);case"none":return void function(e,t){t.set("client_id",e)}(o,n);default:throw new Error(`Unsupported client authentication method: ${e}`)}}async function fw(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const e=q_.parse(JSON.parse(r)),{error:t,error_description:n,error_uri:o}=e;return new(uw[t]||X_)(n||"",o)}catch(e){return new X_(`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${e}. Raw body: ${r}`)}}async function mw(e,t){try{return await yw(e,t)}catch(r){if(r instanceof G_||r instanceof J_)return await(e.invalidateCredentials?.("all")),await yw(e,t);if(r instanceof B_)return await(e.invalidateCredentials?.("tokens")),await yw(e,t);throw r}}async function yw(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){let a,i;try{a=await async function(e,t,r=fetch){const n=await async function(e,t,r,n){const o=new URL(e),s=n?.protocolVersion??rs;let a;if(n?.metadataUrl)a=new URL(n.metadataUrl);else{const e=function(e,t="",r={}){t.endsWith("/")&&(t=t.slice(0,-1));return r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}(t,o.pathname);a=new URL(e,n?.metadataServerUrl??o),a.search=o.search}let i=await ww(a,s,r);if(!n?.metadataUrl&&function(e,t){return!e||e.status>=400&&e.status<500&&"/"!==t}(i,o.pathname)){const e=new URL(`/.well-known/${t}`,o);i=await ww(e,s,r)}return i}(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!n||404===n.status)throw await(n?.body?.cancel()),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw await(n.body?.cancel()),new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return A_.parse(await n.json())}(t,{resourceMetadataUrl:o},s),a.authorization_servers&&a.authorization_servers.length>0&&(i=a.authorization_servers[0])}catch{}i||(i=new URL("/",t));const c=await async function(e,t,r){const n=function(e){const t="string"==typeof e?new URL(e):new URL(e.href);return t.hash="",t}(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(!r)return;if(!function({requestedResource:e,configuredResource:t}){const r="string"==typeof e?new URL(e):new URL(e.href),n="string"==typeof t?new URL(t):new URL(t.href);if(r.origin!==n.origin)return!1;if(r.pathname.length<n.pathname.length)return!1;const o=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return o.startsWith(s)}({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}(t,e,a),u=await async function(e,{fetchFn:t=fetch,protocolVersion:r=rs}={}){const n={"MCP-Protocol-Version":r,Accept:"application/json"},o=function(e){const t="string"==typeof e?new URL(e):e,r="/"!==t.pathname,n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),n;let o=t.pathname;o.endsWith("/")&&(o=o.slice(0,-1));return n.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,t.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${o}`,t.origin),type:"oidc"}),n.push({url:new URL(`${o}/.well-known/openid-configuration`,t.origin),type:"oidc"}),n}(e);for(const{url:e,type:r}of o){const o=await _w(e,n,t);if(o){if(!o.ok){if(await(o.body?.cancel()),o.status>=400&&o.status<500)continue;throw new Error(`HTTP ${o.status} trying to load ${"oauth"===r?"OAuth":"OpenID provider"} metadata from ${e}`)}return"oauth"===r?M_.parse(await o.json()):D_.parse(await o.json())}}return}(i,{fetchFn:s});let l=await Promise.resolve(e.clientInformation());if(!l){if(void 0!==r)throw new Error("Existing OAuth client information is required when exchanging an authorization code");const t=!0===u?.client_id_metadata_document_supported,n=e.clientMetadataUrl;if(n&&!function(e){if(!e)return!1;try{const t=new URL(e);return"https:"===t.protocol&&"/"!==t.pathname}catch{return!1}}(n))throw new aw(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${n}`);if(t&&n)l={client_id:n},await(e.saveClientInformation?.(l));else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const t=await async function(e,{metadata:t,clientMetadata:r,fetchFn:n}){let o;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");o=new URL(t.registration_endpoint)}else o=new URL("/register",e);const s=await(n??fetch)(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok)throw await fw(s);return K_.parse(await s.json())}(i,{metadata:u,clientMetadata:e.clientMetadata,fetchFn:s});await e.saveClientInformation(t),l=t}}const d=!e.redirectUrl;if(void 0!==r||d){const t=await async function(e,t,{metadata:r,resource:n,authorizationCode:o,fetchFn:s}={}){const a=e.clientMetadata.scope;let i;e.prepareTokenRequest&&(i=await e.prepareTokenRequest(a));if(!i){if(!o)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");i=function(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}(o,await e.codeVerifier(),e.redirectUrl)}const c=await e.clientInformation();return $w(t,{metadata:r,tokenRequestParams:i,clientInformation:c??void 0,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:s})}(e,i,{metadata:u,resource:c,authorizationCode:r,fetchFn:s});return await e.saveTokens(t),"AUTHORIZED"}const h=await e.tokens();if(h?.refresh_token)try{const t=await async function(e,{metadata:t,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:s,fetchFn:a}){const i=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),c=await $w(e,{metadata:t,tokenRequestParams:i,clientInformation:r,addClientAuthentication:s,resource:o,fetchFn:a});return{refresh_token:n,...c}}(i,{metadata:u,clientInformation:l,refreshToken:h.refresh_token,resource:c,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(t),"AUTHORIZED"}catch(e){if(e instanceof H_&&!(e instanceof X_))throw e}const f=e.state?await e.state():void 0,{authorizationUrl:m,codeVerifier:y}=await async function(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:o,state:s,resource:a}){let i;if(t){if(i=new URL(t.authorization_endpoint),!t.response_types_supported.includes(dw))throw new Error(`Incompatible auth server: does not support response type ${dw}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(hw))throw new Error(`Incompatible auth server: does not support code challenge method ${hw}`)}else i=new URL("/authorize",e);const c=await p(),u=c.code_verifier,l=c.code_challenge;i.searchParams.set("response_type",dw),i.searchParams.set("client_id",r.client_id),i.searchParams.set("code_challenge",l),i.searchParams.set("code_challenge_method",hw),i.searchParams.set("redirect_uri",String(n)),s&&i.searchParams.set("state",s);o&&i.searchParams.set("scope",o);o?.includes("offline_access")&&i.searchParams.append("prompt","consent");a&&i.searchParams.set("resource",a.href);return{authorizationUrl:i,codeVerifier:u}}(i,{metadata:u,clientInformation:l,state:f,redirectUrl:e.redirectUrl,scope:n||a?.scopes_supported?.join(" ")||e.clientMetadata.scope,resource:c});return await e.saveCodeVerifier(y),await e.redirectToAuthorization(m),"REDIRECT"}function gw(e){const t=e.headers.get("WWW-Authenticate");if(!t)return{};const[r,n]=t.split(" ");if("bearer"!==r.toLowerCase()||!n)return{};const o=vw(e,"resource_metadata")||void 0;let s;if(o)try{s=new URL(o)}catch{}return{resourceMetadataUrl:s,scope:vw(e,"scope")||void 0,error:vw(e,"error")||void 0}}function vw(e,t){const r=e.headers.get("WWW-Authenticate");if(!r)return null;const n=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),o=r.match(n);return o?o[1]||o[2]:null}async function _w(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?_w(e,void 0,r):void 0;throw n}}async function ww(e,t,r=fetch){const n={"MCP-Protocol-Version":t};return await _w(e,n,r)}async function $w(e,{metadata:t,tokenRequestParams:r,clientInformation:n,addClientAuthentication:o,resource:s,fetchFn:a}){const i=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),c=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(s&&r.set("resource",s.href),o)await o(c,r,i,t);else if(n){const e=function(e,t){const r=void 0!==e.client_secret;return 0===t.length?r?"client_secret_post":"none":"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&(n=e.token_endpoint_auth_method,["client_secret_basic","client_secret_post","none"].includes(n))&&t.includes(e.token_endpoint_auth_method)?e.token_endpoint_auth_method:r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none";var n}(n,t?.token_endpoint_auth_methods_supported??[]);pw(e,n,c,r)}const u=await(a??fetch)(i,{method:"POST",headers:c,body:r});if(!u.ok)throw await fw(u);return U_.parse(await u.json())}class bw 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 kw(e){}function Ew(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=kw,onError:r=kw,onRetry:n=kw,onComment:o}=e;let s,a="",i=!0,c="",u="";function l(e){if(""===e)return c.length>0&&t({id:s,event:u||void 0,data:c.endsWith("\n")?c.slice(0,-1):c}),s=void 0,c="",void(u="");if(e.startsWith(":"))return void(o&&o(e.slice(e.startsWith(": ")?2:1)));const r=e.indexOf(":");if(-1!==r){const t=e.slice(0,r),n=" "===e[r+1]?2:1;return void d(t,e.slice(r+n),e)}d(e,"",e)}function d(e,t,o){switch(e){case"event":u=t;break;case"data":c=`${c}${t}\n`;break;case"id":s=t.includes("\0")?void 0:t;break;case"retry":/^\d+$/.test(t)?n(parseInt(t,10)):r(new bw(`Invalid \`retry\` value: "${t}"`,{type:"invalid-retry",value:t,line:o}));break;default:r(new bw(`Unknown field "${e.length>20?`${e.slice(0,20)}…`:e}"`,{type:"unknown-field",field:e,value:t,line:o}))}}return{feed:function(e){const t=i?e.replace(/^\xEF\xBB\xBF/,""):e,[r,n]=function(e){const t=[];let r="",n=0;for(;n<e.length;){const o=e.indexOf("\r",n),s=e.indexOf("\n",n);let a=-1;if(-1!==o&&-1!==s?a=Math.min(o,s):-1!==o?a=o:-1!==s&&(a=s),-1===a){r=e.slice(n);break}{const r=e.slice(n,a);t.push(r),n=a+1,"\r"===e[n-1]&&"\n"===e[n]&&n++}}return[t,r]}(`${a}${t}`);for(const e of r)l(e);a=n,i=!1},reset:function(e={}){a&&e.consume&&l(a),i=!0,s=void 0,c="",u="",a=""}}}class Pw extends TransformStream{constructor({onError:e,onRetry:t,onComment:r}={}){let n;super({start(o){n=Ew({onEvent:e=>{o.enqueue(e)},onError(t){"terminate"===e?o.error(t):"function"==typeof e&&e(t)},onRetry:t,onComment:r})},transform(e){n.feed(e)}})}}const Sw={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class Tw extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}}class Iw{constructor(e,t){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=function(e=fetch,t){return t?async(r,n)=>{const o={...t,...n,headers:n?.headers?{...R_(t.headers),...R_(n.headers)}:t.headers};return e(r,o)}:e}(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??Sw}async _authThenStart(){if(!this._authProvider)throw new lw("No auth provider");let e;try{e=await mw(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(e){throw this.onerror?.(e),e}if("AUTHORIZED"!==e)throw new lw;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){const e={};if(this._authProvider){const t=await this._authProvider.tokens();t&&(e.Authorization=`Bearer ${t.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);const t=R_(this._requestInit?.headers);return new Headers({...e,...t})}async _startOrAuthSse(e){const{resumptionToken:t}=e;try{const r=await this._commonHeaders();r.set("Accept","text/event-stream"),t&&r.set("last-event-id",t);const n=await(this._fetch??fetch)(this._url,{method:"GET",headers:r,signal:this._abortController?.signal});if(!n.ok){if(await(n.body?.cancel()),401===n.status&&this._authProvider)return await this._authThenStart();if(405===n.status)return;throw new Tw(n.status,`Failed to open SSE stream: ${n.statusText}`)}this._handleSseStream(n.body,e,!0)}catch(e){throw this.onerror?.(e),e}}_getNextReconnectionDelay(e){if(void 0!==this._serverRetryMs)return this._serverRetryMs;const t=this._reconnectionOptions.initialReconnectionDelay,r=this._reconnectionOptions.reconnectionDelayGrowFactor,n=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*Math.pow(r,e),n)}_scheduleReconnection(e,t=0){const r=this._reconnectionOptions.maxRetries;if(t>=r)return void this.onerror?.(new Error(`Maximum reconnection attempts (${r}) exceeded.`));const n=this._getNextReconnectionDelay(t);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(r=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${r instanceof Error?r.message:String(r)}`)),this._scheduleReconnection(e,t+1)})},n)}_handleSseStream(e,t,r){if(!e)return;const{onresumptiontoken:n,replayMessageId:o}=t;let s,a=!1,i=!1;(async()=>{try{const t=e.pipeThrough(new TextDecoderStream).pipeThrough(new Pw({onRetry:e=>{this._serverRetryMs=e}})).getReader();for(;;){const{value:e,done:r}=await t.read();if(r)break;if(e.id&&(s=e.id,a=!0,n?.(e.id)),e.data&&(!e.event||"message"===e.event))try{const t=Ts.parse(JSON.parse(e.data));Es(t)&&(i=!0,void 0!==o&&(t.id=o)),this.onmessage?.(t)}catch(e){this.onerror?.(e)}}(r||a)&&!i&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:s,onresumptiontoken:n,replayMessageId:o},0)}catch(e){this.onerror?.(new Error(`SSE stream disconnected: ${e}`));if((r||a)&&!i&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:n,replayMessageId:o},0)}catch(e){this.onerror?.(new Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new lw("No auth provider");if("AUTHORIZED"!==await mw(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit}))throw new lw("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,t){try{const{resumptionToken:n,onresumptiontoken:o}=t||{};if(n)return void this._startOrAuthSse({resumptionToken:n,replayMessageId:$s(e)?e.id:void 0}).catch(e=>this.onerror?.(e));const s=await this._commonHeaders();s.set("content-type","application/json"),s.set("accept","application/json, text/event-stream");const a={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:this._abortController?.signal},i=await(this._fetch??fetch)(this._url,a),c=i.headers.get("mcp-session-id");if(c&&(this._sessionId=c),!i.ok){const t=await i.text().catch(()=>null);if(401===i.status&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Tw(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:t,scope:r}=gw(i);this._resourceMetadataUrl=t,this._scope=r;if("AUTHORIZED"!==await mw(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit}))throw new lw;return this._hasCompletedAuthFlow=!0,this.send(e)}if(403===i.status&&this._authProvider){const{resourceMetadataUrl:t,scope:r,error:n}=gw(i);if("insufficient_scope"===n){const n=i.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===n)throw new Tw(403,"Server returned 403 after trying upscoping");r&&(this._scope=r),t&&(this._resourceMetadataUrl=t),this._lastUpscopingHeader=n??void 0;if("AUTHORIZED"!==await mw(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch}))throw new lw;return this.send(e)}}throw new Tw(i.status,`Error POSTing to endpoint: ${t}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,202===i.status)return await(i.body?.cancel()),r=e,void(Ks.safeParse(r).success&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>this.onerror?.(e)));const u=(Array.isArray(e)?e:[e]).filter(e=>"method"in e&&"id"in e&&void 0!==e.id).length>0,l=i.headers.get("content-type");if(u)if(l?.includes("text/event-stream"))this._handleSseStream(i.body,{onresumptiontoken:o},!1);else{if(!l?.includes("application/json"))throw await(i.body?.cancel()),new Tw(-1,`Unexpected content type: ${l}`);{const e=await i.json(),t=Array.isArray(e)?e.map(e=>Ts.parse(e)):[Ts.parse(e)];for(const e of t)this.onmessage?.(e)}}else await(i.body?.cancel())}catch(e){throw this.onerror?.(e),e}var r}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{const e=await this._commonHeaders(),t={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},r=await(this._fetch??fetch)(this._url,t);if(await(r.body?.cancel()),!r.ok&&405!==r.status)throw new Tw(r.status,`Failed to terminate session: ${r.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}}const xw=K("quickstart");async function Nw(t={}){if(!R)throw new Error("Interactive login is only available in Node.js environment");xw.info("Starting interactive login flow");const r=M();let n;n=t.authIssuer?t.authIssuer:t.authDomain?t.authDomain.startsWith("http")?t.authDomain:`https://${t.authDomain}`:r.authIssuer;const{clientId:o=r.clientId,clientSecret:s=r.clientSecret,audience:a=r.apiAudience,baseUrl:i,port:c=52765}=t;if(!o||!s)throw new Error("AGENT_CLIENT_ID / AGENT_CLIENT_SECRET not set – create a .env file or export in the shell");const u=await he();if(u)try{let e;q(u)?e=D(u):(xw.warn("Cached token has no organization information, using static config"),e=M());const t=new Ee(e.baseUrl,{token:u});return await t.validateCachedToken(),xw.info("Using cached valid token"),t}catch(e){xw.info("Cached token invalid, starting OAuth flow")}else xw.info("No cached token, starting OAuth flow");const l="undefined"!=typeof process&&!(!process.env||"1"!==process.env.BARNDOOR_MANUAL_CODE&&"true"!==process.env.BARNDOOR_MANUAL_CODE);let p,f=null;if(l){const e=process.env&&process.env.BARNDOOR_REDIRECT_HOST||"127.0.0.1";p=e.startsWith("http")?`${e}:${c}/cb`:`http://${e}:${c}/cb`}else{const e=$e(c);p=e[0],f=e[1]}const m=new ve,y=await m.buildAuthorizationUrl({clientId:o,redirectUri:p,audience:a,issuer:n});xw.info(`Auth URL: ${y}`);const g=e.platform();let v,_;try{v=new URL(y)}catch{throw new Error("Invalid auth URL")}if("https:"!==v.protocol&&("http:"!==v.protocol||"localhost"!==v.hostname&&"127.0.0.1"!==v.hostname))throw new Error("Auth URL must use HTTPS (http allowed only for localhost)");try{"darwin"===g?d("open",[y],{detached:!0,stdio:"ignore"}).unref():"win32"===g?d("powershell",["-NoProfile","Start-Process",y],{detached:!0,stdio:"ignore"}).unref():d("xdg-open",[y],{detached:!0,stdio:"ignore"}).unref(),xw.info("Please complete login in your browser…")}catch(e){xw.warn("Failed to open browser automatically. Please visit:",y)}if(l){const e=await new Promise(e=>{const t=h.createInterface({input:process.stdin,output:process.stdout});t.question("Paste the full redirected URL (or just the code= value): ",r=>{t.close(),e(r.trim())})});try{const t=new URL(e);_=t.searchParams.get("code")||e}catch{_=e}}else{const e=new Promise((e,t)=>{setTimeout(()=>{t(new Error(`OAuth callback timeout after 2 minutes. This usually means the callback URL is not registered in Auth0. Please add "${p}" to Allowed Callback URLs in your Auth0 application settings.`))},12e4)});_=(await Promise.race([f,e]))[0]}const w=await m.exchangeCodeForToken({clientId:o,clientSecret:s,code:_,redirectUri:p,issuer:n});let $;if(await pe(w),i)$=i;else if(q(w.access_token)){$=D(w.access_token).baseUrl}else xw.warn("New token has no organization information, using static config"),$=M().baseUrl;return new Ee($,{token:w.access_token})}async function Cw(e,t,r={}){const{timeout:n=90}=r;xw.info(`Ensuring ${t} server is connected`);try{await e.ensureServerConnected(t,{pollSeconds:n}),xw.info(`Server ${t} connected successfully`)}catch(e){throw e instanceof b?xw.error(`Server '${t}' not found`):xw.error(`Failed to connect to ${t}:`,e),e}}async function jw(e,t,r={}){const{serverId:n,serverSlug:o,proxyBaseUrl:s="http://proxy-ingress:8080",transport:a="streamable-http"}=r,i=n||o||t;let c;try{c=await e.getServer(i)}catch(e){if(e instanceof $&&404===e.statusCode)throw new b(i);throw e}const u=c.slug||i;let l;if(q(e.token)){l=`${D(e.token).baseUrl}/mcp/${u}`}else{xw.warn("Token has no organization information, using static config for MCP connection");l=`${M().baseUrl}/mcp/${u}`}return[{url:l,transport:a,headers:{Accept:"application/json, text/event-stream",Authorization:`Bearer ${e.token}`,"x-barndoor-session-id":Ow()}},l]}async function Rw(e,t,r={}){const[n]=await jw(e,t,r),o=n,s=new j_({name:"barndoor-js-sdk",version:"0.1.0"}),a=new Iw(new URL(o.url),{requestInit:{headers:o.headers}});return await s.connect(a),s}function Ow(){if(R&&"function"==typeof i.randomUUID)return i.randomUUID();if("undefined"!=typeof globalThis&&globalThis.crypto?.randomUUID)return globalThis.crypto.randomUUID();let e;if(R&&"function"==typeof i.randomBytes)e=i.randomBytes(16);else{if("undefined"==typeof globalThis||!globalThis.crypto?.getRandomValues)throw new Error("Secure random generator not available for UUID.");e=new Uint8Array(16),globalThis.crypto.getRandomValues(e)}const t=e??new Uint8Array(0);if(t.length<16)throw new Error("Secure random generator not available for UUID.");const r=t[6],n=t[8];t[6]=15&r|64,t[8]=63&n|128;const o=Array.from(t,e=>e.toString(16).padStart(2,"0")).join("");return`${o.substring(0,8)}-${o.substring(8,12)}-${o.substring(12,16)}-${o.substring(16,20)}-${o.substring(20)}`}const zw=function(){try{if("undefined"!=typeof process&&process.versions?.node){const e=l(import.meta.url),t=r(e),o=n(t,"..","package.json");return JSON.parse(f(o,"utf8")).version}return'"1.2.0"'}catch(e){return console.warn("Could not read version from package.json:",e),"0.1.0"}}();export{C as AUTH_CONFIG,N as AgentToken,y as AuthenticationError,z as BarndoorConfig,m as BarndoorError,Ee as BarndoorSDK,E as ConfigurationError,w as ConnectionError,$ as HTTPError,re as JWTVerificationResult,k as OAuthError,ve as PKCEManager,x as ServerDetail,b as ServerNotFoundError,I as ServerSummary,P as TimeoutError,g as TokenError,v as TokenExpiredError,de as TokenManager,_ as TokenValidationError,U as checkTokenOrganization,fe as clearCachedToken,Y as clearOidcConfigCache,K as createScopedLogger,H as debug,Cw as ensureServerConnected,B as error,ke as getClientCredentialsToken,D as getDynamicConfig,L as getLogger,Q as getOidcConfig,M as getStaticConfig,q as hasOrganizationInfo,Z as info,j as isBrowser,R as isNode,me as isTokenActive,ye as isTokenActiveWithRefresh,he as loadUserToken,Nw as loginInteractive,Rw as makeMcpClient,jw as makeMcpConnectionParams,pe as saveUserToken,F as setLogger,X as setTokenLogger,$e as startLocalCallbackServer,ge as validateToken,ue as verifyJWTLocal,zw as version,G as warn};