@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/auth/clientCredentials.d.ts +67 -0
- package/dist/auth/clientCredentials.d.ts.map +1 -0
- package/dist/auth/index.d.ts +2 -0
- package/dist/auth/index.d.ts.map +1 -1
- package/dist/auth/store.d.ts +1 -1
- package/dist/client.d.ts +98 -0
- package/dist/client.d.ts.map +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.esm.js +11 -11
- package/dist/index.js +9 -9
- package/package.json +4 -2
package/dist/index.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
"use strict";var e=require("os"),t=require("path"),r=require("fs/promises"),o=require("jose"),n=require("crypto"),s=require("http"),a=require("url"),i=require("child_process"),c=require("readline"),u=require("pkce-challenge"),l=require("fs"),d="undefined"!=typeof document?document.currentScript:null;class p extends Error{constructor(e){super(e),this.name="BarndoorError"}}class h extends p{constructor(e,t=null){super(e),this.name="AuthenticationError",this.errorCode=t}}class f extends h{constructor(e,t=null){let r=e;r+=t?` ${t}`:" Run 'barndoor-login' to authenticate.",super(r),this.name="TokenError",this.helpText=t}}class m extends f{}class y extends p{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 g extends p{constructor(e,t,r=null){super(g._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 v extends p{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 _=class extends h{};class w extends p{}class $ extends p{}class b{constructor(e=30,t=10){this.read=1e3*e,this.connect=1e3*t}}class k{constructor(e=new b,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 g(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 $(`Request to ${i} timed out after ${e}ms`)}else if(r instanceof g){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 y(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 E{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 E(e)}}class S extends E{constructor(e){super(e),this.url=e.url??null}static fromApiResponse(e){return new S(e)}}class P{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 P(e)}}const T={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"}},x="undefined"!=typeof window&&void 0!==window.document,I="undefined"==typeof window&&"undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node;function N(e,t=""){return I?process.env[e]??t:x&&window.ENV?window.ENV[e]??t:t}class C{constructor(e={}){const t=e.environment??(N("MODE")||N("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=T[this.environment]??T.production,o=N("AUTH_URL"),n=e.authDomain??N("AUTH_DOMAIN");e.authIssuer?this.authIssuer=e.authIssuer:this.authIssuer=o||(n?n.startsWith("http")?n:`https://${n}`:r.issuer),this.clientId=e.clientId??(N("AGENT_CLIENT_ID")||N("AUTH_CLIENT_ID")||""),this.clientSecret=e.clientSecret??(N("AGENT_CLIENT_SECRET")||N("AUTH_CLIENT_SECRET")||""),this.apiAudience=e.apiAudience??(N("API_AUDIENCE")||r.audience),this.promptForLogin=e.promptForLogin??!1,this.skipLoginLocal=e.skipLoginLocal??!1,this.baseUrl=e.baseUrl??(N("BARNDOOR_API")||N("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 C}static getDynamicConfig(e,t={}){const{requireOrganization:r=!0,fallbackOrganizationId:o}=t,n=new C,s=j(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 w("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 w(`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 w("authIssuer is required");if(!this.apiAudience||""===this.apiAudience.trim())throw new w("apiAudience is required");if(!this.baseUrl||""===this.baseUrl.trim())throw new w("baseUrl is required")}}function j(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 R(){return C.getStaticConfig()}function O(e,t){return C.getDynamicConfig(e,t)}function z(e){return j(e).hasOrganization}let A={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 M(e){return{debug:(t,...r)=>{A.debug(`[${e}] ${t}`,...r)},info:(t,...r)=>{A.info(`[${e}] ${t}`,...r)},warn:(t,...r)=>{A.warn(`[${e}] ${t}`,...r)},error:(t,...r)=>{A.error(`[${e}] ${t}`,...r)}}}const U=M("token"),D=new Map;async function q(e){if(D.has(e))return D.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 D.set(e,n),U.debug(`OIDC discovery successful for ${e}`),n}finally{clearTimeout(o)}}catch(r){return U.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 V(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(I)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 F(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 L;exports.JWTVerificationResult=void 0,(L=exports.JWTVerificationResult||(exports.JWTVerificationResult={})).VALID="valid",L.EXPIRED="expired",L.INVALID="invalid";const K=new Map;class H{constructor(e){this.lockAcquired=!1,this.lockFile=`${e}.lock`}async acquire(e=5e3){if(!I)return;const t=Date.now();for(;Date.now()-t<e;)try{return await r.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 f(`Failed to acquire file lock: ${e}`);try{const e=await r.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 r.unlink(this.lockFile).catch(()=>{});continue}}await r.unlink(this.lockFile).catch(()=>{});continue}}catch{await r.unlink(this.lockFile).catch(()=>{});continue}}throw new f("Failed to acquire file lock: timeout")}async release(){if(I&&this.lockAcquired)try{await r.unlink(this.lockFile),this.lockAcquired=!1}catch(e){console.debug("Failed to release file lock:",e)}}}class Z{}class G extends Z{constructor(){super(),this.storageKey="barndoor_token"}async loadToken(){try{const e=localStorage.getItem(this.storageKey);return e?JSON.parse(e):null}catch(e){return U.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 f(`Failed to save token: ${t}`)}}async clearToken(){try{localStorage.removeItem(this.storageKey)}catch(e){U.warn("Failed to clear token from localStorage:",e)}}}class J extends Z{constructor(){super(),this.tokenFile=this._getTokenFilePath()}_getTokenFilePath(){if(I)return t.join(e.homedir(),".barndoor","token.json");throw new Error("NodeTokenStorage can only be used in Node.js environment")}async loadToken(){if(!I)throw new Error("NodeTokenStorage can only be used in Node.js environment");const e=new H(this.tokenFile);try{await e.acquire();const t=await r.readFile(this.tokenFile,"utf8");return JSON.parse(t)}catch(e){return e&&"object"==typeof e&&"code"in e&&"ENOENT"===e.code||U.warn("Failed to load token from file:",e),null}finally{await e.release()}}async saveToken(e){if(!I)throw new Error("NodeTokenStorage can only be used in Node.js environment");const o=new H(this.tokenFile);try{await o.acquire(),await r.mkdir(t.dirname(this.tokenFile),{recursive:!0}),await r.writeFile(this.tokenFile,JSON.stringify(e,null,2)),await r.chmod(this.tokenFile,384),U.debug("Token saved to storage")}catch(e){const t=e instanceof Error?e.message:String(e);throw new f(`Failed to save token: ${t}`)}finally{await o.release()}}async clearToken(){if(!I)throw new Error("NodeTokenStorage can only be used in Node.js environment");try{await r.unlink(this.tokenFile)}catch(e){e&&"object"==typeof e&&"code"in e&&"ENOENT"!==e.code&&U.warn("Failed to clear token file:",e)}}}function W(){if(x)return new G;if(I)return new J;throw new Error("Unsupported environment for token storage")}async function B(e,t,r){try{const n=await async function(e){if(K.has(e))return K.get(e);try{const t=(await q(e)).jwks_uri;if(!t)throw U.debug(`No jwks_uri in OIDC config for ${e}`),new Error("No jwks_uri available");const r=o.createRemoteJWKSet(new URL(t));return K.set(e,r),r}catch(t){throw U.debug(`Failed to get JWKS for ${e}:`,t),t}}(t),s=`${t.replace(/\/$/,"")}/`;return await o.jwtVerify(e,n,{issuer:s,audience:r}),U.debug("Token verified locally using JWKS"),exports.JWTVerificationResult.VALID}catch(e){return e&&"object"==typeof e&&"code"in e&&"ERR_JWT_EXPIRED"===e.code?(U.debug("Token expired (verified locally)"),exports.JWTVerificationResult.EXPIRED):(U.debug("JWT verification failed:",e),exports.JWTVerificationResult.INVALID)}}class Q{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 Y{constructor(e){this._refreshMutex=new Q,this.storage=W()}async getValidToken(){return this._refreshMutex.withLock(async()=>{const e=await this.storage.loadToken();if(!e)throw new f("No token found. Please authenticate.");try{if(this._shouldRefreshToken(e)&&e.refresh_token){U.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 U.error("Token validation/refresh failed:",e),new m("Token expired and refresh failed. Please re-authenticate.")}})}_shouldRefreshToken(e){const t=V(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=R(),o=await B(t,r.authIssuer,r.apiAudience);if(o===exports.JWTVerificationResult.VALID)return U.debug("Token validated locally"),e;if(o===exports.JWTVerificationResult.INVALID&&(U.debug("Local validation failed, trying remote"),await this._isTokenValidRemote(t)))return U.debug("Token validated remotely"),e;if(U.info("Token invalid or expired, attempting refresh"),e.refresh_token){const t=await this._refreshToken(e);return{...e,...t}}throw new m("Token expired and no refresh token available")}async _isTokenValidRemote(e){try{const t=R(),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 F(o,5e3)).ok}catch(e){return U.debug("Remote token validation failed:",e),!1}}async _refreshToken(e){const t=e.refresh_token;if(!t)throw new f("No refresh token available");const r=R();if(x&&r.clientSecret)throw new f("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&&!x&&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 F(e,15e3);if(400===t.status){let e="Invalid refresh token";try{e=(await t.json()).error_description||e}catch{}throw U.warn(`Refresh token invalid: ${e}`),new m(`Refresh token expired or invalid: ${e}`)}if(429===t.status)throw U.warn("Rate limited during token refresh"),new f("Rate limited during token refresh. Please try again later.");if(t.status>=500)throw U.warn(`Auth server error during refresh: ${t.status}`),new f(`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 f||e instanceof m)throw e;if(e&&"object"==typeof e&&"name"in e){if("TimeoutError"===e.name||"AbortError"===e.name)throw U.warn("Timeout during token refresh"),new f("Token refresh timed out. Please check your connection.");if("TypeError"===e.name&&"message"in e&&"string"==typeof e.message&&e.message.includes("fetch"))throw U.warn(`Network error during token refresh: ${e.message}`),new f("Network error during token refresh. Please check your connection.")}U.error("Unexpected error during token refresh:",e);const t=e instanceof Error?e.message:String(e);throw new f(`Token refresh failed: ${t}`)}}}async function X(){try{const e=W(),t=await e.loadToken();return t?.access_token??null}catch(e){return null}}async function ee(e){const t=W();let r;r="string"==typeof e?{access_token:e}:e,await t.saveToken(r)}class te{constructor(){this._codeVerifier=null,this._currentState=null,this._logger=M("pkce")}async buildAuthorizationUrl({domain:e,clientId:t,redirectUri:r,audience:o,scope:s="openid profile email",issuer:a}){this._codeVerifier=re(32);const i=oe(await async function(e){const t=(new TextEncoder).encode(e);if(x&&window.crypto&&window.crypto.subtle){const e=await window.crypto.subtle.digest("SHA-256",t);return new Uint8Array(e)}if(I){const t=n.createHash("sha256").update(e).digest();return new Uint8Array(t)}throw new Error("SHA256 not available in this environment")}(this._codeVerifier));this._currentState=re(16);const c=new URLSearchParams({response_type:"code",client_id:t,redirect_uri:r,scope:s,audience:o,state:this._currentState,code_challenge:i,code_challenge_method:"S256"});let u;if(a){u=(await q(a)).authorization_endpoint}else{if(!e)throw new _("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 _("Either client_secret or PKCE verifier must be provided");let i;if(s){i=(await q(s)).token_endpoint}else{if(!e)throw new _("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 _(`Token exchange failed: ${t.error??t.error_description??e.statusText}`)}const t=await e.json();return this.clearState(),t}catch(e){if(e instanceof _)throw e;const t=e instanceof Error?e.message:String(e);throw new _(`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 re(e){const t=new Uint8Array(e);if(x&&window.crypto&&window.crypto.getRandomValues)window.crypto.getRandomValues(t);else{if(!I)throw new Error("Secure random generator not available for PKCE.");n.randomFillSync(t)}return oe(t)}function oe(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 ne(e=52765){if(!I)throw new Error("Local callback server is only available in Node.js environment");const t=M("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 i=s.createServer((e,o)=>{t.debug(`Callback server received request: ${e.method} ${e.url}`);const s=a.parse(e.url??"",!0);if(t.debug(`Parsed URL - pathname: ${s.pathname}, query:`,s.query),"/cb"===s.pathname){const{code:a,state:c,error:u,error_description:l}=s.query;t.debug(`Callback params - code: ${!!a}, 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 "),i.close(),n(new _(`OAuth error: ${u} - ${l}`))):a?(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 "),i.close(),r([a,c])):(t.warn("No authorization code received in callback"),t.warn(`Full URL: ${e.url}`),t.warn("Query params:",s.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 `),i.close(),n(new _("No authorization code received")))}else t.debug(`404 for path: ${s.pathname}`),o.writeHead(404,{"Content-Type":"text/plain"}),o.end("Not found")});i.listen(e,"0.0.0.0",()=>{console.log(`OAuth callback server listening on ${o}`)}),i.on("error",e=>{n(new _(`Failed to start callback server: ${e.message}`))}),i.on("connection",e=>{t.debug(`New connection from ${e.remoteAddress}:${e.remotePort}`)})});return[o,n]}class se{constructor(e,t={}){this._logger=M("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 w("timeout must be a positive number");if(!Number.isInteger(n)||n<0)throw new w("maxRetries must be a non-negative integer");const a=new b(o,o/3);this._http=new k(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 w(`${t} must be a non-empty string`);try{return new URL(e),e}catch(e){throw new w(`${t} must be a valid URL`)}}_validateToken(e){if(!e||"string"!=typeof e)throw new f("Token must be a non-empty string");if(3!==e.split(".").length)throw new f("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=R(),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=(I?process.env.BARNDOOR_ENV:"")??"";if(["test","ci"].includes(e.toLowerCase()))return void(this._tokenValidated=!0);if(!await this.validateCachedToken())throw new f("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=>E.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 S.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 g&&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 g&&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(!I)throw new Error("ensureServerConnected requires Node.js environment for browser opening");let n;try{n=await this.getServer(t)}catch(e){if(e instanceof g&&404===e.statusCode)throw new v(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 c=e.platform();let u;try{u=new URL(a)}catch{throw new Error("Invalid auth_url returned by server")}if("https:"!==u.protocol&&("http:"!==u.protocol||"localhost"!==u.hostname&&"127.0.0.1"!==u.hostname))throw new Error("Auth URL must use HTTPS (http allowed only for localhost)");try{"darwin"===c?i.spawn("open",[a],{detached:!0,stdio:"ignore"}).unref():"win32"===c?i.spawn("powershell",["-NoProfile","Start-Process",a],{detached:!0,stdio:"ignore"}).unref():i.spawn("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 ae=Object.freeze({status:"aborted"});function ie(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 ce extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const ue={};function le(e){return e&&Object.assign(ue,e),ue}function de(e,t){return"bigint"==typeof t?t.toString():t}function pe(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function he(e){return null==e}function fe(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function me(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 ye(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function ge(e){return JSON.stringify(e)}const ve=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function _e(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const we=pe(()=>{if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function $e(e){if(!1===_e(e))return!1;const t=e.constructor;if(void 0===t)return!0;const r=t.prototype;return!1!==_e(r)&&!1!==Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")}const be=new Set(["string","number","symbol"]);function ke(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ee(e,t,r){const o=new e._zod.constr(t??e._zod.def);return t&&!r?.parent||(o._zod.parent=e),o}function Se(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 Pe={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 Te(e,t=0){for(let r=t;r<e.issues.length;r++)if(!0!==e.issues[r]?.continue)return!0;return!1}function xe(e,t){return t.map(t=>{var r;return(r=t).path??(r.path=[]),t.path.unshift(e),t})}function Ie(e){return"string"==typeof e?e:e?.message}function Ne(e,t,r){const o={...e,path:e.path??[]};if(!e.message){const n=Ie(e.inst?._zod.def?.error?.(e))??Ie(t?.error?.(e))??Ie(r.customError?.(e))??Ie(r.localeError?.(e))??"Invalid input";o.message=n}return delete o.inst,delete o.continue,t?.reportInput||delete o.input,o}function Ce(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 Re=(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,de,2),enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Oe=ie("$ZodError",Re),ze=ie("$ZodError",Re,{Parent:Error});const Ae=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 ce;if(a.issues.length){const t=new(n?.Err??e)(a.issues.map(e=>Ne(e,s,le())));throw ve(t,n?.callee),t}return a.value},Me=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=>Ne(e,s,le())));throw ve(t,n?.callee),t}return a.value},Ue=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 ce;return s.issues.length?{success:!1,error:new(e??Oe)(s.issues.map(e=>Ne(e,n,le())))}:{success:!0,data:s.value}},De=Ue(ze),qe=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=>Ne(e,n,le())))}:{success:!0,data:s.value}},Ve=qe(ze),Fe=/^[cC][^\s-]{8,}$/,Le=/^[0-9a-z]+$/,Ke=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,He=/^[0-9a-vA-V]{20}$/,Ze=/^[A-Za-z0-9]{27}$/,Ge=/^[a-zA-Z0-9_-]{21}$/,Je=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,We=/^([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})$/,Be=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)$/,Qe=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;const Ye=/^(?:(?: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])$/,Xe=/^(([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})$/,et=/^((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])$/,tt=/^(([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])$/,rt=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,ot=/^[A-Za-z0-9_-]*$/,nt=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,st=/^\+(?:[0-9]){6,14}[0-9]$/,at="(?:(?:\\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])))",it=new RegExp(`^${at}$`);function ct(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 ut=/^\d+$/,lt=/^-?\d+(?:\.\d+)?/i,dt=/true|false/i,pt=/null/i,ht=/^[^A-Z]*$/,ft=/^[^a-z]*$/,mt=ie("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),yt={number:"number",bigint:"bigint",object:"date"},gt=ie("$ZodCheckLessThan",(e,t)=>{mt.init(e,t);const r=yt[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})}}),vt=ie("$ZodCheckGreaterThan",(e,t)=>{mt.init(e,t);const r=yt[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})}}),_t=ie("$ZodCheckMultipleOf",(e,t)=>{mt.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})}}),wt=ie("$ZodCheckNumberFormat",(e,t)=>{mt.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),o=r?"int":"number",[n,s]=Pe[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=ut)}),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})}}),$t=ie("$ZodCheckMaxLength",(e,t)=>{var r;mt.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!he(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=Ce(o);r.issues.push({origin:n,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),bt=ie("$ZodCheckMinLength",(e,t)=>{var r;mt.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!he(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=Ce(o);r.issues.push({origin:n,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),kt=ie("$ZodCheckLengthEquals",(e,t)=>{var r;mt.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!he(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=Ce(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})}}),Et=ie("$ZodCheckStringFormat",(e,t)=>{var r,o;mt.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=()=>{})}),St=ie("$ZodCheckRegex",(e,t)=>{Et.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})}}),Pt=ie("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=ht),Et.init(e,t)}),Tt=ie("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=ft),Et.init(e,t)}),xt=ie("$ZodCheckIncludes",(e,t)=>{mt.init(e,t);const r=ke(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})}}),It=ie("$ZodCheckStartsWith",(e,t)=>{mt.init(e,t);const r=new RegExp(`^${ke(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})}}),Nt=ie("$ZodCheckEndsWith",(e,t)=>{mt.init(e,t);const r=new RegExp(`.*${ke(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})}}),Ct=ie("$ZodCheckOverwrite",(e,t)=>{mt.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 Rt={major:4,minor:0,patch:0},Ot=ie("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Rt;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=Te(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 ce;if(o||a instanceof Promise)o=(o??Promise.resolve()).then(async()=>{await a;e.issues.length!==t&&(n||(n=Te(e,t)))});else{if(e.issues.length===t)continue;n||(n=Te(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 ce;return s.then(e=>t(e,o,n))}return t(s,o,n)}}e["~standard"]={validate:t=>{try{const r=De(e,t);return r.success?{value:r.data}:{issues:r.error?.issues}}catch(r){return Ve(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}}),zt=ie("$ZodString",(e,t)=>{var r;Ot.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}}),At=ie("$ZodStringFormat",(e,t)=>{Et.init(e,t),zt.init(e,t)}),Mt=ie("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=We),At.init(e,t)}),Ut=ie("$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=Be(e))}else t.pattern??(t.pattern=Be());At.init(e,t)}),Dt=ie("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Qe),At.init(e,t)}),qt=ie("$ZodURL",(e,t)=>{At.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:nt.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})}}}),Vt=ie("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),At.init(e,t)}),Ft=ie("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Ge),At.init(e,t)}),Lt=ie("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Fe),At.init(e,t)}),Kt=ie("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Le),At.init(e,t)}),Ht=ie("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Ke),At.init(e,t)}),Zt=ie("$ZodXID",(e,t)=>{t.pattern??(t.pattern=He),At.init(e,t)}),Gt=ie("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Ze),At.init(e,t)}),Jt=ie("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=function(e){const t=ct({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(`^${at}T(?:${o})$`)}(t)),At.init(e,t)}),Wt=ie("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=it),At.init(e,t)}),Bt=ie("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=new RegExp(`^${ct(t)}$`)),At.init(e,t)}),Qt=ie("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Je),At.init(e,t)}),Yt=ie("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Ye),At.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.format="ipv4"})}),Xt=ie("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Xe),At.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})}}}),er=ie("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=et),At.init(e,t)}),tr=ie("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=tt),At.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 rr(e){if(""===e)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const or=ie("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=rt),At.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{rr(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});const nr=ie("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=ot),At.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{(function(e){if(!ot.test(e))return!1;const t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return rr(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})}}),sr=ie("$ZodE164",(e,t)=>{t.pattern??(t.pattern=st),At.init(e,t)});const ar=ie("$ZodJWT",(e,t)=>{At.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})}}),ir=ie("$ZodNumber",(e,t)=>{Ot.init(e,t),e._zod.pattern=e._zod.bag.pattern??lt,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}}),cr=ie("$ZodNumber",(e,t)=>{wt.init(e,t),ir.init(e,t)}),ur=ie("$ZodBoolean",(e,t)=>{Ot.init(e,t),e._zod.pattern=dt,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}}),lr=ie("$ZodNull",(e,t)=>{Ot.init(e,t),e._zod.pattern=pt,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}}),dr=ie("$ZodAny",(e,t)=>{Ot.init(e,t),e._zod.parse=e=>e}),pr=ie("$ZodUnknown",(e,t)=>{Ot.init(e,t),e._zod.parse=e=>e}),hr=ie("$ZodNever",(e,t)=>{Ot.init(e,t),e._zod.parse=(t,r)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function fr(e,t,r){e.issues.length&&t.issues.push(...xe(r,e.issues)),t.value[r]=e.value}const mr=ie("$ZodArray",(e,t)=>{Ot.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=>fr(t,r,e))):fr(i,r,e)}return s.length?Promise.all(s).then(()=>r):r}});function yr(e,t,r){e.issues.length&&t.issues.push(...xe(r,e.issues)),t.value[r]=e.value}function gr(e,t,r,o){e.issues.length?void 0===o[r]?t.value[r]=r in o?void 0:e.value:t.issues.push(...xe(r,e.issues)):void 0===e.value?r in o&&(t.value[r]=void 0):t.value[r]=e.value}const vr=ie("$ZodObject",(e,t)=>{Ot.init(e,t);const r=pe(()=>{const e=Object.keys(t.shape);for(const r of e)if(!(t.shape[r]instanceof Ot))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)}});me(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=_e,s=!ue.jitless,a=s&&we.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 p=[];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=ge(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=ge(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 ? [${ge(e)}, ...iss.path] : [${ge(e)}]\n })));`),t.write(`newResult[${ge(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?p.push(o.then(e=>n?gr(e,u,t,d):yr(e,u,t))):n?gr(o,u,t,d):yr(o,u,t)}}if(!i)return p.length?Promise.all(p).then(()=>u):u;const h=[],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){h.push(e);continue}const t=m.run({value:d[e],issues:[]},l);t instanceof Promise?p.push(t.then(t=>yr(t,u,e))):yr(t,u,e)}return h.length&&u.issues.push({code:"unrecognized_keys",keys:h,input:d,inst:e}),p.length?Promise.all(p).then(()=>u):u}});function _r(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=>Ne(e,o,le())))}),t}const wr=ie("$ZodUnion",(e,t)=>{Ot.init(e,t),me(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),me(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),me(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),me(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=>fe(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=>_r(t,r,e,o)):_r(s,r,e,o)}}),$r=ie("$ZodDiscriminatedUnion",(e,t)=>{wr.init(e,t);const r=e._zod.parse;me(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=pe(()=>{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(!_e(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)}}),br=ie("$ZodIntersection",(e,t)=>{Ot.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])=>Er(e,t,r)):Er(e,n,s)}});function kr(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($e(e)&&$e(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=kr(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=kr(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 Er(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),Te(e))return e;const o=kr(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 Sr=ie("$ZodRecord",(e,t)=>{Ot.init(e,t),e._zod.parse=(r,o)=>{const n=r.value;if(!$e(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(...xe(e,t.issues)),r.value[e]=t.value})):(a.issues.length&&r.issues.push(...xe(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=>Ne(e,o,le())),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(...xe(a,e.issues)),r.value[i.value]=e.value})):(c.issues.length&&r.issues.push(...xe(a,c.issues)),r.value[i.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),Pr=ie("$ZodEnum",(e,t)=>{Ot.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=>be.has(typeof e)).map(e=>"string"==typeof e?ke(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}}),Tr=ie("$ZodLiteral",(e,t)=>{Ot.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(e=>"string"==typeof e?ke(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}}),xr=ie("$ZodTransform",(e,t)=>{Ot.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 ce;return e.value=o,e}}),Ir=ie("$ZodOptional",(e,t)=>{Ot.init(e,t),e._zod.optin="optional",e._zod.optout="optional",me(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),me(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${fe(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)}),Nr=ie("$ZodNullable",(e,t)=>{Ot.init(e,t),me(e._zod,"optin",()=>t.innerType._zod.optin),me(e._zod,"optout",()=>t.innerType._zod.optout),me(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${fe(e.source)}|null)$`):void 0}),me(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)}),Cr=ie("$ZodDefault",(e,t)=>{Ot.init(e,t),e._zod.optin="optional",me(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 Rr=ie("$ZodPrefault",(e,t)=>{Ot.init(e,t),e._zod.optin="optional",me(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))}),Or=ie("$ZodNonOptional",(e,t)=>{Ot.init(e,t),me(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=>zr(t,e)):zr(n,e)}});function zr(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 Ar=ie("$ZodCatch",(e,t)=>{Ot.init(e,t),e._zod.optin="optional",me(e._zod,"optout",()=>t.innerType._zod.optout),me(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=>Ne(e,r,le()))},input:e.value}),e.issues=[]),e)):(e.value=o.value,o.issues.length&&(e.value=t.catchValue({...e,error:{issues:o.issues.map(e=>Ne(e,r,le()))},input:e.value}),e.issues=[]),e)}}),Mr=ie("$ZodPipe",(e,t)=>{Ot.init(e,t),me(e._zod,"values",()=>t.in._zod.values),me(e._zod,"optin",()=>t.in._zod.optin),me(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=>Ur(e,t,r)):Ur(o,t,r)}});function Ur(e,t,r){return Te(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}const Dr=ie("$ZodReadonly",(e,t)=>{Ot.init(e,t),me(e._zod,"propValues",()=>t.innerType._zod.propValues),me(e._zod,"values",()=>t.innerType._zod.values),me(e._zod,"optin",()=>t.innerType._zod.optin),me(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(qr):qr(o)}});function qr(e){return e.value=Object.freeze(e.value),e}const Vr=ie("$ZodCustom",(e,t)=>{mt.init(e,t),Ot.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=>Fr(t,r,o,e));Fr(n,r,o,e)}});function Fr(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 Lr{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 Kr(){return new Lr}const Hr=Kr();function Zr(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...Se(t)})}function Gr(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...Se(t)})}function Jr(e,t){return new gt({check:"less_than",...Se(t),value:e,inclusive:!1})}function Wr(e,t){return new gt({check:"less_than",...Se(t),value:e,inclusive:!0})}function Br(e,t){return new vt({check:"greater_than",...Se(t),value:e,inclusive:!1})}function Qr(e,t){return new vt({check:"greater_than",...Se(t),value:e,inclusive:!0})}function Yr(e,t){return new _t({check:"multiple_of",...Se(t),value:e})}function Xr(e,t){return new $t({check:"max_length",...Se(t),maximum:e})}function eo(e,t){return new bt({check:"min_length",...Se(t),minimum:e})}function to(e,t){return new kt({check:"length_equals",...Se(t),length:e})}function ro(e){return new Ct({check:"overwrite",tx:e})}function oo(e){return!!e._zod}function no(e,t){if(oo(e)){return De(e,t)}return e.safeParse(t)}function so(e){if(!e)return;let t;if(oo(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 ao=ie("ZodISODateTime",(e,t)=>{Jt.init(e,t),Eo.init(e,t)});function io(e){return function(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Se(t)})}(ao,e)}const co=ie("ZodISODate",(e,t)=>{Wt.init(e,t),Eo.init(e,t)});function uo(e){return function(e,t){return new e({type:"string",format:"date",check:"string_format",...Se(t)})}(co,e)}const lo=ie("ZodISOTime",(e,t)=>{Bt.init(e,t),Eo.init(e,t)});function po(e){return function(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...Se(t)})}(lo,e)}const ho=ie("ZodISODuration",(e,t)=>{Qt.init(e,t),Eo.init(e,t)});function fo(e){return function(e,t){return new e({type:"string",format:"duration",check:"string_format",...Se(t)})}(ho,e)}const mo=ie("ZodError",(e,t)=>{Oe.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}),yo=Ae(mo),go=Me(mo),vo=Ue(mo),_o=qe(mo),wo=ie("ZodType",(e,t)=>(Ot.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)=>Ee(e,t,r),e.brand=()=>e,e.register=(t,r)=>(t.add(e,r),e),e.parse=(t,r)=>yo(e,t,r,{callee:e.parse}),e.safeParse=(t,r)=>vo(e,t,r),e.parseAsync=async(t,r)=>go(e,t,r,{callee:e.parseAsync}),e.safeParseAsync=async(t,r)=>_o(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,...Se(r)})}(On,e,t)}(t,r)),e.superRefine=t=>e.check(function(e){const t=function(e){const t=new mt({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(ro(t)),e.optional=()=>En(e),e.nullable=()=>Pn(e),e.nullish=()=>En(Pn(e)),e.nonoptional=t=>function(e,t){return new In({type:"nonoptional",innerType:e,...Se(t)})}(e,t),e.array=()=>nn(e),e.or=t=>ln([e,t]),e.and=t=>fn(e,t),e.transform=t=>jn(e,bn(t)),e.default=t=>{return r=t,new Tn({type:"default",innerType:e,get defaultValue(){return"function"==typeof r?r():r}});var r},e.prefault=t=>{return r=t,new xn({type:"prefault",innerType:e,get defaultValue(){return"function"==typeof r?r():r}});var r},e.catch=t=>{return new Nn({type:"catch",innerType:e,catchValue:"function"==typeof(r=t)?r:()=>r});var r},e.pipe=t=>jn(e,t),e.readonly=()=>new Rn({type:"readonly",innerType:e}),e.describe=t=>{const r=e.clone();return Hr.add(r,{description:t}),r},Object.defineProperty(e,"description",{get:()=>Hr.get(e)?.description,configurable:!0}),e.meta=(...t)=>{if(0===t.length)return Hr.get(e);const r=e.clone();return Hr.add(r,t[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),$o=ie("_ZodString",(e,t)=>{zt.init(e,t),wo.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 St({check:"string_format",format:"regex",...Se(t),pattern:e})}(...t)),e.includes=(...t)=>e.check(function(e,t){return new xt({check:"string_format",format:"includes",...Se(t),includes:e})}(...t)),e.startsWith=(...t)=>e.check(function(e,t){return new It({check:"string_format",format:"starts_with",...Se(t),prefix:e})}(...t)),e.endsWith=(...t)=>e.check(function(e,t){return new Nt({check:"string_format",format:"ends_with",...Se(t),suffix:e})}(...t)),e.min=(...t)=>e.check(eo(...t)),e.max=(...t)=>e.check(Xr(...t)),e.length=(...t)=>e.check(to(...t)),e.nonempty=(...t)=>e.check(eo(1,...t)),e.lowercase=t=>e.check(function(e){return new Pt({check:"string_format",format:"lowercase",...Se(e)})}(t)),e.uppercase=t=>e.check(function(e){return new Tt({check:"string_format",format:"uppercase",...Se(e)})}(t)),e.trim=()=>e.check(ro(e=>e.trim())),e.normalize=(...t)=>e.check(function(e){return ro(t=>t.normalize(e))}(...t)),e.toLowerCase=()=>e.check(ro(e=>e.toLowerCase())),e.toUpperCase=()=>e.check(ro(e=>e.toUpperCase()))}),bo=ie("ZodString",(e,t)=>{zt.init(e,t),$o.init(e,t),e.email=t=>e.check(function(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...Se(t)})}(So,t)),e.url=t=>e.check(Gr(xo,t)),e.jwt=t=>e.check(function(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...Se(t)})}(Lo,t)),e.emoji=t=>e.check(function(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...Se(t)})}(Io,t)),e.guid=t=>e.check(Zr(Po,t)),e.uuid=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...Se(t)})}(To,t)),e.uuidv4=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Se(t)})}(To,t)),e.uuidv6=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Se(t)})}(To,t)),e.uuidv7=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Se(t)})}(To,t)),e.nanoid=t=>e.check(function(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...Se(t)})}(No,t)),e.guid=t=>e.check(Zr(Po,t)),e.cuid=t=>e.check(function(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...Se(t)})}(Co,t)),e.cuid2=t=>e.check(function(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...Se(t)})}(jo,t)),e.ulid=t=>e.check(function(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...Se(t)})}(Ro,t)),e.base64=t=>e.check(function(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...Se(t)})}(qo,t)),e.base64url=t=>e.check(function(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...Se(t)})}(Vo,t)),e.xid=t=>e.check(function(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...Se(t)})}(Oo,t)),e.ksuid=t=>e.check(function(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...Se(t)})}(zo,t)),e.ipv4=t=>e.check(function(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...Se(t)})}(Ao,t)),e.ipv6=t=>e.check(function(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...Se(t)})}(Mo,t)),e.cidrv4=t=>e.check(function(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Se(t)})}(Uo,t)),e.cidrv6=t=>e.check(function(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Se(t)})}(Do,t)),e.e164=t=>e.check(function(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...Se(t)})}(Fo,t)),e.datetime=t=>e.check(io(t)),e.date=t=>e.check(uo(t)),e.time=t=>e.check(po(t)),e.duration=t=>e.check(fo(t))});function ko(e){return function(e,t){return new e({type:"string",...Se(t)})}(bo,e)}const Eo=ie("ZodStringFormat",(e,t)=>{At.init(e,t),$o.init(e,t)}),So=ie("ZodEmail",(e,t)=>{Dt.init(e,t),Eo.init(e,t)}),Po=ie("ZodGUID",(e,t)=>{Mt.init(e,t),Eo.init(e,t)}),To=ie("ZodUUID",(e,t)=>{Ut.init(e,t),Eo.init(e,t)}),xo=ie("ZodURL",(e,t)=>{qt.init(e,t),Eo.init(e,t)});const Io=ie("ZodEmoji",(e,t)=>{Vt.init(e,t),Eo.init(e,t)}),No=ie("ZodNanoID",(e,t)=>{Ft.init(e,t),Eo.init(e,t)}),Co=ie("ZodCUID",(e,t)=>{Lt.init(e,t),Eo.init(e,t)}),jo=ie("ZodCUID2",(e,t)=>{Kt.init(e,t),Eo.init(e,t)}),Ro=ie("ZodULID",(e,t)=>{Ht.init(e,t),Eo.init(e,t)}),Oo=ie("ZodXID",(e,t)=>{Zt.init(e,t),Eo.init(e,t)}),zo=ie("ZodKSUID",(e,t)=>{Gt.init(e,t),Eo.init(e,t)}),Ao=ie("ZodIPv4",(e,t)=>{Yt.init(e,t),Eo.init(e,t)}),Mo=ie("ZodIPv6",(e,t)=>{Xt.init(e,t),Eo.init(e,t)}),Uo=ie("ZodCIDRv4",(e,t)=>{er.init(e,t),Eo.init(e,t)}),Do=ie("ZodCIDRv6",(e,t)=>{tr.init(e,t),Eo.init(e,t)}),qo=ie("ZodBase64",(e,t)=>{or.init(e,t),Eo.init(e,t)}),Vo=ie("ZodBase64URL",(e,t)=>{nr.init(e,t),Eo.init(e,t)}),Fo=ie("ZodE164",(e,t)=>{sr.init(e,t),Eo.init(e,t)}),Lo=ie("ZodJWT",(e,t)=>{ar.init(e,t),Eo.init(e,t)}),Ko=ie("ZodNumber",(e,t)=>{ir.init(e,t),wo.init(e,t),e.gt=(t,r)=>e.check(Br(t,r)),e.gte=(t,r)=>e.check(Qr(t,r)),e.min=(t,r)=>e.check(Qr(t,r)),e.lt=(t,r)=>e.check(Jr(t,r)),e.lte=(t,r)=>e.check(Wr(t,r)),e.max=(t,r)=>e.check(Wr(t,r)),e.int=t=>e.check(Go(t)),e.safe=t=>e.check(Go(t)),e.positive=t=>e.check(Br(0,t)),e.nonnegative=t=>e.check(Qr(0,t)),e.negative=t=>e.check(Jr(0,t)),e.nonpositive=t=>e.check(Wr(0,t)),e.multipleOf=(t,r)=>e.check(Yr(t,r)),e.step=(t,r)=>e.check(Yr(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 Ho(e){return function(e,t){return new e({type:"number",checks:[],...Se(t)})}(Ko,e)}const Zo=ie("ZodNumberFormat",(e,t)=>{cr.init(e,t),Ko.init(e,t)});function Go(e){return function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...Se(t)})}(Zo,e)}const Jo=ie("ZodBoolean",(e,t)=>{ur.init(e,t),wo.init(e,t)});function Wo(e){return function(e,t){return new e({type:"boolean",...Se(t)})}(Jo,e)}const Bo=ie("ZodNull",(e,t)=>{lr.init(e,t),wo.init(e,t)});function Qo(e){return function(e,t){return new e({type:"null",...Se(t)})}(Bo,e)}const Yo=ie("ZodAny",(e,t)=>{dr.init(e,t),wo.init(e,t)});const Xo=ie("ZodUnknown",(e,t)=>{pr.init(e,t),wo.init(e,t)});function en(){return new Xo({type:"unknown"})}const tn=ie("ZodNever",(e,t)=>{hr.init(e,t),wo.init(e,t)});function rn(e){return function(e,t){return new e({type:"never",...Se(t)})}(tn,e)}const on=ie("ZodArray",(e,t)=>{mr.init(e,t),wo.init(e,t),e.element=t.element,e.min=(t,r)=>e.check(eo(t,r)),e.nonempty=t=>e.check(eo(1,t)),e.max=(t,r)=>e.check(Xr(t,r)),e.length=(t,r)=>e.check(to(t,r)),e.unwrap=()=>e.element});function nn(e,t){return function(e,t,r){return new e({type:"array",element:t,...Se(r)})}(on,e,t)}const sn=ie("ZodObject",(e,t)=>{vr.init(e,t),wo.init(e,t),me(e,"shape",()=>t.shape),e.keyof=()=>vn(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:en()}),e.loose=()=>e.clone({...e._zod.def,catchall:en()}),e.strict=()=>e.clone({...e._zod.def,catchall:rn()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>function(e,t){if(!$e(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 ye(this,"shape",r),r},checks:[]};return Ee(e,r)}(e,t),e.merge=t=>{return o=t,Ee(r=e,{...r._zod.def,get shape(){const e={...r._zod.def.shape,...o._zod.def.shape};return ye(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 Ee(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 Ee(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 Ee(t,{...t._zod.def,shape:n,checks:[]})}(kn,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 Ee(t,{...t._zod.def,shape:n,checks:[]})}(In,e,t[0])});function an(e,t){const r={type:"object",get shape(){return ye(this,"shape",{...e}),this.shape},...Se(t)};return new sn(r)}function cn(e,t){return new sn({type:"object",get shape(){return ye(this,"shape",{...e}),this.shape},catchall:en(),...Se(t)})}const un=ie("ZodUnion",(e,t)=>{wr.init(e,t),wo.init(e,t),e.options=t.options});function ln(e,t){return new un({type:"union",options:e,...Se(t)})}const dn=ie("ZodDiscriminatedUnion",(e,t)=>{un.init(e,t),$r.init(e,t)});function pn(e,t,r){return new dn({type:"union",options:t,discriminator:e,...Se(r)})}const hn=ie("ZodIntersection",(e,t)=>{br.init(e,t),wo.init(e,t)});function fn(e,t){return new hn({type:"intersection",left:e,right:t})}const mn=ie("ZodRecord",(e,t)=>{Sr.init(e,t),wo.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function yn(e,t,r){return new mn({type:"record",keyType:e,valueType:t,...Se(r)})}const gn=ie("ZodEnum",(e,t)=>{Pr.init(e,t),wo.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 gn({...t,checks:[],...Se(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 gn({...t,checks:[],...Se(o),entries:n})}});function vn(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new gn({type:"enum",entries:r,...Se(t)})}const _n=ie("ZodLiteral",(e,t)=>{Tr.init(e,t),wo.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 wn(e,t){return new _n({type:"literal",values:Array.isArray(e)?e:[e],...Se(t)})}const $n=ie("ZodTransform",(e,t)=>{xr.init(e,t),wo.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 bn(e){return new $n({type:"transform",transform:e})}const kn=ie("ZodOptional",(e,t)=>{Ir.init(e,t),wo.init(e,t),e.unwrap=()=>e._zod.def.innerType});function En(e){return new kn({type:"optional",innerType:e})}const Sn=ie("ZodNullable",(e,t)=>{Nr.init(e,t),wo.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Pn(e){return new Sn({type:"nullable",innerType:e})}const Tn=ie("ZodDefault",(e,t)=>{Cr.init(e,t),wo.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});const xn=ie("ZodPrefault",(e,t)=>{Rr.init(e,t),wo.init(e,t),e.unwrap=()=>e._zod.def.innerType});const In=ie("ZodNonOptional",(e,t)=>{Or.init(e,t),wo.init(e,t),e.unwrap=()=>e._zod.def.innerType});const Nn=ie("ZodCatch",(e,t)=>{Ar.init(e,t),wo.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});const Cn=ie("ZodPipe",(e,t)=>{Mr.init(e,t),wo.init(e,t),e.in=t.in,e.out=t.out});function jn(e,t){return new Cn({type:"pipe",in:e,out:t})}const Rn=ie("ZodReadonly",(e,t)=>{Dr.init(e,t),wo.init(e,t)});const On=ie("ZodCustom",(e,t)=>{Vr.init(e,t),wo.init(e,t)});function zn(e,t){return jn(bn(e),t)}const An="custom";const Mn="2025-11-25",Un=[Mn,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Dn="io.modelcontextprotocol/related-task",qn="2.0",Vn=function(e,t,r){const o=Se(r);return o.abort??(o.abort=!0),new e({type:"custom",check:"custom",fn:t,...o})}(On,(e=>null!==e&&("object"==typeof e||"function"==typeof e))??(()=>!0),Fn);var Fn;const Ln=ln([ko(),Ho().int()]),Kn=ko();cn({ttl:ln([Ho(),Qo()]).optional(),pollInterval:Ho().optional()});const Hn=an({ttl:Ho().optional()}),Zn=an({taskId:ko()}),Gn=cn({progressToken:Ln.optional(),[Dn]:Zn.optional()}),Jn=an({_meta:Gn.optional()}),Wn=Jn.extend({task:Hn.optional()}),Bn=an({method:ko(),params:Jn.loose().optional()}),Qn=an({_meta:Gn.optional()}),Yn=an({method:ko(),params:Qn.loose().optional()}),Xn=cn({_meta:Gn.optional()}),es=ln([ko(),Ho().int()]),ts=an({jsonrpc:wn(qn),id:es,...Bn.shape}).strict(),rs=e=>ts.safeParse(e).success,os=an({jsonrpc:wn(qn),...Yn.shape}).strict(),ns=an({jsonrpc:wn(qn),id:es,result:Xn}).strict(),ss=e=>ns.safeParse(e).success;var as;!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"}(as||(as={}));const is=an({jsonrpc:wn(qn),id:es.optional(),error:an({code:Ho().int(),message:ko(),data:en().optional()})}).strict(),cs=ln([ts,os,ns,is]);ln([ns,is]);const us=Xn.strict(),ls=Qn.extend({requestId:es.optional(),reason:ko().optional()}),ds=Yn.extend({method:wn("notifications/cancelled"),params:ls}),ps=an({src:ko(),mimeType:ko().optional(),sizes:nn(ko()).optional(),theme:vn(["light","dark"]).optional()}),hs=an({icons:nn(ps).optional()}),fs=an({name:ko(),title:ko().optional()}),ms=fs.extend({...fs.shape,...hs.shape,version:ko(),websiteUrl:ko().optional(),description:ko().optional()}),ys=fn(an({applyDefaults:Wo().optional()}),yn(ko(),en())),gs=zn(e=>e&&"object"==typeof e&&!Array.isArray(e)&&0===Object.keys(e).length?{form:{}}:e,fn(an({form:ys.optional(),url:Vn.optional()}),yn(ko(),en()).optional())),vs=cn({list:Vn.optional(),cancel:Vn.optional(),requests:cn({sampling:cn({createMessage:Vn.optional()}).optional(),elicitation:cn({create:Vn.optional()}).optional()}).optional()}),_s=cn({list:Vn.optional(),cancel:Vn.optional(),requests:cn({tools:cn({call:Vn.optional()}).optional()}).optional()}),ws=an({experimental:yn(ko(),Vn).optional(),sampling:an({context:Vn.optional(),tools:Vn.optional()}).optional(),elicitation:gs.optional(),roots:an({listChanged:Wo().optional()}).optional(),tasks:vs.optional()}),$s=Jn.extend({protocolVersion:ko(),capabilities:ws,clientInfo:ms}),bs=Bn.extend({method:wn("initialize"),params:$s}),ks=an({experimental:yn(ko(),Vn).optional(),logging:Vn.optional(),completions:Vn.optional(),prompts:an({listChanged:Wo().optional()}).optional(),resources:an({subscribe:Wo().optional(),listChanged:Wo().optional()}).optional(),tools:an({listChanged:Wo().optional()}).optional(),tasks:_s.optional()}),Es=Xn.extend({protocolVersion:ko(),capabilities:ks,serverInfo:ms,instructions:ko().optional()}),Ss=Yn.extend({method:wn("notifications/initialized"),params:Qn.optional()}),Ps=Bn.extend({method:wn("ping"),params:Jn.optional()}),Ts=an({progress:Ho(),total:En(Ho()),message:En(ko())}),xs=an({...Qn.shape,...Ts.shape,progressToken:Ln}),Is=Yn.extend({method:wn("notifications/progress"),params:xs}),Ns=Jn.extend({cursor:Kn.optional()}),Cs=Bn.extend({params:Ns.optional()}),js=Xn.extend({nextCursor:Kn.optional()}),Rs=vn(["working","input_required","completed","failed","cancelled"]),Os=an({taskId:ko(),status:Rs,ttl:ln([Ho(),Qo()]),createdAt:ko(),lastUpdatedAt:ko(),pollInterval:En(Ho()),statusMessage:En(ko())}),zs=Xn.extend({task:Os}),As=Qn.merge(Os),Ms=Yn.extend({method:wn("notifications/tasks/status"),params:As}),Us=Bn.extend({method:wn("tasks/get"),params:Jn.extend({taskId:ko()})}),Ds=Xn.merge(Os),qs=Bn.extend({method:wn("tasks/result"),params:Jn.extend({taskId:ko()})});Xn.loose();const Vs=Cs.extend({method:wn("tasks/list")}),Fs=js.extend({tasks:nn(Os)}),Ls=Bn.extend({method:wn("tasks/cancel"),params:Jn.extend({taskId:ko()})}),Ks=Xn.merge(Os),Hs=an({uri:ko(),mimeType:En(ko()),_meta:yn(ko(),en()).optional()}),Zs=Hs.extend({text:ko()}),Gs=ko().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Js=Hs.extend({blob:Gs}),Ws=vn(["user","assistant"]),Bs=an({audience:nn(Ws).optional(),priority:Ho().min(0).max(1).optional(),lastModified:io({offset:!0}).optional()}),Qs=an({...fs.shape,...hs.shape,uri:ko(),description:En(ko()),mimeType:En(ko()),annotations:Bs.optional(),_meta:En(cn({}))}),Ys=an({...fs.shape,...hs.shape,uriTemplate:ko(),description:En(ko()),mimeType:En(ko()),annotations:Bs.optional(),_meta:En(cn({}))}),Xs=Cs.extend({method:wn("resources/list")}),ea=js.extend({resources:nn(Qs)}),ta=Cs.extend({method:wn("resources/templates/list")}),ra=js.extend({resourceTemplates:nn(Ys)}),oa=Jn.extend({uri:ko()}),na=oa,sa=Bn.extend({method:wn("resources/read"),params:na}),aa=Xn.extend({contents:nn(ln([Zs,Js]))}),ia=Yn.extend({method:wn("notifications/resources/list_changed"),params:Qn.optional()}),ca=oa,ua=Bn.extend({method:wn("resources/subscribe"),params:ca}),la=oa,da=Bn.extend({method:wn("resources/unsubscribe"),params:la}),pa=Qn.extend({uri:ko()}),ha=Yn.extend({method:wn("notifications/resources/updated"),params:pa}),fa=an({name:ko(),description:En(ko()),required:En(Wo())}),ma=an({...fs.shape,...hs.shape,description:En(ko()),arguments:En(nn(fa)),_meta:En(cn({}))}),ya=Cs.extend({method:wn("prompts/list")}),ga=js.extend({prompts:nn(ma)}),va=Jn.extend({name:ko(),arguments:yn(ko(),ko()).optional()}),_a=Bn.extend({method:wn("prompts/get"),params:va}),wa=an({type:wn("text"),text:ko(),annotations:Bs.optional(),_meta:yn(ko(),en()).optional()}),$a=an({type:wn("image"),data:Gs,mimeType:ko(),annotations:Bs.optional(),_meta:yn(ko(),en()).optional()}),ba=an({type:wn("audio"),data:Gs,mimeType:ko(),annotations:Bs.optional(),_meta:yn(ko(),en()).optional()}),ka=an({type:wn("tool_use"),name:ko(),id:ko(),input:yn(ko(),en()),_meta:yn(ko(),en()).optional()}),Ea=an({type:wn("resource"),resource:ln([Zs,Js]),annotations:Bs.optional(),_meta:yn(ko(),en()).optional()}),Sa=ln([wa,$a,ba,Qs.extend({type:wn("resource_link")}),Ea]),Pa=an({role:Ws,content:Sa}),Ta=Xn.extend({description:ko().optional(),messages:nn(Pa)}),xa=Yn.extend({method:wn("notifications/prompts/list_changed"),params:Qn.optional()}),Ia=an({title:ko().optional(),readOnlyHint:Wo().optional(),destructiveHint:Wo().optional(),idempotentHint:Wo().optional(),openWorldHint:Wo().optional()}),Na=an({taskSupport:vn(["required","optional","forbidden"]).optional()}),Ca=an({...fs.shape,...hs.shape,description:ko().optional(),inputSchema:an({type:wn("object"),properties:yn(ko(),Vn).optional(),required:nn(ko()).optional()}).catchall(en()),outputSchema:an({type:wn("object"),properties:yn(ko(),Vn).optional(),required:nn(ko()).optional()}).catchall(en()).optional(),annotations:Ia.optional(),execution:Na.optional(),_meta:yn(ko(),en()).optional()}),ja=Cs.extend({method:wn("tools/list")}),Ra=js.extend({tools:nn(Ca)}),Oa=Xn.extend({content:nn(Sa).default([]),structuredContent:yn(ko(),en()).optional(),isError:Wo().optional()});Oa.or(Xn.extend({toolResult:en()}));const za=Wn.extend({name:ko(),arguments:yn(ko(),en()).optional()}),Aa=Bn.extend({method:wn("tools/call"),params:za}),Ma=Yn.extend({method:wn("notifications/tools/list_changed"),params:Qn.optional()}),Ua=an({autoRefresh:Wo().default(!0),debounceMs:Ho().int().nonnegative().default(300)}),Da=vn(["debug","info","notice","warning","error","critical","alert","emergency"]),qa=Jn.extend({level:Da}),Va=Bn.extend({method:wn("logging/setLevel"),params:qa}),Fa=Qn.extend({level:Da,logger:ko().optional(),data:en()}),La=Yn.extend({method:wn("notifications/message"),params:Fa}),Ka=an({name:ko().optional()}),Ha=an({hints:nn(Ka).optional(),costPriority:Ho().min(0).max(1).optional(),speedPriority:Ho().min(0).max(1).optional(),intelligencePriority:Ho().min(0).max(1).optional()}),Za=an({mode:vn(["auto","required","none"]).optional()}),Ga=an({type:wn("tool_result"),toolUseId:ko().describe("The unique identifier for the corresponding tool call."),content:nn(Sa).default([]),structuredContent:an({}).loose().optional(),isError:Wo().optional(),_meta:yn(ko(),en()).optional()}),Ja=pn("type",[wa,$a,ba]),Wa=pn("type",[wa,$a,ba,ka,Ga]),Ba=an({role:Ws,content:ln([Wa,nn(Wa)]),_meta:yn(ko(),en()).optional()}),Qa=Wn.extend({messages:nn(Ba),modelPreferences:Ha.optional(),systemPrompt:ko().optional(),includeContext:vn(["none","thisServer","allServers"]).optional(),temperature:Ho().optional(),maxTokens:Ho().int(),stopSequences:nn(ko()).optional(),metadata:Vn.optional(),tools:nn(Ca).optional(),toolChoice:Za.optional()}),Ya=Bn.extend({method:wn("sampling/createMessage"),params:Qa}),Xa=Xn.extend({model:ko(),stopReason:En(vn(["endTurn","stopSequence","maxTokens"]).or(ko())),role:Ws,content:Ja}),ei=Xn.extend({model:ko(),stopReason:En(vn(["endTurn","stopSequence","maxTokens","toolUse"]).or(ko())),role:Ws,content:ln([Wa,nn(Wa)])}),ti=an({type:wn("boolean"),title:ko().optional(),description:ko().optional(),default:Wo().optional()}),ri=an({type:wn("string"),title:ko().optional(),description:ko().optional(),minLength:Ho().optional(),maxLength:Ho().optional(),format:vn(["email","uri","date","date-time"]).optional(),default:ko().optional()}),oi=an({type:vn(["number","integer"]),title:ko().optional(),description:ko().optional(),minimum:Ho().optional(),maximum:Ho().optional(),default:Ho().optional()}),ni=an({type:wn("string"),title:ko().optional(),description:ko().optional(),enum:nn(ko()),default:ko().optional()}),si=an({type:wn("string"),title:ko().optional(),description:ko().optional(),oneOf:nn(an({const:ko(),title:ko()})),default:ko().optional()}),ai=an({type:wn("string"),title:ko().optional(),description:ko().optional(),enum:nn(ko()),enumNames:nn(ko()).optional(),default:ko().optional()}),ii=ln([ni,si]),ci=ln([an({type:wn("array"),title:ko().optional(),description:ko().optional(),minItems:Ho().optional(),maxItems:Ho().optional(),items:an({type:wn("string"),enum:nn(ko())}),default:nn(ko()).optional()}),an({type:wn("array"),title:ko().optional(),description:ko().optional(),minItems:Ho().optional(),maxItems:Ho().optional(),items:an({anyOf:nn(an({const:ko(),title:ko()}))}),default:nn(ko()).optional()})]),ui=ln([ai,ii,ci]),li=ln([ui,ti,ri,oi]),di=ln([Wn.extend({mode:wn("form").optional(),message:ko(),requestedSchema:an({type:wn("object"),properties:yn(ko(),li),required:nn(ko()).optional()})}),Wn.extend({mode:wn("url"),message:ko(),elicitationId:ko(),url:ko().url()})]),pi=Bn.extend({method:wn("elicitation/create"),params:di}),hi=Qn.extend({elicitationId:ko()}),fi=Yn.extend({method:wn("notifications/elicitation/complete"),params:hi}),mi=Xn.extend({action:vn(["accept","decline","cancel"]),content:zn(e=>null===e?void 0:e,yn(ko(),ln([ko(),Ho(),Wo(),nn(ko())])).optional())}),yi=an({type:wn("ref/resource"),uri:ko()}),gi=an({type:wn("ref/prompt"),name:ko()}),vi=Jn.extend({ref:ln([gi,yi]),argument:an({name:ko(),value:ko()}),context:an({arguments:yn(ko(),ko()).optional()}).optional()}),_i=Bn.extend({method:wn("completion/complete"),params:vi}),wi=Xn.extend({completion:cn({values:nn(ko()).max(100),total:En(Ho().int()),hasMore:En(Wo())})}),$i=an({uri:ko().startsWith("file://"),name:ko().optional(),_meta:yn(ko(),en()).optional()}),bi=Bn.extend({method:wn("roots/list"),params:Jn.optional()}),ki=Xn.extend({roots:nn($i)}),Ei=Yn.extend({method:wn("notifications/roots/list_changed"),params:Qn.optional()});ln([Ps,bs,_i,Va,_a,ya,Xs,ta,sa,ua,da,Aa,ja,Us,qs,Vs,Ls]),ln([ds,Is,Ss,Ei,Ms]),ln([us,Xa,ei,mi,ki,Ds,Fs,zs]),ln([Ps,Ya,pi,bi,Us,qs,Vs,Ls]),ln([ds,Is,La,ha,ia,Ma,xa,Ms,fi]),ln([us,Es,wi,Ta,ga,ea,ra,aa,Oa,Ra,Ds,Fs,zs]);class Si 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===as.UrlElicitationRequired&&r){const e=r;if(e.elicitations)return new Pi(e.elicitations,t)}return new Si(e,t,r)}}class Pi extends Si{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(as.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}function Ti(e){return"completed"===e||"failed"===e||"cancelled"===e}function xi(e){const t=so(e),r=t?.method;if(!r)throw new Error("Schema is missing a method literal");const o=function(e){if(oo(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 Ii(e,t){const r=no(e,t);if(!r.success)throw r.error;return r.data}new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");class Ni{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(ds,e=>{this._oncancel(e)}),this.setNotificationHandler(Is,e=>{this._onprogress(e)}),this.setRequestHandler(Ps,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Us,async(e,t)=>{const r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new Si(as.InvalidParams,"Failed to retrieve task: Task not found");return{...r}}),this.setRequestHandler(qs,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 Si(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 Si(as.InvalidParams,`Task not found: ${o}`);if(!Ti(n.status))return await this._waitForTaskUpdate(o,t.signal),await r();if(Ti(n.status)){const e=await this._taskStore.getTaskResult(o,t.sessionId);return this._clearTaskQueue(o),{...e,_meta:{...e._meta,[Dn]:{taskId:o}}}}return await r()};return await r()}),this.setRequestHandler(Vs,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 Si(as.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(Ls,async(e,t)=>{try{const r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new Si(as.InvalidParams,`Task not found: ${e.params.taskId}`);if(Ti(r.status))throw new Si(as.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 Si(as.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...o}}catch(e){if(e instanceof Si)throw e;throw new Si(as.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),Si.fromError(as.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),ss(e)||(r=e,is.safeParse(r).success)?this._onresponse(e):rs(e)?this._onrequest(e,t):(e=>os.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=Si.fromError(as.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?.[Dn]?.taskId;if(void 0===r){const t={jsonrpc:"2.0",id:e.id,error:{code:as.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,Wn.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 Si(as.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:as.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),ss(e))r(e);else{r(new Si(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(ss(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),ss(e))o(e);else{o(Si.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 Si?e:new Si(as.InternalError,String(e))}}return}let n;try{const o=await this.request(e,zs,r);if(!o.task)throw new Si(as.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},Ti(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 Si(as.InternalError,`Task ${n} failed`)}:"cancelled"===e.status&&(yield{type:"error",error:new Si(as.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 Si?e:new Si(as.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++,p={...e,jsonrpc:"2.0",id:d};r?.onprogress&&(this._progressHandlers.set(d,r.onprogress),p.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),a&&(p.params={...p.params,task:a}),i&&(p.params={...p.params,_meta:{...p.params?._meta||{},[Dn]:i}});const h=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 Si?e:new Si(as.RequestTimeout,String(e));u(t)};this._responseHandlers.set(d,e=>{if(!r?.signal?.aborted){if(e instanceof Error)return u(e);try{const r=no(t,e.result);r.success?c(r.data):u(r.error)}catch(e){u(e)}}}),r?.signal?.addEventListener("abort",()=>{h(r?.signal?.reason)});const f=r?.timeout??6e4;this._setupTimeout(d,f,r?.maxTotalTimeout,()=>h(Si.fromError(as.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:p,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(d),u(e)})}else this._transport.send(p,{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},Ds,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},Fs,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},Ks,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||{},[Dn]: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||{},[Dn]: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||{},[Dn]:t.relatedTask}}}),await this._transport.send(o,t)}setRequestHandler(e,t){const r=xi(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(r,o)=>{const n=Ii(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=xi(e);this._notificationHandlers.set(r,r=>{const o=Ii(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&&rs(t.message)){const r=t.message.id,o=this._requestResolvers.get(r);o?(o(new Si(as.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 Si(as.InvalidRequest,"Request cancelled"));const n=setTimeout(e,r);t.addEventListener("abort",()=>{clearTimeout(n),o(new Si(as.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 Si(as.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=Ms.parse({method:"notifications/tasks/status",params:s});await this.notification(t),Ti(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 Si(as.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(Ti(s.status))throw new Si(as.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=Ms.parse({method:"notifications/tasks/status",params:a});await this.notification(t),Ti(a.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>r.listTasks(e,t)}}}function Ci(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 Ri,Oi={exports:{}},zi={},Ai={},Mi={},Ui={},Di={},qi={};function Vi(){return Ri||(Ri=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())}}(qi)),qi}var Fi,Li,Ki={};function Hi(){return Fi||(Fi=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=Vi();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}}}(Ki)),Ki}function Zi(){return Li||(Li=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=Vi(),r=Hi();var o=Vi();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=Hi();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=I(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=I(this.rhs,e,r),this}get names(){return x(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 p 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=I(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class h 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 h{render(e){return"{"+e._n+super.render(e)+"}"+e._n}}class m extends h{}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=I(this.condition,e,t),this}get names(){const e=super.names;return x(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=I(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=x(super.names,this.from);return x(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=I(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 h{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 x(e,r){return r instanceof t._CodeOrName?T(e,r.names):e}function I(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 p(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)}}(Di)),Di}var Gi={};Object.defineProperty(Gi,"__esModule",{value:!0}),Gi.checkStrictMode=Gi.getErrorPath=Gi.Type=Gi.useFunc=Gi.setEvaluated=Gi.evaluatedPropsToName=Gi.mergeEvaluated=Gi.eachItem=Gi.unescapeJsonPointer=Gi.escapeJsonPointer=Gi.escapeFragment=Gi.unescapeFragment=Gi.schemaRefOrVal=Gi.schemaHasRulesButRef=Gi.schemaHasRules=Gi.checkUnknownRules=Gi.alwaysValidSchema=Gi.toHash=void 0;const Ji=Zi(),Wi=Vi();function Bi(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]||sc(e,`unknown keyword: "${r}"`)}function Qi(e,t){if("boolean"==typeof e)return!e;for(const r in e)if(t[r])return!0;return!1}function Yi(e){return"number"==typeof e?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}function Xi(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function ec({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:o}){return(n,s,a,i)=>{const c=void 0===a?s:a instanceof Ji.Name?(s instanceof Ji.Name?e(n,s,a):t(n,s,a),a):s instanceof Ji.Name?(t(n,a,s),s):r(s,a);return i!==Ji.Name||c instanceof Ji.Name?c:o(n,c)}}function tc(e,t){if(!0===t)return e.var("props",!0);const r=e.var("props",Ji._`{}`);return void 0!==t&&rc(e,r,t),r}function rc(e,t,r){Object.keys(r).forEach(r=>e.assign(Ji._`${t}${(0,Ji.getProperty)(r)}`,!0))}Gi.toHash=function(e){const t={};for(const r of e)t[r]=!0;return t},Gi.alwaysValidSchema=function(e,t){return"boolean"==typeof t?t:0===Object.keys(t).length||(Bi(e,t),!Qi(t,e.self.RULES.all))},Gi.checkUnknownRules=Bi,Gi.schemaHasRules=Qi,Gi.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},Gi.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 Ji._`${r}`}return Ji._`${e}${t}${(0,Ji.getProperty)(o)}`},Gi.unescapeFragment=function(e){return Xi(decodeURIComponent(e))},Gi.escapeFragment=function(e){return encodeURIComponent(Yi(e))},Gi.escapeJsonPointer=Yi,Gi.unescapeJsonPointer=Xi,Gi.eachItem=function(e,t){if(Array.isArray(e))for(const r of e)t(r);else t(e)},Gi.mergeEvaluated={props:ec({mergeNames:(e,t,r)=>e.if(Ji._`${r} !== true && ${t} !== undefined`,()=>{e.if(Ji._`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,Ji._`${r} || {}`).code(Ji._`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if(Ji._`${r} !== true`,()=>{!0===t?e.assign(r,!0):(e.assign(r,Ji._`${r} || {}`),rc(e,r,t))}),mergeValues:(e,t)=>!0===e||{...e,...t},resultToName:tc}),items:ec({mergeNames:(e,t,r)=>e.if(Ji._`${r} !== true && ${t} !== undefined`,()=>e.assign(r,Ji._`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if(Ji._`${r} !== true`,()=>e.assign(r,!0===t||Ji._`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>!0===e||Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})},Gi.evaluatedPropsToName=tc,Gi.setEvaluated=rc;const oc={};var nc;function sc(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,!0===r)throw new Error(t);e.self.logger.warn(t)}}Gi.useFunc=function(e,t){return e.scopeValue("func",{ref:t,code:oc[t.code]||(oc[t.code]=new Wi._Code(t.code))})},function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"}(nc||(Gi.Type=nc={})),Gi.getErrorPath=function(e,t,r){if(e instanceof Ji.Name){const o=t===nc.Num;return r?o?Ji._`"[" + ${e} + "]"`:Ji._`"['" + ${e} + "']"`:o?Ji._`"/" + ${e}`:Ji._`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,Ji.getProperty)(e).toString():"/"+Yi(e)},Gi.checkStrictMode=sc;var ac,ic,cc,uc={};function lc(){if(ac)return uc;ac=1,Object.defineProperty(uc,"__esModule",{value:!0});const e=Zi(),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 uc.default=t,uc}function dc(){return ic||(ic=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=Zi(),r=Gi,o=lc();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:p}=u,h=i(r,o,a);(null!=c?c:d||p)?n(l,h):s(u,t._`[${h}]`)},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:p,topSchemaRef:h,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._`${h}${f}`],[o.default.data,c]);p&&s.push([a.propertyName,p])}(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]}}(Ui)),Ui}var pc={},hc={};Object.defineProperty(hc,"__esModule",{value:!0}),hc.getRules=hc.isJSONType=void 0;const fc=new Set(["string","number","integer","boolean","null","object","array"]);hc.isJSONType=function(e){return"string"==typeof e&&fc.has(e)},hc.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 mc,yc={};function gc(){if(mc)return yc;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 mc=1,Object.defineProperty(yc,"__esModule",{value:!0}),yc.shouldUseRule=yc.shouldUseGroup=yc.schemaHasRulesForType=void 0,yc.schemaHasRulesForType=function({schema:t,self:r},o){const n=r.RULES.types[o];return n&&!0!==n&&e(t,n)},yc.shouldUseGroup=e,yc.shouldUseRule=t,yc}Object.defineProperty(pc,"__esModule",{value:!0}),pc.reportTypeError=pc.checkDataTypes=pc.checkDataType=pc.coerceAndCheckDataType=pc.getJSONTypes=pc.getSchemaTypes=pc.DataType=void 0;const vc=hc,_c=gc(),wc=dc(),$c=Zi(),bc=Gi;var kc;function Ec(e){const t=Array.isArray(e)?e:e?[e]:[];if(t.every(vc.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"}(kc||(pc.DataType=kc={})),pc.getSchemaTypes=function(e){const t=Ec(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},pc.getJSONTypes=Ec,pc.coerceAndCheckDataType=function(e,t){const{gen:r,data:o,opts:n}=e,s=function(e,t){return t?e.filter(e=>Sc.has(e)||"array"===t&&"array"===e):[]}(t,n.coerceTypes),a=t.length>0&&!(0===s.length&&1===t.length&&(0,_c.schemaHasRulesForType)(e,t[0]));if(a){const a=Tc(t,o,n.strictNumbers,kc.Wrong);r.if(a,()=>{s.length?function(e,t,r){const{gen:o,data:n,opts:s}=e,a=o.let("dataType",$c._`typeof ${n}`),i=o.let("coerced",$c._`undefined`);"array"===s.coerceTypes&&o.if($c._`${a} == 'object' && Array.isArray(${n}) && ${n}.length == 1`,()=>o.assign(n,$c._`${n}[0]`).assign(a,$c._`typeof ${n}`).if(Tc(t,n,s.strictNumbers),()=>o.assign(i,n)));o.if($c._`${i} !== undefined`);for(const e of r)(Sc.has(e)||"array"===e&&"array"===s.coerceTypes)&&c(e);function c(e){switch(e){case"string":return void o.elseIf($c._`${a} == "number" || ${a} == "boolean"`).assign(i,$c._`"" + ${n}`).elseIf($c._`${n} === null`).assign(i,$c._`""`);case"number":return void o.elseIf($c._`${a} == "boolean" || ${n} === null
|
|
2
|
-
|| (${a} == "string" && ${n} && ${n} == +${n})`).assign(i
|
|
3
|
-
|| (${a} === "string" && ${n} && ${n} == +${n} && !(${n} % 1))`).assign(i
|
|
4
|
-
|| ${a} === "boolean" || ${n} === null`).assign(i,$c._`[${n}]`)}}o.else(),Ic(e),o.endIf(),o.if($c._`${i} !== undefined`,()=>{o.assign(n,i),function({gen:e,parentData:t,parentDataProperty:r},o){e.if($c._`${t} !== undefined`,()=>e.assign($c._`${t}[${r}]`,o))}(e,i)})}(e,t,s):Ic(e)})}return a};const Sc=new Set(["string","number","integer","boolean","null"]);function Pc(e,t,r,o=kc.Correct){const n=o===kc.Correct?$c.operators.EQ:$c.operators.NEQ;let s;switch(e){case"null":return $c._`${t} ${n} null`;case"array":s=$c._`Array.isArray(${t})`;break;case"object":s=$c._`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":s=a($c._`!(${t} % 1) && !isNaN(${t})`);break;case"number":s=a();break;default:return $c._`typeof ${t} ${n} ${e}`}return o===kc.Correct?s:(0,$c.not)(s);function a(e=$c.nil){return(0,$c.and)($c._`typeof ${t} == "number"`,e,r?$c._`isFinite(${t})`:$c.nil)}}function Tc(e,t,r,o){if(1===e.length)return Pc(e[0],t,r,o);let n;const s=(0,bc.toHash)(e);if(s.array&&s.object){const e=$c._`typeof ${t} != "object"`;n=s.null?e:$c._`!${t} || ${e}`,delete s.null,delete s.array,delete s.object}else n=$c.nil;s.number&&delete s.integer;for(const e in s)n=(0,$c.and)(n,Pc(e,t,r,o));return n}pc.checkDataType=Pc,pc.checkDataTypes=Tc;const xc={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>"string"==typeof e?$c._`{type: ${e}}`:$c._`{type: ${t}}`};function Ic(e){const t=function(e){const{gen:t,data:r,schema:o}=e,n=(0,bc.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,wc.reportError)(t,xc)}pc.reportTypeError=Ic;var Nc,Cc={};var jc,Rc,Oc={},zc={};function Ac(){if(jc)return zc;jc=1,Object.defineProperty(zc,"__esModule",{value:!0}),zc.validateUnion=zc.validateArray=zc.usePattern=zc.callValidateCode=zc.schemaProperties=zc.allSchemaProperties=zc.noPropertyInData=zc.propertyInData=zc.isOwnProperty=zc.hasPropFunc=zc.reportMissingProp=zc.checkMissingProp=zc.checkReportMissingProp=void 0;const e=Zi(),t=Gi,r=lc(),o=Gi;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):[]}zc.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()})},zc.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}`)))},zc.reportMissingProp=function(e,t){e.setParams({missingProperty:t},!0),e.error()},zc.hasPropFunc=n,zc.isOwnProperty=s,zc.propertyInData=function(t,r,o,n){const a=e._`${r}${(0,e.getProperty)(o)} !== undefined`;return n?e._`${a} && ${s(t,r,o)}`:a},zc.noPropertyInData=a,zc.allSchemaProperties=i,zc.schemaProperties=function(e,r){return i(r).filter(o=>!(0,t.alwaysValidSchema)(e,r[o]))},zc.callValidateCode=function({schemaCode:t,data:o,it:{gen:n,topSchemaRef:s,schemaPath:a,errorPath:i},it:c},u,l,d){const p=d?e._`${t}, ${o}, ${s}${a}`:o,h=[[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&&h.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);const f=e._`${p}, ${n.object(...h)}`;return l!==e.nil?e._`${u}.call(${l}, ${f})`:e._`${u}(${f})`};const c=e._`new RegExp`;return zc.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})`})},zc.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)})}},zc.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))},zc}function Mc(){if(Rc)return Oc;Rc=1,Object.defineProperty(Oc,"__esModule",{value:!0}),Oc.validateKeywordUsage=Oc.validSchemaType=Oc.funcKeywordCode=Oc.macroKeywordCode=void 0;const e=Zi(),t=lc(),r=Ac(),o=dc();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 Oc.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))},Oc.funcKeywordCode=function(a,i){var c;const{gen:u,keyword:l,schema:d,parentSchema:p,$data:h,it:f}=a;!function({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}(f,i);const m=!h&&i.compile?i.compile.call(f.self,d,p,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&&!h||!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)},Oc.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)},Oc.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)}}},Oc}var Uc,Dc={};var qc={},Vc=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},Fc={exports:{}},Lc=Fc.exports=function(e,t,r){"function"==typeof t&&(r=t,t={}),Kc(t,"function"==typeof(r=t.cb||r)?r:r.pre||function(){},r.post||function(){},e,"",e)};function Kc(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 Lc.arrayKeywords)for(var p=0;p<d.length;p++)Kc(e,t,r,d[p],n+"/"+l+"/"+p,s,n,l,o,p)}else if(l in Lc.propsKeywords){if(d&&"object"==typeof d)for(var h in d)Kc(e,t,r,d[h],n+"/"+l+"/"+Hc(h),s,n,l,o,h)}else(l in Lc.keywords||e.allKeys&&!(l in Lc.skipKeywords))&&Kc(e,t,r,d,n+"/"+l,s,n,l,o)}r(o,n,s,a,i,c,u)}}function Hc(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}Lc.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},Lc.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},Lc.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},Lc.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 Zc=Fc.exports;Object.defineProperty(qc,"__esModule",{value:!0}),qc.getSchemaRefs=qc.resolveUrl=qc.normalizeId=qc._getFullPath=qc.getFullPath=qc.inlineRef=void 0;const Gc=Gi,Jc=Vc,Wc=Zc,Bc=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);qc.inlineRef=function(e,t=!0){return"boolean"==typeof e||(!0===t?!Yc(e):!!t&&Xc(e)<=t)};const Qc=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Yc(e){for(const t in e){if(Qc.has(t))return!0;const r=e[t];if(Array.isArray(r)&&r.some(Yc))return!0;if("object"==typeof r&&Yc(r))return!0}return!1}function Xc(e){let t=0;for(const r in e){if("$ref"===r)return 1/0;if(t++,!Bc.has(r)&&("object"==typeof e[r]&&(0,Gc.eachItem)(e[r],e=>t+=Xc(e)),t===1/0))return 1/0}return t}function eu(e,t="",r){!1!==r&&(t=ou(t));const o=e.parse(t);return tu(e,o)}function tu(e,t){return e.serialize(t).split("#")[0]+"#"}qc.getFullPath=eu,qc._getFullPath=tu;const ru=/#\/?$/;function ou(e){return e?e.replace(ru,""):""}qc.normalizeId=ou,qc.resolveUrl=function(e,t,r){return r=ou(r),e.resolve(t,r)};const nu=/^[a-z_][-a-z0-9._]*$/i;var su;function au(){if(su)return Ai;su=1,Object.defineProperty(Ai,"__esModule",{value:!0}),Ai.getData=Ai.KeywordCxt=Ai.validateFunctionCode=void 0;const e=function(){if(cc)return Mi;cc=1,Object.defineProperty(Mi,"__esModule",{value:!0}),Mi.boolOrEmptySchema=Mi.topBoolOrEmptySchema=void 0;const e=dc(),t=Zi(),r=lc(),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 Mi.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))},Mi.boolOrEmptySchema=function(e,t){const{gen:r,schema:o}=e;!1===o?(r.var(t,!1),n(e)):r.var(t,!0)},Mi}(),t=pc,r=gc(),o=pc,n=function(){if(Nc)return Cc;Nc=1,Object.defineProperty(Cc,"__esModule",{value:!0}),Cc.assignDefaults=void 0;const e=Zi(),t=Gi;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 Cc.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))},Cc}(),s=Mc(),a=function(){if(Uc)return Dc;Uc=1,Object.defineProperty(Dc,"__esModule",{value:!0}),Dc.extendSubschemaMode=Dc.extendSubschemaData=Dc.getSubschema=void 0;const e=Zi(),t=Gi;return Dc.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')},Dc.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)},Dc.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},Dc}(),i=Zi(),c=lc(),u=qc,l=Gi,d=dc();function p({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"; ${h(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(h(r,n)).code(s))}function h(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:p,opts:h,self:f}=e,{RULES:m}=f;function y(l){(0,r.shouldUseGroup)(u,l)&&(l.type?(a.if((0,o.checkDataType)(l.type,d,h.strictNumbers)),$(e,l),1===t.length&&t[0]===l.type&&n&&(a.else(),(0,o.reportTypeError)(e)),a.endIf()):$(e,l),p||a.if(i._`${c.default.errors} === ${s||0}`))}!u.$ref||!h.ignoreKeywordsWithRef&&(0,l.schemaHasRulesButRef)(u,m)?(h.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)}Ai.validateFunctionCode=function(t){y(t)&&(g(t),m(t))?function(e){const{schema:t,opts:r,gen:o}=e;p(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):p(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",I(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)}Ai.KeywordCxt=S;const T=/^\/(?:[^~]|~0|~1)*$/,x=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function I(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=x.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 Ai.getData=I,Ai}qc.getSchemaRefs=function(e,t){if("boolean"==typeof e)return{};const{schemaId:r,uriResolver:o}=this.opts,n=ou(e[r]||t),s={"":n},a=eu(o,n,!1),i={},c=new Set;return Wc(e,{allKeys:!0},(e,t,o,n)=>{if(void 0===n)return;const d=a+t;let p=s[n];function h(t){const r=this.opts.uriResolver.resolve;if(t=ou(p?r(p,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!==ou(d)&&("#"===t[0]?(u(e,i[t],t),i[t]=e):this.refs[t]=d),t}function f(e){if("string"==typeof e){if(!nu.test(e))throw new Error(`invalid anchor "${e}"`);h.call(this,`#${e}`)}}"string"==typeof e[r]&&(p=h.call(this,e[r])),f.call(this,e.$anchor),f.call(this,e.$dynamicAnchor),s[t]=p}),i;function u(e,t,r){if(void 0!==t&&!Jc(e,t))throw l(r)}function l(e){return new Error(`reference "${e}" resolves to more than one schema`)}};var iu,cu={};function uu(){if(iu)return cu;iu=1,Object.defineProperty(cu,"__esModule",{value:!0});class e extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}}return cu.default=e,cu}var lu,du={};function pu(){if(lu)return du;lu=1,Object.defineProperty(du,"__esModule",{value:!0});const e=qc;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 du.default=t,du}var hu={};Object.defineProperty(hu,"__esModule",{value:!0}),hu.resolveSchema=hu.getCompilingSchema=hu.resolveRef=hu.compileSchema=hu.SchemaEnv=void 0;const fu=Zi(),mu=uu(),yu=lc(),gu=qc,vu=Gi,_u=au();let wu=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,gu.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 $u(e){const t=ku.call(this,e);if(t)return t;const r=(0,gu.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:o,lines:n}=this.opts.code,{ownProperties:s}=this.opts,a=new fu.CodeGen(this.scope,{es5:o,lines:n,ownProperties:s});let i;e.$async&&(i=a.scopeValue("Error",{ref:mu.default,code:fu._`require("ajv/dist/runtime/validation_error").default`}));const c=a.scopeName("validate");e.validateName=c;const u={gen:a,allErrors:this.opts.allErrors,data:yu.default.data,parentData:yu.default.parentData,parentDataProperty:yu.default.parentDataProperty,dataNames:[yu.default.data],dataPathArr:[fu.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:a.scopeValue("schema",!0===this.opts.code.source?{ref:e.schema,code:(0,fu.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:i,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:fu.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:fu._`""`,opts:this.opts,self:this};let l;try{this._compilations.add(e),(0,_u.validateFunctionCode)(u),a.optimize(this.opts.code.optimize);const t=a.toString();l=`${a.scopeRefs(yu.default.scope)}return ${t}`,this.opts.code.process&&(l=this.opts.code.process(l,e));const r=new Function(`${yu.default.self}`,`${yu.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 fu.Name?void 0:e,items:t instanceof fu.Name?void 0:t,dynamicProps:e instanceof fu.Name,dynamicItems:t instanceof fu.Name},r.source&&(r.source.evaluated=(0,fu.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 bu(e){return(0,gu.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:$u.call(this,e)}function ku(e){for(const t of this._compilations)if(Eu(t,e))return t}function Eu(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function Su(e,t){let r;for(;"string"==typeof(r=this.refs[t]);)t=r;return r||this.schemas[t]||Pu.call(this,e,t)}function Pu(e,t){const r=this.opts.uriResolver.parse(t),o=(0,gu._getFullPath)(this.opts.uriResolver,r);let n=(0,gu.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&o===n)return xu.call(this,r,e);const s=(0,gu.normalizeId)(o),a=this.refs[s]||this.schemas[s];if("string"==typeof a){const t=Pu.call(this,e,a);if("object"!=typeof(null==t?void 0:t.schema))return;return xu.call(this,r,t)}if("object"==typeof(null==a?void 0:a.schema)){if(a.validate||$u.call(this,a),s===(0,gu.normalizeId)(t)){const{schema:t}=a,{schemaId:r}=this.opts,o=t[r];return o&&(n=(0,gu.resolveUrl)(this.opts.uriResolver,n,o)),new wu({schema:t,schemaId:r,root:e,baseId:n})}return xu.call(this,r,a)}}hu.SchemaEnv=wu,hu.compileSchema=$u,hu.resolveRef=function(e,t,r){var o;r=(0,gu.resolveUrl)(this.opts.uriResolver,t,r);const n=e.refs[r];if(n)return n;let s=Su.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 wu({schema:n,schemaId:a,root:e,baseId:t}))}return void 0!==s?e.refs[r]=bu.call(this,s):void 0},hu.getCompilingSchema=ku,hu.resolveSchema=Pu;const Tu=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function xu(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,vu.unescapeFragment)(o)];if(void 0===e)return;const n="object"==typeof(r=e)&&r[this.opts.schemaId];!Tu.has(o)&&n&&(t=(0,gu.resolveUrl)(this.opts.uriResolver,t,n))}let s;if("boolean"!=typeof r&&r.$ref&&!(0,vu.schemaHasRulesButRef)(r,this.RULES)){const e=(0,gu.resolveUrl)(this.opts.uriResolver,t,r.$ref);s=Pu.call(this,o,e)}const{schemaId:a}=this.opts;return s=s||new wu({schema:r,schemaId:a,root:o,baseId:t}),s.schema!==s.root.schema?s:void 0}var Iu={$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},Nu={},Cu={exports:{}};const ju=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Ru=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 Ou(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 zu(e){return e.length=0,!0}function Au(e,t,r){if(e.length){const o=Ou(e);if(""===o)return r.error=!0,!1;t.push(o),e.length=0}return!0}function Mu(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=Au;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=zu}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===zu?r.zone=n.join(""):a?o.push(n.join("")):o.push(Ou(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 Uu={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(!Ru(r)){const t=Mu(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:Ru,isUUID:ju,normalizeIPv6:Mu,stringArrayToHexStripped:Ou};const{isUUID:Du}=Uu,qu=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,Vu=["http","https","ws","wss","urn","urn:uuid"];function Fu(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 Lu(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function Ku(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 Hu={scheme:"http",domainHost:!0,parse:Lu,serialize:Ku},Zu={scheme:"ws",domainHost:!0,parse:function(e){return e.secure=Fu(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e},serialize:function(e){if(e.port!==(Fu(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}},Gu={http:Hu,https:{scheme:"https",domainHost:Hu.domainHost,parse:Lu,serialize:Ku},ws:Zu,wss:{scheme:"wss",domainHost:Zu.domainHost,parse:Zu.parse,serialize:Zu.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(qu);if(r){const o=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];const n=Ju(`${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=Ju(`${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&&Du(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 Ju(e){return e&&(Gu[e]||Gu[e.toLowerCase()])||void 0}Object.setPrototypeOf(Gu,null);var Wu={wsIsSecure:Fu,SCHEMES:Gu,isValidSchemeName:function(e){return-1!==Vu.indexOf(e)},getSchemeHandler:Ju};const{normalizeIPv6:Bu,removeDotSegments:Qu,recomposeAuthority:Yu,normalizeComponentEncoding:Xu,isIPv4:el,nonSimpleDomain:tl}=Uu,{SCHEMES:rl,getSchemeHandler:ol}=Wu;function nl(e,t,r,o){const n={};return o||(e=il(sl(e,r),r),t=il(sl(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=Qu(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=Qu(t.path||""),n.query=t.query):(t.path?("/"===t.path[0]?n.path=Qu(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=Qu(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 sl(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=ol(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=Yu(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=Qu(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 al=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function il(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(al);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===el(o.host)){const e=Bu(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=ol(r.scheme||o.scheme);if(!(r.unicodeSupport||t&&t.unicodeSupport)&&o.host&&(r.domainHost||t&&t.domainHost)&&!1===n&&tl(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 cl={SCHEMES:rl,normalize:function(e,t){return"string"==typeof e?e=sl(il(e,t),t):"object"==typeof e&&(e=il(sl(e,t),t)),e},resolve:function(e,t,r){const o=r?Object.assign({scheme:"null"},r):{scheme:"null"},n=nl(il(e,o),il(t,o),o,!0);return o.skipEscape=!0,sl(n,o)},resolveComponent:nl,equal:function(e,t,r){return"string"==typeof e?(e=unescape(e),e=sl(Xu(il(e,r),!0),{...r,skipEscape:!0})):"object"==typeof e&&(e=sl(Xu(e,!0),{...r,skipEscape:!0})),"string"==typeof t?(t=unescape(t),t=sl(Xu(il(t,r),!0),{...r,skipEscape:!0})):"object"==typeof t&&(t=sl(Xu(t,!0),{...r,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()},serialize:sl,parse:il};Cu.exports=cl,Cu.exports.default=cl,Cu.exports.fastUri=cl;var ul=Cu.exports;Object.defineProperty(Nu,"__esModule",{value:!0});const ll=ul;ll.code='require("ajv/dist/runtime/uri").default',Nu.default=ll,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=au();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var r=Zi();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=uu(),n=pu(),s=hc,a=hu,i=Zi(),c=qc,u=pc,l=Gi,d=Iu,p=Nu,h=(e,t)=>new RegExp(e,t);h.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 x=e.strict,I=null===(t=e.code)||void 0===t?void 0:t.optimize,N=!0===I||void 0===I?1:I||0,C=null!==(o=null===(r=e.code)||void 0===r?void 0:r.regExp)&&void 0!==o?o:h,j=null!==(n=e.uriResolver)&&void 0!==n?n:p.default;return{strictSchema:null===(a=null!==(s=e.strictSchema)&&void 0!==s?s:x)||void 0===a||a,strictNumbers:null===(c=null!==(i=e.strictNumbers)&&void 0!==i?i:x)||void 0===c||c,strictTypes:null!==(l=null!==(u=e.strictTypes)&&void 0!==u?u:x)&&void 0!==l?l:"log",strictTuples:null!==(f=null!==(d=e.strictTuples)&&void 0!==d?d:x)&&void 0!==f?f:"log",strictRequired:null!==(y=null!==(m=e.strictRequired)&&void 0!==m?m:x)&&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(x.call(this,r,t),!t)return(0,l.eachItem)(r,e=>I.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=>I.call(this,e,o):e=>o.type.forEach(t=>I.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 x(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 I(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]}}}(zi);var dl={},pl={},hl={};Object.defineProperty(hl,"__esModule",{value:!0});const fl={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};hl.default=fl;var ml={};Object.defineProperty(ml,"__esModule",{value:!0}),ml.callRef=ml.getValidate=void 0;const yl=pu(),gl=Ac(),vl=Zi(),_l=lc(),wl=hu,$l=Gi,bl={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 El(e,a,s,s.$async);const r=t.scopeValue("root",{ref:u});return El(e,vl._`${r}.validate`,u,u.$async)}();const l=wl.resolveRef.call(c,u,n,r);if(void 0===l)throw new yl.default(o.opts.uriResolver,n,r);return l instanceof wl.SchemaEnv?function(t){const r=kl(e,t);El(e,r,t,t.$async)}(l):function(o){const n=t.scopeValue("schema",!0===i.code.source?{ref:o,code:(0,vl.stringify)(o)}:{ref:o}),s=t.name("valid"),a=e.subschema({schema:o,dataTypes:[],schemaPath:vl.nil,topSchemaRef:n,errSchemaPath:r},s);e.mergeEvaluated(a),e.ok(s)}(l)}};function kl(e,t){const{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):vl._`${r.scopeValue("wrapper",{ref:t})}.validate`}function El(e,t,r,o){const{gen:n,it:s}=e,{allErrors:a,schemaEnv:i,opts:c}=s,u=c.passContext?_l.default.this:vl.nil;function l(e){const t=vl._`${e}.errors`;n.assign(_l.default.vErrors,vl._`${_l.default.vErrors} === null ? ${t} : ${_l.default.vErrors}.concat(${t})`),n.assign(_l.default.errors,vl._`${_l.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=$l.mergeEvaluated.props(n,o.props,s.props));else{const t=n.var("props",vl._`${e}.evaluated.props`);s.props=$l.mergeEvaluated.props(n,t,s.props,vl.Name)}if(!0!==s.items)if(o&&!o.dynamicItems)void 0!==o.items&&(s.items=$l.mergeEvaluated.items(n,o.items,s.items));else{const t=n.var("items",vl._`${e}.evaluated.items`);s.items=$l.mergeEvaluated.items(n,t,s.items,vl.Name)}}o?function(){if(!i.$async)throw new Error("async schema referenced by sync schema");const r=n.let("valid");n.try(()=>{n.code(vl._`await ${(0,gl.callValidateCode)(e,t,u)}`),d(t),a||n.assign(r,!0)},e=>{n.if(vl._`!(${e} instanceof ${s.ValidationError})`,()=>n.throw(e)),l(e),a||n.assign(r,!1)}),e.ok(r)}():e.result((0,gl.callValidateCode)(e,t,u),()=>d(t),()=>l(t))}ml.getValidate=kl,ml.callRef=El,ml.default=bl,Object.defineProperty(pl,"__esModule",{value:!0});const Sl=ml,Pl=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",hl.default,Sl.default];pl.default=Pl;var Tl={},xl={};Object.defineProperty(xl,"__esModule",{value:!0});const Il=Zi(),Nl=Il.operators,Cl={maximum:{okStr:"<=",ok:Nl.LTE,fail:Nl.GT},minimum:{okStr:">=",ok:Nl.GTE,fail:Nl.LT},exclusiveMaximum:{okStr:"<",ok:Nl.LT,fail:Nl.GTE},exclusiveMinimum:{okStr:">",ok:Nl.GT,fail:Nl.LTE}},jl={message:({keyword:e,schemaCode:t})=>Il.str`must be ${Cl[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>Il._`{comparison: ${Cl[e].okStr}, limit: ${t}}`},Rl={keyword:Object.keys(Cl),type:"number",schemaType:"number",$data:!0,error:jl,code(e){const{keyword:t,data:r,schemaCode:o}=e;e.fail$data(Il._`${r} ${Cl[t].fail} ${o} || isNaN(${r})`)}};xl.default=Rl;var Ol={};Object.defineProperty(Ol,"__esModule",{value:!0});const zl=Zi(),Al={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:e})=>zl.str`must be multiple of ${e}`,params:({schemaCode:e})=>zl._`{multipleOf: ${e}}`},code(e){const{gen:t,data:r,schemaCode:o,it:n}=e,s=n.opts.multipleOfPrecision,a=t.let("res"),i=s?zl._`Math.abs(Math.round(${a}) - ${a}) > 1e-${s}`:zl._`${a} !== parseInt(${a})`;e.fail$data(zl._`(${o} === 0 || (${a} = ${r}/${o}, ${i}))`)}};Ol.default=Al;var Ml={},Ul={};function Dl(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(Ul,"__esModule",{value:!0}),Ul.default=Dl,Dl.code='require("ajv/dist/runtime/ucs2length").default',Object.defineProperty(Ml,"__esModule",{value:!0});const ql=Zi(),Vl=Gi,Fl=Ul,Ll={message({keyword:e,schemaCode:t}){const r="maxLength"===e?"more":"fewer";return ql.str`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>ql._`{limit: ${e}}`},Kl={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:Ll,code(e){const{keyword:t,data:r,schemaCode:o,it:n}=e,s="maxLength"===t?ql.operators.GT:ql.operators.LT,a=!1===n.opts.unicode?ql._`${r}.length`:ql._`${(0,Vl.useFunc)(e.gen,Fl.default)}(${r})`;e.fail$data(ql._`${a} ${s} ${o}`)}};Ml.default=Kl;var Hl={};Object.defineProperty(Hl,"__esModule",{value:!0});const Zl=Ac(),Gl=Zi(),Jl={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>Gl.str`must match pattern "${e}"`,params:({schemaCode:e})=>Gl._`{pattern: ${e}}`},code(e){const{data:t,$data:r,schema:o,schemaCode:n,it:s}=e,a=s.opts.unicodeRegExp?"u":"",i=r?Gl._`(new RegExp(${n}, ${a}))`:(0,Zl.usePattern)(e,o);e.fail$data(Gl._`!${i}.test(${t})`)}};Hl.default=Jl;var Wl={};Object.defineProperty(Wl,"__esModule",{value:!0});const Bl=Zi(),Ql={message({keyword:e,schemaCode:t}){const r="maxProperties"===e?"more":"fewer";return Bl.str`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>Bl._`{limit: ${e}}`},Yl={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:Ql,code(e){const{keyword:t,data:r,schemaCode:o}=e,n="maxProperties"===t?Bl.operators.GT:Bl.operators.LT;e.fail$data(Bl._`Object.keys(${r}).length ${n} ${o}`)}};Wl.default=Yl;var Xl={};Object.defineProperty(Xl,"__esModule",{value:!0});const ed=Ac(),td=Zi(),rd=Gi,od={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:e}})=>td.str`must have required property '${e}'`,params:({params:{missingProperty:e}})=>td._`{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(td.nil,u);else for(const t of r)(0,ed.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,ed.propertyInData)(t,n,r,i.ownProperties)),t.if((0,td.not)(s),()=>{e.error(),t.break()})},td.nil)}(a,r)),e.ok(r)}else t.if((0,ed.checkMissingProp)(e,r,a)),(0,ed.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,rd.checkStrictMode)(a,t,a.opts.strictRequired)}}function u(){t.forOf("prop",o,r=>{e.setParams({missingProperty:r}),t.if((0,ed.noPropertyInData)(t,n,r,i.ownProperties),()=>e.error())})}}};Xl.default=od;var nd={};Object.defineProperty(nd,"__esModule",{value:!0});const sd=Zi(),ad={message({keyword:e,schemaCode:t}){const r="maxItems"===e?"more":"fewer";return sd.str`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>sd._`{limit: ${e}}`},id={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:ad,code(e){const{keyword:t,data:r,schemaCode:o}=e,n="maxItems"===t?sd.operators.GT:sd.operators.LT;e.fail$data(sd._`${r}.length ${n} ${o}`)}};nd.default=id;var cd={},ud={};Object.defineProperty(ud,"__esModule",{value:!0});const ld=Vc;ld.code='require("ajv/dist/runtime/equal").default',ud.default=ld,Object.defineProperty(cd,"__esModule",{value:!0});const dd=pc,pd=Zi(),hd=Gi,fd=ud,md={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:e,j:t}})=>pd.str`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>pd._`{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,dd.getSchemaTypes)(s.items):[];function l(o,n){const s=t.name("item"),a=(0,dd.checkDataTypes)(u,s,i.opts.strictNumbers,dd.DataType.Wrong),l=t.const("indices",pd._`{}`);t.for(pd._`;${o}--;`,()=>{t.let(s,pd._`${r}[${o}]`),t.if(a,pd._`continue`),u.length>1&&t.if(pd._`typeof ${s} == "string"`,pd._`${s} += "_"`),t.if(pd._`typeof ${l}[${s}] == "number"`,()=>{t.assign(n,pd._`${l}[${s}]`),e.error(),t.assign(c,!1).break()}).code(pd._`${l}[${s}] = ${o}`)})}function d(o,n){const s=(0,hd.useFunc)(t,fd.default),a=t.name("outer");t.label(a).for(pd._`;${o}--;`,()=>t.for(pd._`${n} = ${o}; ${n}--;`,()=>t.if(pd._`${s}(${r}[${o}], ${r}[${n}])`,()=>{e.error(),t.assign(c,!1).break(a)})))}e.block$data(c,function(){const o=t.let("i",pd._`${r}.length`),n=t.let("j");e.setParams({i:o,j:n}),t.assign(c,!0),t.if(pd._`${o} > 1`,()=>(u.length>0&&!u.some(e=>"object"===e||"array"===e)?l:d)(o,n))},pd._`${a} === false`),e.ok(c)}};cd.default=md;var yd={};Object.defineProperty(yd,"__esModule",{value:!0});const gd=Zi(),vd=Gi,_d=ud,wd={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:e})=>gd._`{allowedValue: ${e}}`},code(e){const{gen:t,data:r,$data:o,schemaCode:n,schema:s}=e;o||s&&"object"==typeof s?e.fail$data(gd._`!${(0,vd.useFunc)(t,_d.default)}(${r}, ${n})`):e.fail(gd._`${s} !== ${r}`)}};yd.default=wd;var $d={};Object.defineProperty($d,"__esModule",{value:!0});const bd=Zi(),kd=Gi,Ed=ud,Sd={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:e})=>bd._`{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,kd.useFunc)(t,Ed.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(bd._`${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,bd.or)(...n.map((t,o)=>function(e,t){const o=n[t];return"object"==typeof o&&null!==o?bd._`${u()}(${r}, ${e}[${t}])`:bd._`${r} === ${o}`}(e,o)))}e.pass(l)}};$d.default=Sd,Object.defineProperty(Tl,"__esModule",{value:!0});const Pd=Ol,Td=Ml,xd=Hl,Id=Wl,Nd=Xl,Cd=nd,jd=cd,Rd=yd,Od=$d,zd=[xl.default,Pd.default,Td.default,xd.default,Id.default,Nd.default,Cd.default,jd.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Rd.default,Od.default];Tl.default=zd;var Ad={},Md={};Object.defineProperty(Md,"__esModule",{value:!0}),Md.validateAdditionalItems=void 0;const Ud=Zi(),Dd=Gi,qd={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:e}})=>Ud.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>Ud._`{limit: ${e}}`},code(e){const{parentSchema:t,it:r}=e,{items:o}=t;Array.isArray(o)?Vd(e,o):(0,Dd.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas')}};function Vd(e,t){const{gen:r,schema:o,data:n,keyword:s,it:a}=e;a.items=!0;const i=r.const("len",Ud._`${n}.length`);if(!1===o)e.setParams({len:t.length}),e.pass(Ud._`${i} <= ${t.length}`);else if("object"==typeof o&&!(0,Dd.alwaysValidSchema)(a,o)){const o=r.var("valid",Ud._`${i} <= ${t.length}`);r.if((0,Ud.not)(o),()=>function(o){r.forRange("i",t.length,i,t=>{e.subschema({keyword:s,dataProp:t,dataPropType:Dd.Type.Num},o),a.allErrors||r.if((0,Ud.not)(o),()=>r.break())})}(o)),e.ok(o)}}Md.validateAdditionalItems=Vd,Md.default=qd;var Fd={},Ld={};Object.defineProperty(Ld,"__esModule",{value:!0}),Ld.validateTuple=void 0;const Kd=Zi(),Hd=Gi,Zd=Ac(),Gd={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){const{schema:t,it:r}=e;if(Array.isArray(t))return Jd(e,"additionalItems",t);r.items=!0,(0,Hd.alwaysValidSchema)(r,t)||e.ok((0,Zd.validateArray)(e))}};function Jd(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,Hd.checkStrictMode)(i,e,o.strictTuples)}}(n),i.opts.unevaluated&&r.length&&!0!==i.items&&(i.items=Hd.mergeEvaluated.items(o,r.length,i.items));const c=o.name("valid"),u=o.const("len",Kd._`${s}.length`);r.forEach((t,r)=>{(0,Hd.alwaysValidSchema)(i,t)||(o.if(Kd._`${u} > ${r}`,()=>e.subschema({keyword:a,schemaProp:r,dataProp:r},c)),e.ok(c))})}Ld.validateTuple=Jd,Ld.default=Gd,Object.defineProperty(Fd,"__esModule",{value:!0});const Wd=Ld,Bd={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,Wd.validateTuple)(e,"items")};Fd.default=Bd;var Qd={};Object.defineProperty(Qd,"__esModule",{value:!0});const Yd=Zi(),Xd=Gi,ep=Ac(),tp=Md,rp={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:e}})=>Yd.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>Yd._`{limit: ${e}}`},code(e){const{schema:t,parentSchema:r,it:o}=e,{prefixItems:n}=r;o.items=!0,(0,Xd.alwaysValidSchema)(o,t)||(n?(0,tp.validateAdditionalItems)(e,n):e.ok((0,ep.validateArray)(e)))}};Qd.default=rp;var op={};Object.defineProperty(op,"__esModule",{value:!0});const np=Zi(),sp=Gi,ap={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:e,max:t}})=>void 0===t?np.str`must contain at least ${e} valid item(s)`:np.str`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>void 0===t?np._`{minContains: ${e}}`:np._`{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",np._`${n}.length`);if(e.setParams({min:a,max:i}),void 0===i&&0===a)return void(0,sp.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');if(void 0!==i&&a>i)return(0,sp.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),void e.fail();if((0,sp.alwaysValidSchema)(s,r)){let t=np._`${l} >= ${a}`;return void 0!==i&&(t=np._`${t} && ${l} <= ${i}`),void e.pass(t)}s.items=!0;const d=t.name("valid");function p(){const e=t.name("_valid"),r=t.let("count",0);h(e,()=>t.if(e,()=>function(e){t.code(np._`${e}++`),void 0===i?t.if(np._`${e} >= ${a}`,()=>t.assign(d,!0).break()):(t.if(np._`${e} > ${i}`,()=>t.assign(d,!1).break()),1===a?t.assign(d,!0):t.if(np._`${e} >= ${a}`,()=>t.assign(d,!0)))}(r)))}function h(r,o){t.forRange("i",0,l,t=>{e.subschema({keyword:"contains",dataProp:t,dataPropType:sp.Type.Num,compositeRule:!0},r),o()})}void 0===i&&1===a?h(d,()=>t.if(d,()=>t.break())):0===a?(t.let(d,!0),void 0!==i&&t.if(np._`${n}.length > 0`,p)):(t.let(d,!1),p()),e.result(d,()=>e.reset())}};op.default=ap;var ip={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=Zi(),r=Gi,o=Ac();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},
|
|
1
|
+
"use strict";var e=require("os"),t=require("path"),r=require("fs/promises"),o=require("jose"),n=require("crypto"),s=require("http"),a=require("url"),i=require("child_process"),c=require("readline"),u=require("pkce-challenge"),l=require("fs"),d="undefined"!=typeof document?document.currentScript:null;class p extends Error{constructor(e){super(e),this.name="BarndoorError"}}class h extends p{constructor(e,t=null){super(e),this.name="AuthenticationError",this.errorCode=t}}class f extends h{constructor(e,t=null){let r=e;r+=t?` ${t}`:" Run 'barndoor-login' to authenticate.",super(r),this.name="TokenError",this.helpText=t}}class m extends f{}class y extends p{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 g extends p{constructor(e,t,r=null){super(g._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 v extends p{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 _=class extends h{};class w extends p{}class $ extends p{}class b{constructor(e=30,t=10){this.read=1e3*e,this.connect=1e3*t}}class k{constructor(e=new b,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 g(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 $(`Request to ${i} timed out after ${e}ms`)}else if(r instanceof g){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 y(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 E{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 E(e)}}class S extends E{constructor(e){super(e),this.url=e.url??null}static fromApiResponse(e){return new S(e)}}class P{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 P(e)}}const T={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"}},x="undefined"!=typeof window&&void 0!==window.document,I="undefined"==typeof window&&"undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node;function N(e,t=""){return I?process.env[e]??t:x&&window.ENV?window.ENV[e]??t:t}class C{constructor(e={}){const t=e.environment??(N("MODE")||N("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=T[this.environment]??T.production,o=N("AUTH_URL"),n=e.authDomain??N("AUTH_DOMAIN");e.authIssuer?this.authIssuer=e.authIssuer:this.authIssuer=o||(n?n.startsWith("http")?n:`https://${n}`:r.issuer),this.clientId=e.clientId??(N("AGENT_CLIENT_ID")||N("AUTH_CLIENT_ID")||""),this.clientSecret=e.clientSecret??(N("AGENT_CLIENT_SECRET")||N("AUTH_CLIENT_SECRET")||""),this.apiAudience=e.apiAudience??(N("API_AUDIENCE")||r.audience),this.promptForLogin=e.promptForLogin??!1,this.skipLoginLocal=e.skipLoginLocal??!1,this.baseUrl=e.baseUrl??(N("BARNDOOR_API")||N("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 C}static getDynamicConfig(e,t={}){const{requireOrganization:r=!0,fallbackOrganizationId:o}=t,n=new C,s=j(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 w("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 w(`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 w("authIssuer is required");if(!this.apiAudience||""===this.apiAudience.trim())throw new w("apiAudience is required");if(!this.baseUrl||""===this.baseUrl.trim())throw new w("baseUrl is required")}}function j(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 R(){return C.getStaticConfig()}function O(e,t){return C.getDynamicConfig(e,t)}function z(e){return j(e).hasOrganization}let A={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 M(e){return{debug:(t,...r)=>{A.debug(`[${e}] ${t}`,...r)},info:(t,...r)=>{A.info(`[${e}] ${t}`,...r)},warn:(t,...r)=>{A.warn(`[${e}] ${t}`,...r)},error:(t,...r)=>{A.error(`[${e}] ${t}`,...r)}}}const U=M("token"),D=new Map;async function q(e){if(D.has(e))return D.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 D.set(e,n),U.debug(`OIDC discovery successful for ${e}`),n}finally{clearTimeout(o)}}catch(r){return U.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 V(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(I)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 F(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 L;exports.JWTVerificationResult=void 0,(L=exports.JWTVerificationResult||(exports.JWTVerificationResult={})).VALID="valid",L.EXPIRED="expired",L.INVALID="invalid";const K=new Map;class H{constructor(e){this.lockAcquired=!1,this.lockFile=`${e}.lock`}async acquire(e=5e3){if(!I)return;const t=Date.now();for(;Date.now()-t<e;)try{return await r.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 f(`Failed to acquire file lock: ${e}`);try{const e=await r.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 r.unlink(this.lockFile).catch(()=>{});continue}}await r.unlink(this.lockFile).catch(()=>{});continue}}catch{await r.unlink(this.lockFile).catch(()=>{});continue}}throw new f("Failed to acquire file lock: timeout")}async release(){if(I&&this.lockAcquired)try{await r.unlink(this.lockFile),this.lockAcquired=!1}catch(e){console.debug("Failed to release file lock:",e)}}}class Z{}class G extends Z{constructor(){super(),this.storageKey="barndoor_token"}async loadToken(){try{const e=localStorage.getItem(this.storageKey);return e?JSON.parse(e):null}catch(e){return U.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 f(`Failed to save token: ${t}`)}}async clearToken(){try{localStorage.removeItem(this.storageKey)}catch(e){U.warn("Failed to clear token from localStorage:",e)}}}class J extends Z{constructor(){super(),this.tokenFile=this._getTokenFilePath()}_getTokenFilePath(){if(I)return t.join(e.homedir(),".barndoor","token.json");throw new Error("NodeTokenStorage can only be used in Node.js environment")}async loadToken(){if(!I)throw new Error("NodeTokenStorage can only be used in Node.js environment");const e=new H(this.tokenFile);try{await e.acquire();const t=await r.readFile(this.tokenFile,"utf8");return JSON.parse(t)}catch(e){return e&&"object"==typeof e&&"code"in e&&"ENOENT"===e.code||U.warn("Failed to load token from file:",e),null}finally{await e.release()}}async saveToken(e){if(!I)throw new Error("NodeTokenStorage can only be used in Node.js environment");const o=new H(this.tokenFile);try{await o.acquire(),await r.mkdir(t.dirname(this.tokenFile),{recursive:!0}),await r.writeFile(this.tokenFile,JSON.stringify(e,null,2)),await r.chmod(this.tokenFile,384),U.debug("Token saved to storage")}catch(e){const t=e instanceof Error?e.message:String(e);throw new f(`Failed to save token: ${t}`)}finally{await o.release()}}async clearToken(){if(!I)throw new Error("NodeTokenStorage can only be used in Node.js environment");try{await r.unlink(this.tokenFile)}catch(e){e&&"object"==typeof e&&"code"in e&&"ENOENT"!==e.code&&U.warn("Failed to clear token file:",e)}}}function W(){if(x)return new G;if(I)return new J;throw new Error("Unsupported environment for token storage")}async function B(e,t,r){try{const n=await async function(e){if(K.has(e))return K.get(e);try{const t=(await q(e)).jwks_uri;if(!t)throw U.debug(`No jwks_uri in OIDC config for ${e}`),new Error("No jwks_uri available");const r=o.createRemoteJWKSet(new URL(t));return K.set(e,r),r}catch(t){throw U.debug(`Failed to get JWKS for ${e}:`,t),t}}(t),s=`${t.replace(/\/$/,"")}/`;return await o.jwtVerify(e,n,{issuer:s,audience:r}),U.debug("Token verified locally using JWKS"),exports.JWTVerificationResult.VALID}catch(e){return e&&"object"==typeof e&&"code"in e&&"ERR_JWT_EXPIRED"===e.code?(U.debug("Token expired (verified locally)"),exports.JWTVerificationResult.EXPIRED):(U.debug("JWT verification failed:",e),exports.JWTVerificationResult.INVALID)}}class Q{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 Y{constructor(e){this._refreshMutex=new Q,this.storage=W()}async getValidToken(){return this._refreshMutex.withLock(async()=>{const e=await this.storage.loadToken();if(!e)throw new f("No token found. Please authenticate.");try{if(this._shouldRefreshToken(e)&&e.refresh_token){U.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 U.error("Token validation/refresh failed:",e),new m("Token expired and refresh failed. Please re-authenticate.")}})}_shouldRefreshToken(e){const t=V(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=R(),o=await B(t,r.authIssuer,r.apiAudience);if(o===exports.JWTVerificationResult.VALID)return U.debug("Token validated locally"),e;if(o===exports.JWTVerificationResult.INVALID&&(U.debug("Local validation failed, trying remote"),await this._isTokenValidRemote(t)))return U.debug("Token validated remotely"),e;if(U.info("Token invalid or expired, attempting refresh"),e.refresh_token){const t=await this._refreshToken(e);return{...e,...t}}throw new m("Token expired and no refresh token available")}async _isTokenValidRemote(e){try{const t=R(),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 F(o,5e3)).ok}catch(e){return U.debug("Remote token validation failed:",e),!1}}async _refreshToken(e){const t=e.refresh_token;if(!t)throw new f("No refresh token available");const r=R();if(x&&r.clientSecret)throw new f("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&&!x&&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 F(e,15e3);if(400===t.status){let e="Invalid refresh token";try{e=(await t.json()).error_description||e}catch{}throw U.warn(`Refresh token invalid: ${e}`),new m(`Refresh token expired or invalid: ${e}`)}if(429===t.status)throw U.warn("Rate limited during token refresh"),new f("Rate limited during token refresh. Please try again later.");if(t.status>=500)throw U.warn(`Auth server error during refresh: ${t.status}`),new f(`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 f||e instanceof m)throw e;if(e&&"object"==typeof e&&"name"in e){if("TimeoutError"===e.name||"AbortError"===e.name)throw U.warn("Timeout during token refresh"),new f("Token refresh timed out. Please check your connection.");if("TypeError"===e.name&&"message"in e&&"string"==typeof e.message&&e.message.includes("fetch"))throw U.warn(`Network error during token refresh: ${e.message}`),new f("Network error during token refresh. Please check your connection.")}U.error("Unexpected error during token refresh:",e);const t=e instanceof Error?e.message:String(e);throw new f(`Token refresh failed: ${t}`)}}}async function X(){try{const e=W(),t=await e.loadToken();return t?.access_token??null}catch(e){return null}}async function ee(e){const t=W();let r;r="string"==typeof e?{access_token:e}:e,await t.saveToken(r)}class te{constructor(){this._codeVerifier=null,this._currentState=null,this._logger=M("pkce")}async buildAuthorizationUrl({domain:e,clientId:t,redirectUri:r,audience:o,scope:s="openid profile email",issuer:a}){this._codeVerifier=re(32);const i=oe(await async function(e){const t=(new TextEncoder).encode(e);if(x&&window.crypto&&window.crypto.subtle){const e=await window.crypto.subtle.digest("SHA-256",t);return new Uint8Array(e)}if(I){const t=n.createHash("sha256").update(e).digest();return new Uint8Array(t)}throw new Error("SHA256 not available in this environment")}(this._codeVerifier));this._currentState=re(16);const c=new URLSearchParams({response_type:"code",client_id:t,redirect_uri:r,scope:s,audience:o,state:this._currentState,code_challenge:i,code_challenge_method:"S256"});let u;if(a){u=(await q(a)).authorization_endpoint}else{if(!e)throw new _("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 _("Either client_secret or PKCE verifier must be provided");let i;if(s){i=(await q(s)).token_endpoint}else{if(!e)throw new _("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 _(`Token exchange failed: ${t.error??t.error_description??e.statusText}`)}const t=await e.json();return this.clearState(),t}catch(e){if(e instanceof _)throw e;const t=e instanceof Error?e.message:String(e);throw new _(`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 re(e){const t=new Uint8Array(e);if(x&&window.crypto&&window.crypto.getRandomValues)window.crypto.getRandomValues(t);else{if(!I)throw new Error("Secure random generator not available for PKCE.");n.randomFillSync(t)}return oe(t)}function oe(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 ne(e=52765){if(!I)throw new Error("Local callback server is only available in Node.js environment");const t=M("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 i=s.createServer((e,o)=>{t.debug(`Callback server received request: ${e.method} ${e.url}`);const s=a.parse(e.url??"",!0);if(t.debug(`Parsed URL - pathname: ${s.pathname}, query:`,s.query),"/cb"===s.pathname){const{code:a,state:c,error:u,error_description:l}=s.query;t.debug(`Callback params - code: ${!!a}, 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 "),i.close(),n(new _(`OAuth error: ${u} - ${l}`))):a?(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 "),i.close(),r([a,c])):(t.warn("No authorization code received in callback"),t.warn(`Full URL: ${e.url}`),t.warn("Query params:",s.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 `),i.close(),n(new _("No authorization code received")))}else t.debug(`404 for path: ${s.pathname}`),o.writeHead(404,{"Content-Type":"text/plain"}),o.end("Not found")});i.listen(e,"0.0.0.0",()=>{console.log(`OAuth callback server listening on ${o}`)}),i.on("error",e=>{n(new _(`Failed to start callback server: ${e.message}`))}),i.on("connection",e=>{t.debug(`New connection from ${e.remoteAddress}:${e.remotePort}`)})});return[o,n]}const se=M("client-credentials");async function ae(e){const{timeoutMs:t=15e3}=e,{tokenEndpoint:r,body:o}=await async function(e){const{clientId:t,clientSecret:r,audience:o,issuer:n,domain:s}=e;let a;if(n)a=(await q(n)).token_endpoint;else{if(!s)throw new _("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:o})}}(e),n=new AbortController,s=setTimeout(()=>n.abort(),t);try{const e=await fetch(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString(),signal:n.signal});if(!e.ok){const t=await e.json().catch(()=>({}));throw se.error("Client-credentials token endpoint error:",t),new _(`Client-credentials grant failed: ${t.error_description??t.error??e.statusText}`)}const t=await e.json();if(!t.access_token)throw new _("Client-credentials grant: response missing access_token");return t.access_token}catch(e){if(e instanceof _)throw e;if(e instanceof Error&&"AbortError"===e.name)throw new _(`Client-credentials grant timed out after ${t}ms`);const r=e instanceof Error?e.message:String(e);throw new _(`Client-credentials grant failed: ${r}`)}finally{clearTimeout(s)}}class ie{constructor(e,t={}){this._credentials=null,this._logger=M("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 w("timeout must be a positive number");if(!Number.isInteger(n)||n<0)throw new w("maxRetries must be a non-negative integer");const a=new b(o,o/3);this._http=new k(a,n),this._tokenValidated=!1,this._closed=!1,this._logger.info(`Initialized BarndoorSDK for ${this.base}`)}static async fromClientCredentials(e,t){const{timeout:r,maxRetries:o,...n}=t,s={token:await ae(n)};void 0!==r&&(s.timeout=r),void 0!==o&&(s.maxRetries=o);const a=new ie(e,s);return a._credentials={...n},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 w(`${t} must be a non-empty string`);try{return new URL(e),e}catch(e){throw new w(`${t} must be a valid URL`)}}_validateToken(e){if(!e||"string"!=typeof e)throw new f("Token must be a non-empty string");if(3!==e.split(".").length)throw new f("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 o=`${this.base}${t}`,n=()=>{const e={...r.headers??{}};return e.Authorization=`Bearer ${this.token}`,{...r,headers:e}};try{return await this._http.request(e,o,n())}catch(t){if(t instanceof g&&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,o,n());throw t}}async _maybeRefreshM2MToken(){null!==this._credentials&&function(e,t){const r=e.split(".");if(3!==r.length)return!0;const o=r[1];if(!o)return!0;let n;try{const e=o.replace(/-/g,"+").replace(/_/g,"/"),t="undefined"!=typeof Buffer?Buffer.from(e,"base64").toString("utf8"):globalThis.atob(e);n=JSON.parse(t)}catch{return!0}const s=n.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 ae(this._credentials),this._tokenValidated=!0}async validateCachedToken(){if(!this.token)return!1;try{const e=R(),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=(I?process.env.BARNDOOR_ENV:"")??"";if(["test","ci"].includes(e.toLowerCase()))return void(this._tokenValidated=!0);if(!await this.validateCachedToken())throw new f("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=>E.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 S.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 g&&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 g&&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 o={page:e,limit:t,...r};return this._req("GET","/api/v2/policies",{params:o})}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:o=60}=r;if(!I)throw new Error("ensureServerConnected requires Node.js environment for browser opening");let n;try{n=await this.getServer(t)}catch(e){if(e instanceof g&&404===e.statusCode)throw new v(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 c=e.platform();let u;try{u=new URL(a)}catch{throw new Error("Invalid auth_url returned by server")}if("https:"!==u.protocol&&("http:"!==u.protocol||"localhost"!==u.hostname&&"127.0.0.1"!==u.hostname))throw new Error("Auth URL must use HTTPS (http allowed only for localhost)");try{"darwin"===c?i.spawn("open",[a],{detached:!0,stdio:"ignore"}).unref():"win32"===c?i.spawn("powershell",["-NoProfile","Start-Process",a],{detached:!0,stdio:"ignore"}).unref():i.spawn("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 ce=Object.freeze({status:"aborted"});function ue(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 le extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const de={};function pe(e){return e&&Object.assign(de,e),de}function he(e,t){return"bigint"==typeof t?t.toString():t}function fe(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function me(e){return null==e}function ye(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function ge(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 ve(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function _e(e){return JSON.stringify(e)}const we=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function $e(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const be=fe(()=>{if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function ke(e){if(!1===$e(e))return!1;const t=e.constructor;if(void 0===t)return!0;const r=t.prototype;return!1!==$e(r)&&!1!==Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")}const Ee=new Set(["string","number","symbol"]);function Se(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Pe(e,t,r){const o=new e._zod.constr(t??e._zod.def);return t&&!r?.parent||(o._zod.parent=e),o}function Te(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 xe={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 Ie(e,t=0){for(let r=t;r<e.issues.length;r++)if(!0!==e.issues[r]?.continue)return!0;return!1}function Ne(e,t){return t.map(t=>{var r;return(r=t).path??(r.path=[]),t.path.unshift(e),t})}function Ce(e){return"string"==typeof e?e:e?.message}function je(e,t,r){const o={...e,path:e.path??[]};if(!e.message){const n=Ce(e.inst?._zod.def?.error?.(e))??Ce(t?.error?.(e))??Ce(r.customError?.(e))??Ce(r.localeError?.(e))??"Invalid input";o.message=n}return delete o.inst,delete o.continue,t?.reportInput||delete o.input,o}function Re(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function Oe(...e){const[t,r,o]=e;return"string"==typeof t?{message:t,code:"custom",input:r,inst:o}:{...t}}const ze=(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,he,2),enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Ae=ue("$ZodError",ze),Me=ue("$ZodError",ze,{Parent:Error});const Ue=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 le;if(a.issues.length){const t=new(n?.Err??e)(a.issues.map(e=>je(e,s,pe())));throw we(t,n?.callee),t}return a.value},De=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=>je(e,s,pe())));throw we(t,n?.callee),t}return a.value},qe=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 le;return s.issues.length?{success:!1,error:new(e??Ae)(s.issues.map(e=>je(e,n,pe())))}:{success:!0,data:s.value}},Ve=qe(Me),Fe=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=>je(e,n,pe())))}:{success:!0,data:s.value}},Le=Fe(Me),Ke=/^[cC][^\s-]{8,}$/,He=/^[0-9a-z]+$/,Ze=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Ge=/^[0-9a-vA-V]{20}$/,Je=/^[A-Za-z0-9]{27}$/,We=/^[a-zA-Z0-9_-]{21}$/,Be=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Qe=/^([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})$/,Ye=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)$/,Xe=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;const et=/^(?:(?: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])$/,tt=/^(([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})$/,rt=/^((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])$/,ot=/^(([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])$/,nt=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,st=/^[A-Za-z0-9_-]*$/,at=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,it=/^\+(?:[0-9]){6,14}[0-9]$/,ct="(?:(?:\\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])))",ut=new RegExp(`^${ct}$`);function lt(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 dt=/^\d+$/,pt=/^-?\d+(?:\.\d+)?/i,ht=/true|false/i,ft=/null/i,mt=/^[^A-Z]*$/,yt=/^[^a-z]*$/,gt=ue("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),vt={number:"number",bigint:"bigint",object:"date"},_t=ue("$ZodCheckLessThan",(e,t)=>{gt.init(e,t);const r=vt[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})}}),wt=ue("$ZodCheckGreaterThan",(e,t)=>{gt.init(e,t);const r=vt[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})}}),$t=ue("$ZodCheckMultipleOf",(e,t)=>{gt.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})}}),bt=ue("$ZodCheckNumberFormat",(e,t)=>{gt.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),o=r?"int":"number",[n,s]=xe[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=dt)}),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})}}),kt=ue("$ZodCheckMaxLength",(e,t)=>{var r;gt.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!me(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=Re(o);r.issues.push({origin:n,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Et=ue("$ZodCheckMinLength",(e,t)=>{var r;gt.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!me(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=Re(o);r.issues.push({origin:n,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),St=ue("$ZodCheckLengthEquals",(e,t)=>{var r;gt.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!me(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=Re(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})}}),Pt=ue("$ZodCheckStringFormat",(e,t)=>{var r,o;gt.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=()=>{})}),Tt=ue("$ZodCheckRegex",(e,t)=>{Pt.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})}}),xt=ue("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=mt),Pt.init(e,t)}),It=ue("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=yt),Pt.init(e,t)}),Nt=ue("$ZodCheckIncludes",(e,t)=>{gt.init(e,t);const r=Se(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})}}),Ct=ue("$ZodCheckStartsWith",(e,t)=>{gt.init(e,t);const r=new RegExp(`^${Se(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=ue("$ZodCheckEndsWith",(e,t)=>{gt.init(e,t);const r=new RegExp(`.*${Se(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})}}),Rt=ue("$ZodCheckOverwrite",(e,t)=>{gt.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class Ot{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 zt={major:4,minor:0,patch:0},At=ue("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=zt;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=Ie(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 le;if(o||a instanceof Promise)o=(o??Promise.resolve()).then(async()=>{await a;e.issues.length!==t&&(n||(n=Ie(e,t)))});else{if(e.issues.length===t)continue;n||(n=Ie(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 le;return s.then(e=>t(e,o,n))}return t(s,o,n)}}e["~standard"]={validate:t=>{try{const r=Ve(e,t);return r.success?{value:r.data}:{issues:r.error?.issues}}catch(r){return Le(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}}),Mt=ue("$ZodString",(e,t)=>{var r;At.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}}),Ut=ue("$ZodStringFormat",(e,t)=>{Pt.init(e,t),Mt.init(e,t)}),Dt=ue("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Qe),Ut.init(e,t)}),qt=ue("$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=Ye(e))}else t.pattern??(t.pattern=Ye());Ut.init(e,t)}),Vt=ue("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Xe),Ut.init(e,t)}),Ft=ue("$ZodURL",(e,t)=>{Ut.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:at.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})}}}),Lt=ue("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ut.init(e,t)}),Kt=ue("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=We),Ut.init(e,t)}),Ht=ue("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Ke),Ut.init(e,t)}),Zt=ue("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=He),Ut.init(e,t)}),Gt=ue("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Ze),Ut.init(e,t)}),Jt=ue("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Ge),Ut.init(e,t)}),Wt=ue("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Je),Ut.init(e,t)}),Bt=ue("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=function(e){const t=lt({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(`^${ct}T(?:${o})$`)}(t)),Ut.init(e,t)}),Qt=ue("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=ut),Ut.init(e,t)}),Yt=ue("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=new RegExp(`^${lt(t)}$`)),Ut.init(e,t)}),Xt=ue("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Be),Ut.init(e,t)}),er=ue("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=et),Ut.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.format="ipv4"})}),tr=ue("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=tt),Ut.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})}}}),rr=ue("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=rt),Ut.init(e,t)}),or=ue("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=ot),Ut.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 nr(e){if(""===e)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const sr=ue("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=nt),Ut.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{nr(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});const ar=ue("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=st),Ut.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{(function(e){if(!st.test(e))return!1;const t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return nr(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})}}),ir=ue("$ZodE164",(e,t)=>{t.pattern??(t.pattern=it),Ut.init(e,t)});const cr=ue("$ZodJWT",(e,t)=>{Ut.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})}}),ur=ue("$ZodNumber",(e,t)=>{At.init(e,t),e._zod.pattern=e._zod.bag.pattern??pt,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}}),lr=ue("$ZodNumber",(e,t)=>{bt.init(e,t),ur.init(e,t)}),dr=ue("$ZodBoolean",(e,t)=>{At.init(e,t),e._zod.pattern=ht,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}}),pr=ue("$ZodNull",(e,t)=>{At.init(e,t),e._zod.pattern=ft,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}}),hr=ue("$ZodAny",(e,t)=>{At.init(e,t),e._zod.parse=e=>e}),fr=ue("$ZodUnknown",(e,t)=>{At.init(e,t),e._zod.parse=e=>e}),mr=ue("$ZodNever",(e,t)=>{At.init(e,t),e._zod.parse=(t,r)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function yr(e,t,r){e.issues.length&&t.issues.push(...Ne(r,e.issues)),t.value[r]=e.value}const gr=ue("$ZodArray",(e,t)=>{At.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=>yr(t,r,e))):yr(i,r,e)}return s.length?Promise.all(s).then(()=>r):r}});function vr(e,t,r){e.issues.length&&t.issues.push(...Ne(r,e.issues)),t.value[r]=e.value}function _r(e,t,r,o){e.issues.length?void 0===o[r]?t.value[r]=r in o?void 0:e.value:t.issues.push(...Ne(r,e.issues)):void 0===e.value?r in o&&(t.value[r]=void 0):t.value[r]=e.value}const wr=ue("$ZodObject",(e,t)=>{At.init(e,t);const r=fe(()=>{const e=Object.keys(t.shape);for(const r of e)if(!(t.shape[r]instanceof At))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)}});ge(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=$e,s=!de.jitless,a=s&&be.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 p=[];if(s&&a&&!1===l?.async&&!0!==l.jitless)o||(o=(e=>{const t=new Ot(["shape","payload","ctx"]),o=r.value,n=e=>{const t=_e(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=_e(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 ? [${_e(e)}, ...iss.path] : [${_e(e)}]\n })));`),t.write(`newResult[${_e(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?p.push(o.then(e=>n?_r(e,u,t,d):vr(e,u,t))):n?_r(o,u,t,d):vr(o,u,t)}}if(!i)return p.length?Promise.all(p).then(()=>u):u;const h=[],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){h.push(e);continue}const t=m.run({value:d[e],issues:[]},l);t instanceof Promise?p.push(t.then(t=>vr(t,u,e))):vr(t,u,e)}return h.length&&u.issues.push({code:"unrecognized_keys",keys:h,input:d,inst:e}),p.length?Promise.all(p).then(()=>u):u}});function $r(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=>je(e,o,pe())))}),t}const br=ue("$ZodUnion",(e,t)=>{At.init(e,t),ge(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),ge(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),ge(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),ge(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=>ye(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=>$r(t,r,e,o)):$r(s,r,e,o)}}),kr=ue("$ZodDiscriminatedUnion",(e,t)=>{br.init(e,t);const r=e._zod.parse;ge(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=fe(()=>{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(!$e(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)}}),Er=ue("$ZodIntersection",(e,t)=>{At.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])=>Pr(e,t,r)):Pr(e,n,s)}});function Sr(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(ke(e)&&ke(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=Sr(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=Sr(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 Pr(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),Ie(e))return e;const o=Sr(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 Tr=ue("$ZodRecord",(e,t)=>{At.init(e,t),e._zod.parse=(r,o)=>{const n=r.value;if(!ke(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(...Ne(e,t.issues)),r.value[e]=t.value})):(a.issues.length&&r.issues.push(...Ne(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=>je(e,o,pe())),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(...Ne(a,e.issues)),r.value[i.value]=e.value})):(c.issues.length&&r.issues.push(...Ne(a,c.issues)),r.value[i.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),xr=ue("$ZodEnum",(e,t)=>{At.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=>Ee.has(typeof e)).map(e=>"string"==typeof e?Se(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}}),Ir=ue("$ZodLiteral",(e,t)=>{At.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(e=>"string"==typeof e?Se(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}}),Nr=ue("$ZodTransform",(e,t)=>{At.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 le;return e.value=o,e}}),Cr=ue("$ZodOptional",(e,t)=>{At.init(e,t),e._zod.optin="optional",e._zod.optout="optional",ge(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),ge(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${ye(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=ue("$ZodNullable",(e,t)=>{At.init(e,t),ge(e._zod,"optin",()=>t.innerType._zod.optin),ge(e._zod,"optout",()=>t.innerType._zod.optout),ge(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${ye(e.source)}|null)$`):void 0}),ge(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)}),Rr=ue("$ZodDefault",(e,t)=>{At.init(e,t),e._zod.optin="optional",ge(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=>Or(e,t)):Or(o,t)}});function Or(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}const zr=ue("$ZodPrefault",(e,t)=>{At.init(e,t),e._zod.optin="optional",ge(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))}),Ar=ue("$ZodNonOptional",(e,t)=>{At.init(e,t),ge(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=>Mr(t,e)):Mr(n,e)}});function Mr(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 Ur=ue("$ZodCatch",(e,t)=>{At.init(e,t),e._zod.optin="optional",ge(e._zod,"optout",()=>t.innerType._zod.optout),ge(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=>je(e,r,pe()))},input:e.value}),e.issues=[]),e)):(e.value=o.value,o.issues.length&&(e.value=t.catchValue({...e,error:{issues:o.issues.map(e=>je(e,r,pe()))},input:e.value}),e.issues=[]),e)}}),Dr=ue("$ZodPipe",(e,t)=>{At.init(e,t),ge(e._zod,"values",()=>t.in._zod.values),ge(e._zod,"optin",()=>t.in._zod.optin),ge(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=>qr(e,t,r)):qr(o,t,r)}});function qr(e,t,r){return Ie(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}const Vr=ue("$ZodReadonly",(e,t)=>{At.init(e,t),ge(e._zod,"propValues",()=>t.innerType._zod.propValues),ge(e._zod,"values",()=>t.innerType._zod.values),ge(e._zod,"optin",()=>t.innerType._zod.optin),ge(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(Fr):Fr(o)}});function Fr(e){return e.value=Object.freeze(e.value),e}const Lr=ue("$ZodCustom",(e,t)=>{gt.init(e,t),At.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=>Kr(t,r,o,e));Kr(n,r,o,e)}});function Kr(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(Oe(e))}}class Hr{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 Zr(){return new Hr}const Gr=Zr();function Jr(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...Te(t)})}function Wr(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...Te(t)})}function Br(e,t){return new _t({check:"less_than",...Te(t),value:e,inclusive:!1})}function Qr(e,t){return new _t({check:"less_than",...Te(t),value:e,inclusive:!0})}function Yr(e,t){return new wt({check:"greater_than",...Te(t),value:e,inclusive:!1})}function Xr(e,t){return new wt({check:"greater_than",...Te(t),value:e,inclusive:!0})}function eo(e,t){return new $t({check:"multiple_of",...Te(t),value:e})}function to(e,t){return new kt({check:"max_length",...Te(t),maximum:e})}function ro(e,t){return new Et({check:"min_length",...Te(t),minimum:e})}function oo(e,t){return new St({check:"length_equals",...Te(t),length:e})}function no(e){return new Rt({check:"overwrite",tx:e})}function so(e){return!!e._zod}function ao(e,t){if(so(e)){return Ve(e,t)}return e.safeParse(t)}function io(e){if(!e)return;let t;if(so(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 co=ue("ZodISODateTime",(e,t)=>{Bt.init(e,t),Po.init(e,t)});function uo(e){return function(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Te(t)})}(co,e)}const lo=ue("ZodISODate",(e,t)=>{Qt.init(e,t),Po.init(e,t)});function po(e){return function(e,t){return new e({type:"string",format:"date",check:"string_format",...Te(t)})}(lo,e)}const ho=ue("ZodISOTime",(e,t)=>{Yt.init(e,t),Po.init(e,t)});function fo(e){return function(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...Te(t)})}(ho,e)}const mo=ue("ZodISODuration",(e,t)=>{Xt.init(e,t),Po.init(e,t)});function yo(e){return function(e,t){return new e({type:"string",format:"duration",check:"string_format",...Te(t)})}(mo,e)}const go=ue("ZodError",(e,t)=>{Ae.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}),vo=Ue(go),_o=De(go),wo=qe(go),$o=Fe(go),bo=ue("ZodType",(e,t)=>(At.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)=>Pe(e,t,r),e.brand=()=>e,e.register=(t,r)=>(t.add(e,r),e),e.parse=(t,r)=>vo(e,t,r,{callee:e.parse}),e.safeParse=(t,r)=>wo(e,t,r),e.parseAsync=async(t,r)=>_o(e,t,r,{callee:e.parseAsync}),e.safeParseAsync=async(t,r)=>$o(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,...Te(r)})}(An,e,t)}(t,r)),e.superRefine=t=>e.check(function(e){const t=function(e){const t=new gt({check:"custom"});return t._zod.check=e,t}(r=>(r.addIssue=e=>{if("string"==typeof e)r.issues.push(Oe(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(Oe(o))}},e(r.value,r)));return t}(t)),e.overwrite=t=>e.check(no(t)),e.optional=()=>Pn(e),e.nullable=()=>xn(e),e.nullish=()=>Pn(xn(e)),e.nonoptional=t=>function(e,t){return new Cn({type:"nonoptional",innerType:e,...Te(t)})}(e,t),e.array=()=>an(e),e.or=t=>pn([e,t]),e.and=t=>yn(e,t),e.transform=t=>On(e,En(t)),e.default=t=>{return r=t,new In({type:"default",innerType:e,get defaultValue(){return"function"==typeof r?r():r}});var r},e.prefault=t=>{return r=t,new Nn({type:"prefault",innerType:e,get defaultValue(){return"function"==typeof r?r():r}});var r},e.catch=t=>{return new jn({type:"catch",innerType:e,catchValue:"function"==typeof(r=t)?r:()=>r});var r},e.pipe=t=>On(e,t),e.readonly=()=>new zn({type:"readonly",innerType:e}),e.describe=t=>{const r=e.clone();return Gr.add(r,{description:t}),r},Object.defineProperty(e,"description",{get:()=>Gr.get(e)?.description,configurable:!0}),e.meta=(...t)=>{if(0===t.length)return Gr.get(e);const r=e.clone();return Gr.add(r,t[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),ko=ue("_ZodString",(e,t)=>{Mt.init(e,t),bo.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 Tt({check:"string_format",format:"regex",...Te(t),pattern:e})}(...t)),e.includes=(...t)=>e.check(function(e,t){return new Nt({check:"string_format",format:"includes",...Te(t),includes:e})}(...t)),e.startsWith=(...t)=>e.check(function(e,t){return new Ct({check:"string_format",format:"starts_with",...Te(t),prefix:e})}(...t)),e.endsWith=(...t)=>e.check(function(e,t){return new jt({check:"string_format",format:"ends_with",...Te(t),suffix:e})}(...t)),e.min=(...t)=>e.check(ro(...t)),e.max=(...t)=>e.check(to(...t)),e.length=(...t)=>e.check(oo(...t)),e.nonempty=(...t)=>e.check(ro(1,...t)),e.lowercase=t=>e.check(function(e){return new xt({check:"string_format",format:"lowercase",...Te(e)})}(t)),e.uppercase=t=>e.check(function(e){return new It({check:"string_format",format:"uppercase",...Te(e)})}(t)),e.trim=()=>e.check(no(e=>e.trim())),e.normalize=(...t)=>e.check(function(e){return no(t=>t.normalize(e))}(...t)),e.toLowerCase=()=>e.check(no(e=>e.toLowerCase())),e.toUpperCase=()=>e.check(no(e=>e.toUpperCase()))}),Eo=ue("ZodString",(e,t)=>{Mt.init(e,t),ko.init(e,t),e.email=t=>e.check(function(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...Te(t)})}(To,t)),e.url=t=>e.check(Wr(No,t)),e.jwt=t=>e.check(function(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...Te(t)})}(Ho,t)),e.emoji=t=>e.check(function(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...Te(t)})}(Co,t)),e.guid=t=>e.check(Jr(xo,t)),e.uuid=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...Te(t)})}(Io,t)),e.uuidv4=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Te(t)})}(Io,t)),e.uuidv6=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Te(t)})}(Io,t)),e.uuidv7=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Te(t)})}(Io,t)),e.nanoid=t=>e.check(function(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...Te(t)})}(jo,t)),e.guid=t=>e.check(Jr(xo,t)),e.cuid=t=>e.check(function(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...Te(t)})}(Ro,t)),e.cuid2=t=>e.check(function(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...Te(t)})}(Oo,t)),e.ulid=t=>e.check(function(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...Te(t)})}(zo,t)),e.base64=t=>e.check(function(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...Te(t)})}(Fo,t)),e.base64url=t=>e.check(function(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...Te(t)})}(Lo,t)),e.xid=t=>e.check(function(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...Te(t)})}(Ao,t)),e.ksuid=t=>e.check(function(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...Te(t)})}(Mo,t)),e.ipv4=t=>e.check(function(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...Te(t)})}(Uo,t)),e.ipv6=t=>e.check(function(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...Te(t)})}(Do,t)),e.cidrv4=t=>e.check(function(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Te(t)})}(qo,t)),e.cidrv6=t=>e.check(function(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Te(t)})}(Vo,t)),e.e164=t=>e.check(function(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...Te(t)})}(Ko,t)),e.datetime=t=>e.check(uo(t)),e.date=t=>e.check(po(t)),e.time=t=>e.check(fo(t)),e.duration=t=>e.check(yo(t))});function So(e){return function(e,t){return new e({type:"string",...Te(t)})}(Eo,e)}const Po=ue("ZodStringFormat",(e,t)=>{Ut.init(e,t),ko.init(e,t)}),To=ue("ZodEmail",(e,t)=>{Vt.init(e,t),Po.init(e,t)}),xo=ue("ZodGUID",(e,t)=>{Dt.init(e,t),Po.init(e,t)}),Io=ue("ZodUUID",(e,t)=>{qt.init(e,t),Po.init(e,t)}),No=ue("ZodURL",(e,t)=>{Ft.init(e,t),Po.init(e,t)});const Co=ue("ZodEmoji",(e,t)=>{Lt.init(e,t),Po.init(e,t)}),jo=ue("ZodNanoID",(e,t)=>{Kt.init(e,t),Po.init(e,t)}),Ro=ue("ZodCUID",(e,t)=>{Ht.init(e,t),Po.init(e,t)}),Oo=ue("ZodCUID2",(e,t)=>{Zt.init(e,t),Po.init(e,t)}),zo=ue("ZodULID",(e,t)=>{Gt.init(e,t),Po.init(e,t)}),Ao=ue("ZodXID",(e,t)=>{Jt.init(e,t),Po.init(e,t)}),Mo=ue("ZodKSUID",(e,t)=>{Wt.init(e,t),Po.init(e,t)}),Uo=ue("ZodIPv4",(e,t)=>{er.init(e,t),Po.init(e,t)}),Do=ue("ZodIPv6",(e,t)=>{tr.init(e,t),Po.init(e,t)}),qo=ue("ZodCIDRv4",(e,t)=>{rr.init(e,t),Po.init(e,t)}),Vo=ue("ZodCIDRv6",(e,t)=>{or.init(e,t),Po.init(e,t)}),Fo=ue("ZodBase64",(e,t)=>{sr.init(e,t),Po.init(e,t)}),Lo=ue("ZodBase64URL",(e,t)=>{ar.init(e,t),Po.init(e,t)}),Ko=ue("ZodE164",(e,t)=>{ir.init(e,t),Po.init(e,t)}),Ho=ue("ZodJWT",(e,t)=>{cr.init(e,t),Po.init(e,t)}),Zo=ue("ZodNumber",(e,t)=>{ur.init(e,t),bo.init(e,t),e.gt=(t,r)=>e.check(Yr(t,r)),e.gte=(t,r)=>e.check(Xr(t,r)),e.min=(t,r)=>e.check(Xr(t,r)),e.lt=(t,r)=>e.check(Br(t,r)),e.lte=(t,r)=>e.check(Qr(t,r)),e.max=(t,r)=>e.check(Qr(t,r)),e.int=t=>e.check(Wo(t)),e.safe=t=>e.check(Wo(t)),e.positive=t=>e.check(Yr(0,t)),e.nonnegative=t=>e.check(Xr(0,t)),e.negative=t=>e.check(Br(0,t)),e.nonpositive=t=>e.check(Qr(0,t)),e.multipleOf=(t,r)=>e.check(eo(t,r)),e.step=(t,r)=>e.check(eo(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 Go(e){return function(e,t){return new e({type:"number",checks:[],...Te(t)})}(Zo,e)}const Jo=ue("ZodNumberFormat",(e,t)=>{lr.init(e,t),Zo.init(e,t)});function Wo(e){return function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...Te(t)})}(Jo,e)}const Bo=ue("ZodBoolean",(e,t)=>{dr.init(e,t),bo.init(e,t)});function Qo(e){return function(e,t){return new e({type:"boolean",...Te(t)})}(Bo,e)}const Yo=ue("ZodNull",(e,t)=>{pr.init(e,t),bo.init(e,t)});function Xo(e){return function(e,t){return new e({type:"null",...Te(t)})}(Yo,e)}const en=ue("ZodAny",(e,t)=>{hr.init(e,t),bo.init(e,t)});const tn=ue("ZodUnknown",(e,t)=>{fr.init(e,t),bo.init(e,t)});function rn(){return new tn({type:"unknown"})}const on=ue("ZodNever",(e,t)=>{mr.init(e,t),bo.init(e,t)});function nn(e){return function(e,t){return new e({type:"never",...Te(t)})}(on,e)}const sn=ue("ZodArray",(e,t)=>{gr.init(e,t),bo.init(e,t),e.element=t.element,e.min=(t,r)=>e.check(ro(t,r)),e.nonempty=t=>e.check(ro(1,t)),e.max=(t,r)=>e.check(to(t,r)),e.length=(t,r)=>e.check(oo(t,r)),e.unwrap=()=>e.element});function an(e,t){return function(e,t,r){return new e({type:"array",element:t,...Te(r)})}(sn,e,t)}const cn=ue("ZodObject",(e,t)=>{wr.init(e,t),bo.init(e,t),ge(e,"shape",()=>t.shape),e.keyof=()=>wn(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:rn()}),e.loose=()=>e.clone({...e._zod.def,catchall:rn()}),e.strict=()=>e.clone({...e._zod.def,catchall:nn()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>function(e,t){if(!ke(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 ve(this,"shape",r),r},checks:[]};return Pe(e,r)}(e,t),e.merge=t=>{return o=t,Pe(r=e,{...r._zod.def,get shape(){const e={...r._zod.def.shape,...o._zod.def.shape};return ve(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 Pe(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 Pe(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 Pe(t,{...t._zod.def,shape:n,checks:[]})}(Sn,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 Pe(t,{...t._zod.def,shape:n,checks:[]})}(Cn,e,t[0])});function un(e,t){const r={type:"object",get shape(){return ve(this,"shape",{...e}),this.shape},...Te(t)};return new cn(r)}function ln(e,t){return new cn({type:"object",get shape(){return ve(this,"shape",{...e}),this.shape},catchall:rn(),...Te(t)})}const dn=ue("ZodUnion",(e,t)=>{br.init(e,t),bo.init(e,t),e.options=t.options});function pn(e,t){return new dn({type:"union",options:e,...Te(t)})}const hn=ue("ZodDiscriminatedUnion",(e,t)=>{dn.init(e,t),kr.init(e,t)});function fn(e,t,r){return new hn({type:"union",options:t,discriminator:e,...Te(r)})}const mn=ue("ZodIntersection",(e,t)=>{Er.init(e,t),bo.init(e,t)});function yn(e,t){return new mn({type:"intersection",left:e,right:t})}const gn=ue("ZodRecord",(e,t)=>{Tr.init(e,t),bo.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function vn(e,t,r){return new gn({type:"record",keyType:e,valueType:t,...Te(r)})}const _n=ue("ZodEnum",(e,t)=>{xr.init(e,t),bo.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 _n({...t,checks:[],...Te(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 _n({...t,checks:[],...Te(o),entries:n})}});function wn(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new _n({type:"enum",entries:r,...Te(t)})}const $n=ue("ZodLiteral",(e,t)=>{Ir.init(e,t),bo.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 bn(e,t){return new $n({type:"literal",values:Array.isArray(e)?e:[e],...Te(t)})}const kn=ue("ZodTransform",(e,t)=>{Nr.init(e,t),bo.init(e,t),e._zod.parse=(r,o)=>{r.addIssue=o=>{if("string"==typeof o)r.issues.push(Oe(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(Oe(t))}};const n=t.transform(r.value,r);return n instanceof Promise?n.then(e=>(r.value=e,r)):(r.value=n,r)}});function En(e){return new kn({type:"transform",transform:e})}const Sn=ue("ZodOptional",(e,t)=>{Cr.init(e,t),bo.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Pn(e){return new Sn({type:"optional",innerType:e})}const Tn=ue("ZodNullable",(e,t)=>{jr.init(e,t),bo.init(e,t),e.unwrap=()=>e._zod.def.innerType});function xn(e){return new Tn({type:"nullable",innerType:e})}const In=ue("ZodDefault",(e,t)=>{Rr.init(e,t),bo.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});const Nn=ue("ZodPrefault",(e,t)=>{zr.init(e,t),bo.init(e,t),e.unwrap=()=>e._zod.def.innerType});const Cn=ue("ZodNonOptional",(e,t)=>{Ar.init(e,t),bo.init(e,t),e.unwrap=()=>e._zod.def.innerType});const jn=ue("ZodCatch",(e,t)=>{Ur.init(e,t),bo.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});const Rn=ue("ZodPipe",(e,t)=>{Dr.init(e,t),bo.init(e,t),e.in=t.in,e.out=t.out});function On(e,t){return new Rn({type:"pipe",in:e,out:t})}const zn=ue("ZodReadonly",(e,t)=>{Vr.init(e,t),bo.init(e,t)});const An=ue("ZodCustom",(e,t)=>{Lr.init(e,t),bo.init(e,t)});function Mn(e,t){return On(En(e),t)}const Un="custom";const Dn="2025-11-25",qn=[Dn,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Vn="io.modelcontextprotocol/related-task",Fn="2.0",Ln=function(e,t,r){const o=Te(r);return o.abort??(o.abort=!0),new e({type:"custom",check:"custom",fn:t,...o})}(An,(e=>null!==e&&("object"==typeof e||"function"==typeof e))??(()=>!0),Kn);var Kn;const Hn=pn([So(),Go().int()]),Zn=So();ln({ttl:pn([Go(),Xo()]).optional(),pollInterval:Go().optional()});const Gn=un({ttl:Go().optional()}),Jn=un({taskId:So()}),Wn=ln({progressToken:Hn.optional(),[Vn]:Jn.optional()}),Bn=un({_meta:Wn.optional()}),Qn=Bn.extend({task:Gn.optional()}),Yn=un({method:So(),params:Bn.loose().optional()}),Xn=un({_meta:Wn.optional()}),es=un({method:So(),params:Xn.loose().optional()}),ts=ln({_meta:Wn.optional()}),rs=pn([So(),Go().int()]),os=un({jsonrpc:bn(Fn),id:rs,...Yn.shape}).strict(),ns=e=>os.safeParse(e).success,ss=un({jsonrpc:bn(Fn),...es.shape}).strict(),as=un({jsonrpc:bn(Fn),id:rs,result:ts}).strict(),is=e=>as.safeParse(e).success;var cs;!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"}(cs||(cs={}));const us=un({jsonrpc:bn(Fn),id:rs.optional(),error:un({code:Go().int(),message:So(),data:rn().optional()})}).strict(),ls=pn([os,ss,as,us]);pn([as,us]);const ds=ts.strict(),ps=Xn.extend({requestId:rs.optional(),reason:So().optional()}),hs=es.extend({method:bn("notifications/cancelled"),params:ps}),fs=un({src:So(),mimeType:So().optional(),sizes:an(So()).optional(),theme:wn(["light","dark"]).optional()}),ms=un({icons:an(fs).optional()}),ys=un({name:So(),title:So().optional()}),gs=ys.extend({...ys.shape,...ms.shape,version:So(),websiteUrl:So().optional(),description:So().optional()}),vs=yn(un({applyDefaults:Qo().optional()}),vn(So(),rn())),_s=Mn(e=>e&&"object"==typeof e&&!Array.isArray(e)&&0===Object.keys(e).length?{form:{}}:e,yn(un({form:vs.optional(),url:Ln.optional()}),vn(So(),rn()).optional())),ws=ln({list:Ln.optional(),cancel:Ln.optional(),requests:ln({sampling:ln({createMessage:Ln.optional()}).optional(),elicitation:ln({create:Ln.optional()}).optional()}).optional()}),$s=ln({list:Ln.optional(),cancel:Ln.optional(),requests:ln({tools:ln({call:Ln.optional()}).optional()}).optional()}),bs=un({experimental:vn(So(),Ln).optional(),sampling:un({context:Ln.optional(),tools:Ln.optional()}).optional(),elicitation:_s.optional(),roots:un({listChanged:Qo().optional()}).optional(),tasks:ws.optional()}),ks=Bn.extend({protocolVersion:So(),capabilities:bs,clientInfo:gs}),Es=Yn.extend({method:bn("initialize"),params:ks}),Ss=un({experimental:vn(So(),Ln).optional(),logging:Ln.optional(),completions:Ln.optional(),prompts:un({listChanged:Qo().optional()}).optional(),resources:un({subscribe:Qo().optional(),listChanged:Qo().optional()}).optional(),tools:un({listChanged:Qo().optional()}).optional(),tasks:$s.optional()}),Ps=ts.extend({protocolVersion:So(),capabilities:Ss,serverInfo:gs,instructions:So().optional()}),Ts=es.extend({method:bn("notifications/initialized"),params:Xn.optional()}),xs=Yn.extend({method:bn("ping"),params:Bn.optional()}),Is=un({progress:Go(),total:Pn(Go()),message:Pn(So())}),Ns=un({...Xn.shape,...Is.shape,progressToken:Hn}),Cs=es.extend({method:bn("notifications/progress"),params:Ns}),js=Bn.extend({cursor:Zn.optional()}),Rs=Yn.extend({params:js.optional()}),Os=ts.extend({nextCursor:Zn.optional()}),zs=wn(["working","input_required","completed","failed","cancelled"]),As=un({taskId:So(),status:zs,ttl:pn([Go(),Xo()]),createdAt:So(),lastUpdatedAt:So(),pollInterval:Pn(Go()),statusMessage:Pn(So())}),Ms=ts.extend({task:As}),Us=Xn.merge(As),Ds=es.extend({method:bn("notifications/tasks/status"),params:Us}),qs=Yn.extend({method:bn("tasks/get"),params:Bn.extend({taskId:So()})}),Vs=ts.merge(As),Fs=Yn.extend({method:bn("tasks/result"),params:Bn.extend({taskId:So()})});ts.loose();const Ls=Rs.extend({method:bn("tasks/list")}),Ks=Os.extend({tasks:an(As)}),Hs=Yn.extend({method:bn("tasks/cancel"),params:Bn.extend({taskId:So()})}),Zs=ts.merge(As),Gs=un({uri:So(),mimeType:Pn(So()),_meta:vn(So(),rn()).optional()}),Js=Gs.extend({text:So()}),Ws=So().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Bs=Gs.extend({blob:Ws}),Qs=wn(["user","assistant"]),Ys=un({audience:an(Qs).optional(),priority:Go().min(0).max(1).optional(),lastModified:uo({offset:!0}).optional()}),Xs=un({...ys.shape,...ms.shape,uri:So(),description:Pn(So()),mimeType:Pn(So()),annotations:Ys.optional(),_meta:Pn(ln({}))}),ea=un({...ys.shape,...ms.shape,uriTemplate:So(),description:Pn(So()),mimeType:Pn(So()),annotations:Ys.optional(),_meta:Pn(ln({}))}),ta=Rs.extend({method:bn("resources/list")}),ra=Os.extend({resources:an(Xs)}),oa=Rs.extend({method:bn("resources/templates/list")}),na=Os.extend({resourceTemplates:an(ea)}),sa=Bn.extend({uri:So()}),aa=sa,ia=Yn.extend({method:bn("resources/read"),params:aa}),ca=ts.extend({contents:an(pn([Js,Bs]))}),ua=es.extend({method:bn("notifications/resources/list_changed"),params:Xn.optional()}),la=sa,da=Yn.extend({method:bn("resources/subscribe"),params:la}),pa=sa,ha=Yn.extend({method:bn("resources/unsubscribe"),params:pa}),fa=Xn.extend({uri:So()}),ma=es.extend({method:bn("notifications/resources/updated"),params:fa}),ya=un({name:So(),description:Pn(So()),required:Pn(Qo())}),ga=un({...ys.shape,...ms.shape,description:Pn(So()),arguments:Pn(an(ya)),_meta:Pn(ln({}))}),va=Rs.extend({method:bn("prompts/list")}),_a=Os.extend({prompts:an(ga)}),wa=Bn.extend({name:So(),arguments:vn(So(),So()).optional()}),$a=Yn.extend({method:bn("prompts/get"),params:wa}),ba=un({type:bn("text"),text:So(),annotations:Ys.optional(),_meta:vn(So(),rn()).optional()}),ka=un({type:bn("image"),data:Ws,mimeType:So(),annotations:Ys.optional(),_meta:vn(So(),rn()).optional()}),Ea=un({type:bn("audio"),data:Ws,mimeType:So(),annotations:Ys.optional(),_meta:vn(So(),rn()).optional()}),Sa=un({type:bn("tool_use"),name:So(),id:So(),input:vn(So(),rn()),_meta:vn(So(),rn()).optional()}),Pa=un({type:bn("resource"),resource:pn([Js,Bs]),annotations:Ys.optional(),_meta:vn(So(),rn()).optional()}),Ta=pn([ba,ka,Ea,Xs.extend({type:bn("resource_link")}),Pa]),xa=un({role:Qs,content:Ta}),Ia=ts.extend({description:So().optional(),messages:an(xa)}),Na=es.extend({method:bn("notifications/prompts/list_changed"),params:Xn.optional()}),Ca=un({title:So().optional(),readOnlyHint:Qo().optional(),destructiveHint:Qo().optional(),idempotentHint:Qo().optional(),openWorldHint:Qo().optional()}),ja=un({taskSupport:wn(["required","optional","forbidden"]).optional()}),Ra=un({...ys.shape,...ms.shape,description:So().optional(),inputSchema:un({type:bn("object"),properties:vn(So(),Ln).optional(),required:an(So()).optional()}).catchall(rn()),outputSchema:un({type:bn("object"),properties:vn(So(),Ln).optional(),required:an(So()).optional()}).catchall(rn()).optional(),annotations:Ca.optional(),execution:ja.optional(),_meta:vn(So(),rn()).optional()}),Oa=Rs.extend({method:bn("tools/list")}),za=Os.extend({tools:an(Ra)}),Aa=ts.extend({content:an(Ta).default([]),structuredContent:vn(So(),rn()).optional(),isError:Qo().optional()});Aa.or(ts.extend({toolResult:rn()}));const Ma=Qn.extend({name:So(),arguments:vn(So(),rn()).optional()}),Ua=Yn.extend({method:bn("tools/call"),params:Ma}),Da=es.extend({method:bn("notifications/tools/list_changed"),params:Xn.optional()}),qa=un({autoRefresh:Qo().default(!0),debounceMs:Go().int().nonnegative().default(300)}),Va=wn(["debug","info","notice","warning","error","critical","alert","emergency"]),Fa=Bn.extend({level:Va}),La=Yn.extend({method:bn("logging/setLevel"),params:Fa}),Ka=Xn.extend({level:Va,logger:So().optional(),data:rn()}),Ha=es.extend({method:bn("notifications/message"),params:Ka}),Za=un({name:So().optional()}),Ga=un({hints:an(Za).optional(),costPriority:Go().min(0).max(1).optional(),speedPriority:Go().min(0).max(1).optional(),intelligencePriority:Go().min(0).max(1).optional()}),Ja=un({mode:wn(["auto","required","none"]).optional()}),Wa=un({type:bn("tool_result"),toolUseId:So().describe("The unique identifier for the corresponding tool call."),content:an(Ta).default([]),structuredContent:un({}).loose().optional(),isError:Qo().optional(),_meta:vn(So(),rn()).optional()}),Ba=fn("type",[ba,ka,Ea]),Qa=fn("type",[ba,ka,Ea,Sa,Wa]),Ya=un({role:Qs,content:pn([Qa,an(Qa)]),_meta:vn(So(),rn()).optional()}),Xa=Qn.extend({messages:an(Ya),modelPreferences:Ga.optional(),systemPrompt:So().optional(),includeContext:wn(["none","thisServer","allServers"]).optional(),temperature:Go().optional(),maxTokens:Go().int(),stopSequences:an(So()).optional(),metadata:Ln.optional(),tools:an(Ra).optional(),toolChoice:Ja.optional()}),ei=Yn.extend({method:bn("sampling/createMessage"),params:Xa}),ti=ts.extend({model:So(),stopReason:Pn(wn(["endTurn","stopSequence","maxTokens"]).or(So())),role:Qs,content:Ba}),ri=ts.extend({model:So(),stopReason:Pn(wn(["endTurn","stopSequence","maxTokens","toolUse"]).or(So())),role:Qs,content:pn([Qa,an(Qa)])}),oi=un({type:bn("boolean"),title:So().optional(),description:So().optional(),default:Qo().optional()}),ni=un({type:bn("string"),title:So().optional(),description:So().optional(),minLength:Go().optional(),maxLength:Go().optional(),format:wn(["email","uri","date","date-time"]).optional(),default:So().optional()}),si=un({type:wn(["number","integer"]),title:So().optional(),description:So().optional(),minimum:Go().optional(),maximum:Go().optional(),default:Go().optional()}),ai=un({type:bn("string"),title:So().optional(),description:So().optional(),enum:an(So()),default:So().optional()}),ii=un({type:bn("string"),title:So().optional(),description:So().optional(),oneOf:an(un({const:So(),title:So()})),default:So().optional()}),ci=un({type:bn("string"),title:So().optional(),description:So().optional(),enum:an(So()),enumNames:an(So()).optional(),default:So().optional()}),ui=pn([ai,ii]),li=pn([un({type:bn("array"),title:So().optional(),description:So().optional(),minItems:Go().optional(),maxItems:Go().optional(),items:un({type:bn("string"),enum:an(So())}),default:an(So()).optional()}),un({type:bn("array"),title:So().optional(),description:So().optional(),minItems:Go().optional(),maxItems:Go().optional(),items:un({anyOf:an(un({const:So(),title:So()}))}),default:an(So()).optional()})]),di=pn([ci,ui,li]),pi=pn([di,oi,ni,si]),hi=pn([Qn.extend({mode:bn("form").optional(),message:So(),requestedSchema:un({type:bn("object"),properties:vn(So(),pi),required:an(So()).optional()})}),Qn.extend({mode:bn("url"),message:So(),elicitationId:So(),url:So().url()})]),fi=Yn.extend({method:bn("elicitation/create"),params:hi}),mi=Xn.extend({elicitationId:So()}),yi=es.extend({method:bn("notifications/elicitation/complete"),params:mi}),gi=ts.extend({action:wn(["accept","decline","cancel"]),content:Mn(e=>null===e?void 0:e,vn(So(),pn([So(),Go(),Qo(),an(So())])).optional())}),vi=un({type:bn("ref/resource"),uri:So()}),_i=un({type:bn("ref/prompt"),name:So()}),wi=Bn.extend({ref:pn([_i,vi]),argument:un({name:So(),value:So()}),context:un({arguments:vn(So(),So()).optional()}).optional()}),$i=Yn.extend({method:bn("completion/complete"),params:wi}),bi=ts.extend({completion:ln({values:an(So()).max(100),total:Pn(Go().int()),hasMore:Pn(Qo())})}),ki=un({uri:So().startsWith("file://"),name:So().optional(),_meta:vn(So(),rn()).optional()}),Ei=Yn.extend({method:bn("roots/list"),params:Bn.optional()}),Si=ts.extend({roots:an(ki)}),Pi=es.extend({method:bn("notifications/roots/list_changed"),params:Xn.optional()});pn([xs,Es,$i,La,$a,va,ta,oa,ia,da,ha,Ua,Oa,qs,Fs,Ls,Hs]),pn([hs,Cs,Ts,Pi,Ds]),pn([ds,ti,ri,gi,Si,Vs,Ks,Ms]),pn([xs,ei,fi,Ei,qs,Fs,Ls,Hs]),pn([hs,Cs,Ha,ma,ua,Da,Na,Ds,yi]),pn([ds,Ps,bi,Ia,_a,ra,na,ca,Aa,za,Vs,Ks,Ms]);class Ti 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===cs.UrlElicitationRequired&&r){const e=r;if(e.elicitations)return new xi(e.elicitations,t)}return new Ti(e,t,r)}}class xi extends Ti{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(cs.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}function Ii(e){return"completed"===e||"failed"===e||"cancelled"===e}function Ni(e){const t=io(e),r=t?.method;if(!r)throw new Error("Schema is missing a method literal");const o=function(e){if(so(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 Ci(e,t){const r=ao(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(hs,e=>{this._oncancel(e)}),this.setNotificationHandler(Cs,e=>{this._onprogress(e)}),this.setRequestHandler(xs,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(qs,async(e,t)=>{const r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new Ti(cs.InvalidParams,"Failed to retrieve task: Task not found");return{...r}}),this.setRequestHandler(Fs,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 Ti(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 Ti(cs.InvalidParams,`Task not found: ${o}`);if(!Ii(n.status))return await this._waitForTaskUpdate(o,t.signal),await r();if(Ii(n.status)){const e=await this._taskStore.getTaskResult(o,t.sessionId);return this._clearTaskQueue(o),{...e,_meta:{...e._meta,[Vn]:{taskId:o}}}}return await r()};return await r()}),this.setRequestHandler(Ls,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 Ti(cs.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(Hs,async(e,t)=>{try{const r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new Ti(cs.InvalidParams,`Task not found: ${e.params.taskId}`);if(Ii(r.status))throw new Ti(cs.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 Ti(cs.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...o}}catch(e){if(e instanceof Ti)throw e;throw new Ti(cs.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),Ti.fromError(cs.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),is(e)||(r=e,us.safeParse(r).success)?this._onresponse(e):ns(e)?this._onrequest(e,t):(e=>ss.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=Ti.fromError(cs.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?.[Vn]?.taskId;if(void 0===r){const t={jsonrpc:"2.0",id:e.id,error:{code:cs.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,Qn.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 Ti(cs.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:cs.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),is(e))r(e);else{r(new Ti(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(is(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),is(e))o(e);else{o(Ti.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 Ti?e:new Ti(cs.InternalError,String(e))}}return}let n;try{const o=await this.request(e,Ms,r);if(!o.task)throw new Ti(cs.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},Ii(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 Ti(cs.InternalError,`Task ${n} failed`)}:"cancelled"===e.status&&(yield{type:"error",error:new Ti(cs.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 Ti?e:new Ti(cs.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++,p={...e,jsonrpc:"2.0",id:d};r?.onprogress&&(this._progressHandlers.set(d,r.onprogress),p.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),a&&(p.params={...p.params,task:a}),i&&(p.params={...p.params,_meta:{...p.params?._meta||{},[Vn]:i}});const h=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 Ti?e:new Ti(cs.RequestTimeout,String(e));u(t)};this._responseHandlers.set(d,e=>{if(!r?.signal?.aborted){if(e instanceof Error)return u(e);try{const r=ao(t,e.result);r.success?c(r.data):u(r.error)}catch(e){u(e)}}}),r?.signal?.addEventListener("abort",()=>{h(r?.signal?.reason)});const f=r?.timeout??6e4;this._setupTimeout(d,f,r?.maxTotalTimeout,()=>h(Ti.fromError(cs.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:p,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(d),u(e)})}else this._transport.send(p,{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},Vs,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},Ks,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},Zs,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||{},[Vn]: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||{},[Vn]: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||{},[Vn]:t.relatedTask}}}),await this._transport.send(o,t)}setRequestHandler(e,t){const r=Ni(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(r,o)=>{const n=Ci(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=Ni(e);this._notificationHandlers.set(r,r=>{const o=Ci(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&&ns(t.message)){const r=t.message.id,o=this._requestResolvers.get(r);o?(o(new Ti(cs.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 Ti(cs.InvalidRequest,"Request cancelled"));const n=setTimeout(e,r);t.addEventListener("abort",()=>{clearTimeout(n),o(new Ti(cs.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 Ti(cs.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=Ds.parse({method:"notifications/tasks/status",params:s});await this.notification(t),Ii(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 Ti(cs.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(Ii(s.status))throw new Ti(cs.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=Ds.parse({method:"notifications/tasks/status",params:a});await this.notification(t),Ii(a.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>r.listTasks(e,t)}}}function Ri(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function Oi(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var zi,Ai={exports:{}},Mi={},Ui={},Di={},qi={},Vi={},Fi={};function Li(){return zi||(zi=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())}}(Fi)),Fi}var Ki,Hi,Zi={};function Gi(){return Ki||(Ki=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=Li();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}}}(Zi)),Zi}function Ji(){return Hi||(Hi=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=Li(),r=Gi();var o=Li();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=Gi();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=I(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=I(this.rhs,e,r),this}get names(){return x(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 p 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=I(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class h 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 h{render(e){return"{"+e._n+super.render(e)+"}"+e._n}}class m extends h{}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=I(this.condition,e,t),this}get names(){const e=super.names;return x(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=I(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=x(super.names,this.from);return x(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=I(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 h{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 x(e,r){return r instanceof t._CodeOrName?T(e,r.names):e}function I(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 p(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)}}(Vi)),Vi}var Wi={};Object.defineProperty(Wi,"__esModule",{value:!0}),Wi.checkStrictMode=Wi.getErrorPath=Wi.Type=Wi.useFunc=Wi.setEvaluated=Wi.evaluatedPropsToName=Wi.mergeEvaluated=Wi.eachItem=Wi.unescapeJsonPointer=Wi.escapeJsonPointer=Wi.escapeFragment=Wi.unescapeFragment=Wi.schemaRefOrVal=Wi.schemaHasRulesButRef=Wi.schemaHasRules=Wi.checkUnknownRules=Wi.alwaysValidSchema=Wi.toHash=void 0;const Bi=Ji(),Qi=Li();function Yi(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]||ic(e,`unknown keyword: "${r}"`)}function Xi(e,t){if("boolean"==typeof e)return!e;for(const r in e)if(t[r])return!0;return!1}function ec(e){return"number"==typeof e?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}function tc(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function rc({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:o}){return(n,s,a,i)=>{const c=void 0===a?s:a instanceof Bi.Name?(s instanceof Bi.Name?e(n,s,a):t(n,s,a),a):s instanceof Bi.Name?(t(n,a,s),s):r(s,a);return i!==Bi.Name||c instanceof Bi.Name?c:o(n,c)}}function oc(e,t){if(!0===t)return e.var("props",!0);const r=e.var("props",Bi._`{}`);return void 0!==t&&nc(e,r,t),r}function nc(e,t,r){Object.keys(r).forEach(r=>e.assign(Bi._`${t}${(0,Bi.getProperty)(r)}`,!0))}Wi.toHash=function(e){const t={};for(const r of e)t[r]=!0;return t},Wi.alwaysValidSchema=function(e,t){return"boolean"==typeof t?t:0===Object.keys(t).length||(Yi(e,t),!Xi(t,e.self.RULES.all))},Wi.checkUnknownRules=Yi,Wi.schemaHasRules=Xi,Wi.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},Wi.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 Bi._`${r}`}return Bi._`${e}${t}${(0,Bi.getProperty)(o)}`},Wi.unescapeFragment=function(e){return tc(decodeURIComponent(e))},Wi.escapeFragment=function(e){return encodeURIComponent(ec(e))},Wi.escapeJsonPointer=ec,Wi.unescapeJsonPointer=tc,Wi.eachItem=function(e,t){if(Array.isArray(e))for(const r of e)t(r);else t(e)},Wi.mergeEvaluated={props:rc({mergeNames:(e,t,r)=>e.if(Bi._`${r} !== true && ${t} !== undefined`,()=>{e.if(Bi._`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,Bi._`${r} || {}`).code(Bi._`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if(Bi._`${r} !== true`,()=>{!0===t?e.assign(r,!0):(e.assign(r,Bi._`${r} || {}`),nc(e,r,t))}),mergeValues:(e,t)=>!0===e||{...e,...t},resultToName:oc}),items:rc({mergeNames:(e,t,r)=>e.if(Bi._`${r} !== true && ${t} !== undefined`,()=>e.assign(r,Bi._`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if(Bi._`${r} !== true`,()=>e.assign(r,!0===t||Bi._`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>!0===e||Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})},Wi.evaluatedPropsToName=oc,Wi.setEvaluated=nc;const sc={};var ac;function ic(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,!0===r)throw new Error(t);e.self.logger.warn(t)}}Wi.useFunc=function(e,t){return e.scopeValue("func",{ref:t,code:sc[t.code]||(sc[t.code]=new Qi._Code(t.code))})},function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"}(ac||(Wi.Type=ac={})),Wi.getErrorPath=function(e,t,r){if(e instanceof Bi.Name){const o=t===ac.Num;return r?o?Bi._`"[" + ${e} + "]"`:Bi._`"['" + ${e} + "']"`:o?Bi._`"/" + ${e}`:Bi._`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,Bi.getProperty)(e).toString():"/"+ec(e)},Wi.checkStrictMode=ic;var cc,uc,lc,dc={};function pc(){if(cc)return dc;cc=1,Object.defineProperty(dc,"__esModule",{value:!0});const e=Ji(),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 dc.default=t,dc}function hc(){return uc||(uc=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=Ji(),r=Wi,o=pc();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:p}=u,h=i(r,o,a);(null!=c?c:d||p)?n(l,h):s(u,t._`[${h}]`)},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:p,topSchemaRef:h,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._`${h}${f}`],[o.default.data,c]);p&&s.push([a.propertyName,p])}(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]}}(qi)),qi}var fc={},mc={};Object.defineProperty(mc,"__esModule",{value:!0}),mc.getRules=mc.isJSONType=void 0;const yc=new Set(["string","number","integer","boolean","null","object","array"]);mc.isJSONType=function(e){return"string"==typeof e&&yc.has(e)},mc.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 gc,vc={};function _c(){if(gc)return vc;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 gc=1,Object.defineProperty(vc,"__esModule",{value:!0}),vc.shouldUseRule=vc.shouldUseGroup=vc.schemaHasRulesForType=void 0,vc.schemaHasRulesForType=function({schema:t,self:r},o){const n=r.RULES.types[o];return n&&!0!==n&&e(t,n)},vc.shouldUseGroup=e,vc.shouldUseRule=t,vc}Object.defineProperty(fc,"__esModule",{value:!0}),fc.reportTypeError=fc.checkDataTypes=fc.checkDataType=fc.coerceAndCheckDataType=fc.getJSONTypes=fc.getSchemaTypes=fc.DataType=void 0;const wc=mc,$c=_c(),bc=hc(),kc=Ji(),Ec=Wi;var Sc;function Pc(e){const t=Array.isArray(e)?e:e?[e]:[];if(t.every(wc.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"}(Sc||(fc.DataType=Sc={})),fc.getSchemaTypes=function(e){const t=Pc(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},fc.getJSONTypes=Pc,fc.coerceAndCheckDataType=function(e,t){const{gen:r,data:o,opts:n}=e,s=function(e,t){return t?e.filter(e=>Tc.has(e)||"array"===t&&"array"===e):[]}(t,n.coerceTypes),a=t.length>0&&!(0===s.length&&1===t.length&&(0,$c.schemaHasRulesForType)(e,t[0]));if(a){const a=Ic(t,o,n.strictNumbers,Sc.Wrong);r.if(a,()=>{s.length?function(e,t,r){const{gen:o,data:n,opts:s}=e,a=o.let("dataType",kc._`typeof ${n}`),i=o.let("coerced",kc._`undefined`);"array"===s.coerceTypes&&o.if(kc._`${a} == 'object' && Array.isArray(${n}) && ${n}.length == 1`,()=>o.assign(n,kc._`${n}[0]`).assign(a,kc._`typeof ${n}`).if(Ic(t,n,s.strictNumbers),()=>o.assign(i,n)));o.if(kc._`${i} !== undefined`);for(const e of r)(Tc.has(e)||"array"===e&&"array"===s.coerceTypes)&&c(e);function c(e){switch(e){case"string":return void o.elseIf(kc._`${a} == "number" || ${a} == "boolean"`).assign(i,kc._`"" + ${n}`).elseIf(kc._`${n} === null`).assign(i,kc._`""`);case"number":return void o.elseIf(kc._`${a} == "boolean" || ${n} === null
|
|
2
|
+
|| (${a} == "string" && ${n} && ${n} == +${n})`).assign(i,kc._`+${n}`);case"integer":return void o.elseIf(kc._`${a} === "boolean" || ${n} === null
|
|
3
|
+
|| (${a} === "string" && ${n} && ${n} == +${n} && !(${n} % 1))`).assign(i,kc._`+${n}`);case"boolean":return void o.elseIf(kc._`${n} === "false" || ${n} === 0 || ${n} === null`).assign(i,!1).elseIf(kc._`${n} === "true" || ${n} === 1`).assign(i,!0);case"null":return o.elseIf(kc._`${n} === "" || ${n} === 0 || ${n} === false`),void o.assign(i,null);case"array":o.elseIf(kc._`${a} === "string" || ${a} === "number"
|
|
4
|
+
|| ${a} === "boolean" || ${n} === null`).assign(i,kc._`[${n}]`)}}o.else(),Cc(e),o.endIf(),o.if(kc._`${i} !== undefined`,()=>{o.assign(n,i),function({gen:e,parentData:t,parentDataProperty:r},o){e.if(kc._`${t} !== undefined`,()=>e.assign(kc._`${t}[${r}]`,o))}(e,i)})}(e,t,s):Cc(e)})}return a};const Tc=new Set(["string","number","integer","boolean","null"]);function xc(e,t,r,o=Sc.Correct){const n=o===Sc.Correct?kc.operators.EQ:kc.operators.NEQ;let s;switch(e){case"null":return kc._`${t} ${n} null`;case"array":s=kc._`Array.isArray(${t})`;break;case"object":s=kc._`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":s=a(kc._`!(${t} % 1) && !isNaN(${t})`);break;case"number":s=a();break;default:return kc._`typeof ${t} ${n} ${e}`}return o===Sc.Correct?s:(0,kc.not)(s);function a(e=kc.nil){return(0,kc.and)(kc._`typeof ${t} == "number"`,e,r?kc._`isFinite(${t})`:kc.nil)}}function Ic(e,t,r,o){if(1===e.length)return xc(e[0],t,r,o);let n;const s=(0,Ec.toHash)(e);if(s.array&&s.object){const e=kc._`typeof ${t} != "object"`;n=s.null?e:kc._`!${t} || ${e}`,delete s.null,delete s.array,delete s.object}else n=kc.nil;s.number&&delete s.integer;for(const e in s)n=(0,kc.and)(n,xc(e,t,r,o));return n}fc.checkDataType=xc,fc.checkDataTypes=Ic;const Nc={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>"string"==typeof e?kc._`{type: ${e}}`:kc._`{type: ${t}}`};function Cc(e){const t=function(e){const{gen:t,data:r,schema:o}=e,n=(0,Ec.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,bc.reportError)(t,Nc)}fc.reportTypeError=Cc;var jc,Rc={};var Oc,zc,Ac={},Mc={};function Uc(){if(Oc)return Mc;Oc=1,Object.defineProperty(Mc,"__esModule",{value:!0}),Mc.validateUnion=Mc.validateArray=Mc.usePattern=Mc.callValidateCode=Mc.schemaProperties=Mc.allSchemaProperties=Mc.noPropertyInData=Mc.propertyInData=Mc.isOwnProperty=Mc.hasPropFunc=Mc.reportMissingProp=Mc.checkMissingProp=Mc.checkReportMissingProp=void 0;const e=Ji(),t=Wi,r=pc(),o=Wi;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):[]}Mc.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()})},Mc.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}`)))},Mc.reportMissingProp=function(e,t){e.setParams({missingProperty:t},!0),e.error()},Mc.hasPropFunc=n,Mc.isOwnProperty=s,Mc.propertyInData=function(t,r,o,n){const a=e._`${r}${(0,e.getProperty)(o)} !== undefined`;return n?e._`${a} && ${s(t,r,o)}`:a},Mc.noPropertyInData=a,Mc.allSchemaProperties=i,Mc.schemaProperties=function(e,r){return i(r).filter(o=>!(0,t.alwaysValidSchema)(e,r[o]))},Mc.callValidateCode=function({schemaCode:t,data:o,it:{gen:n,topSchemaRef:s,schemaPath:a,errorPath:i},it:c},u,l,d){const p=d?e._`${t}, ${o}, ${s}${a}`:o,h=[[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&&h.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);const f=e._`${p}, ${n.object(...h)}`;return l!==e.nil?e._`${u}.call(${l}, ${f})`:e._`${u}(${f})`};const c=e._`new RegExp`;return Mc.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})`})},Mc.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)})}},Mc.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))},Mc}function Dc(){if(zc)return Ac;zc=1,Object.defineProperty(Ac,"__esModule",{value:!0}),Ac.validateKeywordUsage=Ac.validSchemaType=Ac.funcKeywordCode=Ac.macroKeywordCode=void 0;const e=Ji(),t=pc(),r=Uc(),o=hc();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 Ac.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))},Ac.funcKeywordCode=function(a,i){var c;const{gen:u,keyword:l,schema:d,parentSchema:p,$data:h,it:f}=a;!function({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}(f,i);const m=!h&&i.compile?i.compile.call(f.self,d,p,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&&!h||!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)},Ac.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)},Ac.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)}}},Ac}var qc,Vc={};var Fc={},Lc=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},Kc={exports:{}},Hc=Kc.exports=function(e,t,r){"function"==typeof t&&(r=t,t={}),Zc(t,"function"==typeof(r=t.cb||r)?r:r.pre||function(){},r.post||function(){},e,"",e)};function Zc(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 Hc.arrayKeywords)for(var p=0;p<d.length;p++)Zc(e,t,r,d[p],n+"/"+l+"/"+p,s,n,l,o,p)}else if(l in Hc.propsKeywords){if(d&&"object"==typeof d)for(var h in d)Zc(e,t,r,d[h],n+"/"+l+"/"+Gc(h),s,n,l,o,h)}else(l in Hc.keywords||e.allKeys&&!(l in Hc.skipKeywords))&&Zc(e,t,r,d,n+"/"+l,s,n,l,o)}r(o,n,s,a,i,c,u)}}function Gc(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}Hc.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},Hc.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},Hc.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},Hc.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 Jc=Kc.exports;Object.defineProperty(Fc,"__esModule",{value:!0}),Fc.getSchemaRefs=Fc.resolveUrl=Fc.normalizeId=Fc._getFullPath=Fc.getFullPath=Fc.inlineRef=void 0;const Wc=Wi,Bc=Lc,Qc=Jc,Yc=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);Fc.inlineRef=function(e,t=!0){return"boolean"==typeof e||(!0===t?!eu(e):!!t&&tu(e)<=t)};const Xc=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function eu(e){for(const t in e){if(Xc.has(t))return!0;const r=e[t];if(Array.isArray(r)&&r.some(eu))return!0;if("object"==typeof r&&eu(r))return!0}return!1}function tu(e){let t=0;for(const r in e){if("$ref"===r)return 1/0;if(t++,!Yc.has(r)&&("object"==typeof e[r]&&(0,Wc.eachItem)(e[r],e=>t+=tu(e)),t===1/0))return 1/0}return t}function ru(e,t="",r){!1!==r&&(t=su(t));const o=e.parse(t);return ou(e,o)}function ou(e,t){return e.serialize(t).split("#")[0]+"#"}Fc.getFullPath=ru,Fc._getFullPath=ou;const nu=/#\/?$/;function su(e){return e?e.replace(nu,""):""}Fc.normalizeId=su,Fc.resolveUrl=function(e,t,r){return r=su(r),e.resolve(t,r)};const au=/^[a-z_][-a-z0-9._]*$/i;var iu;function cu(){if(iu)return Ui;iu=1,Object.defineProperty(Ui,"__esModule",{value:!0}),Ui.getData=Ui.KeywordCxt=Ui.validateFunctionCode=void 0;const e=function(){if(lc)return Di;lc=1,Object.defineProperty(Di,"__esModule",{value:!0}),Di.boolOrEmptySchema=Di.topBoolOrEmptySchema=void 0;const e=hc(),t=Ji(),r=pc(),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 Di.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))},Di.boolOrEmptySchema=function(e,t){const{gen:r,schema:o}=e;!1===o?(r.var(t,!1),n(e)):r.var(t,!0)},Di}(),t=fc,r=_c(),o=fc,n=function(){if(jc)return Rc;jc=1,Object.defineProperty(Rc,"__esModule",{value:!0}),Rc.assignDefaults=void 0;const e=Ji(),t=Wi;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 Rc.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))},Rc}(),s=Dc(),a=function(){if(qc)return Vc;qc=1,Object.defineProperty(Vc,"__esModule",{value:!0}),Vc.extendSubschemaMode=Vc.extendSubschemaData=Vc.getSubschema=void 0;const e=Ji(),t=Wi;return Vc.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')},Vc.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)},Vc.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},Vc}(),i=Ji(),c=pc(),u=Fc,l=Wi,d=hc();function p({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"; ${h(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(h(r,n)).code(s))}function h(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:p,opts:h,self:f}=e,{RULES:m}=f;function y(l){(0,r.shouldUseGroup)(u,l)&&(l.type?(a.if((0,o.checkDataType)(l.type,d,h.strictNumbers)),$(e,l),1===t.length&&t[0]===l.type&&n&&(a.else(),(0,o.reportTypeError)(e)),a.endIf()):$(e,l),p||a.if(i._`${c.default.errors} === ${s||0}`))}!u.$ref||!h.ignoreKeywordsWithRef&&(0,l.schemaHasRulesButRef)(u,m)?(h.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)}Ui.validateFunctionCode=function(t){y(t)&&(g(t),m(t))?function(e){const{schema:t,opts:r,gen:o}=e;p(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):p(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",I(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)}Ui.KeywordCxt=S;const T=/^\/(?:[^~]|~0|~1)*$/,x=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function I(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=x.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 Ui.getData=I,Ui}Fc.getSchemaRefs=function(e,t){if("boolean"==typeof e)return{};const{schemaId:r,uriResolver:o}=this.opts,n=su(e[r]||t),s={"":n},a=ru(o,n,!1),i={},c=new Set;return Qc(e,{allKeys:!0},(e,t,o,n)=>{if(void 0===n)return;const d=a+t;let p=s[n];function h(t){const r=this.opts.uriResolver.resolve;if(t=su(p?r(p,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!==su(d)&&("#"===t[0]?(u(e,i[t],t),i[t]=e):this.refs[t]=d),t}function f(e){if("string"==typeof e){if(!au.test(e))throw new Error(`invalid anchor "${e}"`);h.call(this,`#${e}`)}}"string"==typeof e[r]&&(p=h.call(this,e[r])),f.call(this,e.$anchor),f.call(this,e.$dynamicAnchor),s[t]=p}),i;function u(e,t,r){if(void 0!==t&&!Bc(e,t))throw l(r)}function l(e){return new Error(`reference "${e}" resolves to more than one schema`)}};var uu,lu={};function du(){if(uu)return lu;uu=1,Object.defineProperty(lu,"__esModule",{value:!0});class e extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}}return lu.default=e,lu}var pu,hu={};function fu(){if(pu)return hu;pu=1,Object.defineProperty(hu,"__esModule",{value:!0});const e=Fc;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 hu.default=t,hu}var mu={};Object.defineProperty(mu,"__esModule",{value:!0}),mu.resolveSchema=mu.getCompilingSchema=mu.resolveRef=mu.compileSchema=mu.SchemaEnv=void 0;const yu=Ji(),gu=du(),vu=pc(),_u=Fc,wu=Wi,$u=cu();let bu=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,_u.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 ku(e){const t=Su.call(this,e);if(t)return t;const r=(0,_u.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:o,lines:n}=this.opts.code,{ownProperties:s}=this.opts,a=new yu.CodeGen(this.scope,{es5:o,lines:n,ownProperties:s});let i;e.$async&&(i=a.scopeValue("Error",{ref:gu.default,code:yu._`require("ajv/dist/runtime/validation_error").default`}));const c=a.scopeName("validate");e.validateName=c;const u={gen:a,allErrors:this.opts.allErrors,data:vu.default.data,parentData:vu.default.parentData,parentDataProperty:vu.default.parentDataProperty,dataNames:[vu.default.data],dataPathArr:[yu.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:a.scopeValue("schema",!0===this.opts.code.source?{ref:e.schema,code:(0,yu.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:i,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:yu.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:yu._`""`,opts:this.opts,self:this};let l;try{this._compilations.add(e),(0,$u.validateFunctionCode)(u),a.optimize(this.opts.code.optimize);const t=a.toString();l=`${a.scopeRefs(vu.default.scope)}return ${t}`,this.opts.code.process&&(l=this.opts.code.process(l,e));const r=new Function(`${vu.default.self}`,`${vu.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 yu.Name?void 0:e,items:t instanceof yu.Name?void 0:t,dynamicProps:e instanceof yu.Name,dynamicItems:t instanceof yu.Name},r.source&&(r.source.evaluated=(0,yu.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 Eu(e){return(0,_u.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:ku.call(this,e)}function Su(e){for(const t of this._compilations)if(Pu(t,e))return t}function Pu(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function Tu(e,t){let r;for(;"string"==typeof(r=this.refs[t]);)t=r;return r||this.schemas[t]||xu.call(this,e,t)}function xu(e,t){const r=this.opts.uriResolver.parse(t),o=(0,_u._getFullPath)(this.opts.uriResolver,r);let n=(0,_u.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&o===n)return Nu.call(this,r,e);const s=(0,_u.normalizeId)(o),a=this.refs[s]||this.schemas[s];if("string"==typeof a){const t=xu.call(this,e,a);if("object"!=typeof(null==t?void 0:t.schema))return;return Nu.call(this,r,t)}if("object"==typeof(null==a?void 0:a.schema)){if(a.validate||ku.call(this,a),s===(0,_u.normalizeId)(t)){const{schema:t}=a,{schemaId:r}=this.opts,o=t[r];return o&&(n=(0,_u.resolveUrl)(this.opts.uriResolver,n,o)),new bu({schema:t,schemaId:r,root:e,baseId:n})}return Nu.call(this,r,a)}}mu.SchemaEnv=bu,mu.compileSchema=ku,mu.resolveRef=function(e,t,r){var o;r=(0,_u.resolveUrl)(this.opts.uriResolver,t,r);const n=e.refs[r];if(n)return n;let s=Tu.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 bu({schema:n,schemaId:a,root:e,baseId:t}))}return void 0!==s?e.refs[r]=Eu.call(this,s):void 0},mu.getCompilingSchema=Su,mu.resolveSchema=xu;const Iu=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Nu(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,wu.unescapeFragment)(o)];if(void 0===e)return;const n="object"==typeof(r=e)&&r[this.opts.schemaId];!Iu.has(o)&&n&&(t=(0,_u.resolveUrl)(this.opts.uriResolver,t,n))}let s;if("boolean"!=typeof r&&r.$ref&&!(0,wu.schemaHasRulesButRef)(r,this.RULES)){const e=(0,_u.resolveUrl)(this.opts.uriResolver,t,r.$ref);s=xu.call(this,o,e)}const{schemaId:a}=this.opts;return s=s||new bu({schema:r,schemaId:a,root:o,baseId:t}),s.schema!==s.root.schema?s:void 0}var Cu={$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={},Ru={exports:{}};const Ou=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),zu=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 Au(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 Mu(e){return e.length=0,!0}function Uu(e,t,r){if(e.length){const o=Au(e);if(""===o)return r.error=!0,!1;t.push(o),e.length=0}return!0}function Du(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=Uu;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=Mu}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===Mu?r.zone=n.join(""):a?o.push(n.join("")):o.push(Au(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 qu={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(!zu(r)){const t=Du(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:zu,isUUID:Ou,normalizeIPv6:Du,stringArrayToHexStripped:Au};const{isUUID:Vu}=qu,Fu=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,Lu=["http","https","ws","wss","urn","urn:uuid"];function Ku(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 Hu(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function Zu(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 Gu={scheme:"http",domainHost:!0,parse:Hu,serialize:Zu},Ju={scheme:"ws",domainHost:!0,parse:function(e){return e.secure=Ku(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e},serialize:function(e){if(e.port!==(Ku(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}},Wu={http:Gu,https:{scheme:"https",domainHost:Gu.domainHost,parse:Hu,serialize:Zu},ws:Ju,wss:{scheme:"wss",domainHost:Ju.domainHost,parse:Ju.parse,serialize:Ju.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(Fu);if(r){const o=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];const n=Bu(`${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=Bu(`${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&&Vu(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 Bu(e){return e&&(Wu[e]||Wu[e.toLowerCase()])||void 0}Object.setPrototypeOf(Wu,null);var Qu={wsIsSecure:Ku,SCHEMES:Wu,isValidSchemeName:function(e){return-1!==Lu.indexOf(e)},getSchemeHandler:Bu};const{normalizeIPv6:Yu,removeDotSegments:Xu,recomposeAuthority:el,normalizeComponentEncoding:tl,isIPv4:rl,nonSimpleDomain:ol}=qu,{SCHEMES:nl,getSchemeHandler:sl}=Qu;function al(e,t,r,o){const n={};return o||(e=ul(il(e,r),r),t=ul(il(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=Xu(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=Xu(t.path||""),n.query=t.query):(t.path?("/"===t.path[0]?n.path=Xu(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=Xu(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 il(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=sl(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=el(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=Xu(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 cl=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function ul(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(cl);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===rl(o.host)){const e=Yu(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=sl(r.scheme||o.scheme);if(!(r.unicodeSupport||t&&t.unicodeSupport)&&o.host&&(r.domainHost||t&&t.domainHost)&&!1===n&&ol(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 ll={SCHEMES:nl,normalize:function(e,t){return"string"==typeof e?e=il(ul(e,t),t):"object"==typeof e&&(e=ul(il(e,t),t)),e},resolve:function(e,t,r){const o=r?Object.assign({scheme:"null"},r):{scheme:"null"},n=al(ul(e,o),ul(t,o),o,!0);return o.skipEscape=!0,il(n,o)},resolveComponent:al,equal:function(e,t,r){return"string"==typeof e?(e=unescape(e),e=il(tl(ul(e,r),!0),{...r,skipEscape:!0})):"object"==typeof e&&(e=il(tl(e,!0),{...r,skipEscape:!0})),"string"==typeof t?(t=unescape(t),t=il(tl(ul(t,r),!0),{...r,skipEscape:!0})):"object"==typeof t&&(t=il(tl(t,!0),{...r,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()},serialize:il,parse:ul};Ru.exports=ll,Ru.exports.default=ll,Ru.exports.fastUri=ll;var dl=Ru.exports;Object.defineProperty(ju,"__esModule",{value:!0});const pl=dl;pl.code='require("ajv/dist/runtime/uri").default',ju.default=pl,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=cu();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var r=Ji();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=du(),n=fu(),s=mc,a=mu,i=Ji(),c=Fc,u=fc,l=Wi,d=Cu,p=ju,h=(e,t)=>new RegExp(e,t);h.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 x=e.strict,I=null===(t=e.code)||void 0===t?void 0:t.optimize,N=!0===I||void 0===I?1:I||0,C=null!==(o=null===(r=e.code)||void 0===r?void 0:r.regExp)&&void 0!==o?o:h,j=null!==(n=e.uriResolver)&&void 0!==n?n:p.default;return{strictSchema:null===(a=null!==(s=e.strictSchema)&&void 0!==s?s:x)||void 0===a||a,strictNumbers:null===(c=null!==(i=e.strictNumbers)&&void 0!==i?i:x)||void 0===c||c,strictTypes:null!==(l=null!==(u=e.strictTypes)&&void 0!==u?u:x)&&void 0!==l?l:"log",strictTuples:null!==(f=null!==(d=e.strictTuples)&&void 0!==d?d:x)&&void 0!==f?f:"log",strictRequired:null!==(y=null!==(m=e.strictRequired)&&void 0!==m?m:x)&&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(x.call(this,r,t),!t)return(0,l.eachItem)(r,e=>I.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=>I.call(this,e,o):e=>o.type.forEach(t=>I.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 x(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 I(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]}}}(Mi);var hl={},fl={},ml={};Object.defineProperty(ml,"__esModule",{value:!0});const yl={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};ml.default=yl;var gl={};Object.defineProperty(gl,"__esModule",{value:!0}),gl.callRef=gl.getValidate=void 0;const vl=fu(),_l=Uc(),wl=Ji(),$l=pc(),bl=mu,kl=Wi,El={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 Pl(e,a,s,s.$async);const r=t.scopeValue("root",{ref:u});return Pl(e,wl._`${r}.validate`,u,u.$async)}();const l=bl.resolveRef.call(c,u,n,r);if(void 0===l)throw new vl.default(o.opts.uriResolver,n,r);return l instanceof bl.SchemaEnv?function(t){const r=Sl(e,t);Pl(e,r,t,t.$async)}(l):function(o){const n=t.scopeValue("schema",!0===i.code.source?{ref:o,code:(0,wl.stringify)(o)}:{ref:o}),s=t.name("valid"),a=e.subschema({schema:o,dataTypes:[],schemaPath:wl.nil,topSchemaRef:n,errSchemaPath:r},s);e.mergeEvaluated(a),e.ok(s)}(l)}};function Sl(e,t){const{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):wl._`${r.scopeValue("wrapper",{ref:t})}.validate`}function Pl(e,t,r,o){const{gen:n,it:s}=e,{allErrors:a,schemaEnv:i,opts:c}=s,u=c.passContext?$l.default.this:wl.nil;function l(e){const t=wl._`${e}.errors`;n.assign($l.default.vErrors,wl._`${$l.default.vErrors} === null ? ${t} : ${$l.default.vErrors}.concat(${t})`),n.assign($l.default.errors,wl._`${$l.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=kl.mergeEvaluated.props(n,o.props,s.props));else{const t=n.var("props",wl._`${e}.evaluated.props`);s.props=kl.mergeEvaluated.props(n,t,s.props,wl.Name)}if(!0!==s.items)if(o&&!o.dynamicItems)void 0!==o.items&&(s.items=kl.mergeEvaluated.items(n,o.items,s.items));else{const t=n.var("items",wl._`${e}.evaluated.items`);s.items=kl.mergeEvaluated.items(n,t,s.items,wl.Name)}}o?function(){if(!i.$async)throw new Error("async schema referenced by sync schema");const r=n.let("valid");n.try(()=>{n.code(wl._`await ${(0,_l.callValidateCode)(e,t,u)}`),d(t),a||n.assign(r,!0)},e=>{n.if(wl._`!(${e} instanceof ${s.ValidationError})`,()=>n.throw(e)),l(e),a||n.assign(r,!1)}),e.ok(r)}():e.result((0,_l.callValidateCode)(e,t,u),()=>d(t),()=>l(t))}gl.getValidate=Sl,gl.callRef=Pl,gl.default=El,Object.defineProperty(fl,"__esModule",{value:!0});const Tl=gl,xl=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",ml.default,Tl.default];fl.default=xl;var Il={},Nl={};Object.defineProperty(Nl,"__esModule",{value:!0});const Cl=Ji(),jl=Cl.operators,Rl={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}},Ol={message:({keyword:e,schemaCode:t})=>Cl.str`must be ${Rl[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>Cl._`{comparison: ${Rl[e].okStr}, limit: ${t}}`},zl={keyword:Object.keys(Rl),type:"number",schemaType:"number",$data:!0,error:Ol,code(e){const{keyword:t,data:r,schemaCode:o}=e;e.fail$data(Cl._`${r} ${Rl[t].fail} ${o} || isNaN(${r})`)}};Nl.default=zl;var Al={};Object.defineProperty(Al,"__esModule",{value:!0});const Ml=Ji(),Ul={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:e})=>Ml.str`must be multiple of ${e}`,params:({schemaCode:e})=>Ml._`{multipleOf: ${e}}`},code(e){const{gen:t,data:r,schemaCode:o,it:n}=e,s=n.opts.multipleOfPrecision,a=t.let("res"),i=s?Ml._`Math.abs(Math.round(${a}) - ${a}) > 1e-${s}`:Ml._`${a} !== parseInt(${a})`;e.fail$data(Ml._`(${o} === 0 || (${a} = ${r}/${o}, ${i}))`)}};Al.default=Ul;var Dl={},ql={};function Vl(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(ql,"__esModule",{value:!0}),ql.default=Vl,Vl.code='require("ajv/dist/runtime/ucs2length").default',Object.defineProperty(Dl,"__esModule",{value:!0});const Fl=Ji(),Ll=Wi,Kl=ql,Hl={message({keyword:e,schemaCode:t}){const r="maxLength"===e?"more":"fewer";return Fl.str`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>Fl._`{limit: ${e}}`},Zl={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:Hl,code(e){const{keyword:t,data:r,schemaCode:o,it:n}=e,s="maxLength"===t?Fl.operators.GT:Fl.operators.LT,a=!1===n.opts.unicode?Fl._`${r}.length`:Fl._`${(0,Ll.useFunc)(e.gen,Kl.default)}(${r})`;e.fail$data(Fl._`${a} ${s} ${o}`)}};Dl.default=Zl;var Gl={};Object.defineProperty(Gl,"__esModule",{value:!0});const Jl=Uc(),Wl=Wi,Bl=Ji(),Ql={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>Bl.str`must match pattern "${e}"`,params:({schemaCode:e})=>Bl._`{pattern: ${e}}`},code(e){const{gen:t,data:r,$data:o,schema:n,schemaCode:s,it:a}=e,i=a.opts.unicodeRegExp?"u":"";if(o){const{regExp:o}=a.opts.code,n="new RegExp"===o.code?Bl._`new RegExp`:(0,Wl.useFunc)(t,o),c=t.let("valid");t.try(()=>t.assign(c,Bl._`${n}(${s}, ${i}).test(${r})`),()=>t.assign(c,!1)),e.fail$data(Bl._`!${c}`)}else{const t=(0,Jl.usePattern)(e,n);e.fail$data(Bl._`!${t}.test(${r})`)}}};Gl.default=Ql;var Yl={};Object.defineProperty(Yl,"__esModule",{value:!0});const Xl=Ji(),ed={message({keyword:e,schemaCode:t}){const r="maxProperties"===e?"more":"fewer";return Xl.str`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>Xl._`{limit: ${e}}`},td={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:ed,code(e){const{keyword:t,data:r,schemaCode:o}=e,n="maxProperties"===t?Xl.operators.GT:Xl.operators.LT;e.fail$data(Xl._`Object.keys(${r}).length ${n} ${o}`)}};Yl.default=td;var rd={};Object.defineProperty(rd,"__esModule",{value:!0});const od=Uc(),nd=Ji(),sd=Wi,ad={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:e}})=>nd.str`must have required property '${e}'`,params:({params:{missingProperty:e}})=>nd._`{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(nd.nil,u);else for(const t of r)(0,od.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,od.propertyInData)(t,n,r,i.ownProperties)),t.if((0,nd.not)(s),()=>{e.error(),t.break()})},nd.nil)}(a,r)),e.ok(r)}else t.if((0,od.checkMissingProp)(e,r,a)),(0,od.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,sd.checkStrictMode)(a,t,a.opts.strictRequired)}}function u(){t.forOf("prop",o,r=>{e.setParams({missingProperty:r}),t.if((0,od.noPropertyInData)(t,n,r,i.ownProperties),()=>e.error())})}}};rd.default=ad;var id={};Object.defineProperty(id,"__esModule",{value:!0});const cd=Ji(),ud={message({keyword:e,schemaCode:t}){const r="maxItems"===e?"more":"fewer";return cd.str`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>cd._`{limit: ${e}}`},ld={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:ud,code(e){const{keyword:t,data:r,schemaCode:o}=e,n="maxItems"===t?cd.operators.GT:cd.operators.LT;e.fail$data(cd._`${r}.length ${n} ${o}`)}};id.default=ld;var dd={},pd={};Object.defineProperty(pd,"__esModule",{value:!0});const hd=Lc;hd.code='require("ajv/dist/runtime/equal").default',pd.default=hd,Object.defineProperty(dd,"__esModule",{value:!0});const fd=fc,md=Ji(),yd=Wi,gd=pd,vd={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:e,j:t}})=>md.str`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>md._`{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,fd.getSchemaTypes)(s.items):[];function l(o,n){const s=t.name("item"),a=(0,fd.checkDataTypes)(u,s,i.opts.strictNumbers,fd.DataType.Wrong),l=t.const("indices",md._`{}`);t.for(md._`;${o}--;`,()=>{t.let(s,md._`${r}[${o}]`),t.if(a,md._`continue`),u.length>1&&t.if(md._`typeof ${s} == "string"`,md._`${s} += "_"`),t.if(md._`typeof ${l}[${s}] == "number"`,()=>{t.assign(n,md._`${l}[${s}]`),e.error(),t.assign(c,!1).break()}).code(md._`${l}[${s}] = ${o}`)})}function d(o,n){const s=(0,yd.useFunc)(t,gd.default),a=t.name("outer");t.label(a).for(md._`;${o}--;`,()=>t.for(md._`${n} = ${o}; ${n}--;`,()=>t.if(md._`${s}(${r}[${o}], ${r}[${n}])`,()=>{e.error(),t.assign(c,!1).break(a)})))}e.block$data(c,function(){const o=t.let("i",md._`${r}.length`),n=t.let("j");e.setParams({i:o,j:n}),t.assign(c,!0),t.if(md._`${o} > 1`,()=>(u.length>0&&!u.some(e=>"object"===e||"array"===e)?l:d)(o,n))},md._`${a} === false`),e.ok(c)}};dd.default=vd;var _d={};Object.defineProperty(_d,"__esModule",{value:!0});const wd=Ji(),$d=Wi,bd=pd,kd={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:e})=>wd._`{allowedValue: ${e}}`},code(e){const{gen:t,data:r,$data:o,schemaCode:n,schema:s}=e;o||s&&"object"==typeof s?e.fail$data(wd._`!${(0,$d.useFunc)(t,bd.default)}(${r}, ${n})`):e.fail(wd._`${s} !== ${r}`)}};_d.default=kd;var Ed={};Object.defineProperty(Ed,"__esModule",{value:!0});const Sd=Ji(),Pd=Wi,Td=pd,xd={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:e})=>Sd._`{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,Pd.useFunc)(t,Td.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(Sd._`${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,Sd.or)(...n.map((t,o)=>function(e,t){const o=n[t];return"object"==typeof o&&null!==o?Sd._`${u()}(${r}, ${e}[${t}])`:Sd._`${r} === ${o}`}(e,o)))}e.pass(l)}};Ed.default=xd,Object.defineProperty(Il,"__esModule",{value:!0});const Id=Al,Nd=Dl,Cd=Gl,jd=Yl,Rd=rd,Od=id,zd=dd,Ad=_d,Md=Ed,Ud=[Nl.default,Id.default,Nd.default,Cd.default,jd.default,Rd.default,Od.default,zd.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Ad.default,Md.default];Il.default=Ud;var Dd={},qd={};Object.defineProperty(qd,"__esModule",{value:!0}),qd.validateAdditionalItems=void 0;const Vd=Ji(),Fd=Wi,Ld={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:e}})=>Vd.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>Vd._`{limit: ${e}}`},code(e){const{parentSchema:t,it:r}=e,{items:o}=t;Array.isArray(o)?Kd(e,o):(0,Fd.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas')}};function Kd(e,t){const{gen:r,schema:o,data:n,keyword:s,it:a}=e;a.items=!0;const i=r.const("len",Vd._`${n}.length`);if(!1===o)e.setParams({len:t.length}),e.pass(Vd._`${i} <= ${t.length}`);else if("object"==typeof o&&!(0,Fd.alwaysValidSchema)(a,o)){const o=r.var("valid",Vd._`${i} <= ${t.length}`);r.if((0,Vd.not)(o),()=>function(o){r.forRange("i",t.length,i,t=>{e.subschema({keyword:s,dataProp:t,dataPropType:Fd.Type.Num},o),a.allErrors||r.if((0,Vd.not)(o),()=>r.break())})}(o)),e.ok(o)}}qd.validateAdditionalItems=Kd,qd.default=Ld;var Hd={},Zd={};Object.defineProperty(Zd,"__esModule",{value:!0}),Zd.validateTuple=void 0;const Gd=Ji(),Jd=Wi,Wd=Uc(),Bd={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){const{schema:t,it:r}=e;if(Array.isArray(t))return Qd(e,"additionalItems",t);r.items=!0,(0,Jd.alwaysValidSchema)(r,t)||e.ok((0,Wd.validateArray)(e))}};function Qd(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,Jd.checkStrictMode)(i,e,o.strictTuples)}}(n),i.opts.unevaluated&&r.length&&!0!==i.items&&(i.items=Jd.mergeEvaluated.items(o,r.length,i.items));const c=o.name("valid"),u=o.const("len",Gd._`${s}.length`);r.forEach((t,r)=>{(0,Jd.alwaysValidSchema)(i,t)||(o.if(Gd._`${u} > ${r}`,()=>e.subschema({keyword:a,schemaProp:r,dataProp:r},c)),e.ok(c))})}Zd.validateTuple=Qd,Zd.default=Bd,Object.defineProperty(Hd,"__esModule",{value:!0});const Yd=Zd,Xd={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,Yd.validateTuple)(e,"items")};Hd.default=Xd;var ep={};Object.defineProperty(ep,"__esModule",{value:!0});const tp=Ji(),rp=Wi,op=Uc(),np=qd,sp={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:e}})=>tp.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>tp._`{limit: ${e}}`},code(e){const{schema:t,parentSchema:r,it:o}=e,{prefixItems:n}=r;o.items=!0,(0,rp.alwaysValidSchema)(o,t)||(n?(0,np.validateAdditionalItems)(e,n):e.ok((0,op.validateArray)(e)))}};ep.default=sp;var ap={};Object.defineProperty(ap,"__esModule",{value:!0});const ip=Ji(),cp=Wi,up={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:e,max:t}})=>void 0===t?ip.str`must contain at least ${e} valid item(s)`:ip.str`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>void 0===t?ip._`{minContains: ${e}}`:ip._`{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",ip._`${n}.length`);if(e.setParams({min:a,max:i}),void 0===i&&0===a)return void(0,cp.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');if(void 0!==i&&a>i)return(0,cp.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),void e.fail();if((0,cp.alwaysValidSchema)(s,r)){let t=ip._`${l} >= ${a}`;return void 0!==i&&(t=ip._`${t} && ${l} <= ${i}`),void e.pass(t)}s.items=!0;const d=t.name("valid");function p(){const e=t.name("_valid"),r=t.let("count",0);h(e,()=>t.if(e,()=>function(e){t.code(ip._`${e}++`),void 0===i?t.if(ip._`${e} >= ${a}`,()=>t.assign(d,!0).break()):(t.if(ip._`${e} > ${i}`,()=>t.assign(d,!1).break()),1===a?t.assign(d,!0):t.if(ip._`${e} >= ${a}`,()=>t.assign(d,!0)))}(r)))}function h(r,o){t.forRange("i",0,l,t=>{e.subschema({keyword:"contains",dataProp:t,dataPropType:cp.Type.Num,compositeRule:!0},r),o()})}void 0===i&&1===a?h(d,()=>t.if(d,()=>t.break())):0===a?(t.let(d,!0),void 0!==i&&t.if(ip._`${n}.length > 0`,p)):(t.let(d,!1),p()),e.result(d,()=>e.reset())}};ap.default=up;var lp={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=Ji(),r=Wi,o=Uc();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
5
|
missingProperty: ${n},
|
|
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}(ip);var cp={};Object.defineProperty(cp,"__esModule",{value:!0});const up=Zi(),lp=Gi,dp={message:"property name must be valid",params:({params:e})=>up._`{propertyName: ${e.propertyName}}`},pp={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:dp,code(e){const{gen:t,schema:r,data:o,it:n}=e;if((0,lp.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,up.not)(s),()=>{e.error(!0),n.allErrors||t.break()})}),e.ok(s)}};cp.default=pp;var hp={};Object.defineProperty(hp,"__esModule",{value:!0});const fp=Ac(),mp=Zi(),yp=lc(),gp=Gi,vp={message:"must NOT have additional properties",params:({params:e})=>mp._`{additionalProperty: ${e.additionalProperty}}`},_p={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:vp,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,gp.alwaysValidSchema)(a,r))return;const u=(0,fp.allSchemaProperties)(o.properties),l=(0,fp.allSchemaProperties)(o.patternProperties);function d(e){t.code(mp._`delete ${n}[${e}]`)}function p(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,gp.alwaysValidSchema)(a,r)){const r=t.name("valid");"failing"===c.removeAdditional?(h(o,r,!1),t.if((0,mp.not)(r),()=>{e.reset(),d(o)})):(h(o,r),i||t.if((0,mp.not)(r),()=>t.break()))}}}function h(t,r,o){const n={keyword:"additionalProperties",dataProp:t,dataPropType:gp.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,gp.schemaRefOrVal)(a,o.properties,"properties");n=(0,fp.isOwnProperty)(t,e,r)}else n=u.length?(0,mp.or)(...u.map(e=>mp._`${r} === ${e}`)):mp.nil;return l.length&&(n=(0,mp.or)(n,...l.map(t=>mp._`${(0,fp.usePattern)(e,t)}.test(${r})`))),(0,mp.not)(n)}(r),()=>p(r)):p(r)}),e.ok(mp._`${s} === ${yp.default.errors}`)}};hp.default=_p;var wp={};Object.defineProperty(wp,"__esModule",{value:!0});const $p=au(),bp=Ac(),kp=Gi,Ep=hp,Sp={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&&Ep.default.code(new $p.KeywordCxt(s,Ep.default,"additionalProperties"));const a=(0,bp.allSchemaProperties)(r);for(const e of a)s.definedProperties.add(e);s.opts.unevaluated&&a.length&&!0!==s.props&&(s.props=kp.mergeEvaluated.props(t,(0,kp.toHash)(a),s.props));const i=a.filter(e=>!(0,kp.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,bp.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)}}};wp.default=Sp;var Pp={};Object.defineProperty(Pp,"__esModule",{value:!0});const Tp=Ac(),xp=Zi(),Ip=Gi,Np=Gi,Cp={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,Tp.allSchemaProperties)(r),c=i.filter(e=>(0,Ip.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 xp.Name||(s.props=(0,Np.evaluatedPropsToName)(t,s.props));const{props:d}=s;function p(e){for(const t in u)new RegExp(e).test(t)&&(0,Ip.checkStrictMode)(s,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function h(r){t.forIn("key",o,o=>{t.if(xp._`${(0,Tp.usePattern)(e,r)}.test(${o})`,()=>{const n=c.includes(r);n||e.subschema({keyword:"patternProperties",schemaProp:r,dataProp:o,dataPropType:Np.Type.Str},l),s.opts.unevaluated&&!0!==d?t.assign(xp._`${d}[${o}]`,!0):n||s.allErrors||t.if((0,xp.not)(l),()=>t.break())})})}!function(){for(const e of i)u&&p(e),s.allErrors?h(e):(t.var(l,!0),h(e),t.if(l))}()}};Pp.default=Cp;var jp={};Object.defineProperty(jp,"__esModule",{value:!0});const Rp=Gi,Op={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){const{gen:t,schema:r,it:o}=e;if((0,Rp.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"}};jp.default=Op;var zp={};Object.defineProperty(zp,"__esModule",{value:!0});const Ap={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Ac().validateUnion,error:{message:"must match a schema in anyOf"}};zp.default=Ap;var Mp={};Object.defineProperty(Mp,"__esModule",{value:!0});const Up=Zi(),Dp=Gi,qp={message:"must match exactly one schema in oneOf",params:({params:e})=>Up._`{passingSchemas: ${e.passing}}`},Vp={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:qp,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,Dp.alwaysValidSchema)(n,r)?t.var(c,!0):s=e.subschema({keyword:"oneOf",schemaProp:o,compositeRule:!0},c),o>0&&t.if(Up._`${c} && ${a}`).assign(a,!1).assign(i,Up._`[${i}, ${o}]`).else(),t.if(c,()=>{t.assign(a,!0),t.assign(i,o),s&&e.mergeEvaluated(s,Up.Name)})})}),e.result(a,()=>e.reset(),()=>e.error(!0))}};Mp.default=Vp;var Fp={};Object.defineProperty(Fp,"__esModule",{value:!0});const Lp=Gi,Kp={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,Lp.alwaysValidSchema)(o,t))return;const s=e.subschema({keyword:"allOf",schemaProp:r},n);e.ok(n),e.mergeEvaluated(s)})}};Fp.default=Kp;var Hp={};Object.defineProperty(Hp,"__esModule",{value:!0});const Zp=Zi(),Gp=Gi,Jp={message:({params:e})=>Zp.str`must match "${e.ifClause}" schema`,params:({params:e})=>Zp._`{failingKeyword: ${e.ifClause}}`},Wp={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:Jp,code(e){const{gen:t,parentSchema:r,it:o}=e;void 0===r.then&&void 0===r.else&&(0,Gp.checkStrictMode)(o,'"if" without "then" and "else" is ignored');const n=Bp(o,"then"),s=Bp(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,Zp.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,Zp._`${r}`):e.setParams({ifClause:r})}}e.pass(a,()=>e.error(!0))}};function Bp(e,t){const r=e.schema[t];return void 0!==r&&!(0,Gp.alwaysValidSchema)(e,r)}Hp.default=Wp;var Qp={};Object.defineProperty(Qp,"__esModule",{value:!0});const Yp=Gi,Xp={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){void 0===t.if&&(0,Yp.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};Qp.default=Xp,Object.defineProperty(Ad,"__esModule",{value:!0});const eh=Md,th=Fd,rh=Ld,oh=Qd,nh=op,sh=ip,ah=cp,ih=hp,ch=wp,uh=Pp,lh=jp,dh=zp,ph=Mp,hh=Fp,fh=Hp,mh=Qp;Ad.default=function(e=!1){const t=[lh.default,dh.default,ph.default,hh.default,fh.default,mh.default,ah.default,ih.default,sh.default,ch.default,uh.default];return e?t.push(th.default,oh.default):t.push(eh.default,rh.default),t.push(nh.default),t};var yh={},gh={};Object.defineProperty(gh,"__esModule",{value:!0});const vh=Zi(),_h={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>vh.str`must match format "${e}"`,params:({schemaCode:e})=>vh._`{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",vh._`${n}[${a}]`),i=r.let("fType"),u=r.let("format");r.if(vh._`typeof ${s} == "object" && !(${s} instanceof RegExp)`,()=>r.assign(i,vh._`${s}.type || "string"`).assign(u,vh._`${s}.validate`),()=>r.assign(i,vh._`"string"`).assign(u,s)),e.fail$data((0,vh.or)(!1===c.strictSchema?vh.nil:vh._`${a} && !${u}`,function(){const e=l.$async?vh._`(${s}.async ? await ${u}(${o}) : ${u}(${o}))`:vh._`${u}(${o})`,r=vh._`(typeof ${u} == "function" ? ${e} : ${u}.test(${o}))`;return vh._`${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,p]=function(e){const t=e instanceof RegExp?(0,vh.regexpCode)(e):c.code.formats?vh._`${c.code.formats}${(0,vh.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,vh._`${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 vh._`await ${p}(${o})`}return"function"==typeof i?vh._`${p}(${o})`:vh._`${p}.test(${o})`}())}())}};gh.default=_h,Object.defineProperty(yh,"__esModule",{value:!0});const wh=[gh.default];yh.default=wh;var $h={};Object.defineProperty($h,"__esModule",{value:!0}),$h.contentVocabulary=$h.metadataVocabulary=void 0,$h.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],$h.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"],Object.defineProperty(dl,"__esModule",{value:!0});const bh=Tl,kh=Ad,Eh=yh,Sh=$h,Ph=[pl.default,bh.default,(0,kh.default)(),Eh.default,Sh.metadataVocabulary,Sh.contentVocabulary];dl.default=Ph;var Th,xh={},Ih={};Object.defineProperty(Ih,"__esModule",{value:!0}),Ih.DiscrError=void 0,function(e){e.Tag="tag",e.Mapping="mapping"}(Th||(Ih.DiscrError=Th={})),Object.defineProperty(xh,"__esModule",{value:!0});const Nh=Zi(),Ch=Ih,jh=hu,Rh=pu(),Oh=Gi,zh={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:e,tagName:t}})=>e===Ch.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>Nh._`{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",Nh._`${r}${(0,Nh.getProperty)(i)}`);function l(r){const o=t.name("valid"),n=e.subschema({keyword:"oneOf",schemaProp:r},o);return e.mergeEvaluated(n,Nh.Name),o}t.if(Nh._`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,Oh.schemaHasRulesButRef)(n,s.self.RULES)){const e=n.$ref;if(n=jh.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,e),n instanceof jh.SchemaEnv&&(n=n.schema),void 0===n)throw new Rh.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(Nh._`${u} === ${e}`),t.assign(c,l(r[e]));t.else(),e.error(!1,{discrError:Ch.DiscrError.Mapping,tag:u,tagName:i}),t.endIf()}(),()=>e.error(!1,{discrError:Ch.DiscrError.Tag,tag:u,tagName:i})),e.ok(c)}};xh.default=zh;var Ah={$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=zi,o=dl,n=xh,s=Ah,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=au();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return u.KeywordCxt}});var l=Zi();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=uu();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return d.default}});var p=pu();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return p.default}})}(Oi,Oi.exports);var Mh=ji(Oi.exports),Uh={exports:{}},Dh={};!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),p),"iso-time":t(i(),u),"iso-date-time":t(d(),h),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,p),"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,h),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,p=o-u*c-(d<0?1:0);return(23===p||-1===p)&&(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 p(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 h(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/}(Dh);var qh={},Vh={exports:{}},Fh={},Lh={},Kh={},Hh={},Zh={},Gh={};!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())}}(Gh);var Jh={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=Gh;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}}}(Jh),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=Gh,r=Jh;var o=Gh;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=Jh;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=I(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=I(this.rhs,e,r),this}get names(){return x(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 p 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=I(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class h 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 h{render(e){return"{"+e._n+super.render(e)+"}"+e._n}}class m extends h{}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=I(this.condition,e,t),this}get names(){const e=super.names;return x(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=I(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=x(super.names,this.from);return x(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=I(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 h{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 x(e,r){return r instanceof t._CodeOrName?T(e,r.names):e}function I(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 p(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)}}(Zh);var Wh={};Object.defineProperty(Wh,"__esModule",{value:!0}),Wh.checkStrictMode=Wh.getErrorPath=Wh.Type=Wh.useFunc=Wh.setEvaluated=Wh.evaluatedPropsToName=Wh.mergeEvaluated=Wh.eachItem=Wh.unescapeJsonPointer=Wh.escapeJsonPointer=Wh.escapeFragment=Wh.unescapeFragment=Wh.schemaRefOrVal=Wh.schemaHasRulesButRef=Wh.schemaHasRules=Wh.checkUnknownRules=Wh.alwaysValidSchema=Wh.toHash=void 0;const Bh=Zh,Qh=Gh;function Yh(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]||cf(e,`unknown keyword: "${r}"`)}function Xh(e,t){if("boolean"==typeof e)return!e;for(const r in e)if(t[r])return!0;return!1}function ef(e){return"number"==typeof e?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}function tf(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function rf({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:o}){return(n,s,a,i)=>{const c=void 0===a?s:a instanceof Bh.Name?(s instanceof Bh.Name?e(n,s,a):t(n,s,a),a):s instanceof Bh.Name?(t(n,a,s),s):r(s,a);return i!==Bh.Name||c instanceof Bh.Name?c:o(n,c)}}function of(e,t){if(!0===t)return e.var("props",!0);const r=e.var("props",Bh._`{}`);return void 0!==t&&nf(e,r,t),r}function nf(e,t,r){Object.keys(r).forEach(r=>e.assign(Bh._`${t}${(0,Bh.getProperty)(r)}`,!0))}Wh.toHash=function(e){const t={};for(const r of e)t[r]=!0;return t},Wh.alwaysValidSchema=function(e,t){return"boolean"==typeof t?t:0===Object.keys(t).length||(Yh(e,t),!Xh(t,e.self.RULES.all))},Wh.checkUnknownRules=Yh,Wh.schemaHasRules=Xh,Wh.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},Wh.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 Bh._`${r}`}return Bh._`${e}${t}${(0,Bh.getProperty)(o)}`},Wh.unescapeFragment=function(e){return tf(decodeURIComponent(e))},Wh.escapeFragment=function(e){return encodeURIComponent(ef(e))},Wh.escapeJsonPointer=ef,Wh.unescapeJsonPointer=tf,Wh.eachItem=function(e,t){if(Array.isArray(e))for(const r of e)t(r);else t(e)},Wh.mergeEvaluated={props:rf({mergeNames:(e,t,r)=>e.if(Bh._`${r} !== true && ${t} !== undefined`,()=>{e.if(Bh._`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,Bh._`${r} || {}`).code(Bh._`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if(Bh._`${r} !== true`,()=>{!0===t?e.assign(r,!0):(e.assign(r,Bh._`${r} || {}`),nf(e,r,t))}),mergeValues:(e,t)=>!0===e||{...e,...t},resultToName:of}),items:rf({mergeNames:(e,t,r)=>e.if(Bh._`${r} !== true && ${t} !== undefined`,()=>e.assign(r,Bh._`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if(Bh._`${r} !== true`,()=>e.assign(r,!0===t||Bh._`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>!0===e||Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})},Wh.evaluatedPropsToName=of,Wh.setEvaluated=nf;const sf={};var af;function cf(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,!0===r)throw new Error(t);e.self.logger.warn(t)}}Wh.useFunc=function(e,t){return e.scopeValue("func",{ref:t,code:sf[t.code]||(sf[t.code]=new Qh._Code(t.code))})},function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"}(af||(Wh.Type=af={})),Wh.getErrorPath=function(e,t,r){if(e instanceof Bh.Name){const o=t===af.Num;return r?o?Bh._`"[" + ${e} + "]"`:Bh._`"['" + ${e} + "']"`:o?Bh._`"/" + ${e}`:Bh._`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,Bh.getProperty)(e).toString():"/"+ef(e)},Wh.checkStrictMode=cf;var uf,lf,df,pf={};function hf(){if(uf)return pf;uf=1,Object.defineProperty(pf,"__esModule",{value:!0});const e=Zh,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 pf.default=t,pf}function ff(){return lf||(lf=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=Zh,r=Wh,o=hf();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:p}=u,h=i(r,o,a);(null!=c?c:d||p)?n(l,h):s(u,t._`[${h}]`)},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:p,topSchemaRef:h,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._`${h}${f}`],[o.default.data,c]);p&&s.push([a.propertyName,p])}(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]}}(Hh)),Hh}var mf={},yf={};Object.defineProperty(yf,"__esModule",{value:!0}),yf.getRules=yf.isJSONType=void 0;const gf=new Set(["string","number","integer","boolean","null","object","array"]);yf.isJSONType=function(e){return"string"==typeof e&&gf.has(e)},yf.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 vf,_f={};function wf(){if(vf)return _f;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 vf=1,Object.defineProperty(_f,"__esModule",{value:!0}),_f.shouldUseRule=_f.shouldUseGroup=_f.schemaHasRulesForType=void 0,_f.schemaHasRulesForType=function({schema:t,self:r},o){const n=r.RULES.types[o];return n&&!0!==n&&e(t,n)},_f.shouldUseGroup=e,_f.shouldUseRule=t,_f}Object.defineProperty(mf,"__esModule",{value:!0}),mf.reportTypeError=mf.checkDataTypes=mf.checkDataType=mf.coerceAndCheckDataType=mf.getJSONTypes=mf.getSchemaTypes=mf.DataType=void 0;const $f=yf,bf=wf(),kf=ff(),Ef=Zh,Sf=Wh;var Pf;function Tf(e){const t=Array.isArray(e)?e:e?[e]:[];if(t.every($f.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"}(Pf||(mf.DataType=Pf={})),mf.getSchemaTypes=function(e){const t=Tf(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},mf.getJSONTypes=Tf,mf.coerceAndCheckDataType=function(e,t){const{gen:r,data:o,opts:n}=e,s=function(e,t){return t?e.filter(e=>xf.has(e)||"array"===t&&"array"===e):[]}(t,n.coerceTypes),a=t.length>0&&!(0===s.length&&1===t.length&&(0,bf.schemaHasRulesForType)(e,t[0]));if(a){const a=Nf(t,o,n.strictNumbers,Pf.Wrong);r.if(a,()=>{s.length?function(e,t,r){const{gen:o,data:n,opts:s}=e,a=o.let("dataType",Ef._`typeof ${n}`),i=o.let("coerced",Ef._`undefined`);"array"===s.coerceTypes&&o.if(Ef._`${a} == 'object' && Array.isArray(${n}) && ${n}.length == 1`,()=>o.assign(n,Ef._`${n}[0]`).assign(a,Ef._`typeof ${n}`).if(Nf(t,n,s.strictNumbers),()=>o.assign(i,n)));o.if(Ef._`${i} !== undefined`);for(const e of r)(xf.has(e)||"array"===e&&"array"===s.coerceTypes)&&c(e);function c(e){switch(e){case"string":return void o.elseIf(Ef._`${a} == "number" || ${a} == "boolean"`).assign(i,Ef._`"" + ${n}`).elseIf(Ef._`${n} === null`).assign(i,Ef._`""`);case"number":return void o.elseIf(Ef._`${a} == "boolean" || ${n} === null
|
|
8
|
-
|| (${a} == "string" && ${n} && ${n} == +${n})`).assign(i,
|
|
9
|
-
|| (${a} === "string" && ${n} && ${n} == +${n} && !(${n} % 1))`).assign(i,
|
|
10
|
-
|| ${a} === "boolean" || ${n} === null`).assign(i,Ef._`[${n}]`)}}o.else(),jf(e),o.endIf(),o.if(Ef._`${i} !== undefined`,()=>{o.assign(n,i),function({gen:e,parentData:t,parentDataProperty:r},o){e.if(Ef._`${t} !== undefined`,()=>e.assign(Ef._`${t}[${r}]`,o))}(e,i)})}(e,t,s):jf(e)})}return a};const xf=new Set(["string","number","integer","boolean","null"]);function If(e,t,r,o=Pf.Correct){const n=o===Pf.Correct?Ef.operators.EQ:Ef.operators.NEQ;let s;switch(e){case"null":return Ef._`${t} ${n} null`;case"array":s=Ef._`Array.isArray(${t})`;break;case"object":s=Ef._`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":s=a(Ef._`!(${t} % 1) && !isNaN(${t})`);break;case"number":s=a();break;default:return Ef._`typeof ${t} ${n} ${e}`}return o===Pf.Correct?s:(0,Ef.not)(s);function a(e=Ef.nil){return(0,Ef.and)(Ef._`typeof ${t} == "number"`,e,r?Ef._`isFinite(${t})`:Ef.nil)}}function Nf(e,t,r,o){if(1===e.length)return If(e[0],t,r,o);let n;const s=(0,Sf.toHash)(e);if(s.array&&s.object){const e=Ef._`typeof ${t} != "object"`;n=s.null?e:Ef._`!${t} || ${e}`,delete s.null,delete s.array,delete s.object}else n=Ef.nil;s.number&&delete s.integer;for(const e in s)n=(0,Ef.and)(n,If(e,t,r,o));return n}mf.checkDataType=If,mf.checkDataTypes=Nf;const Cf={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>"string"==typeof e?Ef._`{type: ${e}}`:Ef._`{type: ${t}}`};function jf(e){const t=function(e){const{gen:t,data:r,schema:o}=e,n=(0,Sf.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,kf.reportError)(t,Cf)}mf.reportTypeError=jf;var Rf,Of={};var zf,Af,Mf={},Uf={};function Df(){if(zf)return Uf;zf=1,Object.defineProperty(Uf,"__esModule",{value:!0}),Uf.validateUnion=Uf.validateArray=Uf.usePattern=Uf.callValidateCode=Uf.schemaProperties=Uf.allSchemaProperties=Uf.noPropertyInData=Uf.propertyInData=Uf.isOwnProperty=Uf.hasPropFunc=Uf.reportMissingProp=Uf.checkMissingProp=Uf.checkReportMissingProp=void 0;const e=Zh,t=Wh,r=hf(),o=Wh;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):[]}Uf.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()})},Uf.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}`)))},Uf.reportMissingProp=function(e,t){e.setParams({missingProperty:t},!0),e.error()},Uf.hasPropFunc=n,Uf.isOwnProperty=s,Uf.propertyInData=function(t,r,o,n){const a=e._`${r}${(0,e.getProperty)(o)} !== undefined`;return n?e._`${a} && ${s(t,r,o)}`:a},Uf.noPropertyInData=a,Uf.allSchemaProperties=i,Uf.schemaProperties=function(e,r){return i(r).filter(o=>!(0,t.alwaysValidSchema)(e,r[o]))},Uf.callValidateCode=function({schemaCode:t,data:o,it:{gen:n,topSchemaRef:s,schemaPath:a,errorPath:i},it:c},u,l,d){const p=d?e._`${t}, ${o}, ${s}${a}`:o,h=[[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&&h.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);const f=e._`${p}, ${n.object(...h)}`;return l!==e.nil?e._`${u}.call(${l}, ${f})`:e._`${u}(${f})`};const c=e._`new RegExp`;return Uf.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})`})},Uf.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)})}},Uf.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))},Uf}function qf(){if(Af)return Mf;Af=1,Object.defineProperty(Mf,"__esModule",{value:!0}),Mf.validateKeywordUsage=Mf.validSchemaType=Mf.funcKeywordCode=Mf.macroKeywordCode=void 0;const e=Zh,t=hf(),r=Df(),o=ff();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 Mf.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))},Mf.funcKeywordCode=function(a,i){var c;const{gen:u,keyword:l,schema:d,parentSchema:p,$data:h,it:f}=a;!function({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}(f,i);const m=!h&&i.compile?i.compile.call(f.self,d,p,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&&!h||!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)},Mf.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)},Mf.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)}}},Mf}var Vf,Ff={};var Lf={},Kf={exports:{}},Hf=Kf.exports=function(e,t,r){"function"==typeof t&&(r=t,t={}),Zf(t,"function"==typeof(r=t.cb||r)?r:r.pre||function(){},r.post||function(){},e,"",e)};function Zf(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 Hf.arrayKeywords)for(var p=0;p<d.length;p++)Zf(e,t,r,d[p],n+"/"+l+"/"+p,s,n,l,o,p)}else if(l in Hf.propsKeywords){if(d&&"object"==typeof d)for(var h in d)Zf(e,t,r,d[h],n+"/"+l+"/"+Gf(h),s,n,l,o,h)}else(l in Hf.keywords||e.allKeys&&!(l in Hf.skipKeywords))&&Zf(e,t,r,d,n+"/"+l,s,n,l,o)}r(o,n,s,a,i,c,u)}}function Gf(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}Hf.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},Hf.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},Hf.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},Hf.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 Jf=Kf.exports;Object.defineProperty(Lf,"__esModule",{value:!0}),Lf.getSchemaRefs=Lf.resolveUrl=Lf.normalizeId=Lf._getFullPath=Lf.getFullPath=Lf.inlineRef=void 0;const Wf=Wh,Bf=Vc,Qf=Jf,Yf=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);Lf.inlineRef=function(e,t=!0){return"boolean"==typeof e||(!0===t?!em(e):!!t&&tm(e)<=t)};const Xf=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function em(e){for(const t in e){if(Xf.has(t))return!0;const r=e[t];if(Array.isArray(r)&&r.some(em))return!0;if("object"==typeof r&&em(r))return!0}return!1}function tm(e){let t=0;for(const r in e){if("$ref"===r)return 1/0;if(t++,!Yf.has(r)&&("object"==typeof e[r]&&(0,Wf.eachItem)(e[r],e=>t+=tm(e)),t===1/0))return 1/0}return t}function rm(e,t="",r){!1!==r&&(t=sm(t));const o=e.parse(t);return om(e,o)}function om(e,t){return e.serialize(t).split("#")[0]+"#"}Lf.getFullPath=rm,Lf._getFullPath=om;const nm=/#\/?$/;function sm(e){return e?e.replace(nm,""):""}Lf.normalizeId=sm,Lf.resolveUrl=function(e,t,r){return r=sm(r),e.resolve(t,r)};const am=/^[a-z_][-a-z0-9._]*$/i;var im;function cm(){if(im)return Lh;im=1,Object.defineProperty(Lh,"__esModule",{value:!0}),Lh.getData=Lh.KeywordCxt=Lh.validateFunctionCode=void 0;const e=function(){if(df)return Kh;df=1,Object.defineProperty(Kh,"__esModule",{value:!0}),Kh.boolOrEmptySchema=Kh.topBoolOrEmptySchema=void 0;const e=ff(),t=Zh,r=hf(),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 Kh.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))},Kh.boolOrEmptySchema=function(e,t){const{gen:r,schema:o}=e;!1===o?(r.var(t,!1),n(e)):r.var(t,!0)},Kh}(),t=mf,r=wf(),o=mf,n=function(){if(Rf)return Of;Rf=1,Object.defineProperty(Of,"__esModule",{value:!0}),Of.assignDefaults=void 0;const e=Zh,t=Wh;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 Of.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))},Of}(),s=qf(),a=function(){if(Vf)return Ff;Vf=1,Object.defineProperty(Ff,"__esModule",{value:!0}),Ff.extendSubschemaMode=Ff.extendSubschemaData=Ff.getSubschema=void 0;const e=Zh,t=Wh;return Ff.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')},Ff.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)},Ff.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},Ff}(),i=Zh,c=hf(),u=Lf,l=Wh,d=ff();function p({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"; ${h(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(h(r,n)).code(s))}function h(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:p,opts:h,self:f}=e,{RULES:m}=f;function y(l){(0,r.shouldUseGroup)(u,l)&&(l.type?(a.if((0,o.checkDataType)(l.type,d,h.strictNumbers)),$(e,l),1===t.length&&t[0]===l.type&&n&&(a.else(),(0,o.reportTypeError)(e)),a.endIf()):$(e,l),p||a.if(i._`${c.default.errors} === ${s||0}`))}!u.$ref||!h.ignoreKeywordsWithRef&&(0,l.schemaHasRulesButRef)(u,m)?(h.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)}Lh.validateFunctionCode=function(t){y(t)&&(g(t),m(t))?function(e){const{schema:t,opts:r,gen:o}=e;p(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):p(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",I(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)}Lh.KeywordCxt=S;const T=/^\/(?:[^~]|~0|~1)*$/,x=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function I(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=x.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 Lh.getData=I,Lh}Lf.getSchemaRefs=function(e,t){if("boolean"==typeof e)return{};const{schemaId:r,uriResolver:o}=this.opts,n=sm(e[r]||t),s={"":n},a=rm(o,n,!1),i={},c=new Set;return Qf(e,{allKeys:!0},(e,t,o,n)=>{if(void 0===n)return;const d=a+t;let p=s[n];function h(t){const r=this.opts.uriResolver.resolve;if(t=sm(p?r(p,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!==sm(d)&&("#"===t[0]?(u(e,i[t],t),i[t]=e):this.refs[t]=d),t}function f(e){if("string"==typeof e){if(!am.test(e))throw new Error(`invalid anchor "${e}"`);h.call(this,`#${e}`)}}"string"==typeof e[r]&&(p=h.call(this,e[r])),f.call(this,e.$anchor),f.call(this,e.$dynamicAnchor),s[t]=p}),i;function u(e,t,r){if(void 0!==t&&!Bf(e,t))throw l(r)}function l(e){return new Error(`reference "${e}" resolves to more than one schema`)}};var um,lm={};function dm(){if(um)return lm;um=1,Object.defineProperty(lm,"__esModule",{value:!0});class e extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}}return lm.default=e,lm}var pm,hm={};function fm(){if(pm)return hm;pm=1,Object.defineProperty(hm,"__esModule",{value:!0});const e=Lf;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 hm.default=t,hm}var mm={};Object.defineProperty(mm,"__esModule",{value:!0}),mm.resolveSchema=mm.getCompilingSchema=mm.resolveRef=mm.compileSchema=mm.SchemaEnv=void 0;const ym=Zh,gm=dm(),vm=hf(),_m=Lf,wm=Wh,$m=cm();class bm{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,_m.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 km(e){const t=Sm.call(this,e);if(t)return t;const r=(0,_m.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:o,lines:n}=this.opts.code,{ownProperties:s}=this.opts,a=new ym.CodeGen(this.scope,{es5:o,lines:n,ownProperties:s});let i;e.$async&&(i=a.scopeValue("Error",{ref:gm.default,code:ym._`require("ajv/dist/runtime/validation_error").default`}));const c=a.scopeName("validate");e.validateName=c;const u={gen:a,allErrors:this.opts.allErrors,data:vm.default.data,parentData:vm.default.parentData,parentDataProperty:vm.default.parentDataProperty,dataNames:[vm.default.data],dataPathArr:[ym.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:a.scopeValue("schema",!0===this.opts.code.source?{ref:e.schema,code:(0,ym.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:i,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:ym.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:ym._`""`,opts:this.opts,self:this};let l;try{this._compilations.add(e),(0,$m.validateFunctionCode)(u),a.optimize(this.opts.code.optimize);const t=a.toString();l=`${a.scopeRefs(vm.default.scope)}return ${t}`,this.opts.code.process&&(l=this.opts.code.process(l,e));const r=new Function(`${vm.default.self}`,`${vm.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 ym.Name?void 0:e,items:t instanceof ym.Name?void 0:t,dynamicProps:e instanceof ym.Name,dynamicItems:t instanceof ym.Name},r.source&&(r.source.evaluated=(0,ym.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 Em(e){return(0,_m.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:km.call(this,e)}function Sm(e){for(const t of this._compilations)if(Pm(t,e))return t}function Pm(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function Tm(e,t){let r;for(;"string"==typeof(r=this.refs[t]);)t=r;return r||this.schemas[t]||xm.call(this,e,t)}function xm(e,t){const r=this.opts.uriResolver.parse(t),o=(0,_m._getFullPath)(this.opts.uriResolver,r);let n=(0,_m.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&o===n)return Nm.call(this,r,e);const s=(0,_m.normalizeId)(o),a=this.refs[s]||this.schemas[s];if("string"==typeof a){const t=xm.call(this,e,a);if("object"!=typeof(null==t?void 0:t.schema))return;return Nm.call(this,r,t)}if("object"==typeof(null==a?void 0:a.schema)){if(a.validate||km.call(this,a),s===(0,_m.normalizeId)(t)){const{schema:t}=a,{schemaId:r}=this.opts,o=t[r];return o&&(n=(0,_m.resolveUrl)(this.opts.uriResolver,n,o)),new bm({schema:t,schemaId:r,root:e,baseId:n})}return Nm.call(this,r,a)}}mm.SchemaEnv=bm,mm.compileSchema=km,mm.resolveRef=function(e,t,r){var o;r=(0,_m.resolveUrl)(this.opts.uriResolver,t,r);const n=e.refs[r];if(n)return n;let s=Tm.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 bm({schema:n,schemaId:a,root:e,baseId:t}))}return void 0!==s?e.refs[r]=Em.call(this,s):void 0},mm.getCompilingSchema=Sm,mm.resolveSchema=xm;const Im=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Nm(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,wm.unescapeFragment)(o)];if(void 0===e)return;const n="object"==typeof(r=e)&&r[this.opts.schemaId];!Im.has(o)&&n&&(t=(0,_m.resolveUrl)(this.opts.uriResolver,t,n))}let s;if("boolean"!=typeof r&&r.$ref&&!(0,wm.schemaHasRulesButRef)(r,this.RULES)){const e=(0,_m.resolveUrl)(this.opts.uriResolver,t,r.$ref);s=xm.call(this,o,e)}const{schemaId:a}=this.opts;return s=s||new bm({schema:r,schemaId:a,root:o,baseId:t}),s.schema!==s.root.schema?s:void 0}var Cm={$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 Rm=ul;Rm.code='require("ajv/dist/runtime/uri").default',jm.default=Rm,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=cm();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var r=Zh;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=dm(),n=fm(),s=yf,a=mm,i=Zh,c=Lf,u=mf,l=Wh,d=Cm,p=jm,h=(e,t)=>new RegExp(e,t);h.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 x=e.strict,I=null===(t=e.code)||void 0===t?void 0:t.optimize,N=!0===I||void 0===I?1:I||0,C=null!==(o=null===(r=e.code)||void 0===r?void 0:r.regExp)&&void 0!==o?o:h,j=null!==(n=e.uriResolver)&&void 0!==n?n:p.default;return{strictSchema:null===(a=null!==(s=e.strictSchema)&&void 0!==s?s:x)||void 0===a||a,strictNumbers:null===(c=null!==(i=e.strictNumbers)&&void 0!==i?i:x)||void 0===c||c,strictTypes:null!==(l=null!==(u=e.strictTypes)&&void 0!==u?u:x)&&void 0!==l?l:"log",strictTuples:null!==(f=null!==(d=e.strictTuples)&&void 0!==d?d:x)&&void 0!==f?f:"log",strictRequired:null!==(y=null!==(m=e.strictRequired)&&void 0!==m?m:x)&&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(x.call(this,r,t),!t)return(0,l.eachItem)(r,e=>I.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=>I.call(this,e,o):e=>o.type.forEach(t=>I.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 x(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 I(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]}}}(Fh);var Om={},zm={},Am={};Object.defineProperty(Am,"__esModule",{value:!0});const Mm={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Am.default=Mm;var Um={};Object.defineProperty(Um,"__esModule",{value:!0}),Um.callRef=Um.getValidate=void 0;const Dm=fm(),qm=Df(),Vm=Zh,Fm=hf(),Lm=mm,Km=Wh,Hm={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 Gm(e,a,s,s.$async);const r=t.scopeValue("root",{ref:u});return Gm(e,Vm._`${r}.validate`,u,u.$async)}();const l=Lm.resolveRef.call(c,u,n,r);if(void 0===l)throw new Dm.default(o.opts.uriResolver,n,r);return l instanceof Lm.SchemaEnv?function(t){const r=Zm(e,t);Gm(e,r,t,t.$async)}(l):function(o){const n=t.scopeValue("schema",!0===i.code.source?{ref:o,code:(0,Vm.stringify)(o)}:{ref:o}),s=t.name("valid"),a=e.subschema({schema:o,dataTypes:[],schemaPath:Vm.nil,topSchemaRef:n,errSchemaPath:r},s);e.mergeEvaluated(a),e.ok(s)}(l)}};function Zm(e,t){const{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):Vm._`${r.scopeValue("wrapper",{ref:t})}.validate`}function Gm(e,t,r,o){const{gen:n,it:s}=e,{allErrors:a,schemaEnv:i,opts:c}=s,u=c.passContext?Fm.default.this:Vm.nil;function l(e){const t=Vm._`${e}.errors`;n.assign(Fm.default.vErrors,Vm._`${Fm.default.vErrors} === null ? ${t} : ${Fm.default.vErrors}.concat(${t})`),n.assign(Fm.default.errors,Vm._`${Fm.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=Km.mergeEvaluated.props(n,o.props,s.props));else{const t=n.var("props",Vm._`${e}.evaluated.props`);s.props=Km.mergeEvaluated.props(n,t,s.props,Vm.Name)}if(!0!==s.items)if(o&&!o.dynamicItems)void 0!==o.items&&(s.items=Km.mergeEvaluated.items(n,o.items,s.items));else{const t=n.var("items",Vm._`${e}.evaluated.items`);s.items=Km.mergeEvaluated.items(n,t,s.items,Vm.Name)}}o?function(){if(!i.$async)throw new Error("async schema referenced by sync schema");const r=n.let("valid");n.try(()=>{n.code(Vm._`await ${(0,qm.callValidateCode)(e,t,u)}`),d(t),a||n.assign(r,!0)},e=>{n.if(Vm._`!(${e} instanceof ${s.ValidationError})`,()=>n.throw(e)),l(e),a||n.assign(r,!1)}),e.ok(r)}():e.result((0,qm.callValidateCode)(e,t,u),()=>d(t),()=>l(t))}Um.getValidate=Zm,Um.callRef=Gm,Um.default=Hm,Object.defineProperty(zm,"__esModule",{value:!0});const Jm=Um,Wm=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Am.default,Jm.default];zm.default=Wm;var Bm={},Qm={};Object.defineProperty(Qm,"__esModule",{value:!0});const Ym=Zh,Xm=Ym.operators,ey={maximum:{okStr:"<=",ok:Xm.LTE,fail:Xm.GT},minimum:{okStr:">=",ok:Xm.GTE,fail:Xm.LT},exclusiveMaximum:{okStr:"<",ok:Xm.LT,fail:Xm.GTE},exclusiveMinimum:{okStr:">",ok:Xm.GT,fail:Xm.LTE}},ty={message:({keyword:e,schemaCode:t})=>Ym.str`must be ${ey[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>Ym._`{comparison: ${ey[e].okStr}, limit: ${t}}`},ry={keyword:Object.keys(ey),type:"number",schemaType:"number",$data:!0,error:ty,code(e){const{keyword:t,data:r,schemaCode:o}=e;e.fail$data(Ym._`${r} ${ey[t].fail} ${o} || isNaN(${r})`)}};Qm.default=ry;var oy={};Object.defineProperty(oy,"__esModule",{value:!0});const ny=Zh,sy={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:e})=>ny.str`must be multiple of ${e}`,params:({schemaCode:e})=>ny._`{multipleOf: ${e}}`},code(e){const{gen:t,data:r,schemaCode:o,it:n}=e,s=n.opts.multipleOfPrecision,a=t.let("res"),i=s?ny._`Math.abs(Math.round(${a}) - ${a}) > 1e-${s}`:ny._`${a} !== parseInt(${a})`;e.fail$data(ny._`(${o} === 0 || (${a} = ${r}/${o}, ${i}))`)}};oy.default=sy;var ay={},iy={};function cy(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(iy,"__esModule",{value:!0}),iy.default=cy,cy.code='require("ajv/dist/runtime/ucs2length").default',Object.defineProperty(ay,"__esModule",{value:!0});const uy=Zh,ly=Wh,dy=iy,py={message:({keyword:e,schemaCode:t})=>uy.str`must NOT have ${"maxLength"===e?"more":"fewer"} than ${t} characters`,params:({schemaCode:e})=>uy._`{limit: ${e}}`},hy={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:py,code(e){const{keyword:t,data:r,schemaCode:o,it:n}=e,s="maxLength"===t?uy.operators.GT:uy.operators.LT,a=!1===n.opts.unicode?uy._`${r}.length`:uy._`${(0,ly.useFunc)(e.gen,dy.default)}(${r})`;e.fail$data(uy._`${a} ${s} ${o}`)}};ay.default=hy;var fy={};Object.defineProperty(fy,"__esModule",{value:!0});const my=Df(),yy=Zh,gy={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>yy.str`must match pattern "${e}"`,params:({schemaCode:e})=>yy._`{pattern: ${e}}`},code(e){const{data:t,$data:r,schema:o,schemaCode:n,it:s}=e,a=s.opts.unicodeRegExp?"u":"",i=r?yy._`(new RegExp(${n}, ${a}))`:(0,my.usePattern)(e,o);e.fail$data(yy._`!${i}.test(${t})`)}};fy.default=gy;var vy={};Object.defineProperty(vy,"__esModule",{value:!0});const _y=Zh,wy={message:({keyword:e,schemaCode:t})=>_y.str`must NOT have ${"maxProperties"===e?"more":"fewer"} than ${t} properties`,params:({schemaCode:e})=>_y._`{limit: ${e}}`},$y={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:wy,code(e){const{keyword:t,data:r,schemaCode:o}=e,n="maxProperties"===t?_y.operators.GT:_y.operators.LT;e.fail$data(_y._`Object.keys(${r}).length ${n} ${o}`)}};vy.default=$y;var by={};Object.defineProperty(by,"__esModule",{value:!0});const ky=Df(),Ey=Zh,Sy=Wh,Py={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:e}})=>Ey.str`must have required property '${e}'`,params:({params:{missingProperty:e}})=>Ey._`{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(Ey.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,o,()=>{t.assign(s,(0,ky.propertyInData)(t,n,r,i.ownProperties)),t.if((0,Ey.not)(s),()=>{e.error(),t.break()})},Ey.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: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,Sy.checkStrictMode)(a,t,a.opts.strictRequired)}}function u(){t.forOf("prop",o,r=>{e.setParams({missingProperty:r}),t.if((0,ky.noPropertyInData)(t,n,r,i.ownProperties),()=>e.error())})}}};by.default=Py;var Ty={};Object.defineProperty(Ty,"__esModule",{value:!0});const xy=Zh,Iy={message:({keyword:e,schemaCode:t})=>xy.str`must NOT have ${"maxItems"===e?"more":"fewer"} than ${t} items`,params:({schemaCode:e})=>xy._`{limit: ${e}}`},Ny={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Iy,code(e){const{keyword:t,data:r,schemaCode:o}=e,n="maxItems"===t?xy.operators.GT:xy.operators.LT;e.fail$data(xy._`${r}.length ${n} ${o}`)}};Ty.default=Ny;var Cy={},jy={};Object.defineProperty(jy,"__esModule",{value:!0});const Ry=Vc;Ry.code='require("ajv/dist/runtime/equal").default',jy.default=Ry,Object.defineProperty(Cy,"__esModule",{value:!0});const Oy=mf,zy=Zh,Ay=Wh,My=jy,Uy={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:e,j:t}})=>zy.str`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>zy._`{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,Oy.getSchemaTypes)(s.items):[];function l(o,n){const s=t.name("item"),a=(0,Oy.checkDataTypes)(u,s,i.opts.strictNumbers,Oy.DataType.Wrong),l=t.const("indices",zy._`{}`);t.for(zy._`;${o}--;`,()=>{t.let(s,zy._`${r}[${o}]`),t.if(a,zy._`continue`),u.length>1&&t.if(zy._`typeof ${s} == "string"`,zy._`${s} += "_"`),t.if(zy._`typeof ${l}[${s}] == "number"`,()=>{t.assign(n,zy._`${l}[${s}]`),e.error(),t.assign(c,!1).break()}).code(zy._`${l}[${s}] = ${o}`)})}function d(o,n){const s=(0,Ay.useFunc)(t,My.default),a=t.name("outer");t.label(a).for(zy._`;${o}--;`,()=>t.for(zy._`${n} = ${o}; ${n}--;`,()=>t.if(zy._`${s}(${r}[${o}], ${r}[${n}])`,()=>{e.error(),t.assign(c,!1).break(a)})))}e.block$data(c,function(){const o=t.let("i",zy._`${r}.length`),n=t.let("j");e.setParams({i:o,j:n}),t.assign(c,!0),t.if(zy._`${o} > 1`,()=>(u.length>0&&!u.some(e=>"object"===e||"array"===e)?l:d)(o,n))},zy._`${a} === false`),e.ok(c)}};Cy.default=Uy;var Dy={};Object.defineProperty(Dy,"__esModule",{value:!0});const qy=Zh,Vy=Wh,Fy=jy,Ly={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:e})=>qy._`{allowedValue: ${e}}`},code(e){const{gen:t,data:r,$data:o,schemaCode:n,schema:s}=e;o||s&&"object"==typeof s?e.fail$data(qy._`!${(0,Vy.useFunc)(t,Fy.default)}(${r}, ${n})`):e.fail(qy._`${s} !== ${r}`)}};Dy.default=Ly;var Ky={};Object.defineProperty(Ky,"__esModule",{value:!0});const Hy=Zh,Zy=Wh,Gy=jy,Jy={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:e})=>Hy._`{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,Zy.useFunc)(t,Gy.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(Hy._`${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,Hy.or)(...n.map((t,o)=>function(e,t){const o=n[t];return"object"==typeof o&&null!==o?Hy._`${u()}(${r}, ${e}[${t}])`:Hy._`${r} === ${o}`}(e,o)))}e.pass(l)}};Ky.default=Jy,Object.defineProperty(Bm,"__esModule",{value:!0});const Wy=oy,By=ay,Qy=fy,Yy=vy,Xy=by,eg=Ty,tg=Cy,rg=Dy,og=Ky,ng=[Qm.default,Wy.default,By.default,Qy.default,Yy.default,Xy.default,eg.default,tg.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},rg.default,og.default];Bm.default=ng;var sg={},ag={};Object.defineProperty(ag,"__esModule",{value:!0}),ag.validateAdditionalItems=void 0;const ig=Zh,cg=Wh,ug={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:o}=t;Array.isArray(o)?lg(e,o):(0,cg.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas')}};function lg(e,t){const{gen:r,schema:o,data:n,keyword:s,it:a}=e;a.items=!0;const i=r.const("len",ig._`${n}.length`);if(!1===o)e.setParams({len:t.length}),e.pass(ig._`${i} <= ${t.length}`);else if("object"==typeof o&&!(0,cg.alwaysValidSchema)(a,o)){const o=r.var("valid",ig._`${i} <= ${t.length}`);r.if((0,ig.not)(o),()=>function(o){r.forRange("i",t.length,i,t=>{e.subschema({keyword:s,dataProp:t,dataPropType:cg.Type.Num},o),a.allErrors||r.if((0,ig.not)(o),()=>r.break())})}(o)),e.ok(o)}}ag.validateAdditionalItems=lg,ag.default=ug;var dg={},pg={};Object.defineProperty(pg,"__esModule",{value:!0}),pg.validateTuple=void 0;const hg=Zh,fg=Wh,mg=Df(),yg={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){const{schema:t,it:r}=e;if(Array.isArray(t))return gg(e,"additionalItems",t);r.items=!0,(0,fg.alwaysValidSchema)(r,t)||e.ok((0,mg.validateArray)(e))}};function gg(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,fg.checkStrictMode)(i,e,o.strictTuples)}}(n),i.opts.unevaluated&&r.length&&!0!==i.items&&(i.items=fg.mergeEvaluated.items(o,r.length,i.items));const c=o.name("valid"),u=o.const("len",hg._`${s}.length`);r.forEach((t,r)=>{(0,fg.alwaysValidSchema)(i,t)||(o.if(hg._`${u} > ${r}`,()=>e.subschema({keyword:a,schemaProp:r,dataProp:r},c)),e.ok(c))})}pg.validateTuple=gg,pg.default=yg,Object.defineProperty(dg,"__esModule",{value:!0});const vg=pg,_g={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,vg.validateTuple)(e,"items")};dg.default=_g;var wg={};Object.defineProperty(wg,"__esModule",{value:!0});const $g=Zh,bg=Wh,kg=Df(),Eg=ag,Sg={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:e}})=>$g.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>$g._`{limit: ${e}}`},code(e){const{schema:t,parentSchema:r,it:o}=e,{prefixItems:n}=r;o.items=!0,(0,bg.alwaysValidSchema)(o,t)||(n?(0,Eg.validateAdditionalItems)(e,n):e.ok((0,kg.validateArray)(e)))}};wg.default=Sg;var Pg={};Object.defineProperty(Pg,"__esModule",{value:!0});const Tg=Zh,xg=Wh,Ig={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:e,max:t}})=>void 0===t?Tg.str`must contain at least ${e} valid item(s)`:Tg.str`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>void 0===t?Tg._`{minContains: ${e}}`:Tg._`{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",Tg._`${n}.length`);if(e.setParams({min:a,max:i}),void 0===i&&0===a)return void(0,xg.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');if(void 0!==i&&a>i)return(0,xg.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),void e.fail();if((0,xg.alwaysValidSchema)(s,r)){let t=Tg._`${l} >= ${a}`;return void 0!==i&&(t=Tg._`${t} && ${l} <= ${i}`),void e.pass(t)}s.items=!0;const d=t.name("valid");function p(){const e=t.name("_valid"),r=t.let("count",0);h(e,()=>t.if(e,()=>function(e){t.code(Tg._`${e}++`),void 0===i?t.if(Tg._`${e} >= ${a}`,()=>t.assign(d,!0).break()):(t.if(Tg._`${e} > ${i}`,()=>t.assign(d,!1).break()),1===a?t.assign(d,!0):t.if(Tg._`${e} >= ${a}`,()=>t.assign(d,!0)))}(r)))}function h(r,o){t.forRange("i",0,l,t=>{e.subschema({keyword:"contains",dataProp:t,dataPropType:xg.Type.Num,compositeRule:!0},r),o()})}void 0===i&&1===a?h(d,()=>t.if(d,()=>t.break())):0===a?(t.let(d,!0),void 0!==i&&t.if(Tg._`${n}.length > 0`,p)):(t.let(d,!1),p()),e.result(d,()=>e.reset())}};Pg.default=Ig;var Ng={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=Zh,r=Wh,o=Df();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},
|
|
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}(lp);var dp={};Object.defineProperty(dp,"__esModule",{value:!0});const pp=Ji(),hp=Wi,fp={message:"property name must be valid",params:({params:e})=>pp._`{propertyName: ${e.propertyName}}`},mp={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:fp,code(e){const{gen:t,schema:r,data:o,it:n}=e;if((0,hp.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,pp.not)(s),()=>{e.error(!0),n.allErrors||t.break()})}),e.ok(s)}};dp.default=mp;var yp={};Object.defineProperty(yp,"__esModule",{value:!0});const gp=Uc(),vp=Ji(),_p=pc(),wp=Wi,$p={message:"must NOT have additional properties",params:({params:e})=>vp._`{additionalProperty: ${e.additionalProperty}}`},bp={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:$p,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,wp.alwaysValidSchema)(a,r))return;const u=(0,gp.allSchemaProperties)(o.properties),l=(0,gp.allSchemaProperties)(o.patternProperties);function d(e){t.code(vp._`delete ${n}[${e}]`)}function p(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,wp.alwaysValidSchema)(a,r)){const r=t.name("valid");"failing"===c.removeAdditional?(h(o,r,!1),t.if((0,vp.not)(r),()=>{e.reset(),d(o)})):(h(o,r),i||t.if((0,vp.not)(r),()=>t.break()))}}}function h(t,r,o){const n={keyword:"additionalProperties",dataProp:t,dataPropType:wp.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,wp.schemaRefOrVal)(a,o.properties,"properties");n=(0,gp.isOwnProperty)(t,e,r)}else n=u.length?(0,vp.or)(...u.map(e=>vp._`${r} === ${e}`)):vp.nil;return l.length&&(n=(0,vp.or)(n,...l.map(t=>vp._`${(0,gp.usePattern)(e,t)}.test(${r})`))),(0,vp.not)(n)}(r),()=>p(r)):p(r)}),e.ok(vp._`${s} === ${_p.default.errors}`)}};yp.default=bp;var kp={};Object.defineProperty(kp,"__esModule",{value:!0});const Ep=cu(),Sp=Uc(),Pp=Wi,Tp=yp,xp={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&&Tp.default.code(new Ep.KeywordCxt(s,Tp.default,"additionalProperties"));const a=(0,Sp.allSchemaProperties)(r);for(const e of a)s.definedProperties.add(e);s.opts.unevaluated&&a.length&&!0!==s.props&&(s.props=Pp.mergeEvaluated.props(t,(0,Pp.toHash)(a),s.props));const i=a.filter(e=>!(0,Pp.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,Sp.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)}}};kp.default=xp;var Ip={};Object.defineProperty(Ip,"__esModule",{value:!0});const Np=Uc(),Cp=Ji(),jp=Wi,Rp=Wi,Op={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,Np.allSchemaProperties)(r),c=i.filter(e=>(0,jp.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 Cp.Name||(s.props=(0,Rp.evaluatedPropsToName)(t,s.props));const{props:d}=s;function p(e){for(const t in u)new RegExp(e).test(t)&&(0,jp.checkStrictMode)(s,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function h(r){t.forIn("key",o,o=>{t.if(Cp._`${(0,Np.usePattern)(e,r)}.test(${o})`,()=>{const n=c.includes(r);n||e.subschema({keyword:"patternProperties",schemaProp:r,dataProp:o,dataPropType:Rp.Type.Str},l),s.opts.unevaluated&&!0!==d?t.assign(Cp._`${d}[${o}]`,!0):n||s.allErrors||t.if((0,Cp.not)(l),()=>t.break())})})}!function(){for(const e of i)u&&p(e),s.allErrors?h(e):(t.var(l,!0),h(e),t.if(l))}()}};Ip.default=Op;var zp={};Object.defineProperty(zp,"__esModule",{value:!0});const Ap=Wi,Mp={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){const{gen:t,schema:r,it:o}=e;if((0,Ap.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"}};zp.default=Mp;var Up={};Object.defineProperty(Up,"__esModule",{value:!0});const Dp={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Uc().validateUnion,error:{message:"must match a schema in anyOf"}};Up.default=Dp;var qp={};Object.defineProperty(qp,"__esModule",{value:!0});const Vp=Ji(),Fp=Wi,Lp={message:"must match exactly one schema in oneOf",params:({params:e})=>Vp._`{passingSchemas: ${e.passing}}`},Kp={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Lp,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,Fp.alwaysValidSchema)(n,r)?t.var(c,!0):s=e.subschema({keyword:"oneOf",schemaProp:o,compositeRule:!0},c),o>0&&t.if(Vp._`${c} && ${a}`).assign(a,!1).assign(i,Vp._`[${i}, ${o}]`).else(),t.if(c,()=>{t.assign(a,!0),t.assign(i,o),s&&e.mergeEvaluated(s,Vp.Name)})})}),e.result(a,()=>e.reset(),()=>e.error(!0))}};qp.default=Kp;var Hp={};Object.defineProperty(Hp,"__esModule",{value:!0});const Zp=Wi,Gp={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,Zp.alwaysValidSchema)(o,t))return;const s=e.subschema({keyword:"allOf",schemaProp:r},n);e.ok(n),e.mergeEvaluated(s)})}};Hp.default=Gp;var Jp={};Object.defineProperty(Jp,"__esModule",{value:!0});const Wp=Ji(),Bp=Wi,Qp={message:({params:e})=>Wp.str`must match "${e.ifClause}" schema`,params:({params:e})=>Wp._`{failingKeyword: ${e.ifClause}}`},Yp={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:Qp,code(e){const{gen:t,parentSchema:r,it:o}=e;void 0===r.then&&void 0===r.else&&(0,Bp.checkStrictMode)(o,'"if" without "then" and "else" is ignored');const n=Xp(o,"then"),s=Xp(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,Wp.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,Wp._`${r}`):e.setParams({ifClause:r})}}e.pass(a,()=>e.error(!0))}};function Xp(e,t){const r=e.schema[t];return void 0!==r&&!(0,Bp.alwaysValidSchema)(e,r)}Jp.default=Yp;var eh={};Object.defineProperty(eh,"__esModule",{value:!0});const th=Wi,rh={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){void 0===t.if&&(0,th.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};eh.default=rh,Object.defineProperty(Dd,"__esModule",{value:!0});const oh=qd,nh=Hd,sh=Zd,ah=ep,ih=ap,ch=lp,uh=dp,lh=yp,dh=kp,ph=Ip,hh=zp,fh=Up,mh=qp,yh=Hp,gh=Jp,vh=eh;Dd.default=function(e=!1){const t=[hh.default,fh.default,mh.default,yh.default,gh.default,vh.default,uh.default,lh.default,ch.default,dh.default,ph.default];return e?t.push(nh.default,ah.default):t.push(oh.default,sh.default),t.push(ih.default),t};var _h={},wh={};Object.defineProperty(wh,"__esModule",{value:!0});const $h=Ji(),bh={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>$h.str`must match format "${e}"`,params:({schemaCode:e})=>$h._`{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",$h._`${n}[${a}]`),i=r.let("fType"),u=r.let("format");r.if($h._`typeof ${s} == "object" && !(${s} instanceof RegExp)`,()=>r.assign(i,$h._`${s}.type || "string"`).assign(u,$h._`${s}.validate`),()=>r.assign(i,$h._`"string"`).assign(u,s)),e.fail$data((0,$h.or)(!1===c.strictSchema?$h.nil:$h._`${a} && !${u}`,function(){const e=l.$async?$h._`(${s}.async ? await ${u}(${o}) : ${u}(${o}))`:$h._`${u}(${o})`,r=$h._`(typeof ${u} == "function" ? ${e} : ${u}.test(${o}))`;return $h._`${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,p]=function(e){const t=e instanceof RegExp?(0,$h.regexpCode)(e):c.code.formats?$h._`${c.code.formats}${(0,$h.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,$h._`${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 $h._`await ${p}(${o})`}return"function"==typeof i?$h._`${p}(${o})`:$h._`${p}.test(${o})`}())}())}};wh.default=bh,Object.defineProperty(_h,"__esModule",{value:!0});const kh=[wh.default];_h.default=kh;var Eh={};Object.defineProperty(Eh,"__esModule",{value:!0}),Eh.contentVocabulary=Eh.metadataVocabulary=void 0,Eh.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],Eh.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"],Object.defineProperty(hl,"__esModule",{value:!0});const Sh=Il,Ph=Dd,Th=_h,xh=Eh,Ih=[fl.default,Sh.default,(0,Ph.default)(),Th.default,xh.metadataVocabulary,xh.contentVocabulary];hl.default=Ih;var Nh,Ch={},jh={};Object.defineProperty(jh,"__esModule",{value:!0}),jh.DiscrError=void 0,function(e){e.Tag="tag",e.Mapping="mapping"}(Nh||(jh.DiscrError=Nh={})),Object.defineProperty(Ch,"__esModule",{value:!0});const Rh=Ji(),Oh=jh,zh=mu,Ah=fu(),Mh=Wi,Uh={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:e,tagName:t}})=>e===Oh.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>Rh._`{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",Rh._`${r}${(0,Rh.getProperty)(i)}`);function l(r){const o=t.name("valid"),n=e.subschema({keyword:"oneOf",schemaProp:r},o);return e.mergeEvaluated(n,Rh.Name),o}t.if(Rh._`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,Mh.schemaHasRulesButRef)(n,s.self.RULES)){const e=n.$ref;if(n=zh.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,e),n instanceof zh.SchemaEnv&&(n=n.schema),void 0===n)throw new Ah.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(Rh._`${u} === ${e}`),t.assign(c,l(r[e]));t.else(),e.error(!1,{discrError:Oh.DiscrError.Mapping,tag:u,tagName:i}),t.endIf()}(),()=>e.error(!1,{discrError:Oh.DiscrError.Tag,tag:u,tagName:i})),e.ok(c)}};Ch.default=Uh;var Dh={$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=Mi,o=hl,n=Ch,s=Dh,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=cu();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return u.KeywordCxt}});var l=Ji();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=du();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return d.default}});var p=fu();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return p.default}})}(Ai,Ai.exports);var qh=Oi(Ai.exports),Vh={exports:{}},Fh={};!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),p),"iso-time":t(i(),u),"iso-date-time":t(d(),h),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,p),"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,h),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,p=o-u*c-(d<0?1:0);return(23===p||-1===p)&&(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 p(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 h(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/}(Fh);var Lh={},Kh={exports:{}},Hh={},Zh={},Gh={},Jh={},Wh={},Bh={};!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())}}(Bh);var Qh={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=Bh;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}}}(Qh),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=Bh,r=Qh;var o=Bh;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=Qh;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=I(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=I(this.rhs,e,r),this}get names(){return x(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 p 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=I(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class h 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 h{render(e){return"{"+e._n+super.render(e)+"}"+e._n}}class m extends h{}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=I(this.condition,e,t),this}get names(){const e=super.names;return x(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=I(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=x(super.names,this.from);return x(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=I(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 h{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 x(e,r){return r instanceof t._CodeOrName?T(e,r.names):e}function I(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 p(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)}}(Wh);var Yh={};Object.defineProperty(Yh,"__esModule",{value:!0}),Yh.checkStrictMode=Yh.getErrorPath=Yh.Type=Yh.useFunc=Yh.setEvaluated=Yh.evaluatedPropsToName=Yh.mergeEvaluated=Yh.eachItem=Yh.unescapeJsonPointer=Yh.escapeJsonPointer=Yh.escapeFragment=Yh.unescapeFragment=Yh.schemaRefOrVal=Yh.schemaHasRulesButRef=Yh.schemaHasRules=Yh.checkUnknownRules=Yh.alwaysValidSchema=Yh.toHash=void 0;const Xh=Wh,ef=Bh;function tf(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]||df(e,`unknown keyword: "${r}"`)}function rf(e,t){if("boolean"==typeof e)return!e;for(const r in e)if(t[r])return!0;return!1}function of(e){return"number"==typeof e?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}function nf(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function sf({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:o}){return(n,s,a,i)=>{const c=void 0===a?s:a instanceof Xh.Name?(s instanceof Xh.Name?e(n,s,a):t(n,s,a),a):s instanceof Xh.Name?(t(n,a,s),s):r(s,a);return i!==Xh.Name||c instanceof Xh.Name?c:o(n,c)}}function af(e,t){if(!0===t)return e.var("props",!0);const r=e.var("props",Xh._`{}`);return void 0!==t&&cf(e,r,t),r}function cf(e,t,r){Object.keys(r).forEach(r=>e.assign(Xh._`${t}${(0,Xh.getProperty)(r)}`,!0))}Yh.toHash=function(e){const t={};for(const r of e)t[r]=!0;return t},Yh.alwaysValidSchema=function(e,t){return"boolean"==typeof t?t:0===Object.keys(t).length||(tf(e,t),!rf(t,e.self.RULES.all))},Yh.checkUnknownRules=tf,Yh.schemaHasRules=rf,Yh.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},Yh.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 Xh._`${r}`}return Xh._`${e}${t}${(0,Xh.getProperty)(o)}`},Yh.unescapeFragment=function(e){return nf(decodeURIComponent(e))},Yh.escapeFragment=function(e){return encodeURIComponent(of(e))},Yh.escapeJsonPointer=of,Yh.unescapeJsonPointer=nf,Yh.eachItem=function(e,t){if(Array.isArray(e))for(const r of e)t(r);else t(e)},Yh.mergeEvaluated={props:sf({mergeNames:(e,t,r)=>e.if(Xh._`${r} !== true && ${t} !== undefined`,()=>{e.if(Xh._`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,Xh._`${r} || {}`).code(Xh._`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if(Xh._`${r} !== true`,()=>{!0===t?e.assign(r,!0):(e.assign(r,Xh._`${r} || {}`),cf(e,r,t))}),mergeValues:(e,t)=>!0===e||{...e,...t},resultToName:af}),items:sf({mergeNames:(e,t,r)=>e.if(Xh._`${r} !== true && ${t} !== undefined`,()=>e.assign(r,Xh._`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if(Xh._`${r} !== true`,()=>e.assign(r,!0===t||Xh._`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>!0===e||Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})},Yh.evaluatedPropsToName=af,Yh.setEvaluated=cf;const uf={};var lf;function df(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,!0===r)throw new Error(t);e.self.logger.warn(t)}}Yh.useFunc=function(e,t){return e.scopeValue("func",{ref:t,code:uf[t.code]||(uf[t.code]=new ef._Code(t.code))})},function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"}(lf||(Yh.Type=lf={})),Yh.getErrorPath=function(e,t,r){if(e instanceof Xh.Name){const o=t===lf.Num;return r?o?Xh._`"[" + ${e} + "]"`:Xh._`"['" + ${e} + "']"`:o?Xh._`"/" + ${e}`:Xh._`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,Xh.getProperty)(e).toString():"/"+of(e)},Yh.checkStrictMode=df;var pf,hf,ff,mf={};function yf(){if(pf)return mf;pf=1,Object.defineProperty(mf,"__esModule",{value:!0});const e=Wh,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 mf.default=t,mf}function gf(){return hf||(hf=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=Wh,r=Yh,o=yf();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:p}=u,h=i(r,o,a);(null!=c?c:d||p)?n(l,h):s(u,t._`[${h}]`)},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:p,topSchemaRef:h,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._`${h}${f}`],[o.default.data,c]);p&&s.push([a.propertyName,p])}(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]}}(Jh)),Jh}var vf={},_f={};Object.defineProperty(_f,"__esModule",{value:!0}),_f.getRules=_f.isJSONType=void 0;const wf=new Set(["string","number","integer","boolean","null","object","array"]);_f.isJSONType=function(e){return"string"==typeof e&&wf.has(e)},_f.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 $f,bf={};function kf(){if($f)return bf;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 $f=1,Object.defineProperty(bf,"__esModule",{value:!0}),bf.shouldUseRule=bf.shouldUseGroup=bf.schemaHasRulesForType=void 0,bf.schemaHasRulesForType=function({schema:t,self:r},o){const n=r.RULES.types[o];return n&&!0!==n&&e(t,n)},bf.shouldUseGroup=e,bf.shouldUseRule=t,bf}Object.defineProperty(vf,"__esModule",{value:!0}),vf.reportTypeError=vf.checkDataTypes=vf.checkDataType=vf.coerceAndCheckDataType=vf.getJSONTypes=vf.getSchemaTypes=vf.DataType=void 0;const Ef=_f,Sf=kf(),Pf=gf(),Tf=Wh,xf=Yh;var If;function Nf(e){const t=Array.isArray(e)?e:e?[e]:[];if(t.every(Ef.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"}(If||(vf.DataType=If={})),vf.getSchemaTypes=function(e){const t=Nf(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},vf.getJSONTypes=Nf,vf.coerceAndCheckDataType=function(e,t){const{gen:r,data:o,opts:n}=e,s=function(e,t){return t?e.filter(e=>Cf.has(e)||"array"===t&&"array"===e):[]}(t,n.coerceTypes),a=t.length>0&&!(0===s.length&&1===t.length&&(0,Sf.schemaHasRulesForType)(e,t[0]));if(a){const a=Rf(t,o,n.strictNumbers,If.Wrong);r.if(a,()=>{s.length?function(e,t,r){const{gen:o,data:n,opts:s}=e,a=o.let("dataType",Tf._`typeof ${n}`),i=o.let("coerced",Tf._`undefined`);"array"===s.coerceTypes&&o.if(Tf._`${a} == 'object' && Array.isArray(${n}) && ${n}.length == 1`,()=>o.assign(n,Tf._`${n}[0]`).assign(a,Tf._`typeof ${n}`).if(Rf(t,n,s.strictNumbers),()=>o.assign(i,n)));o.if(Tf._`${i} !== undefined`);for(const e of r)(Cf.has(e)||"array"===e&&"array"===s.coerceTypes)&&c(e);function c(e){switch(e){case"string":return void o.elseIf(Tf._`${a} == "number" || ${a} == "boolean"`).assign(i,Tf._`"" + ${n}`).elseIf(Tf._`${n} === null`).assign(i,Tf._`""`);case"number":return void o.elseIf(Tf._`${a} == "boolean" || ${n} === null
|
|
8
|
+
|| (${a} == "string" && ${n} && ${n} == +${n})`).assign(i,Tf._`+${n}`);case"integer":return void o.elseIf(Tf._`${a} === "boolean" || ${n} === null
|
|
9
|
+
|| (${a} === "string" && ${n} && ${n} == +${n} && !(${n} % 1))`).assign(i,Tf._`+${n}`);case"boolean":return void o.elseIf(Tf._`${n} === "false" || ${n} === 0 || ${n} === null`).assign(i,!1).elseIf(Tf._`${n} === "true" || ${n} === 1`).assign(i,!0);case"null":return o.elseIf(Tf._`${n} === "" || ${n} === 0 || ${n} === false`),void o.assign(i,null);case"array":o.elseIf(Tf._`${a} === "string" || ${a} === "number"
|
|
10
|
+
|| ${a} === "boolean" || ${n} === null`).assign(i,Tf._`[${n}]`)}}o.else(),zf(e),o.endIf(),o.if(Tf._`${i} !== undefined`,()=>{o.assign(n,i),function({gen:e,parentData:t,parentDataProperty:r},o){e.if(Tf._`${t} !== undefined`,()=>e.assign(Tf._`${t}[${r}]`,o))}(e,i)})}(e,t,s):zf(e)})}return a};const Cf=new Set(["string","number","integer","boolean","null"]);function jf(e,t,r,o=If.Correct){const n=o===If.Correct?Tf.operators.EQ:Tf.operators.NEQ;let s;switch(e){case"null":return Tf._`${t} ${n} null`;case"array":s=Tf._`Array.isArray(${t})`;break;case"object":s=Tf._`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":s=a(Tf._`!(${t} % 1) && !isNaN(${t})`);break;case"number":s=a();break;default:return Tf._`typeof ${t} ${n} ${e}`}return o===If.Correct?s:(0,Tf.not)(s);function a(e=Tf.nil){return(0,Tf.and)(Tf._`typeof ${t} == "number"`,e,r?Tf._`isFinite(${t})`:Tf.nil)}}function Rf(e,t,r,o){if(1===e.length)return jf(e[0],t,r,o);let n;const s=(0,xf.toHash)(e);if(s.array&&s.object){const e=Tf._`typeof ${t} != "object"`;n=s.null?e:Tf._`!${t} || ${e}`,delete s.null,delete s.array,delete s.object}else n=Tf.nil;s.number&&delete s.integer;for(const e in s)n=(0,Tf.and)(n,jf(e,t,r,o));return n}vf.checkDataType=jf,vf.checkDataTypes=Rf;const Of={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>"string"==typeof e?Tf._`{type: ${e}}`:Tf._`{type: ${t}}`};function zf(e){const t=function(e){const{gen:t,data:r,schema:o}=e,n=(0,xf.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,Pf.reportError)(t,Of)}vf.reportTypeError=zf;var Af,Mf={};var Uf,Df,qf={},Vf={};function Ff(){if(Uf)return Vf;Uf=1,Object.defineProperty(Vf,"__esModule",{value:!0}),Vf.validateUnion=Vf.validateArray=Vf.usePattern=Vf.callValidateCode=Vf.schemaProperties=Vf.allSchemaProperties=Vf.noPropertyInData=Vf.propertyInData=Vf.isOwnProperty=Vf.hasPropFunc=Vf.reportMissingProp=Vf.checkMissingProp=Vf.checkReportMissingProp=void 0;const e=Wh,t=Yh,r=yf(),o=Yh;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):[]}Vf.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()})},Vf.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}`)))},Vf.reportMissingProp=function(e,t){e.setParams({missingProperty:t},!0),e.error()},Vf.hasPropFunc=n,Vf.isOwnProperty=s,Vf.propertyInData=function(t,r,o,n){const a=e._`${r}${(0,e.getProperty)(o)} !== undefined`;return n?e._`${a} && ${s(t,r,o)}`:a},Vf.noPropertyInData=a,Vf.allSchemaProperties=i,Vf.schemaProperties=function(e,r){return i(r).filter(o=>!(0,t.alwaysValidSchema)(e,r[o]))},Vf.callValidateCode=function({schemaCode:t,data:o,it:{gen:n,topSchemaRef:s,schemaPath:a,errorPath:i},it:c},u,l,d){const p=d?e._`${t}, ${o}, ${s}${a}`:o,h=[[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&&h.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);const f=e._`${p}, ${n.object(...h)}`;return l!==e.nil?e._`${u}.call(${l}, ${f})`:e._`${u}(${f})`};const c=e._`new RegExp`;return Vf.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})`})},Vf.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)})}},Vf.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))},Vf}function Lf(){if(Df)return qf;Df=1,Object.defineProperty(qf,"__esModule",{value:!0}),qf.validateKeywordUsage=qf.validSchemaType=qf.funcKeywordCode=qf.macroKeywordCode=void 0;const e=Wh,t=yf(),r=Ff(),o=gf();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 qf.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))},qf.funcKeywordCode=function(a,i){var c;const{gen:u,keyword:l,schema:d,parentSchema:p,$data:h,it:f}=a;!function({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}(f,i);const m=!h&&i.compile?i.compile.call(f.self,d,p,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&&!h||!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)},qf.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)},qf.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)}}},qf}var Kf,Hf={};var Zf={},Gf={exports:{}},Jf=Gf.exports=function(e,t,r){"function"==typeof t&&(r=t,t={}),Wf(t,"function"==typeof(r=t.cb||r)?r:r.pre||function(){},r.post||function(){},e,"",e)};function Wf(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 Jf.arrayKeywords)for(var p=0;p<d.length;p++)Wf(e,t,r,d[p],n+"/"+l+"/"+p,s,n,l,o,p)}else if(l in Jf.propsKeywords){if(d&&"object"==typeof d)for(var h in d)Wf(e,t,r,d[h],n+"/"+l+"/"+Bf(h),s,n,l,o,h)}else(l in Jf.keywords||e.allKeys&&!(l in Jf.skipKeywords))&&Wf(e,t,r,d,n+"/"+l,s,n,l,o)}r(o,n,s,a,i,c,u)}}function Bf(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}Jf.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},Jf.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},Jf.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},Jf.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 Qf=Gf.exports;Object.defineProperty(Zf,"__esModule",{value:!0}),Zf.getSchemaRefs=Zf.resolveUrl=Zf.normalizeId=Zf._getFullPath=Zf.getFullPath=Zf.inlineRef=void 0;const Yf=Yh,Xf=Lc,em=Qf,tm=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);Zf.inlineRef=function(e,t=!0){return"boolean"==typeof e||(!0===t?!om(e):!!t&&nm(e)<=t)};const rm=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function om(e){for(const t in e){if(rm.has(t))return!0;const r=e[t];if(Array.isArray(r)&&r.some(om))return!0;if("object"==typeof r&&om(r))return!0}return!1}function nm(e){let t=0;for(const r in e){if("$ref"===r)return 1/0;if(t++,!tm.has(r)&&("object"==typeof e[r]&&(0,Yf.eachItem)(e[r],e=>t+=nm(e)),t===1/0))return 1/0}return t}function sm(e,t="",r){!1!==r&&(t=cm(t));const o=e.parse(t);return am(e,o)}function am(e,t){return e.serialize(t).split("#")[0]+"#"}Zf.getFullPath=sm,Zf._getFullPath=am;const im=/#\/?$/;function cm(e){return e?e.replace(im,""):""}Zf.normalizeId=cm,Zf.resolveUrl=function(e,t,r){return r=cm(r),e.resolve(t,r)};const um=/^[a-z_][-a-z0-9._]*$/i;var lm;function dm(){if(lm)return Zh;lm=1,Object.defineProperty(Zh,"__esModule",{value:!0}),Zh.getData=Zh.KeywordCxt=Zh.validateFunctionCode=void 0;const e=function(){if(ff)return Gh;ff=1,Object.defineProperty(Gh,"__esModule",{value:!0}),Gh.boolOrEmptySchema=Gh.topBoolOrEmptySchema=void 0;const e=gf(),t=Wh,r=yf(),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 Gh.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))},Gh.boolOrEmptySchema=function(e,t){const{gen:r,schema:o}=e;!1===o?(r.var(t,!1),n(e)):r.var(t,!0)},Gh}(),t=vf,r=kf(),o=vf,n=function(){if(Af)return Mf;Af=1,Object.defineProperty(Mf,"__esModule",{value:!0}),Mf.assignDefaults=void 0;const e=Wh,t=Yh;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 Mf.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))},Mf}(),s=Lf(),a=function(){if(Kf)return Hf;Kf=1,Object.defineProperty(Hf,"__esModule",{value:!0}),Hf.extendSubschemaMode=Hf.extendSubschemaData=Hf.getSubschema=void 0;const e=Wh,t=Yh;return Hf.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')},Hf.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)},Hf.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},Hf}(),i=Wh,c=yf(),u=Zf,l=Yh,d=gf();function p({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"; ${h(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(h(r,n)).code(s))}function h(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:p,opts:h,self:f}=e,{RULES:m}=f;function y(l){(0,r.shouldUseGroup)(u,l)&&(l.type?(a.if((0,o.checkDataType)(l.type,d,h.strictNumbers)),$(e,l),1===t.length&&t[0]===l.type&&n&&(a.else(),(0,o.reportTypeError)(e)),a.endIf()):$(e,l),p||a.if(i._`${c.default.errors} === ${s||0}`))}!u.$ref||!h.ignoreKeywordsWithRef&&(0,l.schemaHasRulesButRef)(u,m)?(h.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)}Zh.validateFunctionCode=function(t){y(t)&&(g(t),m(t))?function(e){const{schema:t,opts:r,gen:o}=e;p(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):p(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",I(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)}Zh.KeywordCxt=S;const T=/^\/(?:[^~]|~0|~1)*$/,x=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function I(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=x.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 Zh.getData=I,Zh}Zf.getSchemaRefs=function(e,t){if("boolean"==typeof e)return{};const{schemaId:r,uriResolver:o}=this.opts,n=cm(e[r]||t),s={"":n},a=sm(o,n,!1),i={},c=new Set;return em(e,{allKeys:!0},(e,t,o,n)=>{if(void 0===n)return;const d=a+t;let p=s[n];function h(t){const r=this.opts.uriResolver.resolve;if(t=cm(p?r(p,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!==cm(d)&&("#"===t[0]?(u(e,i[t],t),i[t]=e):this.refs[t]=d),t}function f(e){if("string"==typeof e){if(!um.test(e))throw new Error(`invalid anchor "${e}"`);h.call(this,`#${e}`)}}"string"==typeof e[r]&&(p=h.call(this,e[r])),f.call(this,e.$anchor),f.call(this,e.$dynamicAnchor),s[t]=p}),i;function u(e,t,r){if(void 0!==t&&!Xf(e,t))throw l(r)}function l(e){return new Error(`reference "${e}" resolves to more than one schema`)}};var pm,hm={};function fm(){if(pm)return hm;pm=1,Object.defineProperty(hm,"__esModule",{value:!0});class e extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}}return hm.default=e,hm}var mm,ym={};function gm(){if(mm)return ym;mm=1,Object.defineProperty(ym,"__esModule",{value:!0});const e=Zf;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 ym.default=t,ym}var vm={};Object.defineProperty(vm,"__esModule",{value:!0}),vm.resolveSchema=vm.getCompilingSchema=vm.resolveRef=vm.compileSchema=vm.SchemaEnv=void 0;const _m=Wh,wm=fm(),$m=yf(),bm=Zf,km=Yh,Em=dm();class Sm{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,bm.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 Pm(e){const t=xm.call(this,e);if(t)return t;const r=(0,bm.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:o,lines:n}=this.opts.code,{ownProperties:s}=this.opts,a=new _m.CodeGen(this.scope,{es5:o,lines:n,ownProperties:s});let i;e.$async&&(i=a.scopeValue("Error",{ref:wm.default,code:_m._`require("ajv/dist/runtime/validation_error").default`}));const c=a.scopeName("validate");e.validateName=c;const u={gen:a,allErrors:this.opts.allErrors,data:$m.default.data,parentData:$m.default.parentData,parentDataProperty:$m.default.parentDataProperty,dataNames:[$m.default.data],dataPathArr:[_m.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:a.scopeValue("schema",!0===this.opts.code.source?{ref:e.schema,code:(0,_m.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:i,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:_m.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:_m._`""`,opts:this.opts,self:this};let l;try{this._compilations.add(e),(0,Em.validateFunctionCode)(u),a.optimize(this.opts.code.optimize);const t=a.toString();l=`${a.scopeRefs($m.default.scope)}return ${t}`,this.opts.code.process&&(l=this.opts.code.process(l,e));const r=new Function(`${$m.default.self}`,`${$m.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 _m.Name?void 0:e,items:t instanceof _m.Name?void 0:t,dynamicProps:e instanceof _m.Name,dynamicItems:t instanceof _m.Name},r.source&&(r.source.evaluated=(0,_m.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 Tm(e){return(0,bm.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:Pm.call(this,e)}function xm(e){for(const t of this._compilations)if(Im(t,e))return t}function Im(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function Nm(e,t){let r;for(;"string"==typeof(r=this.refs[t]);)t=r;return r||this.schemas[t]||Cm.call(this,e,t)}function Cm(e,t){const r=this.opts.uriResolver.parse(t),o=(0,bm._getFullPath)(this.opts.uriResolver,r);let n=(0,bm.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&o===n)return Rm.call(this,r,e);const s=(0,bm.normalizeId)(o),a=this.refs[s]||this.schemas[s];if("string"==typeof a){const t=Cm.call(this,e,a);if("object"!=typeof(null==t?void 0:t.schema))return;return Rm.call(this,r,t)}if("object"==typeof(null==a?void 0:a.schema)){if(a.validate||Pm.call(this,a),s===(0,bm.normalizeId)(t)){const{schema:t}=a,{schemaId:r}=this.opts,o=t[r];return o&&(n=(0,bm.resolveUrl)(this.opts.uriResolver,n,o)),new Sm({schema:t,schemaId:r,root:e,baseId:n})}return Rm.call(this,r,a)}}vm.SchemaEnv=Sm,vm.compileSchema=Pm,vm.resolveRef=function(e,t,r){var o;r=(0,bm.resolveUrl)(this.opts.uriResolver,t,r);const n=e.refs[r];if(n)return n;let s=Nm.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 Sm({schema:n,schemaId:a,root:e,baseId:t}))}return void 0!==s?e.refs[r]=Tm.call(this,s):void 0},vm.getCompilingSchema=xm,vm.resolveSchema=Cm;const jm=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Rm(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,km.unescapeFragment)(o)];if(void 0===e)return;const n="object"==typeof(r=e)&&r[this.opts.schemaId];!jm.has(o)&&n&&(t=(0,bm.resolveUrl)(this.opts.uriResolver,t,n))}let s;if("boolean"!=typeof r&&r.$ref&&!(0,km.schemaHasRulesButRef)(r,this.RULES)){const e=(0,bm.resolveUrl)(this.opts.uriResolver,t,r.$ref);s=Cm.call(this,o,e)}const{schemaId:a}=this.opts;return s=s||new Sm({schema:r,schemaId:a,root:o,baseId:t}),s.schema!==s.root.schema?s:void 0}var Om={$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},zm={};Object.defineProperty(zm,"__esModule",{value:!0});const Am=dl;Am.code='require("ajv/dist/runtime/uri").default',zm.default=Am,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=dm();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var r=Wh;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=fm(),n=gm(),s=_f,a=vm,i=Wh,c=Zf,u=vf,l=Yh,d=Om,p=zm,h=(e,t)=>new RegExp(e,t);h.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 x=e.strict,I=null===(t=e.code)||void 0===t?void 0:t.optimize,N=!0===I||void 0===I?1:I||0,C=null!==(o=null===(r=e.code)||void 0===r?void 0:r.regExp)&&void 0!==o?o:h,j=null!==(n=e.uriResolver)&&void 0!==n?n:p.default;return{strictSchema:null===(a=null!==(s=e.strictSchema)&&void 0!==s?s:x)||void 0===a||a,strictNumbers:null===(c=null!==(i=e.strictNumbers)&&void 0!==i?i:x)||void 0===c||c,strictTypes:null!==(l=null!==(u=e.strictTypes)&&void 0!==u?u:x)&&void 0!==l?l:"log",strictTuples:null!==(f=null!==(d=e.strictTuples)&&void 0!==d?d:x)&&void 0!==f?f:"log",strictRequired:null!==(y=null!==(m=e.strictRequired)&&void 0!==m?m:x)&&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(x.call(this,r,t),!t)return(0,l.eachItem)(r,e=>I.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=>I.call(this,e,o):e=>o.type.forEach(t=>I.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 x(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 I(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]}}}(Hh);var Mm={},Um={},Dm={};Object.defineProperty(Dm,"__esModule",{value:!0});const qm={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Dm.default=qm;var Vm={};Object.defineProperty(Vm,"__esModule",{value:!0}),Vm.callRef=Vm.getValidate=void 0;const Fm=gm(),Lm=Ff(),Km=Wh,Hm=yf(),Zm=vm,Gm=Yh,Jm={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 Bm(e,a,s,s.$async);const r=t.scopeValue("root",{ref:u});return Bm(e,Km._`${r}.validate`,u,u.$async)}();const l=Zm.resolveRef.call(c,u,n,r);if(void 0===l)throw new Fm.default(o.opts.uriResolver,n,r);return l instanceof Zm.SchemaEnv?function(t){const r=Wm(e,t);Bm(e,r,t,t.$async)}(l):function(o){const n=t.scopeValue("schema",!0===i.code.source?{ref:o,code:(0,Km.stringify)(o)}:{ref:o}),s=t.name("valid"),a=e.subschema({schema:o,dataTypes:[],schemaPath:Km.nil,topSchemaRef:n,errSchemaPath:r},s);e.mergeEvaluated(a),e.ok(s)}(l)}};function Wm(e,t){const{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):Km._`${r.scopeValue("wrapper",{ref:t})}.validate`}function Bm(e,t,r,o){const{gen:n,it:s}=e,{allErrors:a,schemaEnv:i,opts:c}=s,u=c.passContext?Hm.default.this:Km.nil;function l(e){const t=Km._`${e}.errors`;n.assign(Hm.default.vErrors,Km._`${Hm.default.vErrors} === null ? ${t} : ${Hm.default.vErrors}.concat(${t})`),n.assign(Hm.default.errors,Km._`${Hm.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=Gm.mergeEvaluated.props(n,o.props,s.props));else{const t=n.var("props",Km._`${e}.evaluated.props`);s.props=Gm.mergeEvaluated.props(n,t,s.props,Km.Name)}if(!0!==s.items)if(o&&!o.dynamicItems)void 0!==o.items&&(s.items=Gm.mergeEvaluated.items(n,o.items,s.items));else{const t=n.var("items",Km._`${e}.evaluated.items`);s.items=Gm.mergeEvaluated.items(n,t,s.items,Km.Name)}}o?function(){if(!i.$async)throw new Error("async schema referenced by sync schema");const r=n.let("valid");n.try(()=>{n.code(Km._`await ${(0,Lm.callValidateCode)(e,t,u)}`),d(t),a||n.assign(r,!0)},e=>{n.if(Km._`!(${e} instanceof ${s.ValidationError})`,()=>n.throw(e)),l(e),a||n.assign(r,!1)}),e.ok(r)}():e.result((0,Lm.callValidateCode)(e,t,u),()=>d(t),()=>l(t))}Vm.getValidate=Wm,Vm.callRef=Bm,Vm.default=Jm,Object.defineProperty(Um,"__esModule",{value:!0});const Qm=Vm,Ym=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Dm.default,Qm.default];Um.default=Ym;var Xm={},ey={};Object.defineProperty(ey,"__esModule",{value:!0});const ty=Wh,ry=ty.operators,oy={maximum:{okStr:"<=",ok:ry.LTE,fail:ry.GT},minimum:{okStr:">=",ok:ry.GTE,fail:ry.LT},exclusiveMaximum:{okStr:"<",ok:ry.LT,fail:ry.GTE},exclusiveMinimum:{okStr:">",ok:ry.GT,fail:ry.LTE}},ny={message:({keyword:e,schemaCode:t})=>ty.str`must be ${oy[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>ty._`{comparison: ${oy[e].okStr}, limit: ${t}}`},sy={keyword:Object.keys(oy),type:"number",schemaType:"number",$data:!0,error:ny,code(e){const{keyword:t,data:r,schemaCode:o}=e;e.fail$data(ty._`${r} ${oy[t].fail} ${o} || isNaN(${r})`)}};ey.default=sy;var ay={};Object.defineProperty(ay,"__esModule",{value:!0});const iy=Wh,cy={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:e})=>iy.str`must be multiple of ${e}`,params:({schemaCode:e})=>iy._`{multipleOf: ${e}}`},code(e){const{gen:t,data:r,schemaCode:o,it:n}=e,s=n.opts.multipleOfPrecision,a=t.let("res"),i=s?iy._`Math.abs(Math.round(${a}) - ${a}) > 1e-${s}`:iy._`${a} !== parseInt(${a})`;e.fail$data(iy._`(${o} === 0 || (${a} = ${r}/${o}, ${i}))`)}};ay.default=cy;var uy={},ly={};function dy(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(ly,"__esModule",{value:!0}),ly.default=dy,dy.code='require("ajv/dist/runtime/ucs2length").default',Object.defineProperty(uy,"__esModule",{value:!0});const py=Wh,hy=Yh,fy=ly,my={message:({keyword:e,schemaCode:t})=>py.str`must NOT have ${"maxLength"===e?"more":"fewer"} than ${t} characters`,params:({schemaCode:e})=>py._`{limit: ${e}}`},yy={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:my,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,hy.useFunc)(e.gen,fy.default)}(${r})`;e.fail$data(py._`${a} ${s} ${o}`)}};uy.default=yy;var gy={};Object.defineProperty(gy,"__esModule",{value:!0});const vy=Ff(),_y=Yh,wy=Wh,$y={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>wy.str`must match pattern "${e}"`,params:({schemaCode:e})=>wy._`{pattern: ${e}}`},code(e){const{gen:t,data:r,$data:o,schema:n,schemaCode:s,it:a}=e,i=a.opts.unicodeRegExp?"u":"";if(o){const{regExp:o}=a.opts.code,n="new RegExp"===o.code?wy._`new RegExp`:(0,_y.useFunc)(t,o),c=t.let("valid");t.try(()=>t.assign(c,wy._`${n}(${s}, ${i}).test(${r})`),()=>t.assign(c,!1)),e.fail$data(wy._`!${c}`)}else{const t=(0,vy.usePattern)(e,n);e.fail$data(wy._`!${t}.test(${r})`)}}};gy.default=$y;var by={};Object.defineProperty(by,"__esModule",{value:!0});const ky=Wh,Ey={message:({keyword:e,schemaCode:t})=>ky.str`must NOT have ${"maxProperties"===e?"more":"fewer"} than ${t} properties`,params:({schemaCode:e})=>ky._`{limit: ${e}}`},Sy={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:Ey,code(e){const{keyword:t,data:r,schemaCode:o}=e,n="maxProperties"===t?ky.operators.GT:ky.operators.LT;e.fail$data(ky._`Object.keys(${r}).length ${n} ${o}`)}};by.default=Sy;var Py={};Object.defineProperty(Py,"__esModule",{value:!0});const Ty=Ff(),xy=Wh,Iy=Yh,Ny={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:e}})=>xy.str`must have required property '${e}'`,params:({params:{missingProperty:e}})=>xy._`{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(xy.nil,u);else for(const t of r)(0,Ty.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,Ty.propertyInData)(t,n,r,i.ownProperties)),t.if((0,xy.not)(s),()=>{e.error(),t.break()})},xy.nil)}(a,r)),e.ok(r)}else t.if((0,Ty.checkMissingProp)(e,r,a)),(0,Ty.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,Iy.checkStrictMode)(a,t,a.opts.strictRequired)}}function u(){t.forOf("prop",o,r=>{e.setParams({missingProperty:r}),t.if((0,Ty.noPropertyInData)(t,n,r,i.ownProperties),()=>e.error())})}}};Py.default=Ny;var Cy={};Object.defineProperty(Cy,"__esModule",{value:!0});const jy=Wh,Ry={message:({keyword:e,schemaCode:t})=>jy.str`must NOT have ${"maxItems"===e?"more":"fewer"} than ${t} items`,params:({schemaCode:e})=>jy._`{limit: ${e}}`},Oy={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Ry,code(e){const{keyword:t,data:r,schemaCode:o}=e,n="maxItems"===t?jy.operators.GT:jy.operators.LT;e.fail$data(jy._`${r}.length ${n} ${o}`)}};Cy.default=Oy;var zy={},Ay={};Object.defineProperty(Ay,"__esModule",{value:!0});const My=Lc;My.code='require("ajv/dist/runtime/equal").default',Ay.default=My,Object.defineProperty(zy,"__esModule",{value:!0});const Uy=vf,Dy=Wh,qy=Yh,Vy=Ay,Fy={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:e,j:t}})=>Dy.str`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>Dy._`{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,Uy.getSchemaTypes)(s.items):[];function l(o,n){const s=t.name("item"),a=(0,Uy.checkDataTypes)(u,s,i.opts.strictNumbers,Uy.DataType.Wrong),l=t.const("indices",Dy._`{}`);t.for(Dy._`;${o}--;`,()=>{t.let(s,Dy._`${r}[${o}]`),t.if(a,Dy._`continue`),u.length>1&&t.if(Dy._`typeof ${s} == "string"`,Dy._`${s} += "_"`),t.if(Dy._`typeof ${l}[${s}] == "number"`,()=>{t.assign(n,Dy._`${l}[${s}]`),e.error(),t.assign(c,!1).break()}).code(Dy._`${l}[${s}] = ${o}`)})}function d(o,n){const s=(0,qy.useFunc)(t,Vy.default),a=t.name("outer");t.label(a).for(Dy._`;${o}--;`,()=>t.for(Dy._`${n} = ${o}; ${n}--;`,()=>t.if(Dy._`${s}(${r}[${o}], ${r}[${n}])`,()=>{e.error(),t.assign(c,!1).break(a)})))}e.block$data(c,function(){const o=t.let("i",Dy._`${r}.length`),n=t.let("j");e.setParams({i:o,j:n}),t.assign(c,!0),t.if(Dy._`${o} > 1`,()=>(u.length>0&&!u.some(e=>"object"===e||"array"===e)?l:d)(o,n))},Dy._`${a} === false`),e.ok(c)}};zy.default=Fy;var Ly={};Object.defineProperty(Ly,"__esModule",{value:!0});const Ky=Wh,Hy=Yh,Zy=Ay,Gy={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:e})=>Ky._`{allowedValue: ${e}}`},code(e){const{gen:t,data:r,$data:o,schemaCode:n,schema:s}=e;o||s&&"object"==typeof s?e.fail$data(Ky._`!${(0,Hy.useFunc)(t,Zy.default)}(${r}, ${n})`):e.fail(Ky._`${s} !== ${r}`)}};Ly.default=Gy;var Jy={};Object.defineProperty(Jy,"__esModule",{value:!0});const Wy=Wh,By=Yh,Qy=Ay,Yy={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:e})=>Wy._`{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,By.useFunc)(t,Qy.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(Wy._`${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,Wy.or)(...n.map((t,o)=>function(e,t){const o=n[t];return"object"==typeof o&&null!==o?Wy._`${u()}(${r}, ${e}[${t}])`:Wy._`${r} === ${o}`}(e,o)))}e.pass(l)}};Jy.default=Yy,Object.defineProperty(Xm,"__esModule",{value:!0});const Xy=ay,eg=uy,tg=gy,rg=by,og=Py,ng=Cy,sg=zy,ag=Ly,ig=Jy,cg=[ey.default,Xy.default,eg.default,tg.default,rg.default,og.default,ng.default,sg.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},ag.default,ig.default];Xm.default=cg;var ug={},lg={};Object.defineProperty(lg,"__esModule",{value:!0}),lg.validateAdditionalItems=void 0;const dg=Wh,pg=Yh,hg={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],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{parentSchema:t,it:r}=e,{items:o}=t;Array.isArray(o)?fg(e,o):(0,pg.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas')}};function fg(e,t){const{gen:r,schema:o,data:n,keyword:s,it:a}=e;a.items=!0;const i=r.const("len",dg._`${n}.length`);if(!1===o)e.setParams({len:t.length}),e.pass(dg._`${i} <= ${t.length}`);else if("object"==typeof o&&!(0,pg.alwaysValidSchema)(a,o)){const o=r.var("valid",dg._`${i} <= ${t.length}`);r.if((0,dg.not)(o),()=>function(o){r.forRange("i",t.length,i,t=>{e.subschema({keyword:s,dataProp:t,dataPropType:pg.Type.Num},o),a.allErrors||r.if((0,dg.not)(o),()=>r.break())})}(o)),e.ok(o)}}lg.validateAdditionalItems=fg,lg.default=hg;var mg={},yg={};Object.defineProperty(yg,"__esModule",{value:!0}),yg.validateTuple=void 0;const gg=Wh,vg=Yh,_g=Ff(),wg={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){const{schema:t,it:r}=e;if(Array.isArray(t))return $g(e,"additionalItems",t);r.items=!0,(0,vg.alwaysValidSchema)(r,t)||e.ok((0,_g.validateArray)(e))}};function $g(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,vg.checkStrictMode)(i,e,o.strictTuples)}}(n),i.opts.unevaluated&&r.length&&!0!==i.items&&(i.items=vg.mergeEvaluated.items(o,r.length,i.items));const c=o.name("valid"),u=o.const("len",gg._`${s}.length`);r.forEach((t,r)=>{(0,vg.alwaysValidSchema)(i,t)||(o.if(gg._`${u} > ${r}`,()=>e.subschema({keyword:a,schemaProp:r,dataProp:r},c)),e.ok(c))})}yg.validateTuple=$g,yg.default=wg,Object.defineProperty(mg,"__esModule",{value:!0});const bg=yg,kg={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,bg.validateTuple)(e,"items")};mg.default=kg;var Eg={};Object.defineProperty(Eg,"__esModule",{value:!0});const Sg=Wh,Pg=Yh,Tg=Ff(),xg=lg,Ig={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:e}})=>Sg.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>Sg._`{limit: ${e}}`},code(e){const{schema:t,parentSchema:r,it:o}=e,{prefixItems:n}=r;o.items=!0,(0,Pg.alwaysValidSchema)(o,t)||(n?(0,xg.validateAdditionalItems)(e,n):e.ok((0,Tg.validateArray)(e)))}};Eg.default=Ig;var Ng={};Object.defineProperty(Ng,"__esModule",{value:!0});const Cg=Wh,jg=Yh,Rg={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:e,max:t}})=>void 0===t?Cg.str`must contain at least ${e} valid item(s)`:Cg.str`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>void 0===t?Cg._`{minContains: ${e}}`:Cg._`{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",Cg._`${n}.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=Cg._`${l} >= ${a}`;return void 0!==i&&(t=Cg._`${t} && ${l} <= ${i}`),void e.pass(t)}s.items=!0;const d=t.name("valid");function p(){const e=t.name("_valid"),r=t.let("count",0);h(e,()=>t.if(e,()=>function(e){t.code(Cg._`${e}++`),void 0===i?t.if(Cg._`${e} >= ${a}`,()=>t.assign(d,!0).break()):(t.if(Cg._`${e} > ${i}`,()=>t.assign(d,!1).break()),1===a?t.assign(d,!0):t.if(Cg._`${e} >= ${a}`,()=>t.assign(d,!0)))}(r)))}function h(r,o){t.forRange("i",0,l,t=>{e.subschema({keyword:"contains",dataProp:t,dataPropType:jg.Type.Num,compositeRule:!0},r),o()})}void 0===i&&1===a?h(d,()=>t.if(d,()=>t.break())):0===a?(t.let(d,!0),void 0!==i&&t.if(Cg._`${n}.length > 0`,p)):(t.let(d,!1),p()),e.result(d,()=>e.reset())}};Ng.default=Rg;var Og={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=Wh,r=Yh,o=Ff();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
11
|
missingProperty: ${n},
|
|
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}(Ng);var Cg={};Object.defineProperty(Cg,"__esModule",{value:!0});const jg=Zh,Rg=Wh,Og={message:"property name must be valid",params:({params:e})=>jg._`{propertyName: ${e.propertyName}}`},zg={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Og,code(e){const{gen:t,schema:r,data:o,it:n}=e;if((0,Rg.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)}};Cg.default=zg;var Ag={};Object.defineProperty(Ag,"__esModule",{value:!0});const Mg=Df(),Ug=Zh,Dg=hf(),qg=Wh,Vg={message:"must NOT have additional properties",params:({params:e})=>Ug._`{additionalProperty: ${e.additionalProperty}}`},Fg={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Vg,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,qg.alwaysValidSchema)(a,r))return;const u=(0,Mg.allSchemaProperties)(o.properties),l=(0,Mg.allSchemaProperties)(o.patternProperties);function d(e){t.code(Ug._`delete ${n}[${e}]`)}function p(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,qg.alwaysValidSchema)(a,r)){const r=t.name("valid");"failing"===c.removeAdditional?(h(o,r,!1),t.if((0,Ug.not)(r),()=>{e.reset(),d(o)})):(h(o,r),i||t.if((0,Ug.not)(r),()=>t.break()))}}}function h(t,r,o){const n={keyword:"additionalProperties",dataProp:t,dataPropType:qg.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,qg.schemaRefOrVal)(a,o.properties,"properties");n=(0,Mg.isOwnProperty)(t,e,r)}else n=u.length?(0,Ug.or)(...u.map(e=>Ug._`${r} === ${e}`)):Ug.nil;return l.length&&(n=(0,Ug.or)(n,...l.map(t=>Ug._`${(0,Mg.usePattern)(e,t)}.test(${r})`))),(0,Ug.not)(n)}(r),()=>p(r)):p(r)}),e.ok(Ug._`${s} === ${Dg.default.errors}`)}};Ag.default=Fg;var Lg={};Object.defineProperty(Lg,"__esModule",{value:!0});const Kg=cm(),Hg=Df(),Zg=Wh,Gg=Ag,Jg={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&&Gg.default.code(new Kg.KeywordCxt(s,Gg.default,"additionalProperties"));const a=(0,Hg.allSchemaProperties)(r);for(const e of a)s.definedProperties.add(e);s.opts.unevaluated&&a.length&&!0!==s.props&&(s.props=Zg.mergeEvaluated.props(t,(0,Zg.toHash)(a),s.props));const i=a.filter(e=>!(0,Zg.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,Hg.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)}}};Lg.default=Jg;var Wg={};Object.defineProperty(Wg,"__esModule",{value:!0});const Bg=Df(),Qg=Zh,Yg=Wh,Xg=Wh,ev={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,Bg.allSchemaProperties)(r),c=i.filter(e=>(0,Yg.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 Qg.Name||(s.props=(0,Xg.evaluatedPropsToName)(t,s.props));const{props:d}=s;function p(e){for(const t in u)new RegExp(e).test(t)&&(0,Yg.checkStrictMode)(s,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function h(r){t.forIn("key",o,o=>{t.if(Qg._`${(0,Bg.usePattern)(e,r)}.test(${o})`,()=>{const n=c.includes(r);n||e.subschema({keyword:"patternProperties",schemaProp:r,dataProp:o,dataPropType:Xg.Type.Str},l),s.opts.unevaluated&&!0!==d?t.assign(Qg._`${d}[${o}]`,!0):n||s.allErrors||t.if((0,Qg.not)(l),()=>t.break())})})}!function(){for(const e of i)u&&p(e),s.allErrors?h(e):(t.var(l,!0),h(e),t.if(l))}()}};Wg.default=ev;var tv={};Object.defineProperty(tv,"__esModule",{value:!0});const rv=Wh,ov={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){const{gen:t,schema:r,it:o}=e;if((0,rv.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"}};tv.default=ov;var nv={};Object.defineProperty(nv,"__esModule",{value:!0});const sv={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Df().validateUnion,error:{message:"must match a schema in anyOf"}};nv.default=sv;var av={};Object.defineProperty(av,"__esModule",{value:!0});const iv=Zh,cv=Wh,uv={message:"must match exactly one schema in oneOf",params:({params:e})=>iv._`{passingSchemas: ${e.passing}}`},lv={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:uv,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,cv.alwaysValidSchema)(n,r)?t.var(c,!0):s=e.subschema({keyword:"oneOf",schemaProp:o,compositeRule:!0},c),o>0&&t.if(iv._`${c} && ${a}`).assign(a,!1).assign(i,iv._`[${i}, ${o}]`).else(),t.if(c,()=>{t.assign(a,!0),t.assign(i,o),s&&e.mergeEvaluated(s,iv.Name)})})}),e.result(a,()=>e.reset(),()=>e.error(!0))}};av.default=lv;var dv={};Object.defineProperty(dv,"__esModule",{value:!0});const pv=Wh,hv={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,pv.alwaysValidSchema)(o,t))return;const s=e.subschema({keyword:"allOf",schemaProp:r},n);e.ok(n),e.mergeEvaluated(s)})}};dv.default=hv;var fv={};Object.defineProperty(fv,"__esModule",{value:!0});const mv=Zh,yv=Wh,gv={message:({params:e})=>mv.str`must match "${e.ifClause}" schema`,params:({params:e})=>mv._`{failingKeyword: ${e.ifClause}}`},vv={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:gv,code(e){const{gen:t,parentSchema:r,it:o}=e;void 0===r.then&&void 0===r.else&&(0,yv.checkStrictMode)(o,'"if" without "then" and "else" is ignored');const n=_v(o,"then"),s=_v(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,mv.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,mv._`${r}`):e.setParams({ifClause:r})}}e.pass(a,()=>e.error(!0))}};function _v(e,t){const r=e.schema[t];return void 0!==r&&!(0,yv.alwaysValidSchema)(e,r)}fv.default=vv;var wv={};Object.defineProperty(wv,"__esModule",{value:!0});const $v=Wh,bv={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){void 0===t.if&&(0,$v.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};wv.default=bv,Object.defineProperty(sg,"__esModule",{value:!0});const kv=ag,Ev=dg,Sv=pg,Pv=wg,Tv=Pg,xv=Ng,Iv=Cg,Nv=Ag,Cv=Lg,jv=Wg,Rv=tv,Ov=nv,zv=av,Av=dv,Mv=fv,Uv=wv;sg.default=function(e=!1){const t=[Rv.default,Ov.default,zv.default,Av.default,Mv.default,Uv.default,Iv.default,Nv.default,xv.default,Cv.default,jv.default];return e?t.push(Ev.default,Pv.default):t.push(kv.default,Sv.default),t.push(Tv.default),t};var Dv={},qv={};Object.defineProperty(qv,"__esModule",{value:!0});const Vv=Zh,Fv={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>Vv.str`must match format "${e}"`,params:({schemaCode:e})=>Vv._`{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",Vv._`${n}[${a}]`),i=r.let("fType"),u=r.let("format");r.if(Vv._`typeof ${s} == "object" && !(${s} instanceof RegExp)`,()=>r.assign(i,Vv._`${s}.type || "string"`).assign(u,Vv._`${s}.validate`),()=>r.assign(i,Vv._`"string"`).assign(u,s)),e.fail$data((0,Vv.or)(!1===c.strictSchema?Vv.nil:Vv._`${a} && !${u}`,function(){const e=l.$async?Vv._`(${s}.async ? await ${u}(${o}) : ${u}(${o}))`:Vv._`${u}(${o})`,r=Vv._`(typeof ${u} == "function" ? ${e} : ${u}.test(${o}))`;return Vv._`${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,p]=function(e){const t=e instanceof RegExp?(0,Vv.regexpCode)(e):c.code.formats?Vv._`${c.code.formats}${(0,Vv.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,Vv._`${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 Vv._`await ${p}(${o})`}return"function"==typeof i?Vv._`${p}(${o})`:Vv._`${p}.test(${o})`}())}())}};qv.default=Fv,Object.defineProperty(Dv,"__esModule",{value:!0});const Lv=[qv.default];Dv.default=Lv;var Kv={};Object.defineProperty(Kv,"__esModule",{value:!0}),Kv.contentVocabulary=Kv.metadataVocabulary=void 0,Kv.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],Kv.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"],Object.defineProperty(Om,"__esModule",{value:!0});const Hv=Bm,Zv=sg,Gv=Dv,Jv=Kv,Wv=[zm.default,Hv.default,(0,Zv.default)(),Gv.default,Jv.metadataVocabulary,Jv.contentVocabulary];Om.default=Wv;var Bv,Qv={},Yv={};Object.defineProperty(Yv,"__esModule",{value:!0}),Yv.DiscrError=void 0,function(e){e.Tag="tag",e.Mapping="mapping"}(Bv||(Yv.DiscrError=Bv={})),Object.defineProperty(Qv,"__esModule",{value:!0});const Xv=Zh,e_=Yv,t_=mm,r_=fm(),o_=Wh,n_={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:e,tagName:t}})=>e===e_.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>Xv._`{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",Xv._`${r}${(0,Xv.getProperty)(i)}`);function l(r){const o=t.name("valid"),n=e.subschema({keyword:"oneOf",schemaProp:r},o);return e.mergeEvaluated(n,Xv.Name),o}t.if(Xv._`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,o_.schemaHasRulesButRef)(n,s.self.RULES)){const e=n.$ref;if(n=t_.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,e),n instanceof t_.SchemaEnv&&(n=n.schema),void 0===n)throw new r_.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(Xv._`${u} === ${e}`),t.assign(c,l(r[e]));t.else(),e.error(!1,{discrError:e_.DiscrError.Mapping,tag:u,tagName:i}),t.endIf()}(),()=>e.error(!1,{discrError:e_.DiscrError.Tag,tag:u,tagName:i})),e.ok(c)}};Qv.default=n_;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=Fh,o=Om,n=Qv,s=s_,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=cm();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return u.KeywordCxt}});var l=Zh;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=dm();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return d.default}});var p=fm();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return p.default}})}(Vh,Vh.exports);var a_=Vh.exports;!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;const t=a_,r=Zh,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 p(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"`,p(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(p(s))}()},dependencies:["format"]};e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)}(qh),function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r=Dh,o=qh,n=Zh,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}(Uh,Uh.exports);var i_=ji(Uh.exports);class c_{constructor(e){this._ajv=e??function(){const e=new Mh({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 u_{constructor(e){this._client=e}async*callToolStream(e,t=Oa,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 Si(as.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 Si(as.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)})}catch(e){return e instanceof Si?void(yield{type:"error",error:e}):void(yield{type:"error",error:new Si(as.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 l_(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]&&l_(t,r[e])}}if(Array.isArray(e.anyOf))for(const r of e.anyOf)"boolean"!=typeof r&&l_(r,t);if(Array.isArray(e.oneOf))for(const r of e.oneOf)"boolean"!=typeof r&&l_(r,t)}}class d_ extends Ni{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 c_,t?.listChanged&&(this._pendingListChangedConfig=t.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Ma,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",xa,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",ia,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new u_(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];Ci(s)&&Ci(n)?r[o]={...s,...n}:r[o]=n}return r}(this._capabilities,e)}setRequestHandler(e,t){const r=so(e),o=r?.method;if(!o)throw new Error("Schema is missing a method literal");let n;if(oo(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=no(pi,e);if(!o.success){const e=o.error instanceof Error?o.error.message:String(o.error);throw new Si(as.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 Si(as.InvalidParams,"Client does not support form-mode elicitation requests");if("url"===n.mode&&!a)throw new Si(as.InvalidParams,"Client does not support URL-mode elicitation requests");const i=await Promise.resolve(t(e,r));if(n.task){const e=no(zs,i);if(!e.success){const t=e.error instanceof Error?e.error.message:String(e.error);throw new Si(as.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}const c=no(mi,i);if(!c.success){const e=c.error instanceof Error?c.error.message:String(c.error);throw new Si(as.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{l_(l,u.content)}catch{}return u};return super.setRequestHandler(e,r)}if("sampling/createMessage"===s){const r=async(e,r)=>{const o=no(Ya,e);if(!o.success){const e=o.error instanceof Error?o.error.message:String(o.error);throw new Si(as.InvalidParams,`Invalid sampling request: ${e}`)}const{params:n}=o.data,s=await Promise.resolve(t(e,r));if(n.task){const e=no(zs,s);if(!e.success){const t=e.error instanceof Error?e.error.message:String(e.error);throw new Si(as.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}const a=no(n.tools||n.toolChoice?ei:Xa,s);if(!a.success){const e=a.error instanceof Error?a.error.message:String(a.error);throw new Si(as.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:Mn,capabilities:this._capabilities,clientInfo:this._clientInfo}},Es,t);if(void 0===r)throw new Error(`Server sent invalid initialize result: ${r}`);if(!Un.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"},us,e)}async complete(e,t){return this.request({method:"completion/complete",params:e},wi,t)}async setLoggingLevel(e,t){return this.request({method:"logging/setLevel",params:{level:e}},us,t)}async getPrompt(e,t){return this.request({method:"prompts/get",params:e},Ta,t)}async listPrompts(e,t){return this.request({method:"prompts/list",params:e},ga,t)}async listResources(e,t){return this.request({method:"resources/list",params:e},ea,t)}async listResourceTemplates(e,t){return this.request({method:"resources/templates/list",params:e},ra,t)}async readResource(e,t){return this.request({method:"resources/read",params:e},aa,t)}async subscribeResource(e,t){return this.request({method:"resources/subscribe",params:e},us,t)}async unsubscribeResource(e,t){return this.request({method:"resources/unsubscribe",params:e},us,t)}async callTool(e,t=Oa,r){if(this.isToolTaskRequired(e.name))throw new Si(as.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 Si(as.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 Si(as.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)}catch(e){if(e instanceof Si)throw e;throw new Si(as.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},Ra,t);return this.cacheToolMetadata(r.tools),r}_setupListChangedHandler(e,t,r,o){const n=Ua.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 p_(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}const h_=Gr(xo,f_).superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:An,message:"URL must be parseable",fatal:!0}),ae}).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 f_;const m_=cn({resource:ko().url(),authorization_servers:nn(h_).optional(),jwks_uri:ko().url().optional(),scopes_supported:nn(ko()).optional(),bearer_methods_supported:nn(ko()).optional(),resource_signing_alg_values_supported:nn(ko()).optional(),resource_name:ko().optional(),resource_documentation:ko().optional(),resource_policy_uri:ko().url().optional(),resource_tos_uri:ko().url().optional(),tls_client_certificate_bound_access_tokens:Wo().optional(),authorization_details_types_supported:nn(ko()).optional(),dpop_signing_alg_values_supported:nn(ko()).optional(),dpop_bound_access_tokens_required:Wo().optional()}),y_=cn({issuer:ko(),authorization_endpoint:h_,token_endpoint:h_,registration_endpoint:h_.optional(),scopes_supported:nn(ko()).optional(),response_types_supported:nn(ko()),response_modes_supported:nn(ko()).optional(),grant_types_supported:nn(ko()).optional(),token_endpoint_auth_methods_supported:nn(ko()).optional(),token_endpoint_auth_signing_alg_values_supported:nn(ko()).optional(),service_documentation:h_.optional(),revocation_endpoint:h_.optional(),revocation_endpoint_auth_methods_supported:nn(ko()).optional(),revocation_endpoint_auth_signing_alg_values_supported:nn(ko()).optional(),introspection_endpoint:ko().optional(),introspection_endpoint_auth_methods_supported:nn(ko()).optional(),introspection_endpoint_auth_signing_alg_values_supported:nn(ko()).optional(),code_challenge_methods_supported:nn(ko()).optional(),client_id_metadata_document_supported:Wo().optional()}),g_=an({...cn({issuer:ko(),authorization_endpoint:h_,token_endpoint:h_,userinfo_endpoint:h_.optional(),jwks_uri:h_,registration_endpoint:h_.optional(),scopes_supported:nn(ko()).optional(),response_types_supported:nn(ko()),response_modes_supported:nn(ko()).optional(),grant_types_supported:nn(ko()).optional(),acr_values_supported:nn(ko()).optional(),subject_types_supported:nn(ko()),id_token_signing_alg_values_supported:nn(ko()),id_token_encryption_alg_values_supported:nn(ko()).optional(),id_token_encryption_enc_values_supported:nn(ko()).optional(),userinfo_signing_alg_values_supported:nn(ko()).optional(),userinfo_encryption_alg_values_supported:nn(ko()).optional(),userinfo_encryption_enc_values_supported:nn(ko()).optional(),request_object_signing_alg_values_supported:nn(ko()).optional(),request_object_encryption_alg_values_supported:nn(ko()).optional(),request_object_encryption_enc_values_supported:nn(ko()).optional(),token_endpoint_auth_methods_supported:nn(ko()).optional(),token_endpoint_auth_signing_alg_values_supported:nn(ko()).optional(),display_values_supported:nn(ko()).optional(),claim_types_supported:nn(ko()).optional(),claims_supported:nn(ko()).optional(),service_documentation:ko().optional(),claims_locales_supported:nn(ko()).optional(),ui_locales_supported:nn(ko()).optional(),claims_parameter_supported:Wo().optional(),request_parameter_supported:Wo().optional(),request_uri_parameter_supported:Wo().optional(),require_request_uri_registration:Wo().optional(),op_policy_uri:h_.optional(),op_tos_uri:h_.optional(),client_id_metadata_document_supported:Wo().optional()}).shape,...y_.pick({code_challenge_methods_supported:!0}).shape}),v_=an({access_token:ko(),id_token:ko().optional(),token_type:ko(),expires_in:function(e){return function(e,t){return new e({type:"number",coerce:!0,checks:[],...Se(t)})}(Ko,e)}().optional(),scope:ko().optional(),refresh_token:ko().optional()}).strip(),__=an({error:ko(),error_description:ko().optional(),error_uri:ko().optional()}),w_=h_.optional().or(wn("").transform(()=>{})),$_=an({redirect_uris:nn(h_),token_endpoint_auth_method:ko().optional(),grant_types:nn(ko()).optional(),response_types:nn(ko()).optional(),client_name:ko().optional(),client_uri:h_.optional(),logo_uri:w_,scope:ko().optional(),contacts:nn(ko()).optional(),tos_uri:w_,policy_uri:ko().optional(),jwks_uri:h_.optional(),jwks:new Yo({type:"any"}).optional(),software_id:ko().optional(),software_version:ko().optional(),software_statement:ko().optional()}).strip(),b_=an({client_id:ko(),client_secret:ko().optional(),client_id_issued_at:Ho().optional(),client_secret_expires_at:Ho().optional()}).strip(),k_=$_.merge(b_);an({error:ko(),error_description:ko().optional()}).strip(),an({token:ko(),token_type_hint:ko().optional()}).strip();class E_ 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 S_ extends E_{}S_.errorCode="invalid_request";class P_ extends E_{}P_.errorCode="invalid_client";class T_ extends E_{}T_.errorCode="invalid_grant";class x_ extends E_{}x_.errorCode="unauthorized_client";class I_ extends E_{}I_.errorCode="unsupported_grant_type";class N_ extends E_{}N_.errorCode="invalid_scope";class C_ extends E_{}C_.errorCode="access_denied";class j_ extends E_{}j_.errorCode="server_error";class R_ extends E_{}R_.errorCode="temporarily_unavailable";class O_ extends E_{}O_.errorCode="unsupported_response_type";class z_ extends E_{}z_.errorCode="unsupported_token_type";class A_ extends E_{}A_.errorCode="invalid_token";class M_ extends E_{}M_.errorCode="method_not_allowed";class U_ extends E_{}U_.errorCode="too_many_requests";class D_ extends E_{}D_.errorCode="invalid_client_metadata";class q_ extends E_{}q_.errorCode="insufficient_scope";class V_ extends E_{}V_.errorCode="invalid_target";const F_={[S_.errorCode]:S_,[P_.errorCode]:P_,[T_.errorCode]:T_,[x_.errorCode]:x_,[I_.errorCode]:I_,[N_.errorCode]:N_,[C_.errorCode]:C_,[j_.errorCode]:j_,[R_.errorCode]:R_,[O_.errorCode]:O_,[z_.errorCode]:z_,[A_.errorCode]:A_,[M_.errorCode]:M_,[U_.errorCode]:U_,[D_.errorCode]:D_,[q_.errorCode]:q_,[V_.errorCode]:V_};class L_ extends Error{constructor(e){super(e??"Unauthorized")}}const K_="code",H_="S256";function Z_(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 G_(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const e=__.parse(JSON.parse(r)),{error:t,error_description:o,error_uri:n}=e;return new(F_[t]||j_)(o||"",n)}catch(e){return new j_(`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${e}. Raw body: ${r}`)}}async function J_(e,t){try{return await W_(e,t)}catch(r){if(r instanceof P_||r instanceof x_)return await(e.invalidateCredentials?.("all")),await W_(e,t);if(r instanceof T_)return await(e.invalidateCredentials?.("tokens")),await W_(e,t);throw r}}async function W_(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??Mn;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 X_(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 X_(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 m_.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),l=await async function(e,{fetchFn:t=fetch,protocolVersion:r=Mn}={}){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 Y_(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?y_.parse(await n.json()):g_.parse(await n.json())}}return}(i,{fetchFn:s});let d=await Promise.resolve(e.clientInformation());if(!d){if(void 0!==r)throw new Error("Existing OAuth client information is required when exchanging an authorization code");const t=!0===l?.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 D_(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${o}`);if(t&&o)d={client_id:o},await(e.saveClientInformation?.(d));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 G_(s);return k_.parse(await s.json())}(i,{metadata:l,clientMetadata:e.clientMetadata,fetchFn:s});await e.saveClientInformation(t),d=t}}const p=!e.redirectUrl;if(void 0!==r||p){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 ew(t,{metadata:r,tokenRequestParams:i,clientInformation:c??void 0,addClientAuthentication:e.addClientAuthentication,resource:o,fetchFn:s})}(e,i,{metadata:l,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 ew(e,{metadata:t,tokenRequestParams:i,clientInformation:r,addClientAuthentication:s,resource:n,fetchFn:a});return{refresh_token:o,...c}}(i,{metadata:l,clientInformation:d,refreshToken:h.refresh_token,resource:c,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(t),"AUTHORIZED"}catch(e){if(e instanceof E_&&!(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(K_))throw new Error(`Incompatible auth server: does not support response type ${K_}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(H_))throw new Error(`Incompatible auth server: does not support code challenge method ${H_}`)}else i=new URL("/authorize",e);const c=await u(),l=c.code_verifier,d=c.code_challenge;i.searchParams.set("response_type",K_),i.searchParams.set("client_id",r.client_id),i.searchParams.set("code_challenge",d),i.searchParams.set("code_challenge_method",H_),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:l}}(i,{metadata:l,clientInformation:d,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 B_(e){const t=e.headers.get("WWW-Authenticate");if(!t)return{};const[r,o]=t.split(" ");if("bearer"!==r.toLowerCase()||!o)return{};const n=Q_(e,"resource_metadata")||void 0;let s;if(n)try{s=new URL(n)}catch{}return{resourceMetadataUrl:s,scope:Q_(e,"scope")||void 0,error:Q_(e,"error")||void 0}}function Q_(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 Y_(e,t,r=fetch){try{return await r(e,{headers:t})}catch(o){if(o instanceof TypeError)return t?Y_(e,void 0,r):void 0;throw o}}async function X_(e,t,r=fetch){const o={"MCP-Protocol-Version":t};return await Y_(e,o,r)}async function ew(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??[]);Z_(e,o,c,r)}const u=await(a??fetch)(i,{method:"POST",headers:c,body:r});if(!u.ok)throw await G_(u);return v_.parse(await u.json())}class tw 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 rw(e){}function ow(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=rw,onError:r=rw,onRetry:o=rw,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 tw(`Invalid \`retry\` value: "${t}"`,{type:"invalid-retry",value:t,line:n}));break;default:r(new tw(`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 nw extends TransformStream{constructor({onError:e,onRetry:t,onComment:r}={}){let o;super({start(n){o=ow({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 sw={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class aw 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,o)=>{const n={...t,...o,headers:o?.headers?{...p_(t.headers),...p_(o.headers)}:t.headers};return e(r,n)}:e}(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??sw}async _authThenStart(){if(!this._authProvider)throw new L_("No auth provider");let e;try{e=await J_(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 L_;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=p_(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 aw(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 nw({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=cs.parse(JSON.parse(e.data));ss(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 L_("No auth provider");if("AUTHORIZED"!==await J_(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit}))throw new L_("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:rs(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 aw(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:t,scope:r}=B_(i);this._resourceMetadataUrl=t,this._scope=r;if("AUTHORIZED"!==await J_(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit}))throw new L_;return this._hasCompletedAuthFlow=!0,this.send(e)}if(403===i.status&&this._authProvider){const{resourceMetadataUrl:t,scope:r,error:o}=B_(i);if("insufficient_scope"===o){const o=i.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===o)throw new aw(403,"Server returned 403 after trying upscoping");r&&(this._scope=r),t&&(this._resourceMetadataUrl=t),this._lastUpscopingHeader=o??void 0;if("AUTHORIZED"!==await J_(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch}))throw new L_;return this.send(e)}}throw new aw(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(Ss.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 aw(-1,`Unexpected content type: ${l}`);{const e=await i.json(),t=Array.isArray(e)?e.map(e=>cs.parse(e)):[cs.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 aw(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 cw=M("quickstart");async function uw(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 g&&404===e.statusCode)throw new v(i);throw e}const u=c.slug||i;let l;if(z(e.token)){l=`${O(e.token).baseUrl}/mcp/${u}`}else{cw.warn("Token has no organization information, using static config for MCP connection");l=`${R().baseUrl}/mcp/${u}`}return[{url:l,transport:a,headers:{Accept:"application/json, text/event-stream",Authorization:`Bearer ${e.token}`,"x-barndoor-session-id":lw()}},l]}function lw(){if(I&&"function"==typeof n.randomUUID)return n.randomUUID();if("undefined"!=typeof globalThis&&globalThis.crypto?.randomUUID)return globalThis.crypto.randomUUID();let e;if(I&&"function"==typeof n.randomBytes)e=n.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 s=Array.from(t,e=>e.toString(16).padStart(2,"0")).join("");return`${s.substring(0,8)}-${s.substring(8,12)}-${s.substring(12,16)}-${s.substring(16,20)}-${s.substring(20)}`}const dw=function(){try{if("undefined"!=typeof process&&process.versions?.node){const e=a.fileURLToPath("undefined"==typeof document?require("url").pathToFileURL(e).href:d&&"SCRIPT"===d.tagName.toUpperCase()&&d.src||new URL("index.js",document.baseURI).href),r=t.dirname(e),o=t.join(r,"..","package.json");return JSON.parse(l.readFileSync(o,"utf8")).version}return'"1.0.2"'}catch(e){return console.warn("Could not read version from package.json:",e),"0.1.0"}}();exports.AUTH_CONFIG=T,exports.AgentToken=P,exports.AuthenticationError=h,exports.BarndoorConfig=C,exports.BarndoorError=p,exports.BarndoorSDK=se,exports.ConfigurationError=w,exports.ConnectionError=y,exports.HTTPError=g,exports.OAuthError=_,exports.PKCEManager=te,exports.ServerDetail=S,exports.ServerNotFoundError=v,exports.ServerSummary=E,exports.TimeoutError=$,exports.TokenError=f,exports.TokenExpiredError=m,exports.TokenManager=Y,exports.TokenValidationError=class extends f{},exports.checkTokenOrganization=function(e){return j(e)},exports.clearCachedToken=async function(){const e=W();await e.clearToken()},exports.clearOidcConfigCache=function(){D.clear()},exports.createScopedLogger=M,exports.debug=function(e,...t){A.debug(e,...t)},exports.ensureServerConnected=async function(e,t,r={}){const{timeout:o=90}=r;cw.info(`Ensuring ${t} server is connected`);try{await e.ensureServerConnected(t,{pollSeconds:o}),cw.info(`Server ${t} connected successfully`)}catch(e){throw e instanceof v?cw.error(`Server '${t}' not found`):cw.error(`Failed to connect to ${t}:`,e),e}},exports.error=function(e,...t){A.error(e,...t)},exports.getDynamicConfig=O,exports.getLogger=function(){return A},exports.getOidcConfig=q,exports.getStaticConfig=R,exports.hasOrganizationInfo=z,exports.info=function(e,...t){A.info(e,...t)},exports.isBrowser=x,exports.isNode=I,exports.isTokenActive=async function(e){try{const e=W(),t=await e.loadToken();if(!t?.access_token)return!1;const r=R(),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 F(n,1e4)).ok}catch(e){return!1}},exports.isTokenActiveWithRefresh=async function(e){try{const t=new Y(e||"");return await t.getValidToken(),!0}catch(e){return U.warn("Token validation/refresh failed:",e),!1}},exports.loadUserToken=X,exports.loginInteractive=async function(t={}){if(!I)throw new Error("Interactive login is only available in Node.js environment");cw.info("Starting interactive login flow");const r=R();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:u,port:l=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 d=await X();if(d)try{let e;z(d)?e=O(d):(cw.warn("Cached token has no organization information, using static config"),e=R());const t=new se(e.baseUrl,{token:d});return await t.validateCachedToken(),cw.info("Using cached valid token"),t}catch(e){cw.info("Cached token invalid, starting OAuth flow")}else cw.info("No cached token, starting OAuth flow");const p="undefined"!=typeof process&&!(!process.env||"1"!==process.env.BARNDOOR_MANUAL_CODE&&"true"!==process.env.BARNDOOR_MANUAL_CODE);let h,f=null;if(p){const e=process.env&&process.env.BARNDOOR_REDIRECT_HOST||"127.0.0.1";h=e.startsWith("http")?`${e}:${l}/cb`:`http://${e}:${l}/cb`}else{const e=ne(l);h=e[0],f=e[1]}const m=new te,y=await m.buildAuthorizationUrl({clientId:n,redirectUri:h,audience:a,issuer:o});cw.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?i.spawn("open",[y],{detached:!0,stdio:"ignore"}).unref():"win32"===g?i.spawn("powershell",["-NoProfile","Start-Process",y],{detached:!0,stdio:"ignore"}).unref():i.spawn("xdg-open",[y],{detached:!0,stdio:"ignore"}).unref(),cw.info("Please complete login in your browser…")}catch(e){cw.warn("Failed to open browser automatically. Please visit:",y)}if(p){const e=await new Promise(e=>{const t=c.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 "${h}" 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:h,issuer:o});let $;if(await ee(w),u)$=u;else if(z(w.access_token)){$=O(w.access_token).baseUrl}else cw.warn("New token has no organization information, using static config"),$=R().baseUrl;return new se($,{token:w.access_token})},exports.makeMcpClient=async function(e,t,r={}){const[o]=await uw(e,t,r),n=o,s=new d_({name:"barndoor-js-sdk",version:"0.1.0"}),a=new iw(new URL(n.url),{requestInit:{headers:n.headers}});return await s.connect(a),s},exports.makeMcpConnectionParams=uw,exports.saveUserToken=ee,exports.setLogger=function(e){A=e},exports.setTokenLogger=function(e){console.warn("setTokenLogger is deprecated. Use setLogger from the main logging module instead.")},exports.startLocalCallbackServer=ne,exports.validateToken=async function(e,t){try{const t=R(),r=await B(e,t.authIssuer,t.apiAudience);if(r===exports.JWTVerificationResult.VALID)return{valid:!0};if(r===exports.JWTVerificationResult.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 F(o,5e3)).ok}}catch(e){return U.warn("Remote token validation failed:",e),{valid:!1}}return{valid:!1}}catch(e){return U.warn("Token validation failed:",e),{valid:!1}}},exports.verifyJWTLocal=B,exports.version=dw,exports.warn=function(e,...t){A.warn(e,...t)};
|
|
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}(Og);var zg={};Object.defineProperty(zg,"__esModule",{value:!0});const Ag=Wh,Mg=Yh,Ug={message:"property name must be valid",params:({params:e})=>Ag._`{propertyName: ${e.propertyName}}`},Dg={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Ug,code(e){const{gen:t,schema:r,data:o,it:n}=e;if((0,Mg.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,Ag.not)(s),()=>{e.error(!0),n.allErrors||t.break()})}),e.ok(s)}};zg.default=Dg;var qg={};Object.defineProperty(qg,"__esModule",{value:!0});const Vg=Ff(),Fg=Wh,Lg=yf(),Kg=Yh,Hg={message:"must NOT have additional properties",params:({params:e})=>Fg._`{additionalProperty: ${e.additionalProperty}}`},Zg={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Hg,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,Kg.alwaysValidSchema)(a,r))return;const u=(0,Vg.allSchemaProperties)(o.properties),l=(0,Vg.allSchemaProperties)(o.patternProperties);function d(e){t.code(Fg._`delete ${n}[${e}]`)}function p(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,Kg.alwaysValidSchema)(a,r)){const r=t.name("valid");"failing"===c.removeAdditional?(h(o,r,!1),t.if((0,Fg.not)(r),()=>{e.reset(),d(o)})):(h(o,r),i||t.if((0,Fg.not)(r),()=>t.break()))}}}function h(t,r,o){const n={keyword:"additionalProperties",dataProp:t,dataPropType:Kg.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,Kg.schemaRefOrVal)(a,o.properties,"properties");n=(0,Vg.isOwnProperty)(t,e,r)}else n=u.length?(0,Fg.or)(...u.map(e=>Fg._`${r} === ${e}`)):Fg.nil;return l.length&&(n=(0,Fg.or)(n,...l.map(t=>Fg._`${(0,Vg.usePattern)(e,t)}.test(${r})`))),(0,Fg.not)(n)}(r),()=>p(r)):p(r)}),e.ok(Fg._`${s} === ${Lg.default.errors}`)}};qg.default=Zg;var Gg={};Object.defineProperty(Gg,"__esModule",{value:!0});const Jg=dm(),Wg=Ff(),Bg=Yh,Qg=qg,Yg={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&&Qg.default.code(new Jg.KeywordCxt(s,Qg.default,"additionalProperties"));const a=(0,Wg.allSchemaProperties)(r);for(const e of a)s.definedProperties.add(e);s.opts.unevaluated&&a.length&&!0!==s.props&&(s.props=Bg.mergeEvaluated.props(t,(0,Bg.toHash)(a),s.props));const i=a.filter(e=>!(0,Bg.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,Wg.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)}}};Gg.default=Yg;var Xg={};Object.defineProperty(Xg,"__esModule",{value:!0});const ev=Ff(),tv=Wh,rv=Yh,ov=Yh,nv={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,ev.allSchemaProperties)(r),c=i.filter(e=>(0,rv.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 tv.Name||(s.props=(0,ov.evaluatedPropsToName)(t,s.props));const{props:d}=s;function p(e){for(const t in u)new RegExp(e).test(t)&&(0,rv.checkStrictMode)(s,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function h(r){t.forIn("key",o,o=>{t.if(tv._`${(0,ev.usePattern)(e,r)}.test(${o})`,()=>{const n=c.includes(r);n||e.subschema({keyword:"patternProperties",schemaProp:r,dataProp:o,dataPropType:ov.Type.Str},l),s.opts.unevaluated&&!0!==d?t.assign(tv._`${d}[${o}]`,!0):n||s.allErrors||t.if((0,tv.not)(l),()=>t.break())})})}!function(){for(const e of i)u&&p(e),s.allErrors?h(e):(t.var(l,!0),h(e),t.if(l))}()}};Xg.default=nv;var sv={};Object.defineProperty(sv,"__esModule",{value:!0});const av=Yh,iv={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){const{gen:t,schema:r,it:o}=e;if((0,av.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"}};sv.default=iv;var cv={};Object.defineProperty(cv,"__esModule",{value:!0});const uv={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Ff().validateUnion,error:{message:"must match a schema in anyOf"}};cv.default=uv;var lv={};Object.defineProperty(lv,"__esModule",{value:!0});const dv=Wh,pv=Yh,hv={message:"must match exactly one schema in oneOf",params:({params:e})=>dv._`{passingSchemas: ${e.passing}}`},fv={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:hv,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,pv.alwaysValidSchema)(n,r)?t.var(c,!0):s=e.subschema({keyword:"oneOf",schemaProp:o,compositeRule:!0},c),o>0&&t.if(dv._`${c} && ${a}`).assign(a,!1).assign(i,dv._`[${i}, ${o}]`).else(),t.if(c,()=>{t.assign(a,!0),t.assign(i,o),s&&e.mergeEvaluated(s,dv.Name)})})}),e.result(a,()=>e.reset(),()=>e.error(!0))}};lv.default=fv;var mv={};Object.defineProperty(mv,"__esModule",{value:!0});const yv=Yh,gv={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,yv.alwaysValidSchema)(o,t))return;const s=e.subschema({keyword:"allOf",schemaProp:r},n);e.ok(n),e.mergeEvaluated(s)})}};mv.default=gv;var vv={};Object.defineProperty(vv,"__esModule",{value:!0});const _v=Wh,wv=Yh,$v={message:({params:e})=>_v.str`must match "${e.ifClause}" schema`,params:({params:e})=>_v._`{failingKeyword: ${e.ifClause}}`},bv={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:$v,code(e){const{gen:t,parentSchema:r,it:o}=e;void 0===r.then&&void 0===r.else&&(0,wv.checkStrictMode)(o,'"if" without "then" and "else" is ignored');const n=kv(o,"then"),s=kv(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,_v.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,_v._`${r}`):e.setParams({ifClause:r})}}e.pass(a,()=>e.error(!0))}};function kv(e,t){const r=e.schema[t];return void 0!==r&&!(0,wv.alwaysValidSchema)(e,r)}vv.default=bv;var Ev={};Object.defineProperty(Ev,"__esModule",{value:!0});const Sv=Yh,Pv={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){void 0===t.if&&(0,Sv.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};Ev.default=Pv,Object.defineProperty(ug,"__esModule",{value:!0});const Tv=lg,xv=mg,Iv=yg,Nv=Eg,Cv=Ng,jv=Og,Rv=zg,Ov=qg,zv=Gg,Av=Xg,Mv=sv,Uv=cv,Dv=lv,qv=mv,Vv=vv,Fv=Ev;ug.default=function(e=!1){const t=[Mv.default,Uv.default,Dv.default,qv.default,Vv.default,Fv.default,Rv.default,Ov.default,jv.default,zv.default,Av.default];return e?t.push(xv.default,Nv.default):t.push(Tv.default,Iv.default),t.push(Cv.default),t};var Lv={},Kv={};Object.defineProperty(Kv,"__esModule",{value:!0});const Hv=Wh,Zv={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>Hv.str`must match format "${e}"`,params:({schemaCode:e})=>Hv._`{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",Hv._`${n}[${a}]`),i=r.let("fType"),u=r.let("format");r.if(Hv._`typeof ${s} == "object" && !(${s} instanceof RegExp)`,()=>r.assign(i,Hv._`${s}.type || "string"`).assign(u,Hv._`${s}.validate`),()=>r.assign(i,Hv._`"string"`).assign(u,s)),e.fail$data((0,Hv.or)(!1===c.strictSchema?Hv.nil:Hv._`${a} && !${u}`,function(){const e=l.$async?Hv._`(${s}.async ? await ${u}(${o}) : ${u}(${o}))`:Hv._`${u}(${o})`,r=Hv._`(typeof ${u} == "function" ? ${e} : ${u}.test(${o}))`;return Hv._`${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,p]=function(e){const t=e instanceof RegExp?(0,Hv.regexpCode)(e):c.code.formats?Hv._`${c.code.formats}${(0,Hv.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,Hv._`${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 Hv._`await ${p}(${o})`}return"function"==typeof i?Hv._`${p}(${o})`:Hv._`${p}.test(${o})`}())}())}};Kv.default=Zv,Object.defineProperty(Lv,"__esModule",{value:!0});const Gv=[Kv.default];Lv.default=Gv;var Jv={};Object.defineProperty(Jv,"__esModule",{value:!0}),Jv.contentVocabulary=Jv.metadataVocabulary=void 0,Jv.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],Jv.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"],Object.defineProperty(Mm,"__esModule",{value:!0});const Wv=Xm,Bv=ug,Qv=Lv,Yv=Jv,Xv=[Um.default,Wv.default,(0,Bv.default)(),Qv.default,Yv.metadataVocabulary,Yv.contentVocabulary];Mm.default=Xv;var e_,t_={},r_={};Object.defineProperty(r_,"__esModule",{value:!0}),r_.DiscrError=void 0,function(e){e.Tag="tag",e.Mapping="mapping"}(e_||(r_.DiscrError=e_={})),Object.defineProperty(t_,"__esModule",{value:!0});const o_=Wh,n_=r_,s_=vm,a_=gm(),i_=Yh,c_={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:e,tagName:t}})=>e===n_.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>o_._`{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",o_._`${r}${(0,o_.getProperty)(i)}`);function l(r){const o=t.name("valid"),n=e.subschema({keyword:"oneOf",schemaProp:r},o);return e.mergeEvaluated(n,o_.Name),o}t.if(o_._`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,i_.schemaHasRulesButRef)(n,s.self.RULES)){const e=n.$ref;if(n=s_.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,e),n instanceof s_.SchemaEnv&&(n=n.schema),void 0===n)throw new a_.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(o_._`${u} === ${e}`),t.assign(c,l(r[e]));t.else(),e.error(!1,{discrError:n_.DiscrError.Mapping,tag:u,tagName:i}),t.endIf()}(),()=>e.error(!1,{discrError:n_.DiscrError.Tag,tag:u,tagName:i})),e.ok(c)}};t_.default=c_;var u_={$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=Hh,o=Mm,n=t_,s=u_,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=dm();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return u.KeywordCxt}});var l=Wh;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=fm();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return d.default}});var p=gm();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return p.default}})}(Kh,Kh.exports);var l_=Kh.exports;!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;const t=l_,r=Wh,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 p(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"`,p(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(p(s))}()},dependencies:["format"]};e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)}(Lh),function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r=Fh,o=Lh,n=Wh,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}(Vh,Vh.exports);var d_=Oi(Vh.exports);class p_{constructor(e){this._ajv=e??function(){const e=new qh({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return d_(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 h_{constructor(e){this._client=e}async*callToolStream(e,t=Aa,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 Ti(cs.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 Ti(cs.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)})}catch(e){return e instanceof Ti?void(yield{type:"error",error:e}):void(yield{type:"error",error:new Ti(cs.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 f_(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]&&f_(t,r[e])}}if(Array.isArray(e.anyOf))for(const r of e.anyOf)"boolean"!=typeof r&&f_(r,t);if(Array.isArray(e.oneOf))for(const r of e.oneOf)"boolean"!=typeof r&&f_(r,t)}}class m_ 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 p_,t?.listChanged&&(this._pendingListChangedConfig=t.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Da,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Na,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",ua,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new h_(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];Ri(s)&&Ri(n)?r[o]={...s,...n}:r[o]=n}return r}(this._capabilities,e)}setRequestHandler(e,t){const r=io(e),o=r?.method;if(!o)throw new Error("Schema is missing a method literal");let n;if(so(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=ao(fi,e);if(!o.success){const e=o.error instanceof Error?o.error.message:String(o.error);throw new Ti(cs.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 Ti(cs.InvalidParams,"Client does not support form-mode elicitation requests");if("url"===n.mode&&!a)throw new Ti(cs.InvalidParams,"Client does not support URL-mode elicitation requests");const i=await Promise.resolve(t(e,r));if(n.task){const e=ao(Ms,i);if(!e.success){const t=e.error instanceof Error?e.error.message:String(e.error);throw new Ti(cs.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}const c=ao(gi,i);if(!c.success){const e=c.error instanceof Error?c.error.message:String(c.error);throw new Ti(cs.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{f_(l,u.content)}catch{}return u};return super.setRequestHandler(e,r)}if("sampling/createMessage"===s){const r=async(e,r)=>{const o=ao(ei,e);if(!o.success){const e=o.error instanceof Error?o.error.message:String(o.error);throw new Ti(cs.InvalidParams,`Invalid sampling request: ${e}`)}const{params:n}=o.data,s=await Promise.resolve(t(e,r));if(n.task){const e=ao(Ms,s);if(!e.success){const t=e.error instanceof Error?e.error.message:String(e.error);throw new Ti(cs.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}const a=ao(n.tools||n.toolChoice?ri:ti,s);if(!a.success){const e=a.error instanceof Error?a.error.message:String(a.error);throw new Ti(cs.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:Dn,capabilities:this._capabilities,clientInfo:this._clientInfo}},Ps,t);if(void 0===r)throw new Error(`Server sent invalid initialize result: ${r}`);if(!qn.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"},ds,e)}async complete(e,t){return this.request({method:"completion/complete",params:e},bi,t)}async setLoggingLevel(e,t){return this.request({method:"logging/setLevel",params:{level:e}},ds,t)}async getPrompt(e,t){return this.request({method:"prompts/get",params:e},Ia,t)}async listPrompts(e,t){return this.request({method:"prompts/list",params:e},_a,t)}async listResources(e,t){return this.request({method:"resources/list",params:e},ra,t)}async listResourceTemplates(e,t){return this.request({method:"resources/templates/list",params:e},na,t)}async readResource(e,t){return this.request({method:"resources/read",params:e},ca,t)}async subscribeResource(e,t){return this.request({method:"resources/subscribe",params:e},ds,t)}async unsubscribeResource(e,t){return this.request({method:"resources/unsubscribe",params:e},ds,t)}async callTool(e,t=Aa,r){if(this.isToolTaskRequired(e.name))throw new Ti(cs.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 Ti(cs.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 Ti(cs.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)}catch(e){if(e instanceof Ti)throw e;throw new Ti(cs.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},za,t);return this.cacheToolMetadata(r.tools),r}_setupListChangedHandler(e,t,r,o){const n=qa.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 y_(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}const g_=Wr(No,v_).superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Un,message:"URL must be parseable",fatal:!0}),ce}).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 v_;const __=ln({resource:So().url(),authorization_servers:an(g_).optional(),jwks_uri:So().url().optional(),scopes_supported:an(So()).optional(),bearer_methods_supported:an(So()).optional(),resource_signing_alg_values_supported:an(So()).optional(),resource_name:So().optional(),resource_documentation:So().optional(),resource_policy_uri:So().url().optional(),resource_tos_uri:So().url().optional(),tls_client_certificate_bound_access_tokens:Qo().optional(),authorization_details_types_supported:an(So()).optional(),dpop_signing_alg_values_supported:an(So()).optional(),dpop_bound_access_tokens_required:Qo().optional()}),w_=ln({issuer:So(),authorization_endpoint:g_,token_endpoint:g_,registration_endpoint:g_.optional(),scopes_supported:an(So()).optional(),response_types_supported:an(So()),response_modes_supported:an(So()).optional(),grant_types_supported:an(So()).optional(),token_endpoint_auth_methods_supported:an(So()).optional(),token_endpoint_auth_signing_alg_values_supported:an(So()).optional(),service_documentation:g_.optional(),revocation_endpoint:g_.optional(),revocation_endpoint_auth_methods_supported:an(So()).optional(),revocation_endpoint_auth_signing_alg_values_supported:an(So()).optional(),introspection_endpoint:So().optional(),introspection_endpoint_auth_methods_supported:an(So()).optional(),introspection_endpoint_auth_signing_alg_values_supported:an(So()).optional(),code_challenge_methods_supported:an(So()).optional(),client_id_metadata_document_supported:Qo().optional()}),$_=un({...ln({issuer:So(),authorization_endpoint:g_,token_endpoint:g_,userinfo_endpoint:g_.optional(),jwks_uri:g_,registration_endpoint:g_.optional(),scopes_supported:an(So()).optional(),response_types_supported:an(So()),response_modes_supported:an(So()).optional(),grant_types_supported:an(So()).optional(),acr_values_supported:an(So()).optional(),subject_types_supported:an(So()),id_token_signing_alg_values_supported:an(So()),id_token_encryption_alg_values_supported:an(So()).optional(),id_token_encryption_enc_values_supported:an(So()).optional(),userinfo_signing_alg_values_supported:an(So()).optional(),userinfo_encryption_alg_values_supported:an(So()).optional(),userinfo_encryption_enc_values_supported:an(So()).optional(),request_object_signing_alg_values_supported:an(So()).optional(),request_object_encryption_alg_values_supported:an(So()).optional(),request_object_encryption_enc_values_supported:an(So()).optional(),token_endpoint_auth_methods_supported:an(So()).optional(),token_endpoint_auth_signing_alg_values_supported:an(So()).optional(),display_values_supported:an(So()).optional(),claim_types_supported:an(So()).optional(),claims_supported:an(So()).optional(),service_documentation:So().optional(),claims_locales_supported:an(So()).optional(),ui_locales_supported:an(So()).optional(),claims_parameter_supported:Qo().optional(),request_parameter_supported:Qo().optional(),request_uri_parameter_supported:Qo().optional(),require_request_uri_registration:Qo().optional(),op_policy_uri:g_.optional(),op_tos_uri:g_.optional(),client_id_metadata_document_supported:Qo().optional()}).shape,...w_.pick({code_challenge_methods_supported:!0}).shape}),b_=un({access_token:So(),id_token:So().optional(),token_type:So(),expires_in:function(e){return function(e,t){return new e({type:"number",coerce:!0,checks:[],...Te(t)})}(Zo,e)}().optional(),scope:So().optional(),refresh_token:So().optional()}).strip(),k_=un({error:So(),error_description:So().optional(),error_uri:So().optional()}),E_=g_.optional().or(bn("").transform(()=>{})),S_=un({redirect_uris:an(g_),token_endpoint_auth_method:So().optional(),grant_types:an(So()).optional(),response_types:an(So()).optional(),client_name:So().optional(),client_uri:g_.optional(),logo_uri:E_,scope:So().optional(),contacts:an(So()).optional(),tos_uri:E_,policy_uri:So().optional(),jwks_uri:g_.optional(),jwks:new en({type:"any"}).optional(),software_id:So().optional(),software_version:So().optional(),software_statement:So().optional()}).strip(),P_=un({client_id:So(),client_secret:So().optional(),client_id_issued_at:Go().optional(),client_secret_expires_at:Go().optional()}).strip(),T_=S_.merge(P_);un({error:So(),error_description:So().optional()}).strip(),un({token:So(),token_type_hint:So().optional()}).strip();class x_ 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 I_ extends x_{}I_.errorCode="invalid_request";class N_ extends x_{}N_.errorCode="invalid_client";class C_ extends x_{}C_.errorCode="invalid_grant";class j_ extends x_{}j_.errorCode="unauthorized_client";class R_ extends x_{}R_.errorCode="unsupported_grant_type";class O_ extends x_{}O_.errorCode="invalid_scope";class z_ extends x_{}z_.errorCode="access_denied";class A_ extends x_{}A_.errorCode="server_error";class M_ extends x_{}M_.errorCode="temporarily_unavailable";class U_ extends x_{}U_.errorCode="unsupported_response_type";class D_ extends x_{}D_.errorCode="unsupported_token_type";class q_ extends x_{}q_.errorCode="invalid_token";class V_ extends x_{}V_.errorCode="method_not_allowed";class F_ extends x_{}F_.errorCode="too_many_requests";class L_ extends x_{}L_.errorCode="invalid_client_metadata";class K_ extends x_{}K_.errorCode="insufficient_scope";class H_ extends x_{}H_.errorCode="invalid_target";const Z_={[I_.errorCode]:I_,[N_.errorCode]:N_,[C_.errorCode]:C_,[j_.errorCode]:j_,[R_.errorCode]:R_,[O_.errorCode]:O_,[z_.errorCode]:z_,[A_.errorCode]:A_,[M_.errorCode]:M_,[U_.errorCode]:U_,[D_.errorCode]:D_,[q_.errorCode]:q_,[V_.errorCode]:V_,[F_.errorCode]:F_,[L_.errorCode]:L_,[K_.errorCode]:K_,[H_.errorCode]:H_};class G_ extends Error{constructor(e){super(e??"Unauthorized")}}const J_="code",W_="S256";function B_(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 Q_(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const e=k_.parse(JSON.parse(r)),{error:t,error_description:o,error_uri:n}=e;return new(Z_[t]||A_)(o||"",n)}catch(e){return new A_(`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${e}. Raw body: ${r}`)}}async function Y_(e,t){try{return await X_(e,t)}catch(r){if(r instanceof N_||r instanceof j_)return await(e.invalidateCredentials?.("all")),await X_(e,t);if(r instanceof C_)return await(e.invalidateCredentials?.("tokens")),await X_(e,t);throw r}}async function X_(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??Dn;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 ow(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 ow(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 __.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),l=await async function(e,{fetchFn:t=fetch,protocolVersion:r=Dn}={}){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 rw(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?w_.parse(await n.json()):$_.parse(await n.json())}}return}(i,{fetchFn:s});let d=await Promise.resolve(e.clientInformation());if(!d){if(void 0!==r)throw new Error("Existing OAuth client information is required when exchanging an authorization code");const t=!0===l?.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 L_(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${o}`);if(t&&o)d={client_id:o},await(e.saveClientInformation?.(d));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 Q_(s);return T_.parse(await s.json())}(i,{metadata:l,clientMetadata:e.clientMetadata,fetchFn:s});await e.saveClientInformation(t),d=t}}const p=!e.redirectUrl;if(void 0!==r||p){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 nw(t,{metadata:r,tokenRequestParams:i,clientInformation:c??void 0,addClientAuthentication:e.addClientAuthentication,resource:o,fetchFn:s})}(e,i,{metadata:l,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 nw(e,{metadata:t,tokenRequestParams:i,clientInformation:r,addClientAuthentication:s,resource:n,fetchFn:a});return{refresh_token:o,...c}}(i,{metadata:l,clientInformation:d,refreshToken:h.refresh_token,resource:c,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(t),"AUTHORIZED"}catch(e){if(e instanceof x_&&!(e instanceof A_))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(J_))throw new Error(`Incompatible auth server: does not support response type ${J_}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(W_))throw new Error(`Incompatible auth server: does not support code challenge method ${W_}`)}else i=new URL("/authorize",e);const c=await u(),l=c.code_verifier,d=c.code_challenge;i.searchParams.set("response_type",J_),i.searchParams.set("client_id",r.client_id),i.searchParams.set("code_challenge",d),i.searchParams.set("code_challenge_method",W_),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:l}}(i,{metadata:l,clientInformation:d,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 ew(e){const t=e.headers.get("WWW-Authenticate");if(!t)return{};const[r,o]=t.split(" ");if("bearer"!==r.toLowerCase()||!o)return{};const n=tw(e,"resource_metadata")||void 0;let s;if(n)try{s=new URL(n)}catch{}return{resourceMetadataUrl:s,scope:tw(e,"scope")||void 0,error:tw(e,"error")||void 0}}function tw(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 rw(e,t,r=fetch){try{return await r(e,{headers:t})}catch(o){if(o instanceof TypeError)return t?rw(e,void 0,r):void 0;throw o}}async function ow(e,t,r=fetch){const o={"MCP-Protocol-Version":t};return await rw(e,o,r)}async function nw(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??[]);B_(e,o,c,r)}const u=await(a??fetch)(i,{method:"POST",headers:c,body:r});if(!u.ok)throw await Q_(u);return b_.parse(await u.json())}class sw 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 aw(e){}function iw(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=aw,onError:r=aw,onRetry:o=aw,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 sw(`Invalid \`retry\` value: "${t}"`,{type:"invalid-retry",value:t,line:n}));break;default:r(new sw(`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 cw extends TransformStream{constructor({onError:e,onRetry:t,onComment:r}={}){let o;super({start(n){o=iw({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 uw={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class lw extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}}class dw{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?{...y_(t.headers),...y_(o.headers)}:t.headers};return e(r,n)}:e}(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??uw}async _authThenStart(){if(!this._authProvider)throw new G_("No auth provider");let e;try{e=await Y_(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 G_;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=y_(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 lw(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 cw({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=ls.parse(JSON.parse(e.data));is(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 G_("No auth provider");if("AUTHORIZED"!==await Y_(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit}))throw new G_("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:ns(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 lw(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:t,scope:r}=ew(i);this._resourceMetadataUrl=t,this._scope=r;if("AUTHORIZED"!==await Y_(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit}))throw new G_;return this._hasCompletedAuthFlow=!0,this.send(e)}if(403===i.status&&this._authProvider){const{resourceMetadataUrl:t,scope:r,error:o}=ew(i);if("insufficient_scope"===o){const o=i.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===o)throw new lw(403,"Server returned 403 after trying upscoping");r&&(this._scope=r),t&&(this._resourceMetadataUrl=t),this._lastUpscopingHeader=o??void 0;if("AUTHORIZED"!==await Y_(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch}))throw new G_;return this.send(e)}}throw new lw(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(Ts.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 lw(-1,`Unexpected content type: ${l}`);{const e=await i.json(),t=Array.isArray(e)?e.map(e=>ls.parse(e)):[ls.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 lw(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 pw=M("quickstart");async function hw(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 g&&404===e.statusCode)throw new v(i);throw e}const u=c.slug||i;let l;if(z(e.token)){l=`${O(e.token).baseUrl}/mcp/${u}`}else{pw.warn("Token has no organization information, using static config for MCP connection");l=`${R().baseUrl}/mcp/${u}`}return[{url:l,transport:a,headers:{Accept:"application/json, text/event-stream",Authorization:`Bearer ${e.token}`,"x-barndoor-session-id":fw()}},l]}function fw(){if(I&&"function"==typeof n.randomUUID)return n.randomUUID();if("undefined"!=typeof globalThis&&globalThis.crypto?.randomUUID)return globalThis.crypto.randomUUID();let e;if(I&&"function"==typeof n.randomBytes)e=n.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 s=Array.from(t,e=>e.toString(16).padStart(2,"0")).join("");return`${s.substring(0,8)}-${s.substring(8,12)}-${s.substring(12,16)}-${s.substring(16,20)}-${s.substring(20)}`}const mw=function(){try{if("undefined"!=typeof process&&process.versions?.node){const e=a.fileURLToPath("undefined"==typeof document?require("url").pathToFileURL(e).href:d&&"SCRIPT"===d.tagName.toUpperCase()&&d.src||new URL("index.js",document.baseURI).href),r=t.dirname(e),o=t.join(r,"..","package.json");return JSON.parse(l.readFileSync(o,"utf8")).version}return'"1.2.0"'}catch(e){return console.warn("Could not read version from package.json:",e),"0.1.0"}}();exports.AUTH_CONFIG=T,exports.AgentToken=P,exports.AuthenticationError=h,exports.BarndoorConfig=C,exports.BarndoorError=p,exports.BarndoorSDK=ie,exports.ConfigurationError=w,exports.ConnectionError=y,exports.HTTPError=g,exports.OAuthError=_,exports.PKCEManager=te,exports.ServerDetail=S,exports.ServerNotFoundError=v,exports.ServerSummary=E,exports.TimeoutError=$,exports.TokenError=f,exports.TokenExpiredError=m,exports.TokenManager=Y,exports.TokenValidationError=class extends f{},exports.checkTokenOrganization=function(e){return j(e)},exports.clearCachedToken=async function(){const e=W();await e.clearToken()},exports.clearOidcConfigCache=function(){D.clear()},exports.createScopedLogger=M,exports.debug=function(e,...t){A.debug(e,...t)},exports.ensureServerConnected=async function(e,t,r={}){const{timeout:o=90}=r;pw.info(`Ensuring ${t} server is connected`);try{await e.ensureServerConnected(t,{pollSeconds:o}),pw.info(`Server ${t} connected successfully`)}catch(e){throw e instanceof v?pw.error(`Server '${t}' not found`):pw.error(`Failed to connect to ${t}:`,e),e}},exports.error=function(e,...t){A.error(e,...t)},exports.getClientCredentialsToken=ae,exports.getDynamicConfig=O,exports.getLogger=function(){return A},exports.getOidcConfig=q,exports.getStaticConfig=R,exports.hasOrganizationInfo=z,exports.info=function(e,...t){A.info(e,...t)},exports.isBrowser=x,exports.isNode=I,exports.isTokenActive=async function(e){try{const e=W(),t=await e.loadToken();if(!t?.access_token)return!1;const r=R(),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 F(n,1e4)).ok}catch(e){return!1}},exports.isTokenActiveWithRefresh=async function(e){try{const t=new Y(e||"");return await t.getValidToken(),!0}catch(e){return U.warn("Token validation/refresh failed:",e),!1}},exports.loadUserToken=X,exports.loginInteractive=async function(t={}){if(!I)throw new Error("Interactive login is only available in Node.js environment");pw.info("Starting interactive login flow");const r=R();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:u,port:l=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 d=await X();if(d)try{let e;z(d)?e=O(d):(pw.warn("Cached token has no organization information, using static config"),e=R());const t=new ie(e.baseUrl,{token:d});return await t.validateCachedToken(),pw.info("Using cached valid token"),t}catch(e){pw.info("Cached token invalid, starting OAuth flow")}else pw.info("No cached token, starting OAuth flow");const p="undefined"!=typeof process&&!(!process.env||"1"!==process.env.BARNDOOR_MANUAL_CODE&&"true"!==process.env.BARNDOOR_MANUAL_CODE);let h,f=null;if(p){const e=process.env&&process.env.BARNDOOR_REDIRECT_HOST||"127.0.0.1";h=e.startsWith("http")?`${e}:${l}/cb`:`http://${e}:${l}/cb`}else{const e=ne(l);h=e[0],f=e[1]}const m=new te,y=await m.buildAuthorizationUrl({clientId:n,redirectUri:h,audience:a,issuer:o});pw.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?i.spawn("open",[y],{detached:!0,stdio:"ignore"}).unref():"win32"===g?i.spawn("powershell",["-NoProfile","Start-Process",y],{detached:!0,stdio:"ignore"}).unref():i.spawn("xdg-open",[y],{detached:!0,stdio:"ignore"}).unref(),pw.info("Please complete login in your browser…")}catch(e){pw.warn("Failed to open browser automatically. Please visit:",y)}if(p){const e=await new Promise(e=>{const t=c.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 "${h}" 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:h,issuer:o});let $;if(await ee(w),u)$=u;else if(z(w.access_token)){$=O(w.access_token).baseUrl}else pw.warn("New token has no organization information, using static config"),$=R().baseUrl;return new ie($,{token:w.access_token})},exports.makeMcpClient=async function(e,t,r={}){const[o]=await hw(e,t,r),n=o,s=new m_({name:"barndoor-js-sdk",version:"0.1.0"}),a=new dw(new URL(n.url),{requestInit:{headers:n.headers}});return await s.connect(a),s},exports.makeMcpConnectionParams=hw,exports.saveUserToken=ee,exports.setLogger=function(e){A=e},exports.setTokenLogger=function(e){console.warn("setTokenLogger is deprecated. Use setLogger from the main logging module instead.")},exports.startLocalCallbackServer=ne,exports.validateToken=async function(e,t){try{const t=R(),r=await B(e,t.authIssuer,t.apiAudience);if(r===exports.JWTVerificationResult.VALID)return{valid:!0};if(r===exports.JWTVerificationResult.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 F(o,5e3)).ok}}catch(e){return U.warn("Remote token validation failed:",e),{valid:!1}}return{valid:!1}}catch(e){return U.warn("Token validation failed:",e),{valid:!1}}},exports.verifyJWTLocal=B,exports.version=mw,exports.warn=function(e,...t){A.warn(e,...t)};
|