@barndoor-ai/sdk 0.2.0 → 0.2.2

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.
Files changed (62) hide show
  1. package/README.md +7 -7
  2. package/{src/auth/index.ts → dist/auth/index.d.ts} +2 -17
  3. package/dist/auth/index.d.ts.map +1 -0
  4. package/dist/auth/pkce.d.ts +92 -0
  5. package/dist/auth/pkce.d.ts.map +1 -0
  6. package/dist/auth/store.d.ts +145 -0
  7. package/dist/auth/store.d.ts.map +1 -0
  8. package/dist/client.d.ts +164 -0
  9. package/dist/client.d.ts.map +1 -0
  10. package/dist/config.d.ts +144 -0
  11. package/dist/config.d.ts.map +1 -0
  12. package/dist/exceptions/index.d.ts +119 -0
  13. package/dist/exceptions/index.d.ts.map +1 -0
  14. package/dist/http/client.d.ts +82 -0
  15. package/dist/http/client.d.ts.map +1 -0
  16. package/dist/index.d.ts +39 -0
  17. package/dist/index.d.ts.map +1 -0
  18. package/dist/index.esm.js +2 -0
  19. package/dist/index.js +2 -0
  20. package/dist/logging.d.ts +48 -0
  21. package/dist/logging.d.ts.map +1 -0
  22. package/dist/models/index.d.ts +116 -0
  23. package/dist/models/index.d.ts.map +1 -0
  24. package/dist/quickstart.d.ts +91 -0
  25. package/dist/quickstart.d.ts.map +1 -0
  26. package/dist/version.d.ts +17 -0
  27. package/dist/version.d.ts.map +1 -0
  28. package/package.json +8 -2
  29. package/.eslintignore +0 -8
  30. package/.eslintrc.cjs +0 -102
  31. package/.github/CODEOWNERS +0 -4
  32. package/.github/workflows/ci.yml +0 -57
  33. package/.prettierignore +0 -6
  34. package/.prettierrc +0 -13
  35. package/RELEASE.md +0 -203
  36. package/examples/README.md +0 -92
  37. package/examples/basic-mcp-client.js +0 -134
  38. package/examples/openai-integration.js +0 -137
  39. package/jest.config.js +0 -16
  40. package/openapi.yaml +0 -681
  41. package/rollup.config.js +0 -63
  42. package/scripts/dump-core-files.js +0 -161
  43. package/scripts/dump-typescript-only.js +0 -150
  44. package/src/auth/pkce.ts +0 -346
  45. package/src/auth/store.ts +0 -809
  46. package/src/client.ts +0 -512
  47. package/src/config.ts +0 -402
  48. package/src/exceptions/index.ts +0 -205
  49. package/src/http/client.ts +0 -272
  50. package/src/index.ts +0 -92
  51. package/src/logging.ts +0 -111
  52. package/src/models/index.ts +0 -156
  53. package/src/quickstart.ts +0 -358
  54. package/src/version.ts +0 -41
  55. package/test/client.test.js +0 -381
  56. package/test/config.test.js +0 -202
  57. package/test/exceptions.test.js +0 -142
  58. package/test/integration.test.js +0 -147
  59. package/test/models.test.js +0 -177
  60. package/test/token-management.test.js +0 -81
  61. package/test/token-validation.test.js +0 -104
  62. package/tsconfig.json +0 -61
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";var e=require("child_process"),t=require("os"),r=require("crypto"),a=require("http"),s=require("url"),o=require("path"),n=require("fs/promises"),i=require("jose"),c=require("pkce-challenge"),l=require("fs"),d="undefined"!=typeof document?document.currentScript:null;class u extends Error{constructor(e){super(e),this.name="BarndoorError"}}class h extends u{constructor(e,t=null){super(e),this.name="AuthenticationError",this.errorCode=t}}class p 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 f extends p{}class m extends u{constructor(e,t){let r;const a=t.toString().toLowerCase();r=a.includes("timeout")?`Connection to ${e} timed out. Please check your internet connection and try again.`:a.includes("connection refused")?`Could not connect to ${e}. The service may be unavailable.`:a.includes("name resolution")||a.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 v extends u{constructor(e,t,r=null){super(v._createUserFriendlyMessage(e,t,r)),this.name="HTTPError",this.statusCode=e,this.responseBody=r}static _createUserFriendlyMessage(e,t,r){const a=`Request failed (HTTP ${e})`;return 400===e?`${a}: Invalid request. Please check your input parameters.`:401===e?`${a}: Authentication failed. Please check your token or re-authenticate.`:403===e?`${a}: Access denied. You don't have permission for this operation.`:404===e?`${a}: Resource not found. Please check the server ID or URL.`:429===e?`${a}: Rate limit exceeded. Please wait before making more requests.`:e>=500&&e<600?`${a}: Server error. Please try again later or contact support.`:`${a}: ${t}`}}class g extends u{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 y=class extends h{};class _ extends u{}class w extends u{}class b{constructor(e=30,t=10){this.read=1e3*e,this.connect=1e3*t}}class P{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:a={},json:s,params:o,...n}=r,i=this._buildUrl(t,o),c={method:e.toUpperCase(),headers:{"Content-Type":"application/json","User-Agent":"barndoor-js-sdk/0.1.0",...a},...n};let l;s&&(c.body=JSON.stringify(s));for(let t=0;t<=this.maxRetries;t++){const r=new AbortController,a=this.timeoutConfig.connect+this.timeoutConfig.read,s=setTimeout(()=>r.abort(),a),o={...c,signal:r.signal};try{const e=await globalThis.fetch(i,o);if(clearTimeout(s),!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 v(e.status,e.statusText,t)}let t="";const r=e,a=r&&r.headers;let n;return a&&("function"==typeof a.get?t=a.get("content-type")||a.get("Content-Type")||"":"object"==typeof a&&(t=a["content-type"]||a["Content-Type"]||"")),n=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,n}catch(r){if(clearTimeout(s),r instanceof Error&&"AbortError"===r.name){const e=this.timeoutConfig.connect+this.timeoutConfig.read;l=new w(`Request to ${i} timed out after ${e}ms`)}else if(r instanceof v){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;l=r}}else l=r instanceof Error&&"TypeError"===r.name&&r.message.includes("fetch")?new m(i,r):r instanceof Error?r:new Error(String(r));if(t===this.maxRetries)break;const a=Math.min(1e3*Math.pow(2,t),1e4);await this._sleep(a)}}throw l||(l=new Error(`Request to ${i} failed after ${this.maxRetries+1} attempts with no specific error`)),l}_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 k extends E{constructor(e){super(e),this.url=e.url??null}static fromApiResponse(e){return new k(e)}}class x{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 x(e)}}const S="undefined"!=typeof window&&void 0!==window.document,T="undefined"==typeof window&&"undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node;function R(e,t=""){return T?process.env[e]??t:S&&window.ENV?window.ENV[e]??t:t}class ${constructor(e={}){this.authDomain=e.authDomain??(R("AUTH_DOMAIN")||"auth.barndoor.ai"),this.clientId=e.clientId??(R("AGENT_CLIENT_ID")||""),this.clientSecret=e.clientSecret??(R("AGENT_CLIENT_SECRET")||""),this.apiAudience=e.apiAudience??(R("API_AUDIENCE")||"https://barndoor.ai/"),this.environment=e.environment??(R("MODE")||R("BARNDOOR_ENV")||"production"),this.promptForLogin=e.promptForLogin??!1,this.skipLoginLocal=e.skipLoginLocal??!1,this.apiBaseUrl="",this.mcpBaseUrl="",this._setEnvironmentDefaults(e)}_setEnvironmentDefaults(e){const t=this.environment.toLowerCase();"localdev"===t||"local"===t?(this.authDomain=this.authDomain||"localhost:3001",this.apiBaseUrl=e.apiBaseUrl??(R("BARNDOOR_API")||"http://localhost:8000"),this.mcpBaseUrl=e.mcpBaseUrl??(R("BARNDOOR_MCP")||R("BARNDOOR_URL")||"http://localhost:8000")):"development"===t||"dev"===t?(this.apiBaseUrl=e.apiBaseUrl??(R("BARNDOOR_API")||"https://api.barndoordev.com"),this.mcpBaseUrl=e.mcpBaseUrl??(R("BARNDOOR_MCP")||R("BARNDOOR_URL")||"https://{organization_id}.mcp.barndoordev.com")):(this.apiBaseUrl=e.apiBaseUrl??(R("BARNDOOR_API")||"https://api.barndoor.ai"),this.mcpBaseUrl=e.mcpBaseUrl??(R("BARNDOOR_MCP")||R("BARNDOOR_URL")||"https://{organization_id}.mcp.barndoor.ai"))}static getStaticConfig(){return new $}static getDynamicConfig(e,t={}){const{requireOrganization:r=!0,fallbackOrganizationId:a}=t,s=new $,o=C(e);if(o.hasOrganization){const e=String(o.organizationId??"").trim().toLowerCase();if(!/^[a-z0-9-]+$/.test(e))throw new _("Invalid organization ID format from token");return s.apiBaseUrl=s.apiBaseUrl.replace("{organization_id}",e),s.mcpBaseUrl=s.mcpBaseUrl.replace("{organization_id}",e),s}if(a)return s.apiBaseUrl=s.apiBaseUrl.replace("{organization_id}",a),s.mcpBaseUrl=s.mcpBaseUrl.replace("{organization_id}",a),s;if(r){const e=o.error||"No organization information found in token";throw new _(`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 s}validate(){if(!this.authDomain||""===this.authDomain.trim())throw new _("authDomain is required");if(!this.apiAudience||""===this.apiAudience.trim())throw new _("apiAudience is required");if(!this.apiBaseUrl||""===this.apiBaseUrl.trim())throw new _("apiBaseUrl is required");if(!this.mcpBaseUrl||""===this.mcpBaseUrl.trim())throw new _("mcpBaseUrl is required")}}function C(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,a;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&&(a=r.user.organization_name??r.user.organization_slug),!a){const e=r["https://barndoor.ai/organization_slug"],t=r["https://barndoor.ai/organization_id"],s=r.organization_slug,o=r.org_slug,n=r.org_id,i=r.organization_id;a=("string"==typeof e?e:void 0)??("string"==typeof t?t:void 0)??("string"==typeof s?s:void 0)??("string"==typeof o?o:void 0)??("string"==typeof n?n:void 0)??("string"==typeof i?i:void 0)}return a&&"string"==typeof a&&""!==a.trim()?{organizationId:a.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 O(){return $.getStaticConfig()}function I(e,t){return $.getDynamicConfig(e,t)}function A(e){return C(e).hasOrganization}let j={debug:(e,...t)=>{"undefined"!=typeof console&&console.debug&&console.debug(e,...t)},info:(e,...t)=>{"undefined"!=typeof console&&console.info&&console.info(e,...t)},warn:(e,...t)=>{"undefined"!=typeof console&&console.warn&&console.warn(e,...t)},error:(e,...t)=>{"undefined"!=typeof console&&console.error&&console.error(e,...t)}};function F(e){return{debug:(t,...r)=>{j.debug(`[${e}] ${t}`,...r)},info:(t,...r)=>{j.info(`[${e}] ${t}`,...r)},warn:(t,...r)=>{j.warn(`[${e}] ${t}`,...r)},error:(t,...r)=>{j.error(`[${e}] ${t}`,...r)}}}class D{constructor(e,t={}){this._logger=F("client");const{token:r,timeout:a=30,maxRetries:s=3}=t;this.base=this._validateUrl(e,"API base URL").replace(/\/$/,"");const o=Object.prototype.hasOwnProperty.call(t,"token");if(this._token=o?this._validateToken(r):null,"number"!=typeof a||a<=0)throw new _("timeout must be a positive number");if(!Number.isInteger(s)||s<0)throw new _("maxRetries must be a non-negative integer");const n=new b(a,a/3);this._http=new P(n,s),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 _(`${t} must be a non-empty string`);try{return new URL(e),e}catch(e){throw new _(`${t} must be a valid URL`)}}_validateToken(e){if(!e||"string"!=typeof e)throw new p("Token must be a non-empty string");if(3!==e.split(".").length)throw new p("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 a=r.headers??{};a.Authorization=`Bearer ${this.token}`;const s=`${this.base}${t}`;return await this._http.request(e,s,{...r,headers:a})}async validateCachedToken(){if(!this.token)return!1;try{const e=O(),t=(await fetch(`https://${e.authDomain}/userinfo`,{headers:{Authorization:`Bearer ${this.token}`}})).ok;return t&&(this._tokenValidated=!0),t}catch(e){return!1}}async ensureValidToken(){if(this._tokenValidated)return;const e=(T?process.env.BARNDOOR_ENV:"")??"";if(["test","ci"].includes(e.toLowerCase()))return void(this._tokenValidated=!0);if(!await this.validateCachedToken())throw new p("Token validation failed. Please re-authenticate.");this._tokenValidated=!0}async listServers(){this._logger.debug("Fetching server list");try{const e=(await this._req("GET","/servers")).data.map(e=>E.fromApiResponse(e));return this._logger.info(`Retrieved ${e.length} servers`),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=await this._req("GET",`/servers/${t}`);return k.fromApiResponse(r)}async initiateConnection(e,t){const r=this._validateServerId(e);let a;t&&(a=this._validateUrl(t,"Return URL")),this._logger.info(`Initiating connection for server ${r}`);const s=a?{return_url:a}:void 0;try{return await this._req("POST",`/servers/${r}/connect`,{params:s,json:{}})}catch(e){if(e instanceof v&&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}`);return(await this._req("GET",`/servers/${t}/connection`)).status}async disconnectServer(e){const t=this._validateServerId(e);this._logger.info(`Disconnecting from server ${t}`);try{await this._req("DELETE",`/servers/${t}/connection`),this._logger.info(`Successfully disconnected from server ${t}`)}catch(e){if(e instanceof v&&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}async close(){this._closed||(await this._http.close(),this._closed=!0)}async aclose(){await this.close()}async ensureServerConnected(r,a={}){const{pollSeconds:s=60}=a;if(!T)throw new Error("ensureServerConnected requires Node.js environment for browser opening");const o=(await this.listServers()).find(e=>e.slug===r||e.provider&&e.provider.toLowerCase()===r.toLowerCase());if(!o)throw new g(r);if("connected"===o.connection_status)return;const n=(await this.initiateConnection(o.id)).auth_url;if(!n)throw new Error("Registry did not return auth_url");const i=t.platform();let c;try{c=new URL(n)}catch{throw new Error("Invalid auth_url returned by server")}if("https:"!==c.protocol&&("http:"!==c.protocol||"localhost"!==c.hostname&&"127.0.0.1"!==c.hostname))throw new Error("Auth URL must use HTTPS (http allowed only for localhost)");try{"darwin"===i?e.spawn("open",[n],{detached:!0,stdio:"ignore"}).unref():"win32"===i?e.spawn("powershell",["-NoProfile","Start-Process",n],{detached:!0,stdio:"ignore"}).unref():e.spawn("xdg-open",[n],{detached:!0,stdio:"ignore"}).unref()}catch(e){this._logger.warn("Failed to open browser",e)}for(let e=0;e<s;e++){if("connected"===await this.getConnectionStatus(o.id))return;await new Promise(e=>setTimeout(e,1e3))}throw new Error("OAuth connection was not completed in time")}}class N{constructor(){this._codeVerifier=null,this._currentState=null,this._logger=F("pkce")}async buildAuthorizationUrl({domain:e,clientId:t,redirectUri:a,audience:s,scope:o="openid profile email"}){this._codeVerifier=U(32);const n=L(await async function(e){const t=(new TextEncoder).encode(e);if(S&&window.crypto&&window.crypto.subtle){const e=await window.crypto.subtle.digest("SHA-256",t);return new Uint8Array(e)}if(T){const t=r.createHash("sha256").update(e).digest();return new Uint8Array(t)}throw new Error("SHA256 not available in this environment")}(this._codeVerifier));this._currentState=U(16);return`https://${e}/authorize?${new URLSearchParams({response_type:"code",client_id:t,redirect_uri:a,scope:o,audience:s,state:this._currentState,code_challenge:n,code_challenge_method:"S256"}).toString()}`}async exchangeCodeForToken({domain:e,clientId:t,code:r,redirectUri:a,clientSecret:s}){const o={grant_type:"authorization_code",client_id:t,code:r,redirect_uri:a};if(s&&(o.client_secret=s),this._codeVerifier&&(o.code_verifier=this._codeVerifier),!s&&!this._codeVerifier)throw new y("Either client_secret or PKCE verifier must be provided");try{const t=await fetch(`https://${e}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!t.ok){const e=await t.json().catch(()=>({}));throw this._logger.error("Token endpoint response:",e),new y(`Token exchange failed: ${e.error??e.error_description??t.statusText}`)}const r=await t.json();return this.clearState(),r}catch(e){if(e instanceof y)throw e;const t=e instanceof Error?e.message:String(e);throw new y(`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 U(e){const t=new Uint8Array(e);if(S&&window.crypto&&window.crypto.getRandomValues)window.crypto.getRandomValues(t);else{if(!T)throw new Error("Secure random generator not available for PKCE.");r.randomFillSync(t)}return L(t)}function L(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 q(e=52765){if(!T)throw new Error("Local callback server is only available in Node.js environment");const t=`http://localhost:${e}/cb`,r=new Promise((r,o)=>{const n=a.createServer((e,t)=>{const a=s.parse(e.url??"",!0);if("/cb"===a.pathname){const{code:e,state:s,error:i,error_description:c}=a.query;t.writeHead(200,{"Content-Type":"text/html"}),i?(t.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 "),n.close(),o(new y(`OAuth error: ${i} - ${c}`))):e?(t.end("\n <html>\n <body>\n <h1>Authentication Successful</h1>\n <p>You can close this window and return to your application.</p>\n </body>\n </html>\n "),n.close(),r([e,s])):(t.end("\n <html>\n <body>\n <h1>Authentication Failed</h1>\n <p>No authorization code received.</p>\n <p>You can close this window.</p>\n </body>\n </html>\n "),n.close(),o(new y("No authorization code received")))}else t.writeHead(404),t.end("Not found")});n.listen(e,"localhost",()=>{console.log(`OAuth callback server listening on ${t}`)}),n.on("error",e=>{o(new y(`Failed to start callback server: ${e.message}`))})});return[t,r]}const z=F("token");function V(e){try{const t=e.split(".");if(3!==t.length)return null;return JSON.parse(function(e){const t=e.replace(/-/g,"+").replace(/_/g,"/");if(T)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]))}catch(e){return null}}function M(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 Z;exports.JWTVerificationResult=void 0,(Z=exports.JWTVerificationResult||(exports.JWTVerificationResult={})).VALID="valid",Z.EXPIRED="expired",Z.INVALID="invalid";const H=new Map;class B{constructor(e){this.lockAcquired=!1,this.lockFile=`${e}.lock`}async acquire(e=5e3){if(!T)return;const t=Date.now();for(;Date.now()-t<e;)try{return await n.writeFile(this.lockFile,process.pid.toString(),{flag:"wx"}),void(this.lockAcquired=!0)}catch(e){if(!e||"object"!=typeof e||!("code"in e)||"EEXIST"!==e.code)throw new p(`Failed to acquire file lock: ${e}`);try{const e=await n.readFile(this.lockFile,"utf8"),t=parseInt(e.trim(),10);try{process.kill(t,0),await new Promise(e=>setTimeout(e,100));continue}catch(e){if(e&&"object"==typeof e&&"code"in e){const t=e;if("EPERM"===t.code){await new Promise(e=>setTimeout(e,100));continue}if("ESRCH"===t.code){await n.unlink(this.lockFile).catch(()=>{});continue}}await n.unlink(this.lockFile).catch(()=>{});continue}}catch{await n.unlink(this.lockFile).catch(()=>{});continue}}throw new p("Failed to acquire file lock: timeout")}async release(){if(T&&this.lockAcquired)try{await n.unlink(this.lockFile),this.lockAcquired=!1}catch(e){console.debug("Failed to release file lock:",e)}}}class Q{}class K extends Q{constructor(){super(),this.storageKey="barndoor_token"}async loadToken(){try{const e=localStorage.getItem(this.storageKey);return e?JSON.parse(e):null}catch(e){return z.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 p(`Failed to save token: ${t}`)}}async clearToken(){try{localStorage.removeItem(this.storageKey)}catch(e){z.warn("Failed to clear token from localStorage:",e)}}}class J extends Q{constructor(){super(),this.tokenFile=this._getTokenFilePath()}_getTokenFilePath(){if(T)return o.join(t.homedir(),".barndoor","token.json");throw new Error("NodeTokenStorage can only be used in Node.js environment")}async loadToken(){if(!T)throw new Error("NodeTokenStorage can only be used in Node.js environment");const e=new B(this.tokenFile);try{await e.acquire();const t=await n.readFile(this.tokenFile,"utf8");return JSON.parse(t)}catch(e){return e&&"object"==typeof e&&"code"in e&&"ENOENT"===e.code||z.warn("Failed to load token from file:",e),null}finally{await e.release()}}async saveToken(e){if(!T)throw new Error("NodeTokenStorage can only be used in Node.js environment");const t=new B(this.tokenFile);try{await t.acquire(),await n.mkdir(o.dirname(this.tokenFile),{recursive:!0}),await n.writeFile(this.tokenFile,JSON.stringify(e,null,2)),await n.chmod(this.tokenFile,384),z.debug("Token saved to storage")}catch(e){const t=e instanceof Error?e.message:String(e);throw new p(`Failed to save token: ${t}`)}finally{await t.release()}}async clearToken(){if(!T)throw new Error("NodeTokenStorage can only be used in Node.js environment");try{await n.unlink(this.tokenFile)}catch(e){e&&"object"==typeof e&&"code"in e&&"ENOENT"!==e.code&&z.warn("Failed to clear token file:",e)}}}function W(){if(S)return new K;if(T)return new J;throw new Error("Unsupported environment for token storage")}async function G(e,t,r){try{const a=function(e){if(!H.has(e)){const t=i.createRemoteJWKSet(new URL(`https://${e}/.well-known/jwks.json`));H.set(e,t)}return H.get(e)}(t);return await i.jwtVerify(e,a,{issuer:`https://${t}/`,audience:r}),z.debug("Token verified locally using JWKS"),exports.JWTVerificationResult.VALID}catch(e){return e&&"object"==typeof e&&"code"in e&&"ERR_JWT_EXPIRED"===e.code?(z.debug("Token expired (verified locally)"),exports.JWTVerificationResult.EXPIRED):(z.debug("JWT verification failed:",e),exports.JWTVerificationResult.INVALID)}}class Y{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 X{constructor(e){this._refreshMutex=new Y,this.storage=W()}async getValidToken(){return this._refreshMutex.withLock(async()=>{const e=await this.storage.loadToken();if(!e)throw new p("No token found. Please authenticate.");try{if(this._shouldRefreshToken(e)&&e.refresh_token){z.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 z.error("Token validation/refresh failed:",e),new f("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=O(),a=await G(t,r.authDomain,r.apiAudience);if(a===exports.JWTVerificationResult.VALID)return z.debug("Token validated locally"),e;if(a===exports.JWTVerificationResult.INVALID&&(z.debug("Local validation failed, trying remote"),await this._isTokenValidRemote(t)))return z.debug("Token validated remotely"),e;if(z.info("Token invalid or expired, attempting refresh"),e.refresh_token){const t=await this._refreshToken(e);return{...e,...t}}throw new f("Token expired and no refresh token available")}async _isTokenValidRemote(e){try{const t=O(),r=fetch(`https://${t.authDomain}/userinfo`,{headers:{Authorization:`Bearer ${e}`},..."undefined"!=typeof AbortSignal&&"timeout"in AbortSignal?{signal:AbortSignal.timeout(5e3)}:{}});return(await M(r,5e3)).ok}catch(e){return z.debug("Remote token validation failed:",e),!1}}async _refreshToken(e){const t=e.refresh_token;if(!t)throw new p("No refresh token available");const r=O();if(S&&r.clientSecret)throw new p("Refresh flow requires a confidential client; run interactive login again.");const a={grant_type:"refresh_token",client_id:r.clientId,refresh_token:t};r.clientSecret&&!S&&(a.client_secret=r.clientSecret);try{const e=fetch(`https://${r.authDomain}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a),..."undefined"!=typeof AbortSignal&&"timeout"in AbortSignal?{signal:AbortSignal.timeout(15e3)}:{}}),t=await M(e,15e3);if(400===t.status){let e="Invalid refresh token";try{e=(await t.json()).error_description||e}catch{}throw z.warn(`Refresh token invalid: ${e}`),new f(`Refresh token expired or invalid: ${e}`)}if(429===t.status)throw z.warn("Rate limited during token refresh"),new p("Rate limited during token refresh. Please try again later.");if(t.status>=500)throw z.warn(`Auth server error during refresh: ${t.status}`),new p(`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 p||e instanceof f)throw e;if(e&&"object"==typeof e&&"name"in e){if("TimeoutError"===e.name||"AbortError"===e.name)throw z.warn("Timeout during token refresh"),new p("Token refresh timed out. Please check your connection.");if("TypeError"===e.name&&"message"in e&&"string"==typeof e.message&&e.message.includes("fetch"))throw z.warn(`Network error during token refresh: ${e.message}`),new p("Network error during token refresh. Please check your connection.")}z.error("Unexpected error during token refresh:",e);const t=e instanceof Error?e.message:String(e);throw new p(`Token refresh failed: ${t}`)}}}async function ee(){try{const e=W(),t=await e.loadToken();return t?.access_token??null}catch(e){return null}}async function te(e){const t=W();let r;r="string"==typeof e?{access_token:e}:e,await t.saveToken(r)}var re,ae;!function(e){e.assertEqual=e=>{},e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},e.getValidEnumValues=t=>{const r=e.objectKeys(t).filter(e=>"number"!=typeof t[t[e]]),a={};for(const e of r)a[e]=t[e];return e.objectValues(a)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},e.find=(e,t)=>{for(const r of e)if(t(r))return r},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(re||(re={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(ae||(ae={}));const se=re.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),oe=e=>{switch(typeof e){case"undefined":return se.undefined;case"string":return se.string;case"number":return Number.isNaN(e)?se.nan:se.number;case"boolean":return se.boolean;case"function":return se.function;case"bigint":return se.bigint;case"symbol":return se.symbol;case"object":return Array.isArray(e)?se.array:null===e?se.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?se.promise:"undefined"!=typeof Map&&e instanceof Map?se.map:"undefined"!=typeof Set&&e instanceof Set?se.set:"undefined"!=typeof Date&&e instanceof Date?se.date:se.object;default:return se.unknown}},ne=re.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class ie extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},r={_errors:[]},a=e=>{for(const s of e.issues)if("invalid_union"===s.code)s.unionErrors.map(a);else if("invalid_return_type"===s.code)a(s.returnTypeError);else if("invalid_arguments"===s.code)a(s.argumentsError);else if(0===s.path.length)r._errors.push(t(s));else{let e=r,a=0;for(;a<s.path.length;){const r=s.path[a];a===s.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(s))):e[r]=e[r]||{_errors:[]},e=e[r],a++}}};return a(this),r}static assert(e){if(!(e instanceof ie))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,re.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},r=[];for(const a of this.issues)if(a.path.length>0){const r=a.path[0];t[r]=t[r]||[],t[r].push(e(a))}else r.push(e(a));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}ie.create=e=>new ie(e);var ce=(e,t)=>{let r;switch(e.code){case ne.invalid_type:r=e.received===se.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case ne.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,re.jsonStringifyReplacer)}`;break;case ne.unrecognized_keys:r=`Unrecognized key(s) in object: ${re.joinValues(e.keys,", ")}`;break;case ne.invalid_union:r="Invalid input";break;case ne.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${re.joinValues(e.options)}`;break;case ne.invalid_enum_value:r=`Invalid enum value. Expected ${re.joinValues(e.options)}, received '${e.received}'`;break;case ne.invalid_arguments:r="Invalid function arguments";break;case ne.invalid_return_type:r="Invalid function return type";break;case ne.invalid_date:r="Invalid date";break;case ne.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:re.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case ne.too_small:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case ne.too_big:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case ne.custom:r="Invalid input";break;case ne.invalid_intersection_types:r="Intersection results could not be merged";break;case ne.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case ne.not_finite:r="Number must be finite";break;default:r=t.defaultError,re.assertNever(e)}return{message:r}};let le=ce;function de(e,t){const r=le,a=(e=>{const{data:t,path:r,errorMaps:a,issueData:s}=e,o=[...r,...s.path||[]],n={...s,path:o};if(void 0!==s.message)return{...s,path:o,message:s.message};let i="";const c=a.filter(e=>!!e).slice().reverse();for(const e of c)i=e(n,{data:t,defaultError:i}).message;return{...s,path:o,message:i}})({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===ce?void 0:ce].filter(e=>!!e)});e.common.issues.push(a)}class ue{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const a of t){if("aborted"===a.status)return he;"dirty"===a.status&&e.dirty(),r.push(a.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const e of t){const t=await e.key,a=await e.value;r.push({key:t,value:a})}return ue.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const a of t){const{key:t,value:s}=a;if("aborted"===t.status)return he;if("aborted"===s.status)return he;"dirty"===t.status&&e.dirty(),"dirty"===s.status&&e.dirty(),"__proto__"===t.value||void 0===s.value&&!a.alwaysSet||(r[t.value]=s.value)}return{status:e.value,value:r}}}const he=Object.freeze({status:"aborted"}),pe=e=>({status:"dirty",value:e}),fe=e=>({status:"valid",value:e}),me=e=>"aborted"===e.status,ve=e=>"dirty"===e.status,ge=e=>"valid"===e.status,ye=e=>"undefined"!=typeof Promise&&e instanceof Promise;var _e;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(_e||(_e={}));class we{constructor(e,t,r,a){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=a}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const be=(e,t)=>{if(ge(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new ie(e.common.issues);return this._error=t,this._error}}};function Pe(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:a,description:s}=e;if(t&&(r||a))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:s};return{errorMap:(t,s)=>{const{message:o}=e;return"invalid_enum_value"===t.code?{message:o??s.defaultError}:void 0===s.data?{message:o??a??s.defaultError}:"invalid_type"!==t.code?{message:s.defaultError}:{message:o??r??s.defaultError}},description:s}}class Ee{get description(){return this._def.description}_getType(e){return oe(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:oe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ue,ctx:{common:e.parent.common,data:e.data,parsedType:oe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(ye(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){const r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:oe(e)},a=this._parseSync({data:e,path:r.path,parent:r});return be(r,a)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:oe(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:t});return ge(r)?{value:r.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>ge(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:oe(e)},a=this._parse({data:e,path:r.path,parent:r}),s=await(ye(a)?a:Promise.resolve(a));return be(r,s)}refine(e,t){const r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,a)=>{const s=e(t),o=()=>a.addIssue({code:ne.custom,...r(t)});return"undefined"!=typeof Promise&&s instanceof Promise?s.then(e=>!!e||(o(),!1)):!!s||(o(),!1)})}refinement(e,t){return this._refinement((r,a)=>!!e(r)||(a.addIssue("function"==typeof t?t(r,a):t),!1))}_refinement(e){return new kt({schema:this,typeName:At.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return xt.create(this,this._def)}nullable(){return St.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return nt.create(this)}promise(){return Et.create(this,this._def)}or(e){return lt.create([this,e],this._def)}and(e){return pt.create(this,e,this._def)}transform(e){return new kt({...Pe(this._def),schema:this,typeName:At.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Tt({...Pe(this._def),innerType:this,defaultValue:t,typeName:At.ZodDefault})}brand(){return new Ct({typeName:At.ZodBranded,type:this,...Pe(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Rt({...Pe(this._def),innerType:this,catchValue:t,typeName:At.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Ot.create(this,e)}readonly(){return It.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const ke=/^c[^\s-]{8,}$/i,xe=/^[0-9a-z]+$/,Se=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Te=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Re=/^[a-z0-9_-]{21}$/i,$e=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Ce=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Oe=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let Ie;const Ae=/^(?:(?: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])$/,je=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Fe=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,De=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ne=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ue=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Le="((\\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])))",qe=new RegExp(`^${Le}$`);function ze(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`);return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function Ve(e){return new RegExp(`^${ze(e)}$`)}function Me(e){let t=`${Le}T${ze(e)}`;const r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function Ze(e,t){return!("v4"!==t&&t||!Ae.test(e))||!("v6"!==t&&t||!Fe.test(e))}function He(e,t){if(!$e.test(e))return!1;try{const[r]=e.split(".");if(!r)return!1;const a=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(a));return"object"==typeof s&&null!==s&&((!("typ"in s)||"JWT"===s?.typ)&&(!!s.alg&&(!t||s.alg===t)))}catch{return!1}}function Be(e,t){return!("v4"!==t&&t||!je.test(e))||!("v6"!==t&&t||!De.test(e))}class Qe extends Ee{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==se.string){const t=this._getOrReturnCtx(e);return de(t,{code:ne.invalid_type,expected:se.string,received:t.parsedType}),he}const t=new ue;let r;for(const a of this._def.checks)if("min"===a.kind)e.data.length<a.value&&(r=this._getOrReturnCtx(e,r),de(r,{code:ne.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),t.dirty());else if("max"===a.kind)e.data.length>a.value&&(r=this._getOrReturnCtx(e,r),de(r,{code:ne.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),t.dirty());else if("length"===a.kind){const s=e.data.length>a.value,o=e.data.length<a.value;(s||o)&&(r=this._getOrReturnCtx(e,r),s?de(r,{code:ne.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):o&&de(r,{code:ne.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),t.dirty())}else if("email"===a.kind)Oe.test(e.data)||(r=this._getOrReturnCtx(e,r),de(r,{validation:"email",code:ne.invalid_string,message:a.message}),t.dirty());else if("emoji"===a.kind)Ie||(Ie=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ie.test(e.data)||(r=this._getOrReturnCtx(e,r),de(r,{validation:"emoji",code:ne.invalid_string,message:a.message}),t.dirty());else if("uuid"===a.kind)Te.test(e.data)||(r=this._getOrReturnCtx(e,r),de(r,{validation:"uuid",code:ne.invalid_string,message:a.message}),t.dirty());else if("nanoid"===a.kind)Re.test(e.data)||(r=this._getOrReturnCtx(e,r),de(r,{validation:"nanoid",code:ne.invalid_string,message:a.message}),t.dirty());else if("cuid"===a.kind)ke.test(e.data)||(r=this._getOrReturnCtx(e,r),de(r,{validation:"cuid",code:ne.invalid_string,message:a.message}),t.dirty());else if("cuid2"===a.kind)xe.test(e.data)||(r=this._getOrReturnCtx(e,r),de(r,{validation:"cuid2",code:ne.invalid_string,message:a.message}),t.dirty());else if("ulid"===a.kind)Se.test(e.data)||(r=this._getOrReturnCtx(e,r),de(r,{validation:"ulid",code:ne.invalid_string,message:a.message}),t.dirty());else if("url"===a.kind)try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),de(r,{validation:"url",code:ne.invalid_string,message:a.message}),t.dirty()}else if("regex"===a.kind){a.regex.lastIndex=0;a.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),de(r,{validation:"regex",code:ne.invalid_string,message:a.message}),t.dirty())}else if("trim"===a.kind)e.data=e.data.trim();else if("includes"===a.kind)e.data.includes(a.value,a.position)||(r=this._getOrReturnCtx(e,r),de(r,{code:ne.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),t.dirty());else if("toLowerCase"===a.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===a.kind)e.data=e.data.toUpperCase();else if("startsWith"===a.kind)e.data.startsWith(a.value)||(r=this._getOrReturnCtx(e,r),de(r,{code:ne.invalid_string,validation:{startsWith:a.value},message:a.message}),t.dirty());else if("endsWith"===a.kind)e.data.endsWith(a.value)||(r=this._getOrReturnCtx(e,r),de(r,{code:ne.invalid_string,validation:{endsWith:a.value},message:a.message}),t.dirty());else if("datetime"===a.kind){Me(a).test(e.data)||(r=this._getOrReturnCtx(e,r),de(r,{code:ne.invalid_string,validation:"datetime",message:a.message}),t.dirty())}else if("date"===a.kind){qe.test(e.data)||(r=this._getOrReturnCtx(e,r),de(r,{code:ne.invalid_string,validation:"date",message:a.message}),t.dirty())}else if("time"===a.kind){Ve(a).test(e.data)||(r=this._getOrReturnCtx(e,r),de(r,{code:ne.invalid_string,validation:"time",message:a.message}),t.dirty())}else"duration"===a.kind?Ce.test(e.data)||(r=this._getOrReturnCtx(e,r),de(r,{validation:"duration",code:ne.invalid_string,message:a.message}),t.dirty()):"ip"===a.kind?Ze(e.data,a.version)||(r=this._getOrReturnCtx(e,r),de(r,{validation:"ip",code:ne.invalid_string,message:a.message}),t.dirty()):"jwt"===a.kind?He(e.data,a.alg)||(r=this._getOrReturnCtx(e,r),de(r,{validation:"jwt",code:ne.invalid_string,message:a.message}),t.dirty()):"cidr"===a.kind?Be(e.data,a.version)||(r=this._getOrReturnCtx(e,r),de(r,{validation:"cidr",code:ne.invalid_string,message:a.message}),t.dirty()):"base64"===a.kind?Ne.test(e.data)||(r=this._getOrReturnCtx(e,r),de(r,{validation:"base64",code:ne.invalid_string,message:a.message}),t.dirty()):"base64url"===a.kind?Ue.test(e.data)||(r=this._getOrReturnCtx(e,r),de(r,{validation:"base64url",code:ne.invalid_string,message:a.message}),t.dirty()):re.assertNever(a);return{status:t.value,value:e.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:ne.invalid_string,..._e.errToObj(r)})}_addCheck(e){return new Qe({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",..._e.errToObj(e)})}url(e){return this._addCheck({kind:"url",..._e.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",..._e.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",..._e.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",..._e.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",..._e.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",..._e.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",..._e.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",..._e.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",..._e.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",..._e.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",..._e.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",..._e.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,..._e.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,..._e.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",..._e.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,..._e.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,..._e.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,..._e.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,..._e.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,..._e.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,..._e.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,..._e.errToObj(t)})}nonempty(e){return this.min(1,_e.errToObj(e))}trim(){return new Qe({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Qe({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Qe({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function Ke(e,t){const r=(e.toString().split(".")[1]||"").length,a=(t.toString().split(".")[1]||"").length,s=r>a?r:a;return Number.parseInt(e.toFixed(s).replace(".",""))%Number.parseInt(t.toFixed(s).replace(".",""))/10**s}Qe.create=e=>new Qe({checks:[],typeName:At.ZodString,coerce:e?.coerce??!1,...Pe(e)});class Je extends Ee{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){this._def.coerce&&(e.data=Number(e.data));if(this._getType(e)!==se.number){const t=this._getOrReturnCtx(e);return de(t,{code:ne.invalid_type,expected:se.number,received:t.parsedType}),he}let t;const r=new ue;for(const a of this._def.checks)if("int"===a.kind)re.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),de(t,{code:ne.invalid_type,expected:"integer",received:"float",message:a.message}),r.dirty());else if("min"===a.kind){(a.inclusive?e.data<a.value:e.data<=a.value)&&(t=this._getOrReturnCtx(e,t),de(t,{code:ne.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),r.dirty())}else if("max"===a.kind){(a.inclusive?e.data>a.value:e.data>=a.value)&&(t=this._getOrReturnCtx(e,t),de(t,{code:ne.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),r.dirty())}else"multipleOf"===a.kind?0!==Ke(e.data,a.value)&&(t=this._getOrReturnCtx(e,t),de(t,{code:ne.not_multiple_of,multipleOf:a.value,message:a.message}),r.dirty()):"finite"===a.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),de(t,{code:ne.not_finite,message:a.message}),r.dirty()):re.assertNever(a);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,_e.toString(t))}gt(e,t){return this.setLimit("min",e,!1,_e.toString(t))}lte(e,t){return this.setLimit("max",e,!0,_e.toString(t))}lt(e,t){return this.setLimit("max",e,!1,_e.toString(t))}setLimit(e,t,r,a){return new Je({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:_e.toString(a)}]})}_addCheck(e){return new Je({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:_e.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:_e.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:_e.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:_e.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:_e.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:_e.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:_e.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:_e.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:_e.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&re.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}Je.create=e=>new Je({checks:[],typeName:At.ZodNumber,coerce:e?.coerce||!1,...Pe(e)});class We extends Ee{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==se.bigint)return this._getInvalidInput(e);let t;const r=new ue;for(const a of this._def.checks)if("min"===a.kind){(a.inclusive?e.data<a.value:e.data<=a.value)&&(t=this._getOrReturnCtx(e,t),de(t,{code:ne.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),r.dirty())}else if("max"===a.kind){(a.inclusive?e.data>a.value:e.data>=a.value)&&(t=this._getOrReturnCtx(e,t),de(t,{code:ne.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),r.dirty())}else"multipleOf"===a.kind?e.data%a.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),de(t,{code:ne.not_multiple_of,multipleOf:a.value,message:a.message}),r.dirty()):re.assertNever(a);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return de(t,{code:ne.invalid_type,expected:se.bigint,received:t.parsedType}),he}gte(e,t){return this.setLimit("min",e,!0,_e.toString(t))}gt(e,t){return this.setLimit("min",e,!1,_e.toString(t))}lte(e,t){return this.setLimit("max",e,!0,_e.toString(t))}lt(e,t){return this.setLimit("max",e,!1,_e.toString(t))}setLimit(e,t,r,a){return new We({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:_e.toString(a)}]})}_addCheck(e){return new We({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:_e.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:_e.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:_e.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:_e.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:_e.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}We.create=e=>new We({checks:[],typeName:At.ZodBigInt,coerce:e?.coerce??!1,...Pe(e)});class Ge extends Ee{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==se.boolean){const t=this._getOrReturnCtx(e);return de(t,{code:ne.invalid_type,expected:se.boolean,received:t.parsedType}),he}return fe(e.data)}}Ge.create=e=>new Ge({typeName:At.ZodBoolean,coerce:e?.coerce||!1,...Pe(e)});class Ye extends Ee{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==se.date){const t=this._getOrReturnCtx(e);return de(t,{code:ne.invalid_type,expected:se.date,received:t.parsedType}),he}if(Number.isNaN(e.data.getTime())){return de(this._getOrReturnCtx(e),{code:ne.invalid_date}),he}const t=new ue;let r;for(const a of this._def.checks)"min"===a.kind?e.data.getTime()<a.value&&(r=this._getOrReturnCtx(e,r),de(r,{code:ne.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),t.dirty()):"max"===a.kind?e.data.getTime()>a.value&&(r=this._getOrReturnCtx(e,r),de(r,{code:ne.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),t.dirty()):re.assertNever(a);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Ye({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:_e.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:_e.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}Ye.create=e=>new Ye({checks:[],coerce:e?.coerce||!1,typeName:At.ZodDate,...Pe(e)});class Xe extends Ee{_parse(e){if(this._getType(e)!==se.symbol){const t=this._getOrReturnCtx(e);return de(t,{code:ne.invalid_type,expected:se.symbol,received:t.parsedType}),he}return fe(e.data)}}Xe.create=e=>new Xe({typeName:At.ZodSymbol,...Pe(e)});class et extends Ee{_parse(e){if(this._getType(e)!==se.undefined){const t=this._getOrReturnCtx(e);return de(t,{code:ne.invalid_type,expected:se.undefined,received:t.parsedType}),he}return fe(e.data)}}et.create=e=>new et({typeName:At.ZodUndefined,...Pe(e)});class tt extends Ee{_parse(e){if(this._getType(e)!==se.null){const t=this._getOrReturnCtx(e);return de(t,{code:ne.invalid_type,expected:se.null,received:t.parsedType}),he}return fe(e.data)}}tt.create=e=>new tt({typeName:At.ZodNull,...Pe(e)});class rt extends Ee{constructor(){super(...arguments),this._any=!0}_parse(e){return fe(e.data)}}rt.create=e=>new rt({typeName:At.ZodAny,...Pe(e)});class at extends Ee{constructor(){super(...arguments),this._unknown=!0}_parse(e){return fe(e.data)}}at.create=e=>new at({typeName:At.ZodUnknown,...Pe(e)});class st extends Ee{_parse(e){const t=this._getOrReturnCtx(e);return de(t,{code:ne.invalid_type,expected:se.never,received:t.parsedType}),he}}st.create=e=>new st({typeName:At.ZodNever,...Pe(e)});class ot extends Ee{_parse(e){if(this._getType(e)!==se.undefined){const t=this._getOrReturnCtx(e);return de(t,{code:ne.invalid_type,expected:se.void,received:t.parsedType}),he}return fe(e.data)}}ot.create=e=>new ot({typeName:At.ZodVoid,...Pe(e)});class nt extends Ee{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),a=this._def;if(t.parsedType!==se.array)return de(t,{code:ne.invalid_type,expected:se.array,received:t.parsedType}),he;if(null!==a.exactLength){const e=t.data.length>a.exactLength.value,s=t.data.length<a.exactLength.value;(e||s)&&(de(t,{code:e?ne.too_big:ne.too_small,minimum:s?a.exactLength.value:void 0,maximum:e?a.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:a.exactLength.message}),r.dirty())}if(null!==a.minLength&&t.data.length<a.minLength.value&&(de(t,{code:ne.too_small,minimum:a.minLength.value,type:"array",inclusive:!0,exact:!1,message:a.minLength.message}),r.dirty()),null!==a.maxLength&&t.data.length>a.maxLength.value&&(de(t,{code:ne.too_big,maximum:a.maxLength.value,type:"array",inclusive:!0,exact:!1,message:a.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((e,r)=>a.type._parseAsync(new we(t,e,t.path,r)))).then(e=>ue.mergeArray(r,e));const s=[...t.data].map((e,r)=>a.type._parseSync(new we(t,e,t.path,r)));return ue.mergeArray(r,s)}get element(){return this._def.type}min(e,t){return new nt({...this._def,minLength:{value:e,message:_e.toString(t)}})}max(e,t){return new nt({...this._def,maxLength:{value:e,message:_e.toString(t)}})}length(e,t){return new nt({...this._def,exactLength:{value:e,message:_e.toString(t)}})}nonempty(e){return this.min(1,e)}}function it(e){if(e instanceof ct){const t={};for(const r in e.shape){const a=e.shape[r];t[r]=xt.create(it(a))}return new ct({...e._def,shape:()=>t})}return e instanceof nt?new nt({...e._def,type:it(e.element)}):e instanceof xt?xt.create(it(e.unwrap())):e instanceof St?St.create(it(e.unwrap())):e instanceof ft?ft.create(e.items.map(e=>it(e))):e}nt.create=(e,t)=>new nt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:At.ZodArray,...Pe(t)});class ct extends Ee{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=re.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==se.object){const t=this._getOrReturnCtx(e);return de(t,{code:ne.invalid_type,expected:se.object,received:t.parsedType}),he}const{status:t,ctx:r}=this._processInputParams(e),{shape:a,keys:s}=this._getCached(),o=[];if(!(this._def.catchall instanceof st&&"strip"===this._def.unknownKeys))for(const e in r.data)s.includes(e)||o.push(e);const n=[];for(const e of s){const t=a[e],s=r.data[e];n.push({key:{status:"valid",value:e},value:t._parse(new we(r,s,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof st){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of o)n.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)o.length>0&&(de(r,{code:ne.unrecognized_keys,keys:o}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of o){const a=r.data[t];n.push({key:{status:"valid",value:t},value:e._parse(new we(r,a,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of n){const r=await t.key,a=await t.value;e.push({key:r,value:a,alwaysSet:t.alwaysSet})}return e}).then(e=>ue.mergeObjectSync(t,e)):ue.mergeObjectSync(t,n)}get shape(){return this._def.shape()}strict(e){return _e.errToObj,new ct({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{const a=this._def.errorMap?.(t,r).message??r.defaultError;return"unrecognized_keys"===t.code?{message:_e.errToObj(e).message??a}:{message:a}}}:{}})}strip(){return new ct({...this._def,unknownKeys:"strip"})}passthrough(){return new ct({...this._def,unknownKeys:"passthrough"})}extend(e){return new ct({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ct({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:At.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ct({...this._def,catchall:e})}pick(e){const t={};for(const r of re.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new ct({...this._def,shape:()=>t})}omit(e){const t={};for(const r of re.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new ct({...this._def,shape:()=>t})}deepPartial(){return it(this)}partial(e){const t={};for(const r of re.objectKeys(this.shape)){const a=this.shape[r];e&&!e[r]?t[r]=a:t[r]=a.optional()}return new ct({...this._def,shape:()=>t})}required(e){const t={};for(const r of re.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof xt;)e=e._def.innerType;t[r]=e}return new ct({...this._def,shape:()=>t})}keyof(){return wt(re.objectKeys(this.shape))}}ct.create=(e,t)=>new ct({shape:()=>e,unknownKeys:"strip",catchall:st.create(),typeName:At.ZodObject,...Pe(t)}),ct.strictCreate=(e,t)=>new ct({shape:()=>e,unknownKeys:"strict",catchall:st.create(),typeName:At.ZodObject,...Pe(t)}),ct.lazycreate=(e,t)=>new ct({shape:e,unknownKeys:"strip",catchall:st.create(),typeName:At.ZodObject,...Pe(t)});class lt extends Ee{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map(async e=>{const r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;const r=e.map(e=>new ie(e.ctx.common.issues));return de(t,{code:ne.invalid_union,unionErrors:r}),he});{let e;const a=[];for(const s of r){const r={...t,common:{...t.common,issues:[]},parent:null},o=s._parseSync({data:t.data,path:t.path,parent:r});if("valid"===o.status)return o;"dirty"!==o.status||e||(e={result:o,ctx:r}),r.common.issues.length&&a.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const s=a.map(e=>new ie(e));return de(t,{code:ne.invalid_union,unionErrors:s}),he}}get options(){return this._def.options}}lt.create=(e,t)=>new lt({options:e,typeName:At.ZodUnion,...Pe(t)});const dt=e=>e instanceof yt?dt(e.schema):e instanceof kt?dt(e.innerType()):e instanceof _t?[e.value]:e instanceof bt?e.options:e instanceof Pt?re.objectValues(e.enum):e instanceof Tt?dt(e._def.innerType):e instanceof et?[void 0]:e instanceof tt?[null]:e instanceof xt?[void 0,...dt(e.unwrap())]:e instanceof St?[null,...dt(e.unwrap())]:e instanceof Ct||e instanceof It?dt(e.unwrap()):e instanceof Rt?dt(e._def.innerType):[];class ut extends Ee{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==se.object)return de(t,{code:ne.invalid_type,expected:se.object,received:t.parsedType}),he;const r=this.discriminator,a=t.data[r],s=this.optionsMap.get(a);return s?t.common.async?s._parseAsync({data:t.data,path:t.path,parent:t}):s._parseSync({data:t.data,path:t.path,parent:t}):(de(t,{code:ne.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),he)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){const a=new Map;for(const r of t){const t=dt(r.shape[e]);if(!t.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const s of t){if(a.has(s))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(s)}`);a.set(s,r)}}return new ut({typeName:At.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:a,...Pe(r)})}}function ht(e,t){const r=oe(e),a=oe(t);if(e===t)return{valid:!0,data:e};if(r===se.object&&a===se.object){const r=re.objectKeys(t),a=re.objectKeys(e).filter(e=>-1!==r.indexOf(e)),s={...e,...t};for(const r of a){const a=ht(e[r],t[r]);if(!a.valid)return{valid:!1};s[r]=a.data}return{valid:!0,data:s}}if(r===se.array&&a===se.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let a=0;a<e.length;a++){const s=ht(e[a],t[a]);if(!s.valid)return{valid:!1};r.push(s.data)}return{valid:!0,data:r}}return r===se.date&&a===se.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}class pt extends Ee{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),a=(e,a)=>{if(me(e)||me(a))return he;const s=ht(e.value,a.value);return s.valid?((ve(e)||ve(a))&&t.dirty(),{status:t.value,value:s.data}):(de(r,{code:ne.invalid_intersection_types}),he)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([e,t])=>a(e,t)):a(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}pt.create=(e,t,r)=>new pt({left:e,right:t,typeName:At.ZodIntersection,...Pe(r)});class ft extends Ee{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==se.array)return de(r,{code:ne.invalid_type,expected:se.array,received:r.parsedType}),he;if(r.data.length<this._def.items.length)return de(r,{code:ne.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),he;!this._def.rest&&r.data.length>this._def.items.length&&(de(r,{code:ne.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const a=[...r.data].map((e,t)=>{const a=this._def.items[t]||this._def.rest;return a?a._parse(new we(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(a).then(e=>ue.mergeArray(t,e)):ue.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new ft({...this._def,rest:e})}}ft.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ft({items:e,typeName:At.ZodTuple,rest:null,...Pe(t)})};class mt extends Ee{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==se.object)return de(r,{code:ne.invalid_type,expected:se.object,received:r.parsedType}),he;const a=[],s=this._def.keyType,o=this._def.valueType;for(const e in r.data)a.push({key:s._parse(new we(r,e,r.path,e)),value:o._parse(new we(r,r.data[e],r.path,e)),alwaysSet:e in r.data});return r.common.async?ue.mergeObjectAsync(t,a):ue.mergeObjectSync(t,a)}get element(){return this._def.valueType}static create(e,t,r){return new mt(t instanceof Ee?{keyType:e,valueType:t,typeName:At.ZodRecord,...Pe(r)}:{keyType:Qe.create(),valueType:e,typeName:At.ZodRecord,...Pe(t)})}}class vt extends Ee{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==se.map)return de(r,{code:ne.invalid_type,expected:se.map,received:r.parsedType}),he;const a=this._def.keyType,s=this._def.valueType,o=[...r.data.entries()].map(([e,t],o)=>({key:a._parse(new we(r,e,r.path,[o,"key"])),value:s._parse(new we(r,t,r.path,[o,"value"]))}));if(r.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const r of o){const a=await r.key,s=await r.value;if("aborted"===a.status||"aborted"===s.status)return he;"dirty"!==a.status&&"dirty"!==s.status||t.dirty(),e.set(a.value,s.value)}return{status:t.value,value:e}})}{const e=new Map;for(const r of o){const a=r.key,s=r.value;if("aborted"===a.status||"aborted"===s.status)return he;"dirty"!==a.status&&"dirty"!==s.status||t.dirty(),e.set(a.value,s.value)}return{status:t.value,value:e}}}}vt.create=(e,t,r)=>new vt({valueType:t,keyType:e,typeName:At.ZodMap,...Pe(r)});class gt extends Ee{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==se.set)return de(r,{code:ne.invalid_type,expected:se.set,received:r.parsedType}),he;const a=this._def;null!==a.minSize&&r.data.size<a.minSize.value&&(de(r,{code:ne.too_small,minimum:a.minSize.value,type:"set",inclusive:!0,exact:!1,message:a.minSize.message}),t.dirty()),null!==a.maxSize&&r.data.size>a.maxSize.value&&(de(r,{code:ne.too_big,maximum:a.maxSize.value,type:"set",inclusive:!0,exact:!1,message:a.maxSize.message}),t.dirty());const s=this._def.valueType;function o(e){const r=new Set;for(const a of e){if("aborted"===a.status)return he;"dirty"===a.status&&t.dirty(),r.add(a.value)}return{status:t.value,value:r}}const n=[...r.data.values()].map((e,t)=>s._parse(new we(r,e,r.path,t)));return r.common.async?Promise.all(n).then(e=>o(e)):o(n)}min(e,t){return new gt({...this._def,minSize:{value:e,message:_e.toString(t)}})}max(e,t){return new gt({...this._def,maxSize:{value:e,message:_e.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}gt.create=(e,t)=>new gt({valueType:e,minSize:null,maxSize:null,typeName:At.ZodSet,...Pe(t)});class yt extends Ee{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}yt.create=(e,t)=>new yt({getter:e,typeName:At.ZodLazy,...Pe(t)});class _t extends Ee{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return de(t,{received:t.data,code:ne.invalid_literal,expected:this._def.value}),he}return{status:"valid",value:e.data}}get value(){return this._def.value}}function wt(e,t){return new bt({values:e,typeName:At.ZodEnum,...Pe(t)})}_t.create=(e,t)=>new _t({value:e,typeName:At.ZodLiteral,...Pe(t)});class bt extends Ee{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return de(t,{expected:re.joinValues(r),received:t.parsedType,code:ne.invalid_type}),he}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return de(t,{received:t.data,code:ne.invalid_enum_value,options:r}),he}return fe(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return bt.create(e,{...this._def,...t})}exclude(e,t=this._def){return bt.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}bt.create=wt;class Pt extends Ee{_parse(e){const t=re.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==se.string&&r.parsedType!==se.number){const e=re.objectValues(t);return de(r,{expected:re.joinValues(e),received:r.parsedType,code:ne.invalid_type}),he}if(this._cache||(this._cache=new Set(re.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=re.objectValues(t);return de(r,{received:r.data,code:ne.invalid_enum_value,options:e}),he}return fe(e.data)}get enum(){return this._def.values}}Pt.create=(e,t)=>new Pt({values:e,typeName:At.ZodNativeEnum,...Pe(t)});class Et extends Ee{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==se.promise&&!1===t.common.async)return de(t,{code:ne.invalid_type,expected:se.promise,received:t.parsedType}),he;const r=t.parsedType===se.promise?t.data:Promise.resolve(t.data);return fe(r.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Et.create=(e,t)=>new Et({type:e,typeName:At.ZodPromise,...Pe(t)});class kt extends Ee{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===At.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),a=this._def.effect||null,s={addIssue:e=>{de(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),"preprocess"===a.type){const e=a.transform(r.data,s);if(r.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return he;const a=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===a.status?he:"dirty"===a.status||"dirty"===t.value?pe(a.value):a});{if("aborted"===t.value)return he;const a=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===a.status?he:"dirty"===a.status||"dirty"===t.value?pe(a.value):a}}if("refinement"===a.type){const e=e=>{const t=a.refinement(e,s);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===r.common.async){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===a.status?he:("dirty"===a.status&&t.dirty(),e(a.value),{status:t.value,value:a.value})}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(r=>"aborted"===r.status?he:("dirty"===r.status&&t.dirty(),e(r.value).then(()=>({status:t.value,value:r.value}))))}if("transform"===a.type){if(!1===r.common.async){const e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!ge(e))return he;const o=a.transform(e.value,s);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(e=>ge(e)?Promise.resolve(a.transform(e.value,s)).then(e=>({status:t.value,value:e})):he)}re.assertNever(a)}}kt.create=(e,t,r)=>new kt({schema:e,typeName:At.ZodEffects,effect:t,...Pe(r)}),kt.createWithPreprocess=(e,t,r)=>new kt({schema:t,effect:{type:"preprocess",transform:e},typeName:At.ZodEffects,...Pe(r)});class xt extends Ee{_parse(e){return this._getType(e)===se.undefined?fe(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}xt.create=(e,t)=>new xt({innerType:e,typeName:At.ZodOptional,...Pe(t)});class St extends Ee{_parse(e){return this._getType(e)===se.null?fe(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}St.create=(e,t)=>new St({innerType:e,typeName:At.ZodNullable,...Pe(t)});class Tt extends Ee{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===se.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Tt.create=(e,t)=>new Tt({innerType:e,typeName:At.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...Pe(t)});class Rt extends Ee{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},a=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return ye(a)?a.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new ie(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===a.status?a.value:this._def.catchValue({get error(){return new ie(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Rt.create=(e,t)=>new Rt({innerType:e,typeName:At.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...Pe(t)});class $t extends Ee{_parse(e){if(this._getType(e)!==se.nan){const t=this._getOrReturnCtx(e);return de(t,{code:ne.invalid_type,expected:se.nan,received:t.parsedType}),he}return{status:"valid",value:e.data}}}$t.create=e=>new $t({typeName:At.ZodNaN,...Pe(e)});class Ct extends Ee{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class Ot extends Ee{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?he:"dirty"===e.status?(t.dirty(),pe(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})()}{const e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?he:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new Ot({in:e,out:t,typeName:At.ZodPipeline})}}class It extends Ee{_parse(e){const t=this._def.innerType._parse(e),r=e=>(ge(e)&&(e.value=Object.freeze(e.value)),e);return ye(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}}var At;It.create=(e,t)=>new It({innerType:e,typeName:At.ZodReadonly,...Pe(t)}),ct.lazycreate,function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"}(At||(At={}));const jt=Qe.create,Ft=Je.create;$t.create,We.create;const Dt=Ge.create;Ye.create,Xe.create,et.create,tt.create;const Nt=rt.create,Ut=at.create;st.create,ot.create;const Lt=nt.create,qt=ct.create;ct.strictCreate;const zt=lt.create,Vt=ut.create;pt.create,ft.create;const Mt=mt.create;vt.create,gt.create,yt.create;const Zt=_t.create,Ht=bt.create;Pt.create,Et.create,kt.create;const Bt=xt.create;St.create,kt.createWithPreprocess;const Qt="2025-06-18",Kt=[Qt,"2025-03-26","2024-11-05","2024-10-07"],Jt="2.0",Wt=zt([jt(),Ft().int()]),Gt=jt(),Yt=qt({progressToken:Bt(Wt)}).passthrough(),Xt=qt({_meta:Bt(Yt)}).passthrough(),er=qt({method:jt(),params:Bt(Xt)}),tr=qt({_meta:Bt(qt({}).passthrough())}).passthrough(),rr=qt({method:jt(),params:Bt(tr)}),ar=qt({_meta:Bt(qt({}).passthrough())}).passthrough(),sr=zt([jt(),Ft().int()]),or=qt({jsonrpc:Zt(Jt),id:sr}).merge(er).strict(),nr=e=>or.safeParse(e).success,ir=qt({jsonrpc:Zt(Jt)}).merge(rr).strict(),cr=qt({jsonrpc:Zt(Jt),id:sr,result:ar}).strict(),lr=e=>cr.safeParse(e).success;var dr;!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"}(dr||(dr={}));const ur=qt({jsonrpc:Zt(Jt),id:sr,error:qt({code:Ft().int(),message:jt(),data:Bt(Ut())})}).strict(),hr=zt([or,ir,cr,ur]),pr=ar.strict(),fr=rr.extend({method:Zt("notifications/cancelled"),params:tr.extend({requestId:sr,reason:jt().optional()})}),mr=qt({name:jt(),title:Bt(jt())}).passthrough(),vr=mr.extend({version:jt()}),gr=qt({experimental:Bt(qt({}).passthrough()),sampling:Bt(qt({}).passthrough()),elicitation:Bt(qt({}).passthrough()),roots:Bt(qt({listChanged:Bt(Dt())}).passthrough())}).passthrough(),yr=er.extend({method:Zt("initialize"),params:Xt.extend({protocolVersion:jt(),capabilities:gr,clientInfo:vr})}),_r=qt({experimental:Bt(qt({}).passthrough()),logging:Bt(qt({}).passthrough()),completions:Bt(qt({}).passthrough()),prompts:Bt(qt({listChanged:Bt(Dt())}).passthrough()),resources:Bt(qt({subscribe:Bt(Dt()),listChanged:Bt(Dt())}).passthrough()),tools:Bt(qt({listChanged:Bt(Dt())}).passthrough())}).passthrough(),wr=ar.extend({protocolVersion:jt(),capabilities:_r,serverInfo:vr,instructions:Bt(jt())}),br=rr.extend({method:Zt("notifications/initialized")}),Pr=er.extend({method:Zt("ping")}),Er=qt({progress:Ft(),total:Bt(Ft()),message:Bt(jt())}).passthrough(),kr=rr.extend({method:Zt("notifications/progress"),params:tr.merge(Er).extend({progressToken:Wt})}),xr=er.extend({params:Xt.extend({cursor:Bt(Gt)}).optional()}),Sr=ar.extend({nextCursor:Bt(Gt)}),Tr=qt({uri:jt(),mimeType:Bt(jt()),_meta:Bt(qt({}).passthrough())}).passthrough(),Rr=Tr.extend({text:jt()}),$r=jt().refine(e=>{try{return atob(e),!0}catch(e){return!1}},{message:"Invalid Base64 string"}),Cr=Tr.extend({blob:$r}),Or=mr.extend({uri:jt(),description:Bt(jt()),mimeType:Bt(jt()),_meta:Bt(qt({}).passthrough())}),Ir=mr.extend({uriTemplate:jt(),description:Bt(jt()),mimeType:Bt(jt()),_meta:Bt(qt({}).passthrough())}),Ar=xr.extend({method:Zt("resources/list")}),jr=Sr.extend({resources:Lt(Or)}),Fr=xr.extend({method:Zt("resources/templates/list")}),Dr=Sr.extend({resourceTemplates:Lt(Ir)}),Nr=er.extend({method:Zt("resources/read"),params:Xt.extend({uri:jt()})}),Ur=ar.extend({contents:Lt(zt([Rr,Cr]))}),Lr=rr.extend({method:Zt("notifications/resources/list_changed")}),qr=er.extend({method:Zt("resources/subscribe"),params:Xt.extend({uri:jt()})}),zr=er.extend({method:Zt("resources/unsubscribe"),params:Xt.extend({uri:jt()})}),Vr=rr.extend({method:Zt("notifications/resources/updated"),params:tr.extend({uri:jt()})}),Mr=qt({name:jt(),description:Bt(jt()),required:Bt(Dt())}).passthrough(),Zr=mr.extend({description:Bt(jt()),arguments:Bt(Lt(Mr)),_meta:Bt(qt({}).passthrough())}),Hr=xr.extend({method:Zt("prompts/list")}),Br=Sr.extend({prompts:Lt(Zr)}),Qr=er.extend({method:Zt("prompts/get"),params:Xt.extend({name:jt(),arguments:Bt(Mt(jt()))})}),Kr=qt({type:Zt("text"),text:jt(),_meta:Bt(qt({}).passthrough())}).passthrough(),Jr=qt({type:Zt("image"),data:$r,mimeType:jt(),_meta:Bt(qt({}).passthrough())}).passthrough(),Wr=qt({type:Zt("audio"),data:$r,mimeType:jt(),_meta:Bt(qt({}).passthrough())}).passthrough(),Gr=qt({type:Zt("resource"),resource:zt([Rr,Cr]),_meta:Bt(qt({}).passthrough())}).passthrough(),Yr=zt([Kr,Jr,Wr,Or.extend({type:Zt("resource_link")}),Gr]),Xr=qt({role:Ht(["user","assistant"]),content:Yr}).passthrough(),ea=ar.extend({description:Bt(jt()),messages:Lt(Xr)}),ta=rr.extend({method:Zt("notifications/prompts/list_changed")}),ra=qt({title:Bt(jt()),readOnlyHint:Bt(Dt()),destructiveHint:Bt(Dt()),idempotentHint:Bt(Dt()),openWorldHint:Bt(Dt())}).passthrough(),aa=mr.extend({description:Bt(jt()),inputSchema:qt({type:Zt("object"),properties:Bt(qt({}).passthrough()),required:Bt(Lt(jt()))}).passthrough(),outputSchema:Bt(qt({type:Zt("object"),properties:Bt(qt({}).passthrough()),required:Bt(Lt(jt()))}).passthrough()),annotations:Bt(ra),_meta:Bt(qt({}).passthrough())}),sa=xr.extend({method:Zt("tools/list")}),oa=Sr.extend({tools:Lt(aa)}),na=ar.extend({content:Lt(Yr).default([]),structuredContent:qt({}).passthrough().optional(),isError:Bt(Dt())});na.or(ar.extend({toolResult:Ut()}));const ia=er.extend({method:Zt("tools/call"),params:Xt.extend({name:jt(),arguments:Bt(Mt(Ut()))})}),ca=rr.extend({method:Zt("notifications/tools/list_changed")}),la=Ht(["debug","info","notice","warning","error","critical","alert","emergency"]),da=er.extend({method:Zt("logging/setLevel"),params:Xt.extend({level:la})}),ua=rr.extend({method:Zt("notifications/message"),params:tr.extend({level:la,logger:Bt(jt()),data:Ut()})}),ha=qt({name:jt().optional()}).passthrough(),pa=qt({hints:Bt(Lt(ha)),costPriority:Bt(Ft().min(0).max(1)),speedPriority:Bt(Ft().min(0).max(1)),intelligencePriority:Bt(Ft().min(0).max(1))}).passthrough(),fa=qt({role:Ht(["user","assistant"]),content:zt([Kr,Jr,Wr])}).passthrough(),ma=er.extend({method:Zt("sampling/createMessage"),params:Xt.extend({messages:Lt(fa),systemPrompt:Bt(jt()),includeContext:Bt(Ht(["none","thisServer","allServers"])),temperature:Bt(Ft()),maxTokens:Ft().int(),stopSequences:Bt(Lt(jt())),metadata:Bt(qt({}).passthrough()),modelPreferences:Bt(pa)})}),va=ar.extend({model:jt(),stopReason:Bt(Ht(["endTurn","stopSequence","maxTokens"]).or(jt())),role:Ht(["user","assistant"]),content:Vt("type",[Kr,Jr,Wr])}),ga=zt([qt({type:Zt("boolean"),title:Bt(jt()),description:Bt(jt()),default:Bt(Dt())}).passthrough(),qt({type:Zt("string"),title:Bt(jt()),description:Bt(jt()),minLength:Bt(Ft()),maxLength:Bt(Ft()),format:Bt(Ht(["email","uri","date","date-time"]))}).passthrough(),qt({type:Ht(["number","integer"]),title:Bt(jt()),description:Bt(jt()),minimum:Bt(Ft()),maximum:Bt(Ft())}).passthrough(),qt({type:Zt("string"),title:Bt(jt()),description:Bt(jt()),enum:Lt(jt()),enumNames:Bt(Lt(jt()))}).passthrough()]),ya=er.extend({method:Zt("elicitation/create"),params:Xt.extend({message:jt(),requestedSchema:qt({type:Zt("object"),properties:Mt(jt(),ga),required:Bt(Lt(jt()))}).passthrough()})}),_a=ar.extend({action:Ht(["accept","decline","cancel"]),content:Bt(Mt(jt(),Ut()))}),wa=qt({type:Zt("ref/resource"),uri:jt()}).passthrough(),ba=qt({type:Zt("ref/prompt"),name:jt()}).passthrough(),Pa=er.extend({method:Zt("completion/complete"),params:Xt.extend({ref:zt([ba,wa]),argument:qt({name:jt(),value:jt()}).passthrough(),context:Bt(qt({arguments:Bt(Mt(jt(),jt()))}))})}),Ea=ar.extend({completion:qt({values:Lt(jt()).max(100),total:Bt(Ft().int()),hasMore:Bt(Dt())}).passthrough()}),ka=qt({uri:jt().startsWith("file://"),name:Bt(jt()),_meta:Bt(qt({}).passthrough())}).passthrough(),xa=er.extend({method:Zt("roots/list")}),Sa=ar.extend({roots:Lt(ka)}),Ta=rr.extend({method:Zt("notifications/roots/list_changed")});zt([Pr,yr,Pa,da,Qr,Hr,Ar,Fr,Nr,qr,zr,ia,sa]),zt([fr,kr,br,Ta]),zt([pr,va,_a,Sa]),zt([Pr,ma,ya,xa]),zt([fr,kr,ua,Vr,Lr,ca,ta]),zt([pr,wr,Ea,ea,Br,jr,Dr,Ur,na,oa]);class Ra extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`),this.code=e,this.data=r,this.name="McpError"}}class $a{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.setNotificationHandler(fr,e=>{const t=this._requestHandlerAbortControllers.get(e.params.requestId);null==t||t.abort(e.params.reason)}),this.setNotificationHandler(kr,e=>{this._onprogress(e)}),this.setRequestHandler(Pr,e=>({}))}_setupTimeout(e,t,r,a,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(a,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:s,onTimeout:a})}_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),new Ra(dr.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){var t,r,a;this._transport=e;const s=null===(t=this.transport)||void 0===t?void 0:t.onclose;this._transport.onclose=()=>{null==s||s(),this._onclose()};const o=null===(r=this.transport)||void 0===r?void 0:r.onerror;this._transport.onerror=e=>{null==o||o(e),this._onerror(e)};const n=null===(a=this._transport)||void 0===a?void 0:a.onmessage;this._transport.onmessage=(e,t)=>{var r;null==n||n(e,t),lr(e)||(r=e,ur.safeParse(r).success)?this._onresponse(e):nr(e)?this._onrequest(e,t):(e=>ir.safeParse(e).success)(e)?this._onnotification(e):this._onerror(new Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){var e;const t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._transport=void 0,null===(e=this.onclose)||void 0===e||e.call(this);const r=new Ra(dr.ConnectionClosed,"Connection closed");for(const e of t.values())e(r)}_onerror(e){var t;null===(t=this.onerror)||void 0===t||t.call(this,e)}_onnotification(e){var t;const r=null!==(t=this._notificationHandlers.get(e.method))&&void 0!==t?t:this.fallbackNotificationHandler;void 0!==r&&Promise.resolve().then(()=>r(e)).catch(e=>this._onerror(new Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){var r,a,s,o;const n=null!==(r=this._requestHandlers.get(e.method))&&void 0!==r?r:this.fallbackRequestHandler;if(void 0===n)return void(null===(a=this._transport)||void 0===a||a.send({jsonrpc:"2.0",id:e.id,error:{code:dr.MethodNotFound,message:"Method not found"}}).catch(e=>this._onerror(new Error(`Failed to send an error response: ${e}`))));const i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);const c={signal:i.signal,sessionId:null===(s=this._transport)||void 0===s?void 0:s.sessionId,_meta:null===(o=e.params)||void 0===o?void 0:o._meta,sendNotification:t=>this.notification(t,{relatedRequestId:e.id}),sendRequest:(t,r,a)=>this.request(t,r,{...a,relatedRequestId:e.id}),authInfo:null==t?void 0:t.authInfo,requestId:e.id,requestInfo:null==t?void 0:t.requestInfo};Promise.resolve().then(()=>n(e,c)).then(t=>{var r;if(!i.signal.aborted)return null===(r=this._transport)||void 0===r?void 0:r.send({result:t,jsonrpc:"2.0",id:e.id})},t=>{var r,a;if(!i.signal.aborted)return null===(r=this._transport)||void 0===r?void 0:r.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:dr.InternalError,message:null!==(a=t.message)&&void 0!==a?a:"Internal error"}})}).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,a=Number(t),s=this._progressHandlers.get(a);if(!s)return void this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));const o=this._responseHandlers.get(a),n=this._timeoutInfo.get(a);if(n&&o&&n.resetTimeoutOnProgress)try{this._resetTimeout(a)}catch(e){return void o(e)}s(r)}_onresponse(e){const t=Number(e.id),r=this._responseHandlers.get(t);if(void 0!==r)if(this._responseHandlers.delete(t),this._progressHandlers.delete(t),this._cleanupTimeout(t),lr(e))r(e);else{r(new Ra(e.error.code,e.error.message,e.error.data))}else this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`))}get transport(){return this._transport}async close(){var e;await(null===(e=this._transport)||void 0===e?void 0:e.close())}request(e,t,r){const{relatedRequestId:a,resumptionToken:s,onresumptiontoken:o}=null!=r?r:{};return new Promise((n,i)=>{var c,l,d,u,h,p;if(!this._transport)return void i(new Error("Not connected"));!0===(null===(c=this._options)||void 0===c?void 0:c.enforceStrictCapabilities)&&this.assertCapabilityForMethod(e.method),null===(l=null==r?void 0:r.signal)||void 0===l||l.throwIfAborted();const f=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:f};(null==r?void 0:r.onprogress)&&(this._progressHandlers.set(f,r.onprogress),m.params={...e.params,_meta:{...(null===(d=e.params)||void 0===d?void 0:d._meta)||{},progressToken:f}});const v=e=>{var t;this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),null===(t=this._transport)||void 0===t||t.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(e)}},{relatedRequestId:a,resumptionToken:s,onresumptiontoken:o}).catch(e=>this._onerror(new Error(`Failed to send cancellation: ${e}`))),i(e)};this._responseHandlers.set(f,e=>{var a;if(!(null===(a=null==r?void 0:r.signal)||void 0===a?void 0:a.aborted)){if(e instanceof Error)return i(e);try{const r=t.parse(e.result);n(r)}catch(e){i(e)}}}),null===(u=null==r?void 0:r.signal)||void 0===u||u.addEventListener("abort",()=>{var e;v(null===(e=null==r?void 0:r.signal)||void 0===e?void 0:e.reason)});const g=null!==(h=null==r?void 0:r.timeout)&&void 0!==h?h:6e4;this._setupTimeout(f,g,null==r?void 0:r.maxTotalTimeout,()=>v(new Ra(dr.RequestTimeout,"Request timed out",{timeout:g})),null!==(p=null==r?void 0:r.resetTimeoutOnProgress)&&void 0!==p&&p),this._transport.send(m,{relatedRequestId:a,resumptionToken:s,onresumptiontoken:o}).catch(e=>{this._cleanupTimeout(f),i(e)})})}async notification(e,t){var r,a;if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);if((null!==(a=null===(r=this._options)||void 0===r?void 0:r.debouncedNotificationMethods)&&void 0!==a?a:[]).includes(e.method)&&!e.params&&!(null==t?void 0:t.relatedRequestId)){if(this._pendingDebouncedNotifications.has(e.method))return;return this._pendingDebouncedNotifications.add(e.method),void Promise.resolve().then(()=>{var r;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;const a={...e,jsonrpc:"2.0"};null===(r=this._transport)||void 0===r||r.send(a,t).catch(e=>this._onerror(e))})}const s={...e,jsonrpc:"2.0"};await this._transport.send(s,t)}setRequestHandler(e,t){const r=e.shape.method.value;this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(r,a)=>Promise.resolve(t(e.parse(r),a)))}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){this._notificationHandlers.set(e.shape.method.value,r=>Promise.resolve(t(e.parse(r))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}}"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;function Ca(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Oa={exports:{}};
2
+ /** @license URI.js v4.4.1 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js */!function(e){function t(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];if(t.length>1){t[0]=t[0].slice(0,-1);for(var a=t.length-1,s=1;s<a;++s)t[s]=t[s].slice(1,-1);return t[a]=t[a].slice(1),t.join("")}return t[0]}function r(e){return"(?:"+e+")"}function a(e){return void 0===e?"undefined":null===e?"null":Object.prototype.toString.call(e).split(" ").pop().split("]").shift().toLowerCase()}function s(e){return e.toUpperCase()}function o(e){return null!=e?e instanceof Array?e:"number"!=typeof e.length||e.split||e.setInterval||e.call?[e]:Array.prototype.slice.call(e):[]}function n(e,t){var r=e;if(t)for(var a in t)r[a]=t[a];return r}function i(e){var a="[A-Za-z]",s="[0-9]",o=t(s,"[A-Fa-f]"),n=r(r("%[EFef]"+o+"%"+o+o+"%"+o+o)+"|"+r("%[89A-Fa-f]"+o+"%"+o+o)+"|"+r("%"+o+o)),i="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",c=t("[\\:\\/\\?\\#\\[\\]\\@]",i),l=e?"[\\uE000-\\uF8FF]":"[]",d=t(a,s,"[\\-\\.\\_\\~]",e?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]");r(a+t(a,s,"[\\+\\-\\.]")+"*"),r(r(n+"|"+t(d,i,"[\\:]"))+"*");var u=r(r("25[0-5]")+"|"+r("2[0-4]"+s)+"|"+r("1"+s+s)+"|"+r("0?[1-9]"+s)+"|0?0?"+s),h=r(u+"\\."+u+"\\."+u+"\\."+u),p=r(o+"{1,4}"),f=r(r(p+"\\:"+p)+"|"+h),m=r(r(p+"\\:")+"{6}"+f),v=r("\\:\\:"+r(p+"\\:")+"{5}"+f),g=r(r(p)+"?\\:\\:"+r(p+"\\:")+"{4}"+f),y=r(r(r(p+"\\:")+"{0,1}"+p)+"?\\:\\:"+r(p+"\\:")+"{3}"+f),_=r(r(r(p+"\\:")+"{0,2}"+p)+"?\\:\\:"+r(p+"\\:")+"{2}"+f),w=r(r(r(p+"\\:")+"{0,3}"+p)+"?\\:\\:"+p+"\\:"+f),b=r(r(r(p+"\\:")+"{0,4}"+p)+"?\\:\\:"+f),P=r(r(r(p+"\\:")+"{0,5}"+p)+"?\\:\\:"+p),E=r(r(r(p+"\\:")+"{0,6}"+p)+"?\\:\\:"),k=r([m,v,g,y,_,w,b,P,E].join("|")),x=r(r(d+"|"+n)+"+");r("[vV]"+o+"+\\."+t(d,i,"[\\:]")+"+"),r(r(n+"|"+t(d,i))+"*");var S=r(n+"|"+t(d,i,"[\\:\\@]"));return r(r(n+"|"+t(d,i,"[\\@]"))+"+"),r(r(S+"|"+t("[\\/\\?]",l))+"*"),{NOT_SCHEME:new RegExp(t("[^]",a,s,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(t("[^\\%\\:]",d,i),"g"),NOT_HOST:new RegExp(t("[^\\%\\[\\]\\:]",d,i),"g"),NOT_PATH:new RegExp(t("[^\\%\\/\\:\\@]",d,i),"g"),NOT_PATH_NOSCHEME:new RegExp(t("[^\\%\\/\\@]",d,i),"g"),NOT_QUERY:new RegExp(t("[^\\%]",d,i,"[\\:\\@\\/\\?]",l),"g"),NOT_FRAGMENT:new RegExp(t("[^\\%]",d,i,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(t("[^]",d,i),"g"),UNRESERVED:new RegExp(d,"g"),OTHER_CHARS:new RegExp(t("[^\\%]",d,c),"g"),PCT_ENCODED:new RegExp(n,"g"),IPV4ADDRESS:new RegExp("^("+h+")$"),IPV6ADDRESS:new RegExp("^\\[?("+k+")"+r(r("\\%25|\\%(?!"+o+"{2})")+"("+x+")")+"?\\]?$")}}var c=i(!1),l=i(!0),d=function(){function e(e,t){var r=[],a=!0,s=!1,o=void 0;try{for(var n,i=e[Symbol.iterator]();!(a=(n=i.next()).done)&&(r.push(n.value),!t||r.length!==t);a=!0);}catch(e){s=!0,o=e}finally{try{!a&&i.return&&i.return()}finally{if(s)throw o}}return r}return function(t,r){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return e(t,r);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),u=function(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}return Array.from(e)},h=2147483647,p=36,f=1,m=26,v=38,g=700,y=72,_=128,w="-",b=/^xn--/,P=/[^\0-\x7E]/,E=/[\x2E\u3002\uFF0E\uFF61]/g,k={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},x=p-f,S=Math.floor,T=String.fromCharCode;function R(e){throw new RangeError(k[e])}function $(e,t){for(var r=[],a=e.length;a--;)r[a]=t(e[a]);return r}function C(e,t){var r=e.split("@"),a="";return r.length>1&&(a=r[0]+"@",e=r[1]),a+$((e=e.replace(E,".")).split("."),t).join(".")}function O(e){for(var t=[],r=0,a=e.length;r<a;){var s=e.charCodeAt(r++);if(s>=55296&&s<=56319&&r<a){var o=e.charCodeAt(r++);56320==(64512&o)?t.push(((1023&s)<<10)+(1023&o)+65536):(t.push(s),r--)}else t.push(s)}return t}var I=function(e){return e-48<10?e-22:e-65<26?e-65:e-97<26?e-97:p},A=function(e,t){return e+22+75*(e<26)-((0!=t)<<5)},j=function(e,t,r){var a=0;for(e=r?S(e/g):e>>1,e+=S(e/t);e>x*m>>1;a+=p)e=S(e/x);return S(a+(x+1)*e/(e+v))},F=function(e){var t=[],r=e.length,a=0,s=_,o=y,n=e.lastIndexOf(w);n<0&&(n=0);for(var i=0;i<n;++i)e.charCodeAt(i)>=128&&R("not-basic"),t.push(e.charCodeAt(i));for(var c=n>0?n+1:0;c<r;){for(var l=a,d=1,u=p;;u+=p){c>=r&&R("invalid-input");var v=I(e.charCodeAt(c++));(v>=p||v>S((h-a)/d))&&R("overflow"),a+=v*d;var g=u<=o?f:u>=o+m?m:u-o;if(v<g)break;var b=p-g;d>S(h/b)&&R("overflow"),d*=b}var P=t.length+1;o=j(a-l,P,0==l),S(a/P)>h-s&&R("overflow"),s+=S(a/P),a%=P,t.splice(a++,0,s)}return String.fromCodePoint.apply(String,t)},D=function(e){var t=[],r=(e=O(e)).length,a=_,s=0,o=y,n=!0,i=!1,c=void 0;try{for(var l,d=e[Symbol.iterator]();!(n=(l=d.next()).done);n=!0){var u=l.value;u<128&&t.push(T(u))}}catch(e){i=!0,c=e}finally{try{!n&&d.return&&d.return()}finally{if(i)throw c}}var v=t.length,g=v;for(v&&t.push(w);g<r;){var b=h,P=!0,E=!1,k=void 0;try{for(var x,$=e[Symbol.iterator]();!(P=(x=$.next()).done);P=!0){var C=x.value;C>=a&&C<b&&(b=C)}}catch(e){E=!0,k=e}finally{try{!P&&$.return&&$.return()}finally{if(E)throw k}}var I=g+1;b-a>S((h-s)/I)&&R("overflow"),s+=(b-a)*I,a=b;var F=!0,D=!1,N=void 0;try{for(var U,L=e[Symbol.iterator]();!(F=(U=L.next()).done);F=!0){var q=U.value;if(q<a&&++s>h&&R("overflow"),q==a){for(var z=s,V=p;;V+=p){var M=V<=o?f:V>=o+m?m:V-o;if(z<M)break;var Z=z-M,H=p-M;t.push(T(A(M+Z%H,0))),z=S(Z/H)}t.push(T(A(z,0))),o=j(s,I,g==v),s=0,++g}}}catch(e){D=!0,N=e}finally{try{!F&&L.return&&L.return()}finally{if(D)throw N}}++s,++a}return t.join("")},N=function(e){return C(e,function(e){return b.test(e)?F(e.slice(4).toLowerCase()):e})},U=function(e){return C(e,function(e){return P.test(e)?"xn--"+D(e):e})},L={version:"2.1.0",ucs2:{decode:O,encode:function(e){return String.fromCodePoint.apply(String,u(e))}},decode:F,encode:D,toASCII:U,toUnicode:N},q={};function z(e){var t=e.charCodeAt(0);return t<16?"%0"+t.toString(16).toUpperCase():t<128?"%"+t.toString(16).toUpperCase():t<2048?"%"+(t>>6|192).toString(16).toUpperCase()+"%"+(63&t|128).toString(16).toUpperCase():"%"+(t>>12|224).toString(16).toUpperCase()+"%"+(t>>6&63|128).toString(16).toUpperCase()+"%"+(63&t|128).toString(16).toUpperCase()}function V(e){for(var t="",r=0,a=e.length;r<a;){var s=parseInt(e.substr(r+1,2),16);if(s<128)t+=String.fromCharCode(s),r+=3;else if(s>=194&&s<224){if(a-r>=6){var o=parseInt(e.substr(r+4,2),16);t+=String.fromCharCode((31&s)<<6|63&o)}else t+=e.substr(r,6);r+=6}else if(s>=224){if(a-r>=9){var n=parseInt(e.substr(r+4,2),16),i=parseInt(e.substr(r+7,2),16);t+=String.fromCharCode((15&s)<<12|(63&n)<<6|63&i)}else t+=e.substr(r,9);r+=9}else t+=e.substr(r,3),r+=3}return t}function M(e,t){function r(e){var r=V(e);return r.match(t.UNRESERVED)?r:e}return e.scheme&&(e.scheme=String(e.scheme).replace(t.PCT_ENCODED,r).toLowerCase().replace(t.NOT_SCHEME,"")),void 0!==e.userinfo&&(e.userinfo=String(e.userinfo).replace(t.PCT_ENCODED,r).replace(t.NOT_USERINFO,z).replace(t.PCT_ENCODED,s)),void 0!==e.host&&(e.host=String(e.host).replace(t.PCT_ENCODED,r).toLowerCase().replace(t.NOT_HOST,z).replace(t.PCT_ENCODED,s)),void 0!==e.path&&(e.path=String(e.path).replace(t.PCT_ENCODED,r).replace(e.scheme?t.NOT_PATH:t.NOT_PATH_NOSCHEME,z).replace(t.PCT_ENCODED,s)),void 0!==e.query&&(e.query=String(e.query).replace(t.PCT_ENCODED,r).replace(t.NOT_QUERY,z).replace(t.PCT_ENCODED,s)),void 0!==e.fragment&&(e.fragment=String(e.fragment).replace(t.PCT_ENCODED,r).replace(t.NOT_FRAGMENT,z).replace(t.PCT_ENCODED,s)),e}function Z(e){return e.replace(/^0*(.*)/,"$1")||"0"}function H(e,t){var r=e.match(t.IPV4ADDRESS)||[],a=d(r,2)[1];return a?a.split(".").map(Z).join("."):e}function B(e,t){var r=e.match(t.IPV6ADDRESS)||[],a=d(r,3),s=a[1],o=a[2];if(s){for(var n=s.toLowerCase().split("::").reverse(),i=d(n,2),c=i[0],l=i[1],u=l?l.split(":").map(Z):[],h=c.split(":").map(Z),p=t.IPV4ADDRESS.test(h[h.length-1]),f=p?7:8,m=h.length-f,v=Array(f),g=0;g<f;++g)v[g]=u[g]||h[m+g]||"";p&&(v[f-1]=H(v[f-1],t));var y=v.reduce(function(e,t,r){if(!t||"0"===t){var a=e[e.length-1];a&&a.index+a.length===r?a.length++:e.push({index:r,length:1})}return e},[]).sort(function(e,t){return t.length-e.length})[0],_=void 0;if(y&&y.length>1){var w=v.slice(0,y.index),b=v.slice(y.index+y.length);_=w.join(":")+"::"+b.join(":")}else _=v.join(":");return o&&(_+="%"+o),_}return e}var Q=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,K=void 0==="".match(/(){0}/)[1];function J(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r={},a=!1!==t.iri?l:c;"suffix"===t.reference&&(e=(t.scheme?t.scheme+":":"")+"//"+e);var s=e.match(Q);if(s){K?(r.scheme=s[1],r.userinfo=s[3],r.host=s[4],r.port=parseInt(s[5],10),r.path=s[6]||"",r.query=s[7],r.fragment=s[8],isNaN(r.port)&&(r.port=s[5])):(r.scheme=s[1]||void 0,r.userinfo=-1!==e.indexOf("@")?s[3]:void 0,r.host=-1!==e.indexOf("//")?s[4]:void 0,r.port=parseInt(s[5],10),r.path=s[6]||"",r.query=-1!==e.indexOf("?")?s[7]:void 0,r.fragment=-1!==e.indexOf("#")?s[8]:void 0,isNaN(r.port)&&(r.port=e.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?s[4]:void 0)),r.host&&(r.host=B(H(r.host,a),a)),void 0!==r.scheme||void 0!==r.userinfo||void 0!==r.host||void 0!==r.port||r.path||void 0!==r.query?void 0===r.scheme?r.reference="relative":void 0===r.fragment?r.reference="absolute":r.reference="uri":r.reference="same-document",t.reference&&"suffix"!==t.reference&&t.reference!==r.reference&&(r.error=r.error||"URI is not a "+t.reference+" reference.");var o=q[(t.scheme||r.scheme||"").toLowerCase()];if(t.unicodeSupport||o&&o.unicodeSupport)M(r,a);else{if(r.host&&(t.domainHost||o&&o.domainHost))try{r.host=L.toASCII(r.host.replace(a.PCT_ENCODED,V).toLowerCase())}catch(e){r.error=r.error||"Host's domain name can not be converted to ASCII via punycode: "+e}M(r,c)}o&&o.parse&&o.parse(r,t)}else r.error=r.error||"URI can not be parsed.";return r}function W(e,t){var r=!1!==t.iri?l:c,a=[];return void 0!==e.userinfo&&(a.push(e.userinfo),a.push("@")),void 0!==e.host&&a.push(B(H(String(e.host),r),r).replace(r.IPV6ADDRESS,function(e,t,r){return"["+t+(r?"%25"+r:"")+"]"})),"number"!=typeof e.port&&"string"!=typeof e.port||(a.push(":"),a.push(String(e.port))),a.length?a.join(""):void 0}var G=/^\.\.?\//,Y=/^\/\.(\/|$)/,X=/^\/\.\.(\/|$)/,ee=/^\/?(?:.|\n)*?(?=\/|$)/;function te(e){for(var t=[];e.length;)if(e.match(G))e=e.replace(G,"");else if(e.match(Y))e=e.replace(Y,"/");else if(e.match(X))e=e.replace(X,"/"),t.pop();else if("."===e||".."===e)e="";else{var r=e.match(ee);if(!r)throw new Error("Unexpected dot segment condition");var a=r[0];e=e.slice(a.length),t.push(a)}return t.join("")}function re(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.iri?l:c,a=[],s=q[(t.scheme||e.scheme||"").toLowerCase()];if(s&&s.serialize&&s.serialize(e,t),e.host)if(r.IPV6ADDRESS.test(e.host));else if(t.domainHost||s&&s.domainHost)try{e.host=t.iri?L.toUnicode(e.host):L.toASCII(e.host.replace(r.PCT_ENCODED,V).toLowerCase())}catch(r){e.error=e.error||"Host's domain name can not be converted to "+(t.iri?"Unicode":"ASCII")+" via punycode: "+r}M(e,r),"suffix"!==t.reference&&e.scheme&&(a.push(e.scheme),a.push(":"));var o=W(e,t);if(void 0!==o&&("suffix"!==t.reference&&a.push("//"),a.push(o),e.path&&"/"!==e.path.charAt(0)&&a.push("/")),void 0!==e.path){var n=e.path;t.absolutePath||s&&s.absolutePath||(n=te(n)),void 0===o&&(n=n.replace(/^\/\//,"/%2F")),a.push(n)}return void 0!==e.query&&(a.push("?"),a.push(e.query)),void 0!==e.fragment&&(a.push("#"),a.push(e.fragment)),a.join("")}function ae(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},a={};return arguments[3]||(e=J(re(e,r),r),t=J(re(t,r),r)),!(r=r||{}).tolerant&&t.scheme?(a.scheme=t.scheme,a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=te(t.path||""),a.query=t.query):(void 0!==t.userinfo||void 0!==t.host||void 0!==t.port?(a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=te(t.path||""),a.query=t.query):(t.path?("/"===t.path.charAt(0)?a.path=te(t.path):(void 0===e.userinfo&&void 0===e.host&&void 0===e.port||e.path?e.path?a.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:a.path=t.path:a.path="/"+t.path,a.path=te(a.path)),a.query=t.query):(a.path=e.path,void 0!==t.query?a.query=t.query:a.query=e.query),a.userinfo=e.userinfo,a.host=e.host,a.port=e.port),a.scheme=e.scheme),a.fragment=t.fragment,a}function se(e,t,r){var a=n({scheme:"null"},r);return re(ae(J(e,a),J(t,a),a,!0),a)}function oe(e,t){return"string"==typeof e?e=re(J(e,t),t):"object"===a(e)&&(e=J(re(e,t),t)),e}function ne(e,t,r){return"string"==typeof e?e=re(J(e,r),r):"object"===a(e)&&(e=re(e,r)),"string"==typeof t?t=re(J(t,r),r):"object"===a(t)&&(t=re(t,r)),e===t}function ie(e,t){return e&&e.toString().replace(t&&t.iri?l.ESCAPE:c.ESCAPE,z)}function ce(e,t){return e&&e.toString().replace(t&&t.iri?l.PCT_ENCODED:c.PCT_ENCODED,V)}var le={scheme:"http",domainHost:!0,parse:function(e,t){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e},serialize:function(e,t){var r="https"===String(e.scheme).toLowerCase();return e.port!==(r?443:80)&&""!==e.port||(e.port=void 0),e.path||(e.path="/"),e}},de={scheme:"https",domainHost:le.domainHost,parse:le.parse,serialize:le.serialize};function ue(e){return"boolean"==typeof e.secure?e.secure:"wss"===String(e.scheme).toLowerCase()}var he={scheme:"ws",domainHost:!0,parse:function(e,t){var r=e;return r.secure=ue(r),r.resourceName=(r.path||"/")+(r.query?"?"+r.query:""),r.path=void 0,r.query=void 0,r},serialize:function(e,t){if(e.port!==(ue(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){var r=e.resourceName.split("?"),a=d(r,2),s=a[0],o=a[1];e.path=s&&"/"!==s?s:void 0,e.query=o,e.resourceName=void 0}return e.fragment=void 0,e}},pe={scheme:"wss",domainHost:he.domainHost,parse:he.parse,serialize:he.serialize},fe={},me="[A-Za-z0-9\\-\\.\\_\\~\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]",ve="[0-9A-Fa-f]",ge=r(r("%[EFef]"+ve+"%"+ve+ve+"%"+ve+ve)+"|"+r("%[89A-Fa-f]"+ve+"%"+ve+ve)+"|"+r("%"+ve+ve)),ye="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",_e=t("[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",'[\\"\\\\]'),we="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",be=new RegExp(me,"g"),Pe=new RegExp(ge,"g"),Ee=new RegExp(t("[^]",ye,"[\\.]",'[\\"]',_e),"g"),ke=new RegExp(t("[^]",me,we),"g"),xe=ke;function Se(e){var t=V(e);return t.match(be)?t:e}var Te={scheme:"mailto",parse:function(e,t){var r=e,a=r.to=r.path?r.path.split(","):[];if(r.path=void 0,r.query){for(var s=!1,o={},n=r.query.split("&"),i=0,c=n.length;i<c;++i){var l=n[i].split("=");switch(l[0]){case"to":for(var d=l[1].split(","),u=0,h=d.length;u<h;++u)a.push(d[u]);break;case"subject":r.subject=ce(l[1],t);break;case"body":r.body=ce(l[1],t);break;default:s=!0,o[ce(l[0],t)]=ce(l[1],t)}}s&&(r.headers=o)}r.query=void 0;for(var p=0,f=a.length;p<f;++p){var m=a[p].split("@");if(m[0]=ce(m[0]),t.unicodeSupport)m[1]=ce(m[1],t).toLowerCase();else try{m[1]=L.toASCII(ce(m[1],t).toLowerCase())}catch(e){r.error=r.error||"Email address's domain name can not be converted to ASCII via punycode: "+e}a[p]=m.join("@")}return r},serialize:function(e,t){var r=e,a=o(e.to);if(a){for(var n=0,i=a.length;n<i;++n){var c=String(a[n]),l=c.lastIndexOf("@"),d=c.slice(0,l).replace(Pe,Se).replace(Pe,s).replace(Ee,z),u=c.slice(l+1);try{u=t.iri?L.toUnicode(u):L.toASCII(ce(u,t).toLowerCase())}catch(e){r.error=r.error||"Email address's domain name can not be converted to "+(t.iri?"Unicode":"ASCII")+" via punycode: "+e}a[n]=d+"@"+u}r.path=a.join(",")}var h=e.headers=e.headers||{};e.subject&&(h.subject=e.subject),e.body&&(h.body=e.body);var p=[];for(var f in h)h[f]!==fe[f]&&p.push(f.replace(Pe,Se).replace(Pe,s).replace(ke,z)+"="+h[f].replace(Pe,Se).replace(Pe,s).replace(xe,z));return p.length&&(r.query=p.join("&")),r}},Re=/^([^\:]+)\:(.*)/,$e={scheme:"urn",parse:function(e,t){var r=e.path&&e.path.match(Re),a=e;if(r){var s=t.scheme||a.scheme||"urn",o=r[1].toLowerCase(),n=r[2],i=s+":"+(t.nid||o),c=q[i];a.nid=o,a.nss=n,a.path=void 0,c&&(a=c.parse(a,t))}else a.error=a.error||"URN can not be parsed.";return a},serialize:function(e,t){var r=t.scheme||e.scheme||"urn",a=e.nid,s=r+":"+(t.nid||a),o=q[s];o&&(e=o.serialize(e,t));var n=e,i=e.nss;return n.path=(a||t.nid)+":"+i,n}},Ce=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,Oe={scheme:"urn:uuid",parse:function(e,t){var r=e;return r.uuid=r.nss,r.nss=void 0,t.tolerant||r.uuid&&r.uuid.match(Ce)||(r.error=r.error||"UUID is not valid."),r},serialize:function(e,t){var r=e;return r.nss=(e.uuid||"").toLowerCase(),r}};q[le.scheme]=le,q[de.scheme]=de,q[he.scheme]=he,q[pe.scheme]=pe,q[Te.scheme]=Te,q[$e.scheme]=$e,q[Oe.scheme]=Oe,e.SCHEMES=q,e.pctEncChar=z,e.pctDecChars=V,e.parse=J,e.removeDotSegments=te,e.serialize=re,e.resolveComponents=ae,e.resolve=se,e.normalize=oe,e.equal=ne,e.escapeComponent=ie,e.unescapeComponent=ce,Object.defineProperty(e,"__esModule",{value:!0})}(Oa.exports);var Ia=Oa.exports,Aa=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 a,s,o;if(Array.isArray(t)){if((a=t.length)!=r.length)return!1;for(s=a;0!==s--;)if(!e(t[s],r[s]))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((a=(o=Object.keys(t)).length)!==Object.keys(r).length)return!1;for(s=a;0!==s--;)if(!Object.prototype.hasOwnProperty.call(r,o[s]))return!1;for(s=a;0!==s--;){var n=o[s];if(!e(t[n],r[n]))return!1}return!0}return t!=t&&r!=r},ja={copy:function(e,t){for(var r in t=t||{},e)t[r]=e[r];return t},checkDataType:Fa,checkDataTypes:function(e,t,r){if(1===e.length)return Fa(e[0],t,r,!0);var a="",s=Na(e);for(var o in s.array&&s.object&&(a=s.null?"(":"(!"+t+" || ",a+="typeof "+t+' !== "object")',delete s.null,delete s.array,delete s.object),s.number&&delete s.integer,s)a+=(a?" && ":"")+Fa(o,t,r,!0);return a},coerceToTypes:function(e,t){if(Array.isArray(t)){for(var r=[],a=0;a<t.length;a++){var s=t[a];(Da[s]||"array"===e&&"array"===s)&&(r[r.length]=s)}if(r.length)return r}else{if(Da[t])return[t];if("array"===e&&"array"===t)return["array"]}},toHash:Na,getProperty:qa,escapeQuotes:za,equal:Aa,ucs2length:function(e){for(var t,r=0,a=e.length,s=0;s<a;)r++,(t=e.charCodeAt(s++))>=55296&&t<=56319&&s<a&&56320==(64512&(t=e.charCodeAt(s)))&&s++;return r},varOccurences:function(e,t){t+="[^0-9]";var r=e.match(new RegExp(t,"g"));return r?r.length:0},varReplace:function(e,t,r){return t+="([^0-9])",r=r.replace(/\$/g,"$$$$"),e.replace(new RegExp(t,"g"),r+"$1")},schemaHasRules:function(e,t){if("boolean"==typeof e)return!e;for(var r in e)if(t[r])return!0},schemaHasRulesExcept:function(e,t,r){if("boolean"==typeof e)return!e&&"not"!=r;for(var a in e)if(a!=r&&t[a])return!0},schemaUnknownRules:function(e,t){if("boolean"==typeof e)return;for(var r in e)if(!t[r])return r},toQuotedString:Va,getPathExpr:function(e,t,r,a){var s=r?"'/' + "+t+(a?"":".replace(/~/g, '~0').replace(/\\//g, '~1')"):a?"'[' + "+t+" + ']'":"'[\\'' + "+t+" + '\\']'";return Ha(e,s)},getPath:function(e,t,r){var a=Va(r?"/"+Ba(t):qa(t));return Ha(e,a)},getData:function(e,t,r){var a,s,o,n;if(""===e)return"rootData";if("/"==e[0]){if(!Ma.test(e))throw new Error("Invalid JSON-pointer: "+e);s=e,o="rootData"}else{if(!(n=e.match(Za)))throw new Error("Invalid JSON-pointer: "+e);if(a=+n[1],"#"==(s=n[2])){if(a>=t)throw new Error("Cannot access property/index "+a+" levels up, current level is "+t);return r[t-a]}if(a>t)throw new Error("Cannot access data "+a+" levels up, current level is "+t);if(o="data"+(t-a||""),!s)return o}for(var i=o,c=s.split("/"),l=0;l<c.length;l++){var d=c[l];d&&(i+=" && "+(o+=qa(Qa(d))))}return i},unescapeFragment:function(e){return Qa(decodeURIComponent(e))},unescapeJsonPointer:Qa,escapeFragment:function(e){return encodeURIComponent(Ba(e))},escapeJsonPointer:Ba};function Fa(e,t,r,a){var s=a?" !== ":" === ",o=a?" || ":" && ",n=a?"!":"",i=a?"":"!";switch(e){case"null":return t+s+"null";case"array":return n+"Array.isArray("+t+")";case"object":return"("+n+t+o+"typeof "+t+s+'"object"'+o+i+"Array.isArray("+t+"))";case"integer":return"(typeof "+t+s+'"number"'+o+i+"("+t+" % 1)"+o+t+s+t+(r?o+n+"isFinite("+t+")":"")+")";case"number":return"(typeof "+t+s+'"'+e+'"'+(r?o+n+"isFinite("+t+")":"")+")";default:return"typeof "+t+s+'"'+e+'"'}}var Da=Na(["string","number","integer","boolean","null"]);function Na(e){for(var t={},r=0;r<e.length;r++)t[e[r]]=!0;return t}var Ua=/^[a-z$_][a-z$_0-9]*$/i,La=/'|\\/g;function qa(e){return"number"==typeof e?"["+e+"]":Ua.test(e)?"."+e:"['"+za(e)+"']"}function za(e){return e.replace(La,"\\$&").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\f/g,"\\f").replace(/\t/g,"\\t")}function Va(e){return"'"+za(e)+"'"}var Ma=/^\/(?:[^~]|~0|~1)*$/,Za=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Ha(e,t){return'""'==e?t:(e+" + "+t).replace(/([^\\])' \+ '/g,"$1")}function Ba(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function Qa(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}var Ka=ja,Ja=function(e){Ka.copy(e,this)};var Wa={exports:{}},Ga=Wa.exports=function(e,t,r){"function"==typeof t&&(r=t,t={}),Ya(t,"function"==typeof(r=t.cb||r)?r:r.pre||function(){},r.post||function(){},e,"",e)};function Ya(e,t,r,a,s,o,n,i,c,l){if(a&&"object"==typeof a&&!Array.isArray(a)){for(var d in t(a,s,o,n,i,c,l),a){var u=a[d];if(Array.isArray(u)){if(d in Ga.arrayKeywords)for(var h=0;h<u.length;h++)Ya(e,t,r,u[h],s+"/"+d+"/"+h,o,s,d,a,h)}else if(d in Ga.propsKeywords){if(u&&"object"==typeof u)for(var p in u)Ya(e,t,r,u[p],s+"/"+d+"/"+Xa(p),o,s,d,a,p)}else(d in Ga.keywords||e.allKeys&&!(d in Ga.skipKeywords))&&Ya(e,t,r,u,s+"/"+d,o,s,d,a)}r(a,s,o,n,i,c,l)}}function Xa(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}Ga.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0},Ga.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},Ga.propsKeywords={definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},Ga.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 es=Wa.exports,ts=Ia,rs=Aa,as=ja,ss=Ja,os=es,ns=is;function is(e,t,r){var a=this._refs[r];if("string"==typeof a){if(!this._refs[a])return is.call(this,e,t,a);a=this._refs[a]}if((a=a||this._schemas[r])instanceof ss)return ps(a.schema,this._opts.inlineRefs)?a.schema:a.validate||this._compile(a);var s,o,n,i=cs.call(this,t,r);return i&&(s=i.schema,t=i.root,n=i.baseId),s instanceof ss?o=s.validate||e.call(this,s.schema,t,void 0,n):void 0!==s&&(o=ps(s,this._opts.inlineRefs)?s:e.call(this,s,t,void 0,n)),o}function cs(e,t){var r=ts.parse(t),a=gs(r),s=vs(this._getId(e.schema));if(0===Object.keys(e.schema).length||a!==s){var o=_s(a),n=this._refs[o];if("string"==typeof n)return ls.call(this,e,n,r);if(n instanceof ss)n.validate||this._compile(n),e=n;else{if(!((n=this._schemas[o])instanceof ss))return;if(n.validate||this._compile(n),o==_s(t))return{schema:n,root:e,baseId:s};e=n}if(!e.schema)return;s=vs(this._getId(e.schema))}return us.call(this,r,s,e.schema,e)}function ls(e,t,r){var a=cs.call(this,e,t);if(a){var s=a.schema,o=a.baseId;e=a.root;var n=this._getId(s);return n&&(o=ws(o,n)),us.call(this,r,o,s,e)}}is.normalizeId=_s,is.fullPath=vs,is.url=ws,is.ids=function(e){var t=_s(this._getId(e)),r={"":t},a={"":vs(t,!1)},s={},o=this;return os(e,{allKeys:!0},function(e,t,n,i,c,l,d){if(""!==t){var u=o._getId(e),h=r[i],p=a[i]+"/"+c;if(void 0!==d&&(p+="/"+("number"==typeof d?d:as.escapeFragment(d))),"string"==typeof u){u=h=_s(h?ts.resolve(h,u):u);var f=o._refs[u];if("string"==typeof f&&(f=o._refs[f]),f&&f.schema){if(!rs(e,f.schema))throw new Error('id "'+u+'" resolves to more than one schema')}else if(u!=_s(p))if("#"==u[0]){if(s[u]&&!rs(e,s[u]))throw new Error('id "'+u+'" resolves to more than one schema');s[u]=e}else o._refs[u]=p}r[t]=h,a[t]=p}}),s},is.inlineRef=ps,is.schema=cs;var ds=as.toHash(["properties","patternProperties","enum","dependencies","definitions"]);function us(e,t,r,a){if(e.fragment=e.fragment||"","/"==e.fragment.slice(0,1)){for(var s=e.fragment.split("/"),o=1;o<s.length;o++){var n=s[o];if(n){if(void 0===(r=r[n=as.unescapeFragment(n)]))break;var i;if(!ds[n]&&((i=this._getId(r))&&(t=ws(t,i)),r.$ref)){var c=ws(t,r.$ref),l=cs.call(this,a,c);l&&(r=l.schema,a=l.root,t=l.baseId)}}}return void 0!==r&&r!==a.schema?{schema:r,root:a,baseId:t}:void 0}}var hs=as.toHash(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum"]);function ps(e,t){return!1!==t&&(void 0===t||!0===t?fs(e):t?ms(e)<=t:void 0)}function fs(e){var t;if(Array.isArray(e)){for(var r=0;r<e.length;r++)if("object"==typeof(t=e[r])&&!fs(t))return!1}else for(var a in e){if("$ref"==a)return!1;if("object"==typeof(t=e[a])&&!fs(t))return!1}return!0}function ms(e){var t,r=0;if(Array.isArray(e)){for(var a=0;a<e.length;a++)if("object"==typeof(t=e[a])&&(r+=ms(t)),r==1/0)return 1/0}else for(var s in e){if("$ref"==s)return 1/0;if(hs[s])r++;else if("object"==typeof(t=e[s])&&(r+=ms(t)+1),r==1/0)return 1/0}return r}function vs(e,t){return!1!==t&&(e=_s(e)),gs(ts.parse(e))}function gs(e){return ts.serialize(e).split("#")[0]+"#"}var ys=/#\/?$/;function _s(e){return e?e.replace(ys,""):""}function ws(e,t){return t=_s(t),ts.resolve(e,t)}var bs=ns,Ps={Validation:ks(function(e){this.message="validation failed",this.errors=e,this.ajv=this.validation=!0}),MissingRef:ks(Es)};function Es(e,t,r){this.message=r||Es.message(e,t),this.missingRef=bs.url(e,t),this.missingSchema=bs.normalizeId(bs.fullPath(this.missingRef))}function ks(e){return e.prototype=Object.create(Error.prototype),e.prototype.constructor=e,e}Es.message=function(e,t){return"can't resolve reference "+t+" from id "+e};var xs=function(e,t){t||(t={}),"function"==typeof t&&(t={cmp:t});var r,a="boolean"==typeof t.cycles&&t.cycles,s=t.cmp&&(r=t.cmp,function(e){return function(t,a){var s={key:t,value:e[t]},o={key:a,value:e[a]};return r(s,o)}}),o=[];return function e(t){if(t&&t.toJSON&&"function"==typeof t.toJSON&&(t=t.toJSON()),void 0!==t){if("number"==typeof t)return isFinite(t)?""+t:"null";if("object"!=typeof t)return JSON.stringify(t);var r,n;if(Array.isArray(t)){for(n="[",r=0;r<t.length;r++)r&&(n+=","),n+=e(t[r])||"null";return n+"]"}if(null===t)return"null";if(-1!==o.indexOf(t)){if(a)return JSON.stringify("__cycle__");throw new TypeError("Converting circular structure to JSON")}var i=o.push(t)-1,c=Object.keys(t).sort(s&&s(t));for(n="",r=0;r<c.length;r++){var l=c[r],d=e(t[l]);d&&(n&&(n+=","),n+=JSON.stringify(l)+":"+d)}return o.splice(i,1),"{"+n+"}"}}(e)},Ss=function(e,t,r){var a="",s=!0===e.schema.$async,o=e.util.schemaHasRulesExcept(e.schema,e.RULES.all,"$ref"),n=e.self._getId(e.schema);if(e.opts.strictKeywords){var i=e.util.schemaUnknownRules(e.schema,e.RULES.keywords);if(i){var c="unknown keyword: "+i;if("log"!==e.opts.strictKeywords)throw new Error(c);e.logger.warn(c)}}if(e.isTop&&(a+=" var validate = ",s&&(e.async=!0,a+="async "),a+="function(data, dataPath, parentData, parentDataProperty, rootData) { 'use strict'; ",n&&(e.opts.sourceCode||e.opts.processCode)&&(a+=" /*# sourceURL="+n+" */ ")),"boolean"==typeof e.schema||!o&&!e.schema.$ref){t="false schema";var l=e.level,d=e.dataLevel,u=e.schema[t],h=e.schemaPath+e.util.getProperty(t),p=e.errSchemaPath+"/"+t,f=!e.opts.allErrors,m="data"+(d||""),v="valid"+l;if(!1===e.schema){e.isTop?f=!0:a+=" var "+v+" = false; ",(W=W||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'false schema' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(p)+" , params: {} ",!1!==e.opts.messages&&(a+=" , message: 'boolean schema is false' "),e.opts.verbose&&(a+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),a+=" } "):a+=" {} ";var g=a;a=W.pop(),!e.compositeRule&&f?e.async?a+=" throw new ValidationError(["+g+"]); ":a+=" validate.errors = ["+g+"]; return false; ":a+=" var err = "+g+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else e.isTop?a+=s?" return data; ":" validate.errors = null; return true; ":a+=" var "+v+" = true; ";return e.isTop&&(a+=" }; return validate; "),a}if(e.isTop){var y=e.isTop;l=e.level=0,d=e.dataLevel=0,m="data";if(e.rootId=e.resolve.fullPath(e.self._getId(e.root.schema)),e.baseId=e.baseId||e.rootId,delete e.isTop,e.dataPathArr=[""],void 0!==e.schema.default&&e.opts.useDefaults&&e.opts.strictDefaults){var _="default is ignored in the schema root";if("log"!==e.opts.strictDefaults)throw new Error(_);e.logger.warn(_)}a+=" var vErrors = null; ",a+=" var errors = 0; ",a+=" if (rootData === undefined) rootData = data; "}else{l=e.level,m="data"+((d=e.dataLevel)||"");if(n&&(e.baseId=e.resolve.url(e.baseId,n)),s&&!e.async)throw new Error("async schema in sync schema");a+=" var errs_"+l+" = errors;"}v="valid"+l,f=!e.opts.allErrors;var w="",b="",P=e.schema.type,E=Array.isArray(P);if(P&&e.opts.nullable&&!0===e.schema.nullable&&(E?-1==P.indexOf("null")&&(P=P.concat("null")):"null"!=P&&(P=[P,"null"],E=!0)),E&&1==P.length&&(P=P[0],E=!1),e.schema.$ref&&o){if("fail"==e.opts.extendRefs)throw new Error('$ref: validation keywords used in schema at path "'+e.errSchemaPath+'" (see option extendRefs)');!0!==e.opts.extendRefs&&(o=!1,e.logger.warn('$ref: keywords ignored in schema at path "'+e.errSchemaPath+'"'))}if(e.schema.$comment&&e.opts.$comment&&(a+=" "+e.RULES.all.$comment.code(e,"$comment")),P){if(e.opts.coerceTypes)var k=e.util.coerceToTypes(e.opts.coerceTypes,P);var x=e.RULES.types[P];if(k||E||!0===x||x&&!G(x)){h=e.schemaPath+".type",p=e.errSchemaPath+"/type",h=e.schemaPath+".type",p=e.errSchemaPath+"/type";var S=E?"checkDataTypes":"checkDataType";if(a+=" if ("+e.util[S](P,m,e.opts.strictNumbers,!0)+") { ",k){var T="dataType"+l,R="coerced"+l;a+=" var "+T+" = typeof "+m+"; var "+R+" = undefined; ","array"==e.opts.coerceTypes&&(a+=" if ("+T+" == 'object' && Array.isArray("+m+") && "+m+".length == 1) { "+m+" = "+m+"[0]; "+T+" = typeof "+m+"; if ("+e.util.checkDataType(e.schema.type,m,e.opts.strictNumbers)+") "+R+" = "+m+"; } "),a+=" if ("+R+" !== undefined) ; ";var $=k;if($)for(var C,O=-1,I=$.length-1;O<I;)"string"==(C=$[O+=1])?a+=" else if ("+T+" == 'number' || "+T+" == 'boolean') "+R+" = '' + "+m+"; else if ("+m+" === null) "+R+" = ''; ":"number"==C||"integer"==C?(a+=" else if ("+T+" == 'boolean' || "+m+" === null || ("+T+" == 'string' && "+m+" && "+m+" == +"+m+" ","integer"==C&&(a+=" && !("+m+" % 1)"),a+=")) "+R+" = +"+m+"; "):"boolean"==C?a+=" else if ("+m+" === 'false' || "+m+" === 0 || "+m+" === null) "+R+" = false; else if ("+m+" === 'true' || "+m+" === 1) "+R+" = true; ":"null"==C?a+=" else if ("+m+" === '' || "+m+" === 0 || "+m+" === false) "+R+" = null; ":"array"==e.opts.coerceTypes&&"array"==C&&(a+=" else if ("+T+" == 'string' || "+T+" == 'number' || "+T+" == 'boolean' || "+m+" == null) "+R+" = ["+m+"]; ");a+=" else { ",(W=W||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'type' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(p)+" , params: { type: '",a+=E?""+P.join(","):""+P,a+="' } ",!1!==e.opts.messages&&(a+=" , message: 'should be ",a+=E?""+P.join(","):""+P,a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+h+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),a+=" } "):a+=" {} ";g=a;a=W.pop(),!e.compositeRule&&f?e.async?a+=" throw new ValidationError(["+g+"]); ":a+=" validate.errors = ["+g+"]; return false; ":a+=" var err = "+g+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } if ("+R+" !== undefined) { ";var A=d?"data"+(d-1||""):"parentData";a+=" "+m+" = "+R+"; ",d||(a+="if ("+A+" !== undefined)"),a+=" "+A+"["+(d?e.dataPathArr[d]:"parentDataProperty")+"] = "+R+"; } "}else{(W=W||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'type' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(p)+" , params: { type: '",a+=E?""+P.join(","):""+P,a+="' } ",!1!==e.opts.messages&&(a+=" , message: 'should be ",a+=E?""+P.join(","):""+P,a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+h+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),a+=" } "):a+=" {} ";g=a;a=W.pop(),!e.compositeRule&&f?e.async?a+=" throw new ValidationError(["+g+"]); ":a+=" validate.errors = ["+g+"]; return false; ":a+=" var err = "+g+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}a+=" } "}}if(e.schema.$ref&&!o)a+=" "+e.RULES.all.$ref.code(e,"$ref")+" ",f&&(a+=" } if (errors === ",a+=y?"0":"errs_"+l,a+=") { ",b+="}");else{var j=e.RULES;if(j)for(var F=-1,D=j.length-1;F<D;)if(G(x=j[F+=1])){if(x.type&&(a+=" if ("+e.util.checkDataType(x.type,m,e.opts.strictNumbers)+") { "),e.opts.useDefaults)if("object"==x.type&&e.schema.properties){u=e.schema.properties;var N=Object.keys(u);if(N)for(var U,L=-1,q=N.length-1;L<q;){if(void 0!==(M=u[U=N[L+=1]]).default){var z=m+e.util.getProperty(U);if(e.compositeRule){if(e.opts.strictDefaults){_="default is ignored for: "+z;if("log"!==e.opts.strictDefaults)throw new Error(_);e.logger.warn(_)}}else a+=" if ("+z+" === undefined ","empty"==e.opts.useDefaults&&(a+=" || "+z+" === null || "+z+" === '' "),a+=" ) "+z+" = ","shared"==e.opts.useDefaults?a+=" "+e.useDefault(M.default)+" ":a+=" "+JSON.stringify(M.default)+" ",a+="; "}}}else if("array"==x.type&&Array.isArray(e.schema.items)){var V=e.schema.items;if(V){O=-1;for(var M,Z=V.length-1;O<Z;)if(void 0!==(M=V[O+=1]).default){z=m+"["+O+"]";if(e.compositeRule){if(e.opts.strictDefaults){_="default is ignored for: "+z;if("log"!==e.opts.strictDefaults)throw new Error(_);e.logger.warn(_)}}else a+=" if ("+z+" === undefined ","empty"==e.opts.useDefaults&&(a+=" || "+z+" === null || "+z+" === '' "),a+=" ) "+z+" = ","shared"==e.opts.useDefaults?a+=" "+e.useDefault(M.default)+" ":a+=" "+JSON.stringify(M.default)+" ",a+="; "}}}var H=x.rules;if(H)for(var B,Q=-1,K=H.length-1;Q<K;)if(Y(B=H[Q+=1])){var J=B.code(e,B.keyword,x.type);J&&(a+=" "+J+" ",f&&(w+="}"))}if(f&&(a+=" "+w+" ",w=""),x.type&&(a+=" } ",P&&P===x.type&&!k)){a+=" else { ";var W;h=e.schemaPath+".type",p=e.errSchemaPath+"/type";(W=W||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'type' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(p)+" , params: { type: '",a+=E?""+P.join(","):""+P,a+="' } ",!1!==e.opts.messages&&(a+=" , message: 'should be ",a+=E?""+P.join(","):""+P,a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+h+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),a+=" } "):a+=" {} ";g=a;a=W.pop(),!e.compositeRule&&f?e.async?a+=" throw new ValidationError(["+g+"]); ":a+=" validate.errors = ["+g+"]; return false; ":a+=" var err = "+g+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } "}f&&(a+=" if (errors === ",a+=y?"0":"errs_"+l,a+=") { ",b+="}")}}function G(e){for(var t=e.rules,r=0;r<t.length;r++)if(Y(t[r]))return!0}function Y(t){return void 0!==e.schema[t.keyword]||t.implements&&function(t){for(var r=t.implements,a=0;a<r.length;a++)if(void 0!==e.schema[r[a]])return!0}(t)}return f&&(a+=" "+b+" "),y?(s?(a+=" if (errors === 0) return data; ",a+=" else throw new ValidationError(vErrors); "):(a+=" validate.errors = vErrors; ",a+=" return errors === 0; "),a+=" }; return validate;"):a+=" var "+v+" = errors === errs_"+l+";",a},Ts=ns,Rs=ja,$s=Ps,Cs=xs,Os=Ss,Is=Rs.ucs2length,As=Aa,js=$s.Validation,Fs=function e(t,r,a,s){var o=this,n=this._opts,i=[void 0],c={},l=[],d={},u=[],h={},p=[];r=r||{schema:t,refVal:i,refs:c};var f=Ds.call(this,t,r,s),m=this._compilations[f.index];if(f.compiling)return m.callValidate=function e(){var t=m.validate,r=t.apply(this,arguments);return e.errors=t.errors,r};var v=this._formats,g=this.RULES;try{var y=w(t,r,a,s);m.validate=y;var _=m.callValidate;return _&&(_.schema=y.schema,_.errors=null,_.refs=y.refs,_.refVal=y.refVal,_.root=y.root,_.$async=y.$async,n.sourceCode&&(_.source=y.source)),y}finally{Ns.call(this,t,r,s)}function w(t,a,s,d){var h=!a||a&&a.schema==t;if(a.schema!=r.schema)return e.call(o,t,a,s,d);var f,m=!0===t.$async,y=Os({isTop:!0,schema:t,isRoot:h,baseId:d,root:a,schemaPath:"",errSchemaPath:"#",errorPath:'""',MissingRefError:$s.MissingRef,RULES:g,validate:Os,util:Rs,resolve:Ts,resolveRef:b,usePattern:k,useDefault:x,useCustomRule:S,opts:n,formats:v,logger:o.logger,self:o});y=Ms(i,zs)+Ms(l,Ls)+Ms(u,qs)+Ms(p,Vs)+y,n.processCode&&(y=n.processCode(y,t));try{f=new Function("self","RULES","formats","root","refVal","defaults","customRules","equal","ucs2length","ValidationError",y)(o,g,v,r,i,u,p,As,Is,js),i[0]=f}catch(e){throw o.logger.error("Error compiling schema, function code:",y),e}return f.schema=t,f.errors=null,f.refs=c,f.refVal=i,f.root=h?f:a,m&&(f.$async=!0),!0===n.sourceCode&&(f.source={code:y,patterns:l,defaults:u}),f}function b(t,s,l){s=Ts.url(t,s);var d,u,h=c[s];if(void 0!==h)return E(d=i[h],u="refVal["+h+"]");if(!l&&r.refs){var p=r.refs[s];if(void 0!==p)return E(d=r.refVal[p],u=P(s,d))}u=P(s);var f=Ts.call(o,w,r,s);if(void 0===f){var m=a&&a[s];m&&(f=Ts.inlineRef(m,n.inlineRefs)?m:e.call(o,m,r,a,t))}if(void 0!==f)return function(e,t){var r=c[e];i[r]=t}(s,f),E(f,u);!function(e){delete c[e]}(s)}function P(e,t){var r=i.length;return i[r]=t,c[e]=r,"refVal"+r}function E(e,t){return"object"==typeof e||"boolean"==typeof e?{code:t,schema:e,inline:!0}:{code:t,$async:e&&!!e.$async}}function k(e){var t=d[e];return void 0===t&&(t=d[e]=l.length,l[t]=e),"pattern"+t}function x(e){switch(typeof e){case"boolean":case"number":return""+e;case"string":return Rs.toQuotedString(e);case"object":if(null===e)return"null";var t=Cs(e),r=h[t];return void 0===r&&(r=h[t]=u.length,u[r]=e),"default"+r}}function S(e,t,r,a){if(!1!==o._opts.validateSchema){var s=e.definition.dependencies;if(s&&!s.every(function(e){return Object.prototype.hasOwnProperty.call(r,e)}))throw new Error("parent schema must have all required keywords: "+s.join(","));var i=e.definition.validateSchema;if(i)if(!i(t)){var c="keyword schema is invalid: "+o.errorsText(i.errors);if("log"!=o._opts.validateSchema)throw new Error(c);o.logger.error(c)}}var l,d=e.definition.compile,u=e.definition.inline,h=e.definition.macro;if(d)l=d.call(o,t,r,a);else if(h)l=h.call(o,t,r,a),!1!==n.validateSchema&&o.validateSchema(l,!0);else if(u)l=u.call(o,a,e.keyword,t,r);else if(!(l=e.definition.validate))return;if(void 0===l)throw new Error('custom keyword "'+e.keyword+'"failed to compile');var f=p.length;return p[f]=l,{code:"customRule"+f,validate:l}}};function Ds(e,t,r){var a=Us.call(this,e,t,r);return a>=0?{index:a,compiling:!0}:(a=this._compilations.length,this._compilations[a]={schema:e,root:t,baseId:r},{index:a,compiling:!1})}function Ns(e,t,r){var a=Us.call(this,e,t,r);a>=0&&this._compilations.splice(a,1)}function Us(e,t,r){for(var a=0;a<this._compilations.length;a++){var s=this._compilations[a];if(s.schema==e&&s.root==t&&s.baseId==r)return a}return-1}function Ls(e,t){return"var pattern"+e+" = new RegExp("+Rs.toQuotedString(t[e])+");"}function qs(e){return"var default"+e+" = defaults["+e+"];"}function zs(e,t){return void 0===t[e]?"":"var refVal"+e+" = refVal["+e+"];"}function Vs(e){return"var customRule"+e+" = customRules["+e+"];"}function Ms(e,t){if(!e.length)return"";for(var r="",a=0;a<e.length;a++)r+=t(a,e);return r}var Zs={exports:{}},Hs=Zs.exports=function(){this._cache={}};Hs.prototype.put=function(e,t){this._cache[e]=t},Hs.prototype.get=function(e){return this._cache[e]},Hs.prototype.del=function(e){delete this._cache[e]},Hs.prototype.clear=function(){this._cache={}};var Bs=Zs.exports,Qs=ja,Ks=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Js=[0,31,28,31,30,31,30,31,31,30,31,30,31],Ws=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,Gs=/^(?=.{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,Ys=/^(?:[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,Xs=/^(?:(?:[^\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,eo=/^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i,to=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,ro=/^(?:\/(?:[^~/]|~0|~1)*)*$/,ao=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,so=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,oo=no;function no(e){return e="full"==e?"full":"fast",Qs.copy(no[e])}function io(e){var t=e.match(Ks);if(!t)return!1;var r=+t[1],a=+t[2],s=+t[3];return a>=1&&a<=12&&s>=1&&s<=(2==a&&function(e){return e%4==0&&(e%100!=0||e%400==0)}(r)?29:Js[a])}function co(e,t){var r=e.match(Ws);if(!r)return!1;var a=r[1],s=r[2],o=r[3],n=r[5];return(a<=23&&s<=59&&o<=59||23==a&&59==s&&60==o)&&(!t||n)}no.fast={date:/^\d\d\d\d-[0-1]\d-[0-3]\d$/,time:/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,"date-time":/^\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,uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,"uri-template":Xs,url:eo,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,hostname:Gs,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[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}))|:)))(?:%.+)?\s*$/i,regex:po,uuid:to,"json-pointer":ro,"json-pointer-uri-fragment":ao,"relative-json-pointer":so},no.full={date:io,time:co,"date-time":function(e){var t=e.split(lo);return 2==t.length&&io(t[0])&&co(t[1],!0)},uri:function(e){return uo.test(e)&&Ys.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":Xs,url:eo,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:Gs,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[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}))|:)))(?:%.+)?\s*$/i,regex:po,uuid:to,"json-pointer":ro,"json-pointer-uri-fragment":ao,"relative-json-pointer":so};var lo=/t|\s/i;var uo=/\/|:/;var ho=/[^\\]\\Z/;function po(e){if(ho.test(e))return!1;try{return new RegExp(e),!0}catch(e){return!1}}var fo=function(e,t,r){var a,s=" ",o=e.level,n=e.dataLevel,i=e.schema[t],c=e.schemaPath+e.util.getProperty(t),l=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,u="data"+(n||""),h=e.opts.$data&&i&&i.$data;h?(s+=" var schema"+o+" = "+e.util.getData(i.$data,n,e.dataPathArr)+"; ",a="schema"+o):a=i;var p="maximum"==t,f=p?"exclusiveMaximum":"exclusiveMinimum",m=e.schema[f],v=e.opts.$data&&m&&m.$data,g=p?"<":">",y=p?">":"<",_=void 0;if(!h&&"number"!=typeof i&&void 0!==i)throw new Error(t+" must be number");if(!v&&void 0!==m&&"number"!=typeof m&&"boolean"!=typeof m)throw new Error(f+" must be number or boolean");if(v){var w=e.util.getData(m.$data,n,e.dataPathArr),b="exclusive"+o,P="exclType"+o,E="exclIsNumber"+o,k="' + "+(T="op"+o)+" + '";s+=" var schemaExcl"+o+" = "+w+"; ",s+=" var "+b+"; var "+P+" = typeof "+(w="schemaExcl"+o)+"; if ("+P+" != 'boolean' && "+P+" != 'undefined' && "+P+" != 'number') { ";var x;_=f;(x=x||[]).push(s),s="",!1!==e.createErrors?(s+=" { keyword: '"+(_||"_exclusiveLimit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: {} ",!1!==e.opts.messages&&(s+=" , message: '"+f+" should be boolean' "),e.opts.verbose&&(s+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),s+=" } "):s+=" {} ";var S=s;s=x.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+S+"]); ":s+=" validate.errors = ["+S+"]; return false; ":s+=" var err = "+S+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+=" } else if ( ",h&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=" "+P+" == 'number' ? ( ("+b+" = "+a+" === undefined || "+w+" "+g+"= "+a+") ? "+u+" "+y+"= "+w+" : "+u+" "+y+" "+a+" ) : ( ("+b+" = "+w+" === true) ? "+u+" "+y+"= "+a+" : "+u+" "+y+" "+a+" ) || "+u+" !== "+u+") { var op"+o+" = "+b+" ? '"+g+"' : '"+g+"='; ",void 0===i&&(_=f,l=e.errSchemaPath+"/"+f,a=w,h=v)}else{k=g;if((E="number"==typeof m)&&h){var T="'"+k+"'";s+=" if ( ",h&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=" ( "+a+" === undefined || "+m+" "+g+"= "+a+" ? "+u+" "+y+"= "+m+" : "+u+" "+y+" "+a+" ) || "+u+" !== "+u+") { "}else{E&&void 0===i?(b=!0,_=f,l=e.errSchemaPath+"/"+f,a=m,y+="="):(E&&(a=Math[p?"min":"max"](m,i)),m===(!E||a)?(b=!0,_=f,l=e.errSchemaPath+"/"+f,y+="="):(b=!1,k+="="));T="'"+k+"'";s+=" if ( ",h&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=" "+u+" "+y+" "+a+" || "+u+" !== "+u+") { "}}_=_||t,(x=x||[]).push(s),s="",!1!==e.createErrors?(s+=" { keyword: '"+(_||"_limit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { comparison: "+T+", limit: "+a+", exclusive: "+b+" } ",!1!==e.opts.messages&&(s+=" , message: 'should be "+k+" ",s+=h?"' + "+a:a+"'"),e.opts.verbose&&(s+=" , schema: ",s+=h?"validate.schema"+c:""+i,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),s+=" } "):s+=" {} ";S=s;return s=x.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+S+"]); ":s+=" validate.errors = ["+S+"]; return false; ":s+=" var err = "+S+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+=" } ",d&&(s+=" else { "),s},mo=function(e,t,r){var a,s=" ",o=e.level,n=e.dataLevel,i=e.schema[t],c=e.schemaPath+e.util.getProperty(t),l=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,u="data"+(n||""),h=e.opts.$data&&i&&i.$data;if(h?(s+=" var schema"+o+" = "+e.util.getData(i.$data,n,e.dataPathArr)+"; ",a="schema"+o):a=i,!h&&"number"!=typeof i)throw new Error(t+" must be number");s+="if ( ",h&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=" "+u+".length "+("maxItems"==t?">":"<")+" "+a+") { ";var p=t,f=f||[];f.push(s),s="",!1!==e.createErrors?(s+=" { keyword: '"+(p||"_limitItems")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { limit: "+a+" } ",!1!==e.opts.messages&&(s+=" , message: 'should NOT have ",s+="maxItems"==t?"more":"fewer",s+=" than ",s+=h?"' + "+a+" + '":""+i,s+=" items' "),e.opts.verbose&&(s+=" , schema: ",s+=h?"validate.schema"+c:""+i,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),s+=" } "):s+=" {} ";var m=s;return s=f.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+m+"]); ":s+=" validate.errors = ["+m+"]; return false; ":s+=" var err = "+m+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+="} ",d&&(s+=" else { "),s},vo=function(e,t,r){var a,s=" ",o=e.level,n=e.dataLevel,i=e.schema[t],c=e.schemaPath+e.util.getProperty(t),l=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,u="data"+(n||""),h=e.opts.$data&&i&&i.$data;if(h?(s+=" var schema"+o+" = "+e.util.getData(i.$data,n,e.dataPathArr)+"; ",a="schema"+o):a=i,!h&&"number"!=typeof i)throw new Error(t+" must be number");var p="maxLength"==t?">":"<";s+="if ( ",h&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),!1===e.opts.unicode?s+=" "+u+".length ":s+=" ucs2length("+u+") ",s+=" "+p+" "+a+") { ";var f=t,m=m||[];m.push(s),s="",!1!==e.createErrors?(s+=" { keyword: '"+(f||"_limitLength")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { limit: "+a+" } ",!1!==e.opts.messages&&(s+=" , message: 'should NOT be ",s+="maxLength"==t?"longer":"shorter",s+=" than ",s+=h?"' + "+a+" + '":""+i,s+=" characters' "),e.opts.verbose&&(s+=" , schema: ",s+=h?"validate.schema"+c:""+i,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),s+=" } "):s+=" {} ";var v=s;return s=m.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+v+"]); ":s+=" validate.errors = ["+v+"]; return false; ":s+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+="} ",d&&(s+=" else { "),s},go=function(e,t,r){var a,s=" ",o=e.level,n=e.dataLevel,i=e.schema[t],c=e.schemaPath+e.util.getProperty(t),l=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,u="data"+(n||""),h=e.opts.$data&&i&&i.$data;if(h?(s+=" var schema"+o+" = "+e.util.getData(i.$data,n,e.dataPathArr)+"; ",a="schema"+o):a=i,!h&&"number"!=typeof i)throw new Error(t+" must be number");s+="if ( ",h&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=" Object.keys("+u+").length "+("maxProperties"==t?">":"<")+" "+a+") { ";var p=t,f=f||[];f.push(s),s="",!1!==e.createErrors?(s+=" { keyword: '"+(p||"_limitProperties")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { limit: "+a+" } ",!1!==e.opts.messages&&(s+=" , message: 'should NOT have ",s+="maxProperties"==t?"more":"fewer",s+=" than ",s+=h?"' + "+a+" + '":""+i,s+=" properties' "),e.opts.verbose&&(s+=" , schema: ",s+=h?"validate.schema"+c:""+i,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),s+=" } "):s+=" {} ";var m=s;return s=f.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+m+"]); ":s+=" validate.errors = ["+m+"]; return false; ":s+=" var err = "+m+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+="} ",d&&(s+=" else { "),s},yo={$ref:function(e,t,r){var a,s,o=" ",n=e.level,i=e.dataLevel,c=e.schema[t],l=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,u="data"+(i||""),h="valid"+n;if("#"==c||"#/"==c)e.isRoot?(a=e.async,s="validate"):(a=!0===e.root.schema.$async,s="root.refVal[0]");else{var p=e.resolveRef(e.baseId,c,e.isRoot);if(void 0===p){var f=e.MissingRefError.message(e.baseId,c);if("fail"==e.opts.missingRefs){e.logger.error(f),(y=y||[]).push(o),o="",!1!==e.createErrors?(o+=" { keyword: '$ref' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { ref: '"+e.util.escapeQuotes(c)+"' } ",!1!==e.opts.messages&&(o+=" , message: 'can\\'t resolve reference "+e.util.escapeQuotes(c)+"' "),e.opts.verbose&&(o+=" , schema: "+e.util.toQuotedString(c)+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),o+=" } "):o+=" {} ";var m=o;o=y.pop(),!e.compositeRule&&d?e.async?o+=" throw new ValidationError(["+m+"]); ":o+=" validate.errors = ["+m+"]; return false; ":o+=" var err = "+m+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",d&&(o+=" if (false) { ")}else{if("ignore"!=e.opts.missingRefs)throw new e.MissingRefError(e.baseId,c,f);e.logger.warn(f),d&&(o+=" if (true) { ")}}else if(p.inline){var v=e.util.copy(e);v.level++;var g="valid"+v.level;v.schema=p.schema,v.schemaPath="",v.errSchemaPath=c,o+=" "+e.validate(v).replace(/validate\.schema/g,p.code)+" ",d&&(o+=" if ("+g+") { ")}else a=!0===p.$async||e.async&&!1!==p.$async,s=p.code}if(s){var y;(y=y||[]).push(o),o="",e.opts.passContext?o+=" "+s+".call(this, ":o+=" "+s+"( ",o+=" "+u+", (dataPath || '')",'""'!=e.errorPath&&(o+=" + "+e.errorPath);var _=o+=" , "+(i?"data"+(i-1||""):"parentData")+" , "+(i?e.dataPathArr[i]:"parentDataProperty")+", rootData) ";if(o=y.pop(),a){if(!e.async)throw new Error("async schema referenced by sync schema");d&&(o+=" var "+h+"; "),o+=" try { await "+_+"; ",d&&(o+=" "+h+" = true; "),o+=" } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; ",d&&(o+=" "+h+" = false; "),o+=" } ",d&&(o+=" if ("+h+") { ")}else o+=" if (!"+_+") { if (vErrors === null) vErrors = "+s+".errors; else vErrors = vErrors.concat("+s+".errors); errors = vErrors.length; } ",d&&(o+=" else { ")}return o},allOf:function(e,t,r){var a=" ",s=e.schema[t],o=e.schemaPath+e.util.getProperty(t),n=e.errSchemaPath+"/"+t,i=!e.opts.allErrors,c=e.util.copy(e),l="";c.level++;var d="valid"+c.level,u=c.baseId,h=!0,p=s;if(p)for(var f,m=-1,v=p.length-1;m<v;)f=p[m+=1],(e.opts.strictKeywords?"object"==typeof f&&Object.keys(f).length>0||!1===f:e.util.schemaHasRules(f,e.RULES.all))&&(h=!1,c.schema=f,c.schemaPath=o+"["+m+"]",c.errSchemaPath=n+"/"+m,a+=" "+e.validate(c)+" ",c.baseId=u,i&&(a+=" if ("+d+") { ",l+="}"));return i&&(a+=h?" if (true) { ":" "+l.slice(0,-1)+" "),a},anyOf:function(e,t,r){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[t],i=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(o||""),u="valid"+s,h="errs__"+s,p=e.util.copy(e),f="";p.level++;var m="valid"+p.level,v=n.every(function(t){return e.opts.strictKeywords?"object"==typeof t&&Object.keys(t).length>0||!1===t:e.util.schemaHasRules(t,e.RULES.all)});if(v){var g=p.baseId;a+=" var "+h+" = errors; var "+u+" = false; ";var y=e.compositeRule;e.compositeRule=p.compositeRule=!0;var _=n;if(_)for(var w,b=-1,P=_.length-1;b<P;)w=_[b+=1],p.schema=w,p.schemaPath=i+"["+b+"]",p.errSchemaPath=c+"/"+b,a+=" "+e.validate(p)+" ",p.baseId=g,a+=" "+u+" = "+u+" || "+m+"; if (!"+u+") { ",f+="}";e.compositeRule=p.compositeRule=y,a+=" "+f+" if (!"+u+") { var err = ",!1!==e.createErrors?(a+=" { keyword: 'anyOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",!1!==e.opts.messages&&(a+=" , message: 'should match some schema in anyOf' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&l&&(e.async?a+=" throw new ValidationError(vErrors); ":a+=" validate.errors = vErrors; return false; "),a+=" } else { errors = "+h+"; if (vErrors !== null) { if ("+h+") vErrors.length = "+h+"; else vErrors = null; } ",e.opts.allErrors&&(a+=" } ")}else l&&(a+=" if (true) { ");return a},$comment:function(e,t,r){var a=" ",s=e.schema[t],o=e.errSchemaPath+"/"+t;e.opts.allErrors;var n=e.util.toQuotedString(s);return!0===e.opts.$comment?a+=" console.log("+n+");":"function"==typeof e.opts.$comment&&(a+=" self._opts.$comment("+n+", "+e.util.toQuotedString(o)+", validate.root.schema);"),a},const:function(e,t,r){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[t],i=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(o||""),u="valid"+s,h=e.opts.$data&&n&&n.$data;h&&(a+=" var schema"+s+" = "+e.util.getData(n.$data,o,e.dataPathArr)+"; "),h||(a+=" var schema"+s+" = validate.schema"+i+";"),a+="var "+u+" = equal("+d+", schema"+s+"); if (!"+u+") { ";var p=p||[];p.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'const' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { allowedValue: schema"+s+" } ",!1!==e.opts.messages&&(a+=" , message: 'should be equal to constant' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ";var f=a;return a=p.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+f+"]); ":a+=" validate.errors = ["+f+"]; return false; ":a+=" var err = "+f+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" }",l&&(a+=" else { "),a},contains:function(e,t,r){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[t],i=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(o||""),u="valid"+s,h="errs__"+s,p=e.util.copy(e);p.level++;var f="valid"+p.level,m="i"+s,v=p.dataLevel=e.dataLevel+1,g="data"+v,y=e.baseId,_=e.opts.strictKeywords?"object"==typeof n&&Object.keys(n).length>0||!1===n:e.util.schemaHasRules(n,e.RULES.all);if(a+="var "+h+" = errors;var "+u+";",_){var w=e.compositeRule;e.compositeRule=p.compositeRule=!0,p.schema=n,p.schemaPath=i,p.errSchemaPath=c,a+=" var "+f+" = false; for (var "+m+" = 0; "+m+" < "+d+".length; "+m+"++) { ",p.errorPath=e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers,!0);var b=d+"["+m+"]";p.dataPathArr[v]=m;var P=e.validate(p);p.baseId=y,e.util.varOccurences(P,g)<2?a+=" "+e.util.varReplace(P,g,b)+" ":a+=" var "+g+" = "+b+"; "+P+" ",a+=" if ("+f+") break; } ",e.compositeRule=p.compositeRule=w,a+=" if (!"+f+") {"}else a+=" if ("+d+".length == 0) {";var E=E||[];E.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'contains' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",!1!==e.opts.messages&&(a+=" , message: 'should contain a valid item' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ";var k=a;return a=E.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+k+"]); ":a+=" validate.errors = ["+k+"]; return false; ":a+=" var err = "+k+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } else { ",_&&(a+=" errors = "+h+"; if (vErrors !== null) { if ("+h+") vErrors.length = "+h+"; else vErrors = null; } "),e.opts.allErrors&&(a+=" } "),a},dependencies:function(e,t,r){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[t],i=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(o||""),u="errs__"+s,h=e.util.copy(e),p="";h.level++;var f="valid"+h.level,m={},v={},g=e.opts.ownProperties;for(b in n)if("__proto__"!=b){var y=n[b],_=Array.isArray(y)?v:m;_[b]=y}a+="var "+u+" = errors;";var w=e.errorPath;for(var b in a+="var missing"+s+";",v)if((_=v[b]).length){if(a+=" if ( "+d+e.util.getProperty(b)+" !== undefined ",g&&(a+=" && Object.prototype.hasOwnProperty.call("+d+", '"+e.util.escapeQuotes(b)+"') "),l){a+=" && ( ";var P=_;if(P)for(var E=-1,k=P.length-1;E<k;){C=P[E+=1],E&&(a+=" || "),a+=" ( ( "+(j=d+(A=e.util.getProperty(C)))+" === undefined ",g&&(a+=" || ! Object.prototype.hasOwnProperty.call("+d+", '"+e.util.escapeQuotes(C)+"') "),a+=") && (missing"+s+" = "+e.util.toQuotedString(e.opts.jsonPointers?C:A)+") ) "}a+=")) { ";var x="missing"+s,S="' + "+x+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.opts.jsonPointers?e.util.getPathExpr(w,x,!0):w+" + "+x);var T=T||[];T.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'dependencies' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { property: '"+e.util.escapeQuotes(b)+"', missingProperty: '"+S+"', depsCount: "+_.length+", deps: '"+e.util.escapeQuotes(1==_.length?_[0]:_.join(", "))+"' } ",!1!==e.opts.messages&&(a+=" , message: 'should have ",1==_.length?a+="property "+e.util.escapeQuotes(_[0]):a+="properties "+e.util.escapeQuotes(_.join(", ")),a+=" when property "+e.util.escapeQuotes(b)+" is present' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ";var R=a;a=T.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+R+"]); ":a+=" validate.errors = ["+R+"]; return false; ":a+=" var err = "+R+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else{a+=" ) { ";var $=_;if($)for(var C,O=-1,I=$.length-1;O<I;){C=$[O+=1];var A=e.util.getProperty(C),j=(S=e.util.escapeQuotes(C),d+A);e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(w,C,e.opts.jsonPointers)),a+=" if ( "+j+" === undefined ",g&&(a+=" || ! Object.prototype.hasOwnProperty.call("+d+", '"+e.util.escapeQuotes(C)+"') "),a+=") { var err = ",!1!==e.createErrors?(a+=" { keyword: 'dependencies' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { property: '"+e.util.escapeQuotes(b)+"', missingProperty: '"+S+"', depsCount: "+_.length+", deps: '"+e.util.escapeQuotes(1==_.length?_[0]:_.join(", "))+"' } ",!1!==e.opts.messages&&(a+=" , message: 'should have ",1==_.length?a+="property "+e.util.escapeQuotes(_[0]):a+="properties "+e.util.escapeQuotes(_.join(", ")),a+=" when property "+e.util.escapeQuotes(b)+" is present' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}a+=" } ",l&&(p+="}",a+=" else { ")}e.errorPath=w;var F=h.baseId;for(var b in m){y=m[b];(e.opts.strictKeywords?"object"==typeof y&&Object.keys(y).length>0||!1===y:e.util.schemaHasRules(y,e.RULES.all))&&(a+=" "+f+" = true; if ( "+d+e.util.getProperty(b)+" !== undefined ",g&&(a+=" && Object.prototype.hasOwnProperty.call("+d+", '"+e.util.escapeQuotes(b)+"') "),a+=") { ",h.schema=y,h.schemaPath=i+e.util.getProperty(b),h.errSchemaPath=c+"/"+e.util.escapeFragment(b),a+=" "+e.validate(h)+" ",h.baseId=F,a+=" } ",l&&(a+=" if ("+f+") { ",p+="}"))}return l&&(a+=" "+p+" if ("+u+" == errors) {"),a},enum:function(e,t,r){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[t],i=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(o||""),u="valid"+s,h=e.opts.$data&&n&&n.$data;h&&(a+=" var schema"+s+" = "+e.util.getData(n.$data,o,e.dataPathArr)+"; ");var p="i"+s,f="schema"+s;h||(a+=" var "+f+" = validate.schema"+i+";"),a+="var "+u+";",h&&(a+=" if (schema"+s+" === undefined) "+u+" = true; else if (!Array.isArray(schema"+s+")) "+u+" = false; else {"),a+=u+" = false;for (var "+p+"=0; "+p+"<"+f+".length; "+p+"++) if (equal("+d+", "+f+"["+p+"])) { "+u+" = true; break; }",h&&(a+=" } "),a+=" if (!"+u+") { ";var m=m||[];m.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'enum' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { allowedValues: schema"+s+" } ",!1!==e.opts.messages&&(a+=" , message: 'should be equal to one of the allowed values' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ";var v=a;return a=m.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+v+"]); ":a+=" validate.errors = ["+v+"]; return false; ":a+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" }",l&&(a+=" else { "),a},format:function(e,t,r){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[t],i=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(o||"");if(!1===e.opts.format)return l&&(a+=" if (true) { "),a;var u,h=e.opts.$data&&n&&n.$data;h?(a+=" var schema"+s+" = "+e.util.getData(n.$data,o,e.dataPathArr)+"; ",u="schema"+s):u=n;var p=e.opts.unknownFormats,f=Array.isArray(p);if(h){a+=" var "+(m="format"+s)+" = formats["+u+"]; var "+(v="isObject"+s)+" = typeof "+m+" == 'object' && !("+m+" instanceof RegExp) && "+m+".validate; var "+(g="formatType"+s)+" = "+v+" && "+m+".type || 'string'; if ("+v+") { ",e.async&&(a+=" var async"+s+" = "+m+".async; "),a+=" "+m+" = "+m+".validate; } if ( ",h&&(a+=" ("+u+" !== undefined && typeof "+u+" != 'string') || "),a+=" (","ignore"!=p&&(a+=" ("+u+" && !"+m+" ",f&&(a+=" && self._opts.unknownFormats.indexOf("+u+") == -1 "),a+=") || "),a+=" ("+m+" && "+g+" == '"+r+"' && !(typeof "+m+" == 'function' ? ",e.async?a+=" (async"+s+" ? await "+m+"("+d+") : "+m+"("+d+")) ":a+=" "+m+"("+d+") ",a+=" : "+m+".test("+d+"))))) {"}else{var m;if(!(m=e.formats[n])){if("ignore"==p)return e.logger.warn('unknown format "'+n+'" ignored in schema at path "'+e.errSchemaPath+'"'),l&&(a+=" if (true) { "),a;if(f&&p.indexOf(n)>=0)return l&&(a+=" if (true) { "),a;throw new Error('unknown format "'+n+'" is used in schema at path "'+e.errSchemaPath+'"')}var v,g=(v="object"==typeof m&&!(m instanceof RegExp)&&m.validate)&&m.type||"string";if(v){var y=!0===m.async;m=m.validate}if(g!=r)return l&&(a+=" if (true) { "),a;if(y){if(!e.async)throw new Error("async format in sync schema");a+=" if (!(await "+(_="formats"+e.util.getProperty(n)+".validate")+"("+d+"))) { "}else{a+=" if (! ";var _="formats"+e.util.getProperty(n);v&&(_+=".validate"),a+="function"==typeof m?" "+_+"("+d+") ":" "+_+".test("+d+") ",a+=") { "}}var w=w||[];w.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'format' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { format: ",a+=h?""+u:""+e.util.toQuotedString(n),a+=" } ",!1!==e.opts.messages&&(a+=" , message: 'should match format \"",a+=h?"' + "+u+" + '":""+e.util.escapeQuotes(n),a+="\"' "),e.opts.verbose&&(a+=" , schema: ",a+=h?"validate.schema"+i:""+e.util.toQuotedString(n),a+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ";var b=a;return a=w.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+b+"]); ":a+=" validate.errors = ["+b+"]; return false; ":a+=" var err = "+b+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } ",l&&(a+=" else { "),a},if:function(e,t,r){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[t],i=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(o||""),u="valid"+s,h="errs__"+s,p=e.util.copy(e);p.level++;var f="valid"+p.level,m=e.schema.then,v=e.schema.else,g=void 0!==m&&(e.opts.strictKeywords?"object"==typeof m&&Object.keys(m).length>0||!1===m:e.util.schemaHasRules(m,e.RULES.all)),y=void 0!==v&&(e.opts.strictKeywords?"object"==typeof v&&Object.keys(v).length>0||!1===v:e.util.schemaHasRules(v,e.RULES.all)),_=p.baseId;if(g||y){var w;p.createErrors=!1,p.schema=n,p.schemaPath=i,p.errSchemaPath=c,a+=" var "+h+" = errors; var "+u+" = true; ";var b=e.compositeRule;e.compositeRule=p.compositeRule=!0,a+=" "+e.validate(p)+" ",p.baseId=_,p.createErrors=!0,a+=" errors = "+h+"; if (vErrors !== null) { if ("+h+") vErrors.length = "+h+"; else vErrors = null; } ",e.compositeRule=p.compositeRule=b,g?(a+=" if ("+f+") { ",p.schema=e.schema.then,p.schemaPath=e.schemaPath+".then",p.errSchemaPath=e.errSchemaPath+"/then",a+=" "+e.validate(p)+" ",p.baseId=_,a+=" "+u+" = "+f+"; ",g&&y?a+=" var "+(w="ifClause"+s)+" = 'then'; ":w="'then'",a+=" } ",y&&(a+=" else { ")):a+=" if (!"+f+") { ",y&&(p.schema=e.schema.else,p.schemaPath=e.schemaPath+".else",p.errSchemaPath=e.errSchemaPath+"/else",a+=" "+e.validate(p)+" ",p.baseId=_,a+=" "+u+" = "+f+"; ",g&&y?a+=" var "+(w="ifClause"+s)+" = 'else'; ":w="'else'",a+=" } "),a+=" if (!"+u+") { var err = ",!1!==e.createErrors?(a+=" { keyword: 'if' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { failingKeyword: "+w+" } ",!1!==e.opts.messages&&(a+=" , message: 'should match \"' + "+w+" + '\" schema' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&l&&(e.async?a+=" throw new ValidationError(vErrors); ":a+=" validate.errors = vErrors; return false; "),a+=" } ",l&&(a+=" else { ")}else l&&(a+=" if (true) { ");return a},items:function(e,t,r){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[t],i=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(o||""),u="valid"+s,h="errs__"+s,p=e.util.copy(e),f="";p.level++;var m="valid"+p.level,v="i"+s,g=p.dataLevel=e.dataLevel+1,y="data"+g,_=e.baseId;if(a+="var "+h+" = errors;var "+u+";",Array.isArray(n)){var w=e.schema.additionalItems;if(!1===w){a+=" "+u+" = "+d+".length <= "+n.length+"; ";var b=c;c=e.errSchemaPath+"/additionalItems",a+=" if (!"+u+") { ";var P=P||[];P.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'additionalItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { limit: "+n.length+" } ",!1!==e.opts.messages&&(a+=" , message: 'should NOT have more than "+n.length+" items' "),e.opts.verbose&&(a+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ";var E=a;a=P.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+E+"]); ":a+=" validate.errors = ["+E+"]; return false; ":a+=" var err = "+E+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } ",c=b,l&&(f+="}",a+=" else { ")}var k=n;if(k)for(var x,S=-1,T=k.length-1;S<T;)if(x=k[S+=1],e.opts.strictKeywords?"object"==typeof x&&Object.keys(x).length>0||!1===x:e.util.schemaHasRules(x,e.RULES.all)){a+=" "+m+" = true; if ("+d+".length > "+S+") { ";var R=d+"["+S+"]";p.schema=x,p.schemaPath=i+"["+S+"]",p.errSchemaPath=c+"/"+S,p.errorPath=e.util.getPathExpr(e.errorPath,S,e.opts.jsonPointers,!0),p.dataPathArr[g]=S;var $=e.validate(p);p.baseId=_,e.util.varOccurences($,y)<2?a+=" "+e.util.varReplace($,y,R)+" ":a+=" var "+y+" = "+R+"; "+$+" ",a+=" } ",l&&(a+=" if ("+m+") { ",f+="}")}if("object"==typeof w&&(e.opts.strictKeywords?"object"==typeof w&&Object.keys(w).length>0||!1===w:e.util.schemaHasRules(w,e.RULES.all))){p.schema=w,p.schemaPath=e.schemaPath+".additionalItems",p.errSchemaPath=e.errSchemaPath+"/additionalItems",a+=" "+m+" = true; if ("+d+".length > "+n.length+") { for (var "+v+" = "+n.length+"; "+v+" < "+d+".length; "+v+"++) { ",p.errorPath=e.util.getPathExpr(e.errorPath,v,e.opts.jsonPointers,!0);R=d+"["+v+"]";p.dataPathArr[g]=v;$=e.validate(p);p.baseId=_,e.util.varOccurences($,y)<2?a+=" "+e.util.varReplace($,y,R)+" ":a+=" var "+y+" = "+R+"; "+$+" ",l&&(a+=" if (!"+m+") break; "),a+=" } } ",l&&(a+=" if ("+m+") { ",f+="}")}}else if(e.opts.strictKeywords?"object"==typeof n&&Object.keys(n).length>0||!1===n:e.util.schemaHasRules(n,e.RULES.all)){p.schema=n,p.schemaPath=i,p.errSchemaPath=c,a+=" for (var "+v+" = 0; "+v+" < "+d+".length; "+v+"++) { ",p.errorPath=e.util.getPathExpr(e.errorPath,v,e.opts.jsonPointers,!0);R=d+"["+v+"]";p.dataPathArr[g]=v;$=e.validate(p);p.baseId=_,e.util.varOccurences($,y)<2?a+=" "+e.util.varReplace($,y,R)+" ":a+=" var "+y+" = "+R+"; "+$+" ",l&&(a+=" if (!"+m+") break; "),a+=" }"}return l&&(a+=" "+f+" if ("+h+" == errors) {"),a},maximum:fo,minimum:fo,maxItems:mo,minItems:mo,maxLength:vo,minLength:vo,maxProperties:go,minProperties:go,multipleOf:function(e,t,r){var a,s=" ",o=e.level,n=e.dataLevel,i=e.schema[t],c=e.schemaPath+e.util.getProperty(t),l=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,u="data"+(n||""),h=e.opts.$data&&i&&i.$data;if(h?(s+=" var schema"+o+" = "+e.util.getData(i.$data,n,e.dataPathArr)+"; ",a="schema"+o):a=i,!h&&"number"!=typeof i)throw new Error(t+" must be number");s+="var division"+o+";if (",h&&(s+=" "+a+" !== undefined && ( typeof "+a+" != 'number' || "),s+=" (division"+o+" = "+u+" / "+a+", ",e.opts.multipleOfPrecision?s+=" Math.abs(Math.round(division"+o+") - division"+o+") > 1e-"+e.opts.multipleOfPrecision+" ":s+=" division"+o+" !== parseInt(division"+o+") ",s+=" ) ",h&&(s+=" ) "),s+=" ) { ";var p=p||[];p.push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'multipleOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { multipleOf: "+a+" } ",!1!==e.opts.messages&&(s+=" , message: 'should be multiple of ",s+=h?"' + "+a:a+"'"),e.opts.verbose&&(s+=" , schema: ",s+=h?"validate.schema"+c:""+i,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),s+=" } "):s+=" {} ";var f=s;return s=p.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+f+"]); ":s+=" validate.errors = ["+f+"]; return false; ":s+=" var err = "+f+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+="} ",d&&(s+=" else { "),s},not:function(e,t,r){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[t],i=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(o||""),u="errs__"+s,h=e.util.copy(e);h.level++;var p="valid"+h.level;if(e.opts.strictKeywords?"object"==typeof n&&Object.keys(n).length>0||!1===n:e.util.schemaHasRules(n,e.RULES.all)){h.schema=n,h.schemaPath=i,h.errSchemaPath=c,a+=" var "+u+" = errors; ";var f,m=e.compositeRule;e.compositeRule=h.compositeRule=!0,h.createErrors=!1,h.opts.allErrors&&(f=h.opts.allErrors,h.opts.allErrors=!1),a+=" "+e.validate(h)+" ",h.createErrors=!0,f&&(h.opts.allErrors=f),e.compositeRule=h.compositeRule=m,a+=" if ("+p+") { ";var v=v||[];v.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",!1!==e.opts.messages&&(a+=" , message: 'should NOT be valid' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ";var g=a;a=v.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+g+"]); ":a+=" validate.errors = ["+g+"]; return false; ":a+=" var err = "+g+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } else { errors = "+u+"; if (vErrors !== null) { if ("+u+") vErrors.length = "+u+"; else vErrors = null; } ",e.opts.allErrors&&(a+=" } ")}else a+=" var err = ",!1!==e.createErrors?(a+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",!1!==e.opts.messages&&(a+=" , message: 'should NOT be valid' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",l&&(a+=" if (false) { ");return a},oneOf:function(e,t,r){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[t],i=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(o||""),u="valid"+s,h="errs__"+s,p=e.util.copy(e),f="";p.level++;var m="valid"+p.level,v=p.baseId,g="prevValid"+s,y="passingSchemas"+s;a+="var "+h+" = errors , "+g+" = false , "+u+" = false , "+y+" = null; ";var _=e.compositeRule;e.compositeRule=p.compositeRule=!0;var w=n;if(w)for(var b,P=-1,E=w.length-1;P<E;)b=w[P+=1],(e.opts.strictKeywords?"object"==typeof b&&Object.keys(b).length>0||!1===b:e.util.schemaHasRules(b,e.RULES.all))?(p.schema=b,p.schemaPath=i+"["+P+"]",p.errSchemaPath=c+"/"+P,a+=" "+e.validate(p)+" ",p.baseId=v):a+=" var "+m+" = true; ",P&&(a+=" if ("+m+" && "+g+") { "+u+" = false; "+y+" = ["+y+", "+P+"]; } else { ",f+="}"),a+=" if ("+m+") { "+u+" = "+g+" = true; "+y+" = "+P+"; }";return e.compositeRule=p.compositeRule=_,a+=f+"if (!"+u+") { var err = ",!1!==e.createErrors?(a+=" { keyword: 'oneOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { passingSchemas: "+y+" } ",!1!==e.opts.messages&&(a+=" , message: 'should match exactly one schema in oneOf' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&l&&(e.async?a+=" throw new ValidationError(vErrors); ":a+=" validate.errors = vErrors; return false; "),a+="} else { errors = "+h+"; if (vErrors !== null) { if ("+h+") vErrors.length = "+h+"; else vErrors = null; }",e.opts.allErrors&&(a+=" } "),a},pattern:function(e,t,r){var a,s=" ",o=e.level,n=e.dataLevel,i=e.schema[t],c=e.schemaPath+e.util.getProperty(t),l=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,u="data"+(n||""),h=e.opts.$data&&i&&i.$data;h?(s+=" var schema"+o+" = "+e.util.getData(i.$data,n,e.dataPathArr)+"; ",a="schema"+o):a=i,s+="if ( ",h&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'string') || "),s+=" !"+(h?"(new RegExp("+a+"))":e.usePattern(i))+".test("+u+") ) { ";var p=p||[];p.push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'pattern' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { pattern: ",s+=h?""+a:""+e.util.toQuotedString(i),s+=" } ",!1!==e.opts.messages&&(s+=" , message: 'should match pattern \"",s+=h?"' + "+a+" + '":""+e.util.escapeQuotes(i),s+="\"' "),e.opts.verbose&&(s+=" , schema: ",s+=h?"validate.schema"+c:""+e.util.toQuotedString(i),s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),s+=" } "):s+=" {} ";var f=s;return s=p.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+f+"]); ":s+=" validate.errors = ["+f+"]; return false; ":s+=" var err = "+f+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+="} ",d&&(s+=" else { "),s},properties:function(e,t,r){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[t],i=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(o||""),u="errs__"+s,h=e.util.copy(e),p="";h.level++;var f="valid"+h.level,m="key"+s,v="idx"+s,g=h.dataLevel=e.dataLevel+1,y="data"+g,_="dataProperties"+s,w=Object.keys(n||{}).filter(A),b=e.schema.patternProperties||{},P=Object.keys(b).filter(A),E=e.schema.additionalProperties,k=w.length||P.length,x=!1===E,S="object"==typeof E&&Object.keys(E).length,T=e.opts.removeAdditional,R=x||S||T,$=e.opts.ownProperties,C=e.baseId,O=e.schema.required;if(O&&(!e.opts.$data||!O.$data)&&O.length<e.opts.loopRequired)var I=e.util.toHash(O);function A(e){return"__proto__"!==e}if(a+="var "+u+" = errors;var "+f+" = true;",$&&(a+=" var "+_+" = undefined;"),R){if(a+=$?" "+_+" = "+_+" || Object.keys("+d+"); for (var "+v+"=0; "+v+"<"+_+".length; "+v+"++) { var "+m+" = "+_+"["+v+"]; ":" for (var "+m+" in "+d+") { ",k){if(a+=" var isAdditional"+s+" = !(false ",w.length)if(w.length>8)a+=" || validate.schema"+i+".hasOwnProperty("+m+") ";else{var j=w;if(j)for(var F=-1,D=j.length-1;F<D;)J=j[F+=1],a+=" || "+m+" == "+e.util.toQuotedString(J)+" "}if(P.length){var N=P;if(N)for(var U=-1,L=N.length-1;U<L;)oe=N[U+=1],a+=" || "+e.usePattern(oe)+".test("+m+") "}a+=" ); if (isAdditional"+s+") { "}if("all"==T)a+=" delete "+d+"["+m+"]; ";else{var q=e.errorPath,z="' + "+m+" + '";if(e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers)),x)if(T)a+=" delete "+d+"["+m+"]; ";else{a+=" "+f+" = false; ";var V=c;c=e.errSchemaPath+"/additionalProperties",(re=re||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'additionalProperties' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { additionalProperty: '"+z+"' } ",!1!==e.opts.messages&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is an invalid additional property":a+="should NOT have additional properties",a+="' "),e.opts.verbose&&(a+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ";var M=a;a=re.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+M+"]); ":a+=" validate.errors = ["+M+"]; return false; ":a+=" var err = "+M+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",c=V,l&&(a+=" break; ")}else if(S)if("failing"==T){a+=" var "+u+" = errors; ";var Z=e.compositeRule;e.compositeRule=h.compositeRule=!0,h.schema=E,h.schemaPath=e.schemaPath+".additionalProperties",h.errSchemaPath=e.errSchemaPath+"/additionalProperties",h.errorPath=e.opts._errorDataPathProperty?e.errorPath:e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers);var H=d+"["+m+"]";h.dataPathArr[g]=m;var B=e.validate(h);h.baseId=C,e.util.varOccurences(B,y)<2?a+=" "+e.util.varReplace(B,y,H)+" ":a+=" var "+y+" = "+H+"; "+B+" ",a+=" if (!"+f+") { errors = "+u+"; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete "+d+"["+m+"]; } ",e.compositeRule=h.compositeRule=Z}else{h.schema=E,h.schemaPath=e.schemaPath+".additionalProperties",h.errSchemaPath=e.errSchemaPath+"/additionalProperties",h.errorPath=e.opts._errorDataPathProperty?e.errorPath:e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers);H=d+"["+m+"]";h.dataPathArr[g]=m;B=e.validate(h);h.baseId=C,e.util.varOccurences(B,y)<2?a+=" "+e.util.varReplace(B,y,H)+" ":a+=" var "+y+" = "+H+"; "+B+" ",l&&(a+=" if (!"+f+") break; ")}e.errorPath=q}k&&(a+=" } "),a+=" } ",l&&(a+=" if ("+f+") { ",p+="}")}var Q=e.opts.useDefaults&&!e.compositeRule;if(w.length){var K=w;if(K)for(var J,W=-1,G=K.length-1;W<G;){var Y=n[J=K[W+=1]];if(e.opts.strictKeywords?"object"==typeof Y&&Object.keys(Y).length>0||!1===Y:e.util.schemaHasRules(Y,e.RULES.all)){var X=e.util.getProperty(J),ee=(H=d+X,Q&&void 0!==Y.default);h.schema=Y,h.schemaPath=i+X,h.errSchemaPath=c+"/"+e.util.escapeFragment(J),h.errorPath=e.util.getPath(e.errorPath,J,e.opts.jsonPointers),h.dataPathArr[g]=e.util.toQuotedString(J);B=e.validate(h);if(h.baseId=C,e.util.varOccurences(B,y)<2){B=e.util.varReplace(B,y,H);var te=H}else{te=y;a+=" var "+y+" = "+H+"; "}if(ee)a+=" "+B+" ";else{if(I&&I[J]){a+=" if ( "+te+" === undefined ",$&&(a+=" || ! Object.prototype.hasOwnProperty.call("+d+", '"+e.util.escapeQuotes(J)+"') "),a+=") { "+f+" = false; ";q=e.errorPath,V=c;var re,ae=e.util.escapeQuotes(J);e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(q,J,e.opts.jsonPointers)),c=e.errSchemaPath+"/required",(re=re||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+ae+"' } ",!1!==e.opts.messages&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is a required property":a+="should have required property \\'"+ae+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ";M=a;a=re.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+M+"]); ":a+=" validate.errors = ["+M+"]; return false; ":a+=" var err = "+M+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",c=V,e.errorPath=q,a+=" } else { "}else l?(a+=" if ( "+te+" === undefined ",$&&(a+=" || ! Object.prototype.hasOwnProperty.call("+d+", '"+e.util.escapeQuotes(J)+"') "),a+=") { "+f+" = true; } else { "):(a+=" if ("+te+" !== undefined ",$&&(a+=" && Object.prototype.hasOwnProperty.call("+d+", '"+e.util.escapeQuotes(J)+"') "),a+=" ) { ");a+=" "+B+" } "}}l&&(a+=" if ("+f+") { ",p+="}")}}if(P.length){var se=P;if(se)for(var oe,ne=-1,ie=se.length-1;ne<ie;){Y=b[oe=se[ne+=1]];if(e.opts.strictKeywords?"object"==typeof Y&&Object.keys(Y).length>0||!1===Y:e.util.schemaHasRules(Y,e.RULES.all)){h.schema=Y,h.schemaPath=e.schemaPath+".patternProperties"+e.util.getProperty(oe),h.errSchemaPath=e.errSchemaPath+"/patternProperties/"+e.util.escapeFragment(oe),a+=$?" "+_+" = "+_+" || Object.keys("+d+"); for (var "+v+"=0; "+v+"<"+_+".length; "+v+"++) { var "+m+" = "+_+"["+v+"]; ":" for (var "+m+" in "+d+") { ",a+=" if ("+e.usePattern(oe)+".test("+m+")) { ",h.errorPath=e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers);H=d+"["+m+"]";h.dataPathArr[g]=m;B=e.validate(h);h.baseId=C,e.util.varOccurences(B,y)<2?a+=" "+e.util.varReplace(B,y,H)+" ":a+=" var "+y+" = "+H+"; "+B+" ",l&&(a+=" if (!"+f+") break; "),a+=" } ",l&&(a+=" else "+f+" = true; "),a+=" } ",l&&(a+=" if ("+f+") { ",p+="}")}}}return l&&(a+=" "+p+" if ("+u+" == errors) {"),a},propertyNames:function(e,t,r){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[t],i=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(o||""),u="errs__"+s,h=e.util.copy(e);h.level++;var p="valid"+h.level;if(a+="var "+u+" = errors;",e.opts.strictKeywords?"object"==typeof n&&Object.keys(n).length>0||!1===n:e.util.schemaHasRules(n,e.RULES.all)){h.schema=n,h.schemaPath=i,h.errSchemaPath=c;var f="key"+s,m="idx"+s,v="i"+s,g="' + "+f+" + '",y="data"+(h.dataLevel=e.dataLevel+1),_="dataProperties"+s,w=e.opts.ownProperties,b=e.baseId;w&&(a+=" var "+_+" = undefined; "),a+=w?" "+_+" = "+_+" || Object.keys("+d+"); for (var "+m+"=0; "+m+"<"+_+".length; "+m+"++) { var "+f+" = "+_+"["+m+"]; ":" for (var "+f+" in "+d+") { ",a+=" var startErrs"+s+" = errors; ";var P=f,E=e.compositeRule;e.compositeRule=h.compositeRule=!0;var k=e.validate(h);h.baseId=b,e.util.varOccurences(k,y)<2?a+=" "+e.util.varReplace(k,y,P)+" ":a+=" var "+y+" = "+P+"; "+k+" ",e.compositeRule=h.compositeRule=E,a+=" if (!"+p+") { for (var "+v+"=startErrs"+s+"; "+v+"<errors; "+v+"++) { vErrors["+v+"].propertyName = "+f+"; } var err = ",!1!==e.createErrors?(a+=" { keyword: 'propertyNames' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { propertyName: '"+g+"' } ",!1!==e.opts.messages&&(a+=" , message: 'property name \\'"+g+"\\' is invalid' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&l&&(e.async?a+=" throw new ValidationError(vErrors); ":a+=" validate.errors = vErrors; return false; "),l&&(a+=" break; "),a+=" } }"}return l&&(a+=" if ("+u+" == errors) {"),a},required:function(e,t,r){var a=" ",s=e.level,o=e.dataLevel,n=e.schema[t],i=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(o||""),u="valid"+s,h=e.opts.$data&&n&&n.$data;h&&(a+=" var schema"+s+" = "+e.util.getData(n.$data,o,e.dataPathArr)+"; ");var p="schema"+s;if(!h)if(n.length<e.opts.loopRequired&&e.schema.properties&&Object.keys(e.schema.properties).length){var f=[],m=n;if(m)for(var v,g=-1,y=m.length-1;g<y;){v=m[g+=1];var _=e.schema.properties[v];_&&(e.opts.strictKeywords?"object"==typeof _&&Object.keys(_).length>0||!1===_:e.util.schemaHasRules(_,e.RULES.all))||(f[f.length]=v)}}else f=n;if(h||f.length){var w=e.errorPath,b=h||f.length>=e.opts.loopRequired,P=e.opts.ownProperties;if(l)if(a+=" var missing"+s+"; ",b){h||(a+=" var "+p+" = validate.schema"+i+"; ");var E="' + "+($="schema"+s+"["+(S="i"+s)+"]")+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(w,$,e.opts.jsonPointers)),a+=" var "+u+" = true; ",h&&(a+=" if (schema"+s+" === undefined) "+u+" = true; else if (!Array.isArray(schema"+s+")) "+u+" = false; else {"),a+=" for (var "+S+" = 0; "+S+" < "+p+".length; "+S+"++) { "+u+" = "+d+"["+p+"["+S+"]] !== undefined ",P&&(a+=" && Object.prototype.hasOwnProperty.call("+d+", "+p+"["+S+"]) "),a+="; if (!"+u+") break; } ",h&&(a+=" } "),a+=" if (!"+u+") { ",(R=R||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+E+"' } ",!1!==e.opts.messages&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is a required property":a+="should have required property \\'"+E+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ";var k=a;a=R.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+k+"]); ":a+=" validate.errors = ["+k+"]; return false; ":a+=" var err = "+k+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } else { "}else{a+=" if ( ";var x=f;if(x)for(var S=-1,T=x.length-1;S<T;){O=x[S+=1],S&&(a+=" || "),a+=" ( ( "+(F=d+(j=e.util.getProperty(O)))+" === undefined ",P&&(a+=" || ! Object.prototype.hasOwnProperty.call("+d+", '"+e.util.escapeQuotes(O)+"') "),a+=") && (missing"+s+" = "+e.util.toQuotedString(e.opts.jsonPointers?O:j)+") ) "}a+=") { ";var R;E="' + "+($="missing"+s)+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.opts.jsonPointers?e.util.getPathExpr(w,$,!0):w+" + "+$),(R=R||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+E+"' } ",!1!==e.opts.messages&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is a required property":a+="should have required property \\'"+E+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ";k=a;a=R.pop(),!e.compositeRule&&l?e.async?a+=" throw new ValidationError(["+k+"]); ":a+=" validate.errors = ["+k+"]; return false; ":a+=" var err = "+k+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } else { "}else if(b){h||(a+=" var "+p+" = validate.schema"+i+"; ");var $;E="' + "+($="schema"+s+"["+(S="i"+s)+"]")+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(w,$,e.opts.jsonPointers)),h&&(a+=" if ("+p+" && !Array.isArray("+p+")) { var err = ",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+E+"' } ",!1!==e.opts.messages&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is a required property":a+="should have required property \\'"+E+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if ("+p+" !== undefined) { "),a+=" for (var "+S+" = 0; "+S+" < "+p+".length; "+S+"++) { if ("+d+"["+p+"["+S+"]] === undefined ",P&&(a+=" || ! Object.prototype.hasOwnProperty.call("+d+", "+p+"["+S+"]) "),a+=") { var err = ",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+E+"' } ",!1!==e.opts.messages&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is a required property":a+="should have required property \\'"+E+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ",h&&(a+=" } ")}else{var C=f;if(C)for(var O,I=-1,A=C.length-1;I<A;){O=C[I+=1];var j=e.util.getProperty(O),F=(E=e.util.escapeQuotes(O),d+j);e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(w,O,e.opts.jsonPointers)),a+=" if ( "+F+" === undefined ",P&&(a+=" || ! Object.prototype.hasOwnProperty.call("+d+", '"+e.util.escapeQuotes(O)+"') "),a+=") { var err = ",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+E+"' } ",!1!==e.opts.messages&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is a required property":a+="should have required property \\'"+E+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}e.errorPath=w}else l&&(a+=" if (true) {");return a},uniqueItems:function(e,t,r){var a,s=" ",o=e.level,n=e.dataLevel,i=e.schema[t],c=e.schemaPath+e.util.getProperty(t),l=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,u="data"+(n||""),h="valid"+o,p=e.opts.$data&&i&&i.$data;if(p?(s+=" var schema"+o+" = "+e.util.getData(i.$data,n,e.dataPathArr)+"; ",a="schema"+o):a=i,(i||p)&&!1!==e.opts.uniqueItems){p&&(s+=" var "+h+"; if ("+a+" === false || "+a+" === undefined) "+h+" = true; else if (typeof "+a+" != 'boolean') "+h+" = false; else { "),s+=" var i = "+u+".length , "+h+" = true , j; if (i > 1) { ";var f=e.schema.items&&e.schema.items.type,m=Array.isArray(f);if(!f||"object"==f||"array"==f||m&&(f.indexOf("object")>=0||f.indexOf("array")>=0))s+=" outer: for (;i--;) { for (j = i; j--;) { if (equal("+u+"[i], "+u+"[j])) { "+h+" = false; break outer; } } } ";else{s+=" var itemIndices = {}, item; for (;i--;) { var item = "+u+"[i]; ";var v="checkDataType"+(m?"s":"");s+=" if ("+e.util[v](f,"item",e.opts.strictNumbers,!0)+") continue; ",m&&(s+=" if (typeof item == 'string') item = '\"' + item; "),s+=" if (typeof itemIndices[item] == 'number') { "+h+" = false; j = itemIndices[item]; break; } itemIndices[item] = i; } "}s+=" } ",p&&(s+=" } "),s+=" if (!"+h+") { ";var g=g||[];g.push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'uniqueItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { i: i, j: j } ",!1!==e.opts.messages&&(s+=" , message: 'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)' "),e.opts.verbose&&(s+=" , schema: ",s+=p?"validate.schema"+c:""+i,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),s+=" } "):s+=" {} ";var y=s;s=g.pop(),!e.compositeRule&&d?e.async?s+=" throw new ValidationError(["+y+"]); ":s+=" validate.errors = ["+y+"]; return false; ":s+=" var err = "+y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+=" } ",d&&(s+=" else { ")}else d&&(s+=" if (true) { ");return s},validate:Ss},_o=yo,wo=ja.toHash,bo=["multipleOf","maximum","exclusiveMaximum","minimum","exclusiveMinimum","maxLength","minLength","pattern","additionalItems","maxItems","minItems","uniqueItems","maxProperties","minProperties","required","additionalProperties","enum","format","const"],Po=Ps.MissingRef,Eo=function e(t,r,a){var s=this;if("function"!=typeof this._opts.loadSchema)throw new Error("options.loadSchema should be a function");"function"==typeof r&&(a=r,r=void 0);var o=n(t).then(function(){var e=s._addSchema(t,void 0,r);return e.validate||i(e)});a&&o.then(function(e){a(null,e)},a);return o;function n(t){var r=t.$schema;return r&&!s.getSchema(r)?e.call(s,{$ref:r},!0):Promise.resolve()}function i(e){try{return s._compile(e)}catch(t){if(t instanceof Po)return function(t){var a=t.missingSchema;if(l(a))throw new Error("Schema "+a+" is loaded but "+t.missingRef+" cannot be resolved");var o=s._loadingSchemas[a];o||(o=s._loadingSchemas[a]=s._opts.loadSchema(a)).then(c,c);return o.then(function(e){if(!l(a))return n(e).then(function(){l(a)||s.addSchema(e,a,void 0,r)})}).then(function(){return i(e)});function c(){delete s._loadingSchemas[a]}function l(e){return s._refs[e]||s._schemas[e]}}(t);throw t}}};var ko={$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},xo=ko,So={$id:"https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js",definitions:{simpleTypes:xo.definitions.simpleTypes},type:"object",dependencies:{schema:["validate"],$data:["validate"],statements:["inline"],valid:{not:{required:["macro"]}}},properties:{type:xo.properties.type,schema:{type:"boolean"},statements:{type:"boolean"},dependencies:{type:"array",items:{type:"string"}},metaSchema:{type:"object"},modifying:{type:"boolean"},valid:{type:"boolean"},$data:{type:"boolean"},async:{type:"boolean"},errors:{anyOf:[{type:"boolean"},{const:"full"}]}}},To=/^[a-z_$][a-z0-9_$-]*$/i,Ro=function(e,t,r){var a,s,o=" ",n=e.level,i=e.dataLevel,c=e.schema[t],l=e.schemaPath+e.util.getProperty(t),d=e.errSchemaPath+"/"+t,u=!e.opts.allErrors,h="data"+(i||""),p="valid"+n,f="errs__"+n,m=e.opts.$data&&c&&c.$data;m?(o+=" var schema"+n+" = "+e.util.getData(c.$data,i,e.dataPathArr)+"; ",s="schema"+n):s=c;var v,g,y,_,w,b=this,P="definition"+n,E=b.definition,k="";if(m&&E.$data){w="keywordValidate"+n;var x=E.validateSchema;o+=" var "+P+" = RULES.custom['"+t+"'].definition; var "+w+" = "+P+".validate;"}else{if(!(_=e.useCustomRule(b,c,e.schema,e)))return;s="validate.schema"+l,w=_.code,v=E.compile,g=E.inline,y=E.macro}var S=w+".errors",T="i"+n,R="ruleErr"+n,$=E.async;if($&&!e.async)throw new Error("async keyword in sync schema");if(g||y||(o+=S+" = null;"),o+="var "+f+" = errors;var "+p+";",m&&E.$data&&(k+="}",o+=" if ("+s+" === undefined) { "+p+" = true; } else { ",x&&(k+="}",o+=" "+p+" = "+P+".validateSchema("+s+"); if ("+p+") { ")),g)E.statements?o+=" "+_.validate+" ":o+=" "+p+" = "+_.validate+"; ";else if(y){var C=e.util.copy(e);k="";C.level++;var O="valid"+C.level;C.schema=_.validate,C.schemaPath="";var I=e.compositeRule;e.compositeRule=C.compositeRule=!0;var A=e.validate(C).replace(/validate\.schema/g,w);e.compositeRule=C.compositeRule=I,o+=" "+A}else{(N=N||[]).push(o),o="",o+=" "+w+".call( ",e.opts.passContext?o+="this":o+="self",v||!1===E.schema?o+=" , "+h+" ":o+=" , "+s+" , "+h+" , validate.schema"+e.schemaPath+" ",o+=" , (dataPath || '')",'""'!=e.errorPath&&(o+=" + "+e.errorPath);var j=i?"data"+(i-1||""):"parentData",F=i?e.dataPathArr[i]:"parentDataProperty",D=o+=" , "+j+" , "+F+" , rootData ) ";o=N.pop(),!1===E.errors?(o+=" "+p+" = ",$&&(o+="await "),o+=D+"; "):o+=$?" var "+(S="customErrors"+n)+" = null; try { "+p+" = await "+D+"; } catch (e) { "+p+" = false; if (e instanceof ValidationError) "+S+" = e.errors; else throw e; } ":" "+S+" = null; "+p+" = "+D+"; "}if(E.modifying&&(o+=" if ("+j+") "+h+" = "+j+"["+F+"];"),o+=""+k,E.valid)u&&(o+=" if (true) { ");else{var N;o+=" if ( ",void 0===E.valid?(o+=" !",o+=y?""+O:""+p):o+=" "+!E.valid+" ",o+=") { ",a=b.keyword,(N=N||[]).push(o),o="",(N=N||[]).push(o),o="",!1!==e.createErrors?(o+=" { keyword: '"+(a||"custom")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { keyword: '"+b.keyword+"' } ",!1!==e.opts.messages&&(o+=" , message: 'should pass \""+b.keyword+"\" keyword validation' "),e.opts.verbose&&(o+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),o+=" } "):o+=" {} ";var U=o;o=N.pop(),!e.compositeRule&&u?e.async?o+=" throw new ValidationError(["+U+"]); ":o+=" validate.errors = ["+U+"]; return false; ":o+=" var err = "+U+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";var L=o;o=N.pop(),g?E.errors?"full"!=E.errors&&(o+=" for (var "+T+"="+f+"; "+T+"<errors; "+T+"++) { var "+R+" = vErrors["+T+"]; if ("+R+".dataPath === undefined) "+R+".dataPath = (dataPath || '') + "+e.errorPath+"; if ("+R+".schemaPath === undefined) { "+R+'.schemaPath = "'+d+'"; } ',e.opts.verbose&&(o+=" "+R+".schema = "+s+"; "+R+".data = "+h+"; "),o+=" } "):!1===E.errors?o+=" "+L+" ":(o+=" if ("+f+" == errors) { "+L+" } else { for (var "+T+"="+f+"; "+T+"<errors; "+T+"++) { var "+R+" = vErrors["+T+"]; if ("+R+".dataPath === undefined) "+R+".dataPath = (dataPath || '') + "+e.errorPath+"; if ("+R+".schemaPath === undefined) { "+R+'.schemaPath = "'+d+'"; } ',e.opts.verbose&&(o+=" "+R+".schema = "+s+"; "+R+".data = "+h+"; "),o+=" } } "):y?(o+=" var err = ",!1!==e.createErrors?(o+=" { keyword: '"+(a||"custom")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { keyword: '"+b.keyword+"' } ",!1!==e.opts.messages&&(o+=" , message: 'should pass \""+b.keyword+"\" keyword validation' "),e.opts.verbose&&(o+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),o+=" } "):o+=" {} ",o+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&u&&(e.async?o+=" throw new ValidationError(vErrors); ":o+=" validate.errors = vErrors; return false; ")):!1===E.errors?o+=" "+L+" ":(o+=" if (Array.isArray("+S+")) { if (vErrors === null) vErrors = "+S+"; else vErrors = vErrors.concat("+S+"); errors = vErrors.length; for (var "+T+"="+f+"; "+T+"<errors; "+T+"++) { var "+R+" = vErrors["+T+"]; if ("+R+".dataPath === undefined) "+R+".dataPath = (dataPath || '') + "+e.errorPath+"; "+R+'.schemaPath = "'+d+'"; ',e.opts.verbose&&(o+=" "+R+".schema = "+s+"; "+R+".data = "+h+"; "),o+=" } } else { "+L+" } "),o+=" } ",u&&(o+=" else { ")}return o},$o=So,Co={add:function(e,t){var r=this.RULES;if(r.keywords[e])throw new Error("Keyword "+e+" is already defined");if(!To.test(e))throw new Error("Keyword "+e+" is not a valid identifier");if(t){this.validateKeyword(t,!0);var a=t.type;if(Array.isArray(a))for(var s=0;s<a.length;s++)n(e,a[s],t);else n(e,a,t);var o=t.metaSchema;o&&(t.$data&&this._opts.$data&&(o={anyOf:[o,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]}),t.validateSchema=this.compile(o,!0))}function n(e,t,a){for(var s,o=0;o<r.length;o++){var n=r[o];if(n.type==t){s=n;break}}s||(s={type:t,rules:[]},r.push(s));var i={keyword:e,definition:a,custom:!0,code:Ro,implements:a.implements};s.rules.push(i),r.custom[e]=i}return r.keywords[e]=r.all[e]=!0,this},get:function(e){var t=this.RULES.custom[e];return t?t.definition:this.RULES.keywords[e]||!1},remove:function(e){var t=this.RULES;delete t.keywords[e],delete t.all[e],delete t.custom[e];for(var r=0;r<t.length;r++)for(var a=t[r].rules,s=0;s<a.length;s++)if(a[s].keyword==e){a.splice(s,1);break}return this},validate:function e(t,r){e.errors=null;var a=this._validateKeyword=this._validateKeyword||this.compile($o,!0);if(a(t))return!0;if(e.errors=a.errors,r)throw new Error("custom keyword definition is invalid: "+this.errorsText(a.errors));return!1}};var Oo={$schema:"http://json-schema.org/draft-07/schema#",$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON Schema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1},Io=Fs,Ao=ns,jo=Bs,Fo=Ja,Do=xs,No=oo,Uo=function(){var e=[{type:"number",rules:[{maximum:["exclusiveMaximum"]},{minimum:["exclusiveMinimum"]},"multipleOf","format"]},{type:"string",rules:["maxLength","minLength","pattern","format"]},{type:"array",rules:["maxItems","minItems","items","contains","uniqueItems"]},{type:"object",rules:["maxProperties","minProperties","required","dependencies","propertyNames",{properties:["additionalProperties","patternProperties"]}]},{rules:["$ref","const","enum","not","anyOf","oneOf","allOf","if"]}],t=["type","$comment"];return e.all=wo(t),e.types=wo(["number","integer","string","array","object","boolean","null"]),e.forEach(function(r){r.rules=r.rules.map(function(r){var a;if("object"==typeof r){var s=Object.keys(r)[0];a=r[s],r=s,a.forEach(function(r){t.push(r),e.all[r]=!0})}return t.push(r),e.all[r]={keyword:r,code:_o[r],implements:a}}),e.all.$comment={keyword:"$comment",code:_o.$comment},r.type&&(e.types[r.type]=r)}),e.keywords=wo(t.concat(["$schema","$id","id","$data","$async","title","description","default","definitions","examples","readOnly","writeOnly","contentMediaType","contentEncoding","additionalItems","then","else"])),e.custom={},e},Lo=function(e,t){for(var r=0;r<t.length;r++){e=JSON.parse(JSON.stringify(e));var a,s=t[r].split("/"),o=e;for(a=1;a<s.length;a++)o=o[s[a]];for(a=0;a<bo.length;a++){var n=bo[a],i=o[n];i&&(o[n]={anyOf:[i,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]})}}return e},qo=ja,zo=Qo;Qo.prototype.validate=function(e,t){var r;if("string"==typeof e){if(!(r=this.getSchema(e)))throw new Error('no schema with key or ref "'+e+'"')}else{var a=this._addSchema(e);r=a.validate||this._compile(a)}var s=r(t);!0!==r.$async&&(this.errors=r.errors);return s},Qo.prototype.compile=function(e,t){var r=this._addSchema(e,void 0,t);return r.validate||this._compile(r)},Qo.prototype.addSchema=function(e,t,r,a){if(Array.isArray(e)){for(var s=0;s<e.length;s++)this.addSchema(e[s],void 0,r,a);return this}var o=this._getId(e);if(void 0!==o&&"string"!=typeof o)throw new Error("schema id must be string");return Xo(this,t=Ao.normalizeId(t||o)),this._schemas[t]=this._addSchema(e,r,a,!0),this},Qo.prototype.addMetaSchema=function(e,t,r){return this.addSchema(e,t,r,!0),this},Qo.prototype.validateSchema=function(e,t){var r=e.$schema;if(void 0!==r&&"string"!=typeof r)throw new Error("$schema must be a string");if(r=r||this._opts.defaultMeta||function(e){var t=e._opts.meta;return e._opts.defaultMeta="object"==typeof t?e._getId(t)||t:e.getSchema(Zo)?Zo:void 0,e._opts.defaultMeta}(this),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;var a=this.validate(r,e);if(!a&&t){var s="schema is invalid: "+this.errorsText();if("log"!=this._opts.validateSchema)throw new Error(s);this.logger.error(s)}return a},Qo.prototype.getSchema=function(e){var t=Ko(this,e);switch(typeof t){case"object":return t.validate||this._compile(t);case"string":return this.getSchema(t);case"undefined":return function(e,t){var r=Ao.schema.call(e,{schema:{}},t);if(r){var a=r.schema,s=r.root,o=r.baseId,n=Io.call(e,a,s,void 0,o);return e._fragments[t]=new Fo({ref:t,fragment:!0,schema:a,root:s,baseId:o,validate:n}),n}}(this,e)}},Qo.prototype.removeSchema=function(e){if(e instanceof RegExp)return Jo(this,this._schemas,e),Jo(this,this._refs,e),this;switch(typeof e){case"undefined":return Jo(this,this._schemas),Jo(this,this._refs),this._cache.clear(),this;case"string":var t=Ko(this,e);return t&&this._cache.del(t.cacheKey),delete this._schemas[e],delete this._refs[e],this;case"object":var r=this._opts.serialize,a=r?r(e):e;this._cache.del(a);var s=this._getId(e);s&&(s=Ao.normalizeId(s),delete this._schemas[s],delete this._refs[s])}return this},Qo.prototype.addFormat=function(e,t){"string"==typeof t&&(t=new RegExp(t));return this._formats[e]=t,this},Qo.prototype.errorsText=function(e,t){if(!(e=e||this.errors))return"No errors";for(var r=void 0===(t=t||{}).separator?", ":t.separator,a=void 0===t.dataVar?"data":t.dataVar,s="",o=0;o<e.length;o++){var n=e[o];n&&(s+=a+n.dataPath+" "+n.message+r)}return s.slice(0,-r.length)},Qo.prototype._addSchema=function(e,t,r,a){if("object"!=typeof e&&"boolean"!=typeof e)throw new Error("schema should be object or boolean");var s=this._opts.serialize,o=s?s(e):e,n=this._cache.get(o);if(n)return n;a=a||!1!==this._opts.addUsedSchema;var i=Ao.normalizeId(this._getId(e));i&&a&&Xo(this,i);var c,l=!1!==this._opts.validateSchema&&!t;l&&!(c=i&&i==Ao.normalizeId(e.$schema))&&this.validateSchema(e,!0);var d=Ao.ids.call(this,e),u=new Fo({id:i,schema:e,localRefs:d,cacheKey:o,meta:r});"#"!=i[0]&&a&&(this._refs[i]=u);this._cache.put(o,u),l&&c&&this.validateSchema(e,!0);return u},Qo.prototype._compile=function(e,t){if(e.compiling)return e.validate=s,s.schema=e.schema,s.errors=null,s.root=t||s,!0===e.schema.$async&&(s.$async=!0),s;var r,a;e.compiling=!0,e.meta&&(r=this._opts,this._opts=this._metaOpts);try{a=Io.call(this,e.schema,t,e.localRefs)}catch(t){throw delete e.validate,t}finally{e.compiling=!1,e.meta&&(this._opts=r)}return e.validate=a,e.refs=a.refs,e.refVal=a.refVal,e.root=a.root,a;function s(){var t=e.validate,r=t.apply(this,arguments);return s.errors=t.errors,r}},Qo.prototype.compileAsync=Eo;var Vo=Co;Qo.prototype.addKeyword=Vo.add,Qo.prototype.getKeyword=Vo.get,Qo.prototype.removeKeyword=Vo.remove,Qo.prototype.validateKeyword=Vo.validate;var Mo=Ps;Qo.ValidationError=Mo.Validation,Qo.MissingRefError=Mo.MissingRef,Qo.$dataMetaSchema=Lo;var Zo="http://json-schema.org/draft-07/schema",Ho=["removeAdditional","useDefaults","coerceTypes","strictDefaults"],Bo=["/properties"];function Qo(e){if(!(this instanceof Qo))return new Qo(e);e=this._opts=qo.copy(e)||{},function(e){var t=e._opts.logger;if(!1===t)e.logger={log:en,warn:en,error:en};else{if(void 0===t&&(t=console),!("object"==typeof t&&t.log&&t.warn&&t.error))throw new Error("logger must implement log, warn and error methods");e.logger=t}}(this),this._schemas={},this._refs={},this._fragments={},this._formats=No(e.format),this._cache=e.cache||new jo,this._loadingSchemas={},this._compilations=[],this.RULES=Uo(),this._getId=function(e){switch(e.schemaId){case"auto":return Yo;case"id":return Wo;default:return Go}}(e),e.loopRequired=e.loopRequired||1/0,"property"==e.errorDataPath&&(e._errorDataPathProperty=!0),void 0===e.serialize&&(e.serialize=Do),this._metaOpts=function(e){for(var t=qo.copy(e._opts),r=0;r<Ho.length;r++)delete t[Ho[r]];return t}(this),e.formats&&function(e){for(var t in e._opts.formats){var r=e._opts.formats[t];e.addFormat(t,r)}}(this),e.keywords&&function(e){for(var t in e._opts.keywords){var r=e._opts.keywords[t];e.addKeyword(t,r)}}(this),function(e){var t;e._opts.$data&&(t=Oo,e.addMetaSchema(t,t.$id,!0));if(!1===e._opts.meta)return;var r=ko;e._opts.$data&&(r=Lo(r,Bo));e.addMetaSchema(r,Zo,!0),e._refs["http://json-schema.org/schema"]=Zo}(this),"object"==typeof e.meta&&this.addMetaSchema(e.meta),e.nullable&&this.addKeyword("nullable",{metaSchema:{type:"boolean"}}),function(e){var t=e._opts.schemas;if(!t)return;if(Array.isArray(t))e.addSchema(t);else for(var r in t)e.addSchema(t[r],r)}(this)}function Ko(e,t){return t=Ao.normalizeId(t),e._schemas[t]||e._refs[t]||e._fragments[t]}function Jo(e,t,r){for(var a in t){var s=t[a];s.meta||r&&!r.test(a)||(e._cache.del(s.cacheKey),delete t[a])}}function Wo(e){return e.$id&&this.logger.warn("schema $id ignored",e.$id),e.id}function Go(e){return e.id&&this.logger.warn("schema id ignored",e.id),e.$id}function Yo(e){if(e.$id&&e.id&&e.$id!=e.id)throw new Error("schema $id is different from id");return e.$id||e.id}function Xo(e,t){if(e._schemas[t]||e._refs[t])throw new Error('schema with key or id "'+t+'" already exists')}function en(){}var tn=Ca(zo);class rn extends $a{constructor(e,t){var r;super(t),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._capabilities=null!==(r=null==t?void 0:t.capabilities)&&void 0!==r?r:{},this._ajv=new tn}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");var t,r;this._capabilities=(t=this._capabilities,r=e,Object.entries(r).reduce((e,[t,r])=>(e[t]=r&&"object"==typeof r&&e[t]?{...e[t],...r}:r,e),{...t}))}assertCapability(e,t){var r;if(!(null===(r=this._serverCapabilities)||void 0===r?void 0:r[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:Qt,capabilities:this._capabilities,clientInfo:this._clientInfo}},wr,t);if(void 0===r)throw new Error(`Server sent invalid initialize result: ${r}`);if(!Kt.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"})}catch(e){throw this.close(),e}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){var t,r,a,s,o;switch(e){case"logging/setLevel":if(!(null===(t=this._serverCapabilities)||void 0===t?void 0:t.logging))throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!(null===(r=this._serverCapabilities)||void 0===r?void 0:r.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(!(null===(a=this._serverCapabilities)||void 0===a?void 0:a.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(!(null===(s=this._serverCapabilities)||void 0===s?void 0:s.tools))throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!(null===(o=this._serverCapabilities)||void 0===o?void 0:o.completions))throw new Error(`Server does not support completions (required for ${e})`)}}assertNotificationCapability(e){var t;if("notifications/roots/list_changed"===e)if(!(null===(t=this._capabilities.roots)||void 0===t?void 0:t.listChanged))throw new Error(`Client does not support roots list changed notifications (required for ${e})`)}assertRequestHandlerCapability(e){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})`)}}async ping(e){return this.request({method:"ping"},pr,e)}async complete(e,t){return this.request({method:"completion/complete",params:e},Ea,t)}async setLoggingLevel(e,t){return this.request({method:"logging/setLevel",params:{level:e}},pr,t)}async getPrompt(e,t){return this.request({method:"prompts/get",params:e},ea,t)}async listPrompts(e,t){return this.request({method:"prompts/list",params:e},Br,t)}async listResources(e,t){return this.request({method:"resources/list",params:e},jr,t)}async listResourceTemplates(e,t){return this.request({method:"resources/templates/list",params:e},Dr,t)}async readResource(e,t){return this.request({method:"resources/read",params:e},Ur,t)}async subscribeResource(e,t){return this.request({method:"resources/subscribe",params:e},pr,t)}async unsubscribeResource(e,t){return this.request({method:"resources/unsubscribe",params:e},pr,t)}async callTool(e,t=na,r){const a=await this.request({method:"tools/call",params:e},t,r),s=this.getToolOutputValidator(e.name);if(s){if(!a.structuredContent&&!a.isError)throw new Ra(dr.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(a.structuredContent)try{if(!s(a.structuredContent))throw new Ra(dr.InvalidParams,`Structured content does not match the tool's output schema: ${this._ajv.errorsText(s.errors)}`)}catch(e){if(e instanceof Ra)throw e;throw new Ra(dr.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)}}return a}cacheToolOutputSchemas(e){this._cachedToolOutputValidators.clear();for(const t of e)if(t.outputSchema)try{const e=this._ajv.compile(t.outputSchema);this._cachedToolOutputValidators.set(t.name,e)}catch(e){}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,t){const r=await this.request({method:"tools/list",params:e},oa,t);return this.cacheToolOutputSchemas(r.tools),r}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}const an=qt({resource:jt().url(),authorization_servers:Lt(jt().url()).optional(),jwks_uri:jt().url().optional(),scopes_supported:Lt(jt()).optional(),bearer_methods_supported:Lt(jt()).optional(),resource_signing_alg_values_supported:Lt(jt()).optional(),resource_name:jt().optional(),resource_documentation:jt().optional(),resource_policy_uri:jt().url().optional(),resource_tos_uri:jt().url().optional(),tls_client_certificate_bound_access_tokens:Dt().optional(),authorization_details_types_supported:Lt(jt()).optional(),dpop_signing_alg_values_supported:Lt(jt()).optional(),dpop_bound_access_tokens_required:Dt().optional()}).passthrough(),sn=qt({issuer:jt(),authorization_endpoint:jt(),token_endpoint:jt(),registration_endpoint:jt().optional(),scopes_supported:Lt(jt()).optional(),response_types_supported:Lt(jt()),response_modes_supported:Lt(jt()).optional(),grant_types_supported:Lt(jt()).optional(),token_endpoint_auth_methods_supported:Lt(jt()).optional(),token_endpoint_auth_signing_alg_values_supported:Lt(jt()).optional(),service_documentation:jt().optional(),revocation_endpoint:jt().optional(),revocation_endpoint_auth_methods_supported:Lt(jt()).optional(),revocation_endpoint_auth_signing_alg_values_supported:Lt(jt()).optional(),introspection_endpoint:jt().optional(),introspection_endpoint_auth_methods_supported:Lt(jt()).optional(),introspection_endpoint_auth_signing_alg_values_supported:Lt(jt()).optional(),code_challenge_methods_supported:Lt(jt()).optional()}).passthrough(),on=qt({issuer:jt(),authorization_endpoint:jt(),token_endpoint:jt(),userinfo_endpoint:jt().optional(),jwks_uri:jt(),registration_endpoint:jt().optional(),scopes_supported:Lt(jt()).optional(),response_types_supported:Lt(jt()),response_modes_supported:Lt(jt()).optional(),grant_types_supported:Lt(jt()).optional(),acr_values_supported:Lt(jt()).optional(),subject_types_supported:Lt(jt()),id_token_signing_alg_values_supported:Lt(jt()),id_token_encryption_alg_values_supported:Lt(jt()).optional(),id_token_encryption_enc_values_supported:Lt(jt()).optional(),userinfo_signing_alg_values_supported:Lt(jt()).optional(),userinfo_encryption_alg_values_supported:Lt(jt()).optional(),userinfo_encryption_enc_values_supported:Lt(jt()).optional(),request_object_signing_alg_values_supported:Lt(jt()).optional(),request_object_encryption_alg_values_supported:Lt(jt()).optional(),request_object_encryption_enc_values_supported:Lt(jt()).optional(),token_endpoint_auth_methods_supported:Lt(jt()).optional(),token_endpoint_auth_signing_alg_values_supported:Lt(jt()).optional(),display_values_supported:Lt(jt()).optional(),claim_types_supported:Lt(jt()).optional(),claims_supported:Lt(jt()).optional(),service_documentation:jt().optional(),claims_locales_supported:Lt(jt()).optional(),ui_locales_supported:Lt(jt()).optional(),claims_parameter_supported:Dt().optional(),request_parameter_supported:Dt().optional(),request_uri_parameter_supported:Dt().optional(),require_request_uri_registration:Dt().optional(),op_policy_uri:jt().optional(),op_tos_uri:jt().optional()}).passthrough().merge(sn.pick({code_challenge_methods_supported:!0})),nn=qt({access_token:jt(),id_token:jt().optional(),token_type:jt(),expires_in:Ft().optional(),scope:jt().optional(),refresh_token:jt().optional()}).strip(),cn=qt({error:jt(),error_description:jt().optional(),error_uri:jt().optional()}),ln=qt({redirect_uris:Lt(jt()).refine(e=>e.every(e=>URL.canParse(e)),{message:"redirect_uris must contain valid URLs"}),token_endpoint_auth_method:jt().optional(),grant_types:Lt(jt()).optional(),response_types:Lt(jt()).optional(),client_name:jt().optional(),client_uri:jt().optional(),logo_uri:jt().optional(),scope:jt().optional(),contacts:Lt(jt()).optional(),tos_uri:jt().optional(),policy_uri:jt().optional(),jwks_uri:jt().optional(),jwks:Nt().optional(),software_id:jt().optional(),software_version:jt().optional(),software_statement:jt().optional()}).strip(),dn=qt({client_id:jt(),client_secret:jt().optional(),client_id_issued_at:Ft().optional(),client_secret_expires_at:Ft().optional()}).strip(),un=ln.merge(dn);qt({error:jt(),error_description:jt().optional()}).strip(),qt({token:jt(),token_type_hint:jt().optional()}).strip();class hn 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 pn extends hn{}pn.errorCode="invalid_request";class fn extends hn{}fn.errorCode="invalid_client";class mn extends hn{}mn.errorCode="invalid_grant";class vn extends hn{}vn.errorCode="unauthorized_client";class gn extends hn{}gn.errorCode="unsupported_grant_type";class yn extends hn{}yn.errorCode="invalid_scope";class _n extends hn{}_n.errorCode="access_denied";class wn extends hn{}wn.errorCode="server_error";class bn extends hn{}bn.errorCode="temporarily_unavailable";class Pn extends hn{}Pn.errorCode="unsupported_response_type";class En extends hn{}En.errorCode="unsupported_token_type";class kn extends hn{}kn.errorCode="invalid_token";class xn extends hn{}xn.errorCode="method_not_allowed";class Sn extends hn{}Sn.errorCode="too_many_requests";class Tn extends hn{}Tn.errorCode="invalid_client_metadata";class Rn extends hn{}Rn.errorCode="insufficient_scope";const $n={[pn.errorCode]:pn,[fn.errorCode]:fn,[mn.errorCode]:mn,[vn.errorCode]:vn,[gn.errorCode]:gn,[yn.errorCode]:yn,[_n.errorCode]:_n,[wn.errorCode]:wn,[bn.errorCode]:bn,[Pn.errorCode]:Pn,[En.errorCode]:En,[kn.errorCode]:kn,[xn.errorCode]:xn,[Sn.errorCode]:Sn,[Tn.errorCode]:Tn,[Rn.errorCode]:Rn};class Cn extends Error{constructor(e){super(null!=e?e:"Unauthorized")}}function On(e,t){const r=void 0!==e.client_secret;return 0===t.length?r?"client_secret_post":"none":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"}function In(e,t,r,a){const{client_id:s,client_secret:o}=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 a=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${a}`)}(s,o,r);case"client_secret_post":return void function(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}(s,o,a);case"none":return void function(e,t){t.set("client_id",e)}(s,a);default:throw new Error(`Unsupported client authentication method: ${e}`)}}async function An(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const e=cn.parse(JSON.parse(r)),{error:t,error_description:a,error_uri:s}=e;return new($n[t]||wn)(a||"",s)}catch(e){return new wn(`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${e}. Raw body: ${r}`)}}async function jn(e,t){var r,a;try{return await Fn(e,t)}catch(s){if(s instanceof fn||s instanceof vn)return await(null===(r=e.invalidateCredentials)||void 0===r?void 0:r.call(e,"all")),await Fn(e,t);if(s instanceof mn)return await(null===(a=e.invalidateCredentials)||void 0===a?void 0:a.call(e,"tokens")),await Fn(e,t);throw s}}async function Fn(e,{serverUrl:t,authorizationCode:r,scope:a,resourceMetadataUrl:s,fetchFn:o}){let n,i;try{n=await async function(e,t,r=fetch){const a=await async function(e,t,r,a){var s,o;const n=new URL(e),i=null!==(s=null==a?void 0:a.protocolVersion)&&void 0!==s?s:Qt;let c;if(null==a?void 0:a.metadataUrl)c=new URL(a.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);c=new URL(e,null!==(o=null==a?void 0:a.metadataServerUrl)&&void 0!==o?o:n),c.search=n.search}let l=await Nn(c,i,r);if(!(null==a?void 0:a.metadataUrl)&&function(e,t){return!e||404===e.status&&"/"!==t}(l,n.pathname)){const e=new URL(`/.well-known/${t}`,n);l=await Nn(e,i,r)}return l}(e,"oauth-protected-resource",r,{protocolVersion:null==t?void 0:t.protocolVersion,metadataUrl:null==t?void 0:t.resourceMetadataUrl});if(!a||404===a.status)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!a.ok)throw new Error(`HTTP ${a.status} trying to load well-known OAuth protected resource metadata.`);return an.parse(await a.json())}(t,{resourceMetadataUrl:s},o),n.authorization_servers&&n.authorization_servers.length>0&&(i=n.authorization_servers[0])}catch(e){}i||(i=t);const l=await async function(e,t,r){const a=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(a,null==r?void 0:r.resource);if(!r)return;if(!function({requestedResource:e,configuredResource:t}){const r="string"==typeof e?new URL(e):new URL(e.href),a="string"==typeof t?new URL(t):new URL(t.href);if(r.origin!==a.origin)return!1;if(r.pathname.length<a.pathname.length)return!1;const s=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",o=a.pathname.endsWith("/")?a.pathname:a.pathname+"/";return s.startsWith(o)}({requestedResource:a,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${a} (or origin)`);return new URL(r.resource)}(t,e,n),d=await async function(e,{fetchFn:t=fetch,protocolVersion:r=Qt}={}){var a;const s={"MCP-Protocol-Version":r},o=function(e){const t="string"==typeof e?new URL(e):e,r="/"!==t.pathname,a=[];if(!r)return a.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),a.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),a;let s=t.pathname;s.endsWith("/")&&(s=s.slice(0,-1));return a.push({url:new URL(`/.well-known/oauth-authorization-server${s}`,t.origin),type:"oauth"}),a.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),a.push({url:new URL(`/.well-known/openid-configuration${s}`,t.origin),type:"oidc"}),a.push({url:new URL(`${s}/.well-known/openid-configuration`,t.origin),type:"oidc"}),a}(e);for(const{url:e,type:r}of o){const o=await Dn(e,s,t);if(!o)throw new Error(`CORS error trying to load ${"oauth"===r?"OAuth":"OpenID provider"} metadata from ${e}`);if(!o.ok){if(o.status>=400&&o.status<500)continue;throw new Error(`HTTP ${o.status} trying to load ${"oauth"===r?"OAuth":"OpenID provider"} metadata from ${e}`)}if("oauth"===r)return sn.parse(await o.json());{const t=on.parse(await o.json());if(!(null===(a=t.code_challenge_methods_supported)||void 0===a?void 0:a.includes("S256")))throw new Error(`Incompatible OIDC provider at ${e}: does not support S256 code challenge method required by MCP specification`);return t}}return}(i,{fetchFn:o});let u=await Promise.resolve(e.clientInformation());if(!u){if(void 0!==r)throw new Error("Existing OAuth client information is required when exchanging an authorization code");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:a}){let s;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");s=new URL(t.registration_endpoint)}else s=new URL("/register",e);const o=await(null!=a?a:fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok)throw await An(o);return un.parse(await o.json())}(i,{metadata:d,clientMetadata:e.clientMetadata});await e.saveClientInformation(t),u=t}if(void 0!==r){const t=await e.codeVerifier(),a=await async function(e,{metadata:t,clientInformation:r,authorizationCode:a,codeVerifier:s,redirectUri:o,resource:n,addClientAuthentication:i,fetchFn:c}){var l;const d="authorization_code",u=(null==t?void 0:t.token_endpoint)?new URL(t.token_endpoint):new URL("/token",e);if((null==t?void 0:t.grant_types_supported)&&!t.grant_types_supported.includes(d))throw new Error(`Incompatible auth server: does not support grant type ${d}`);const h=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),p=new URLSearchParams({grant_type:d,code:a,code_verifier:s,redirect_uri:String(o)});if(i)i(h,p,e,t);else{In(On(r,null!==(l=null==t?void 0:t.token_endpoint_auth_methods_supported)&&void 0!==l?l:[]),r,h,p)}n&&p.set("resource",n.href);const f=await(null!=c?c:fetch)(u,{method:"POST",headers:h,body:p});if(!f.ok)throw await An(f);return nn.parse(await f.json())}(i,{metadata:d,clientInformation:u,authorizationCode:r,codeVerifier:t,redirectUri:e.redirectUrl,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(a),"AUTHORIZED"}const h=await e.tokens();if(null==h?void 0:h.refresh_token)try{const t=await async function(e,{metadata:t,clientInformation:r,refreshToken:a,resource:s,addClientAuthentication:o,fetchFn:n}){var i;const c="refresh_token";let l;if(t){if(l=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(c))throw new Error(`Incompatible auth server: does not support grant type ${c}`)}else l=new URL("/token",e);const d=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),u=new URLSearchParams({grant_type:c,refresh_token:a});if(o)o(d,u,e,t);else{In(On(r,null!==(i=null==t?void 0:t.token_endpoint_auth_methods_supported)&&void 0!==i?i:[]),r,d,u)}s&&u.set("resource",s.href);const h=await(null!=n?n:fetch)(l,{method:"POST",headers:d,body:u});if(!h.ok)throw await An(h);return nn.parse({refresh_token:a,...await h.json()})}(i,{metadata:d,clientInformation:u,refreshToken:h.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication});return await e.saveTokens(t),"AUTHORIZED"}catch(e){if(e instanceof hn&&!(e instanceof wn))throw e}const p=e.state?await e.state():void 0,{authorizationUrl:f,codeVerifier:m}=await async function(e,{metadata:t,clientInformation:r,redirectUrl:a,scope:s,state:o,resource:n}){const i="code",l="S256";let d;if(t){if(d=new URL(t.authorization_endpoint),!t.response_types_supported.includes(i))throw new Error(`Incompatible auth server: does not support response type ${i}`);if(!t.code_challenge_methods_supported||!t.code_challenge_methods_supported.includes(l))throw new Error(`Incompatible auth server: does not support code challenge method ${l}`)}else d=new URL("/authorize",e);const u=await c(),h=u.code_verifier,p=u.code_challenge;d.searchParams.set("response_type",i),d.searchParams.set("client_id",r.client_id),d.searchParams.set("code_challenge",p),d.searchParams.set("code_challenge_method",l),d.searchParams.set("redirect_uri",String(a)),o&&d.searchParams.set("state",o);s&&d.searchParams.set("scope",s);(null==s?void 0:s.includes("offline_access"))&&d.searchParams.append("prompt","consent");n&&d.searchParams.set("resource",n.href);return{authorizationUrl:d,codeVerifier:h}}(i,{metadata:d,clientInformation:u,state:p,redirectUrl:e.redirectUrl,scope:a||e.clientMetadata.scope,resource:l});return await e.saveCodeVerifier(m),await e.redirectToAuthorization(f),"REDIRECT"}async function Dn(e,t,r=fetch){try{return await r(e,{headers:t})}catch(a){if(a instanceof TypeError)return t?Dn(e,void 0,r):void 0;throw a}}async function Nn(e,t,r=fetch){const a={"MCP-Protocol-Version":t};return await Dn(e,a,r)}class Un 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 Ln(e){}function qn(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=Ln,onError:r=Ln,onRetry:a=Ln,onComment:s}=e;let o,n="",i=!0,c="",l="";function d(e){if(""===e)return c.length>0&&t({id:o,event:l||void 0,data:c.endsWith("\n")?c.slice(0,-1):c}),o=void 0,c="",void(l="");if(e.startsWith(":"))return void(s&&s(e.slice(e.startsWith(": ")?2:1)));const r=e.indexOf(":");if(-1!==r){const t=e.slice(0,r),a=" "===e[r+1]?2:1;return void u(t,e.slice(r+a),e)}u(e,"",e)}function u(e,t,s){switch(e){case"event":l=t;break;case"data":c=`${c}${t}\n`;break;case"id":o=t.includes("\0")?void 0:t;break;case"retry":/^\d+$/.test(t)?a(parseInt(t,10)):r(new Un(`Invalid \`retry\` value: "${t}"`,{type:"invalid-retry",value:t,line:s}));break;default:r(new Un(`Unknown field "${e.length>20?`${e.slice(0,20)}…`:e}"`,{type:"unknown-field",field:e,value:t,line:s}))}}return{feed:function(e){const t=i?e.replace(/^\xEF\xBB\xBF/,""):e,[r,a]=function(e){const t=[];let r="",a=0;for(;a<e.length;){const s=e.indexOf("\r",a),o=e.indexOf("\n",a);let n=-1;if(-1!==s&&-1!==o?n=Math.min(s,o):-1!==s?n=s:-1!==o&&(n=o),-1===n){r=e.slice(a);break}{const r=e.slice(a,n);t.push(r),a=n+1,"\r"===e[a-1]&&"\n"===e[a]&&a++}}return[t,r]}(`${n}${t}`);for(const e of r)d(e);n=a,i=!1},reset:function(e={}){n&&e.consume&&d(n),i=!0,o=void 0,c="",l="",n=""}}}class zn extends TransformStream{constructor({onError:e,onRetry:t,onComment:r}={}){let a;super({start(s){a=qn({onEvent:e=>{s.enqueue(e)},onError(t){"terminate"===e?s.error(t):"function"==typeof e&&e(t)},onRetry:t,onComment:r})},transform(e){a.feed(e)}})}}const Vn={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class Mn extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}}class Zn{constructor(e,t){var r;this._url=e,this._resourceMetadataUrl=void 0,this._requestInit=null==t?void 0:t.requestInit,this._authProvider=null==t?void 0:t.authProvider,this._fetch=null==t?void 0:t.fetch,this._sessionId=null==t?void 0:t.sessionId,this._reconnectionOptions=null!==(r=null==t?void 0:t.reconnectionOptions)&&void 0!==r?r:Vn}async _authThenStart(){var e;if(!this._authProvider)throw new Cn("No auth provider");let t;try{t=await jn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(t){throw null===(e=this.onerror)||void 0===e||e.call(this,t),t}if("AUTHORIZED"!==t)throw new Cn;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;const t={};if(this._authProvider){const e=await this._authProvider.tokens();e&&(t.Authorization=`Bearer ${e.access_token}`)}this._sessionId&&(t["mcp-session-id"]=this._sessionId),this._protocolVersion&&(t["mcp-protocol-version"]=this._protocolVersion);const r=this._normalizeHeaders(null===(e=this._requestInit)||void 0===e?void 0:e.headers);return new Headers({...t,...r})}async _startOrAuthSse(e){var t,r,a;const{resumptionToken:s}=e;try{const a=await this._commonHeaders();a.set("Accept","text/event-stream"),s&&a.set("last-event-id",s);const o=await(null!==(t=this._fetch)&&void 0!==t?t:fetch)(this._url,{method:"GET",headers:a,signal:null===(r=this._abortController)||void 0===r?void 0:r.signal});if(!o.ok){if(401===o.status&&this._authProvider)return await this._authThenStart();if(405===o.status)return;throw new Mn(o.status,`Failed to open SSE stream: ${o.statusText}`)}this._handleSseStream(o.body,e,!0)}catch(e){throw null===(a=this.onerror)||void 0===a||a.call(this,e),e}}_getNextReconnectionDelay(e){const t=this._reconnectionOptions.initialReconnectionDelay,r=this._reconnectionOptions.reconnectionDelayGrowFactor,a=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*Math.pow(r,e),a)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,t=0){var r;const a=this._reconnectionOptions.maxRetries;if(a>0&&t>=a)return void(null===(r=this.onerror)||void 0===r||r.call(this,new Error(`Maximum reconnection attempts (${a}) exceeded.`)));const s=this._getNextReconnectionDelay(t);setTimeout(()=>{this._startOrAuthSse(e).catch(r=>{var a;null===(a=this.onerror)||void 0===a||a.call(this,new Error(`Failed to reconnect SSE stream: ${r instanceof Error?r.message:String(r)}`)),this._scheduleReconnection(e,t+1)})},s)}_handleSseStream(e,t,r){if(!e)return;const{onresumptiontoken:a,replayMessageId:s}=t;let o;(async()=>{var t,n,i,c;try{const r=e.pipeThrough(new TextDecoderStream).pipeThrough(new zn).getReader();for(;;){const{value:e,done:i}=await r.read();if(i)break;if(e.id&&(o=e.id,null==a||a(e.id)),!e.event||"message"===e.event)try{const r=hr.parse(JSON.parse(e.data));void 0!==s&&lr(r)&&(r.id=s),null===(t=this.onmessage)||void 0===t||t.call(this,r)}catch(e){null===(n=this.onerror)||void 0===n||n.call(this,e)}}}catch(e){if(null===(i=this.onerror)||void 0===i||i.call(this,new Error(`SSE stream disconnected: ${e}`)),r&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:o,onresumptiontoken:a,replayMessageId:s},0)}catch(e){null===(c=this.onerror)||void 0===c||c.call(this,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 Cn("No auth provider");if("AUTHORIZED"!==await jn(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch}))throw new Cn("Failed to authorize")}async close(){var e,t;null===(e=this._abortController)||void 0===e||e.abort(),null===(t=this.onclose)||void 0===t||t.call(this)}async send(e,t){var r,a,s,o,n;try{const{resumptionToken:o,onresumptiontoken:i}=t||{};if(o)return void this._startOrAuthSse({resumptionToken:o,replayMessageId:nr(e)?e.id:void 0}).catch(e=>{var t;return null===(t=this.onerror)||void 0===t?void 0:t.call(this,e)});const c=await this._commonHeaders();c.set("content-type","application/json"),c.set("accept","application/json, text/event-stream");const l={...this._requestInit,method:"POST",headers:c,body:JSON.stringify(e),signal:null===(r=this._abortController)||void 0===r?void 0:r.signal},d=await(null!==(a=this._fetch)&&void 0!==a?a:fetch)(this._url,l),u=d.headers.get("mcp-session-id");if(u&&(this._sessionId=u),!d.ok){if(401===d.status&&this._authProvider){this._resourceMetadataUrl=function(e){const t=e.headers.get("WWW-Authenticate");if(!t)return;const[r,a]=t.split(" ");if("bearer"!==r.toLowerCase()||!a)return;const s=/resource_metadata="([^"]*)"/.exec(t);if(s)try{return new URL(s[1])}catch(e){return}}(d);if("AUTHORIZED"!==await jn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch}))throw new Cn;return this.send(e)}const t=await d.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${d.status}): ${t}`)}if(202===d.status)return n=e,void(br.safeParse(n).success&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>{var t;return null===(t=this.onerror)||void 0===t?void 0:t.call(this,e)}));const h=(Array.isArray(e)?e:[e]).filter(e=>"method"in e&&"id"in e&&void 0!==e.id).length>0,p=d.headers.get("content-type");if(h)if(null==p?void 0:p.includes("text/event-stream"))this._handleSseStream(d.body,{onresumptiontoken:i},!1);else{if(!(null==p?void 0:p.includes("application/json")))throw new Mn(-1,`Unexpected content type: ${p}`);{const e=await d.json(),t=Array.isArray(e)?e.map(e=>hr.parse(e)):[hr.parse(e)];for(const e of t)null===(s=this.onmessage)||void 0===s||s.call(this,e)}}}catch(e){throw null===(o=this.onerror)||void 0===o||o.call(this,e),e}}get sessionId(){return this._sessionId}async terminateSession(){var e,t,r;if(this._sessionId)try{const r=await this._commonHeaders(),a={...this._requestInit,method:"DELETE",headers:r,signal:null===(e=this._abortController)||void 0===e?void 0:e.signal},s=await(null!==(t=this._fetch)&&void 0!==t?t:fetch)(this._url,a);if(!s.ok&&405!==s.status)throw new Mn(s.status,`Failed to terminate session: ${s.statusText}`);this._sessionId=void 0}catch(e){throw null===(r=this.onerror)||void 0===r||r.call(this,e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}}const Hn=F("quickstart");async function Bn(e,t,r={}){const{proxyBaseUrl:a="http://proxy-ingress:8080",transport:s="streamable-http"}=r,o=await e.listServers(),n=new Set(o.map(e=>e.slug));if(!n.has(t))throw new g(t,Array.from(n));const i=(T?process.env.BARNDOOR_ENV||process.env.MODE:"")||"localdev";let c;if(["localdev","local","development","dev"].includes(i.toLowerCase()))if(A(e.token)){c=`${I(e.token).mcpBaseUrl}/mcp/${t}`}else{Hn.warn("Token has no organization information, using static config for MCP connection");c=`${O().mcpBaseUrl}/mcp/${t}`}else if(A(e.token)){c=`${I(e.token).mcpBaseUrl}/mcp/${t}`}else{Hn.warn("Token has no organization information, using static config for MCP connection");c=`${O().mcpBaseUrl}/mcp/${t}`}return[{url:c,transport:s,headers:{Accept:"application/json, text/event-stream",Authorization:`Bearer ${e.token}`,"x-barndoor-session-id":Qn()}},c]}function Qn(){if(T&&"function"==typeof r.randomUUID)return r.randomUUID();if("undefined"!=typeof globalThis&&globalThis.crypto?.randomUUID)return globalThis.crypto.randomUUID();let e;if(T&&"function"==typeof r.randomBytes)e=r.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 a=t[6],s=t[8];t[6]=15&a|64,t[8]=63&s|128;const o=Array.from(t,e=>e.toString(16).padStart(2,"0")).join("");return`${o.substring(0,8)}-${o.substring(8,12)}-${o.substring(12,16)}-${o.substring(16,20)}-${o.substring(20)}`}const Kn=function(){try{if("undefined"!=typeof process&&process.versions?.node){const e=s.fileURLToPath("undefined"==typeof document?require("url").pathToFileURL(e).href:d&&"SCRIPT"===d.tagName.toUpperCase()&&d.src||new URL("index.js",document.baseURI).href),t=o.dirname(e),r=o.join(t,"..","package.json");return JSON.parse(l.readFileSync(r,"utf8")).version}return'"0.2.2"'}catch(e){return console.warn("Could not read version from package.json:",e),"0.1.0"}}();exports.AgentToken=x,exports.AuthenticationError=h,exports.BarndoorConfig=$,exports.BarndoorError=u,exports.BarndoorSDK=D,exports.ConfigurationError=_,exports.ConnectionError=m,exports.HTTPError=v,exports.OAuthError=y,exports.PKCEManager=N,exports.ServerDetail=k,exports.ServerNotFoundError=g,exports.ServerSummary=E,exports.TimeoutError=w,exports.TokenError=p,exports.TokenExpiredError=f,exports.TokenManager=X,exports.TokenValidationError=class extends p{},exports.checkTokenOrganization=function(e){return C(e)},exports.clearCachedToken=async function(){const e=W();await e.clearToken()},exports.createScopedLogger=F,exports.debug=function(e,...t){j.debug(e,...t)},exports.ensureServerConnected=async function(e,t,r={}){const{timeout:a=90}=r;Hn.info(`Ensuring ${t} server is connected`);try{await e.ensureServerConnected(t,{pollSeconds:a}),Hn.info(`Server ${t} connected successfully`)}catch(e){throw e instanceof g?Hn.error(`Server '${t}' not found`):Hn.error(`Failed to connect to ${t}:`,e),e}},exports.error=function(e,...t){j.error(e,...t)},exports.getDynamicConfig=I,exports.getLogger=function(){return j},exports.getStaticConfig=O,exports.hasOrganizationInfo=A,exports.info=function(e,...t){j.info(e,...t)},exports.isBrowser=S,exports.isNode=T,exports.isTokenActive=async function(e){try{const e=W(),t=await e.loadToken();if(!t?.access_token)return!1;const r=O(),a=fetch(`https://${r.authDomain}/userinfo`,{headers:{Authorization:`Bearer ${t.access_token}`},..."undefined"!=typeof AbortSignal&&"timeout"in AbortSignal?{signal:AbortSignal.timeout(1e4)}:{}});return(await M(a,1e4)).ok}catch(e){return!1}},exports.isTokenActiveWithRefresh=async function(e){try{const t=new X(e||"");return await t.getValidToken(),!0}catch(e){return z.warn("Token validation/refresh failed:",e),!1}},exports.loadUserToken=ee,exports.loginInteractive=async function(r={}){if(!T)throw new Error("Interactive login is only available in Node.js environment");Hn.info("Starting interactive login flow");const a=O(),{authDomain:s=a.authDomain,clientId:o=a.clientId,clientSecret:n=a.clientSecret,audience:i=a.apiAudience,apiBaseUrl:c=a.apiBaseUrl,port:l=52765}=r;if(!o||!n)throw new Error("AGENT_CLIENT_ID / AGENT_CLIENT_SECRET not set – create a .env file or export in the shell");const d=await ee();if(d)try{let e;A(d)?e=I(d):(Hn.warn("Cached token has no organization information, using static config"),e=O());const t=new D(e.apiBaseUrl,{token:d});return await t.validateCachedToken(),Hn.info("Using cached valid token"),t}catch(e){Hn.info("Cached token invalid, starting OAuth flow")}else Hn.info("No cached token, starting OAuth flow");const[u,h]=q(l),p=new N,f=await p.buildAuthorizationUrl({domain:s,clientId:o,redirectUri:u,audience:i}),m=t.platform();let v;try{v=new URL(f)}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"===m?e.spawn("open",[f],{detached:!0,stdio:"ignore"}).unref():"win32"===m?e.spawn("powershell",["-NoProfile","Start-Process",f],{detached:!0,stdio:"ignore"}).unref():e.spawn("xdg-open",[f],{detached:!0,stdio:"ignore"}).unref(),Hn.info("Please complete login in your browser…")}catch(e){Hn.warn("Failed to open browser automatically. Please visit:",f)}const[g,y]=await h,_=await p.exchangeCodeForToken({domain:s,clientId:o,clientSecret:n,code:g,redirectUri:u});let w;return await te(_),A(_.access_token)?w=I(_.access_token):(Hn.warn("New token has no organization information, using static config"),w=O()),new D(w.apiBaseUrl,{token:_.access_token})},exports.makeMcpClient=async function(e,t,r={}){const[a]=await Bn(e,t,r),s=a,o=new rn({name:"barndoor-js-sdk",version:"0.1.0"}),n=new Zn(new URL(s.url),{requestInit:{headers:s.headers}});return await o.connect(n),o},exports.makeMcpConnectionParams=Bn,exports.saveUserToken=te,exports.setLogger=function(e){j=e},exports.setTokenLogger=function(e){console.warn("setTokenLogger is deprecated. Use setLogger from the main logging module instead.")},exports.startLocalCallbackServer=q,exports.validateToken=async function(e,t){try{const t=O(),r=await G(e,t.authDomain,t.apiAudience);if(r===exports.JWTVerificationResult.VALID)return{valid:!0};if(r===exports.JWTVerificationResult.INVALID)try{const r=fetch(`https://${t.authDomain}/userinfo`,{headers:{Authorization:`Bearer ${e}`},..."undefined"!=typeof AbortSignal&&"timeout"in AbortSignal?{signal:AbortSignal.timeout(5e3)}:{}});return{valid:(await M(r,5e3)).ok}}catch(e){return z.warn("Remote token validation failed:",e),{valid:!1}}return{valid:!1}}catch(e){return z.warn("Token validation failed:",e),{valid:!1}}},exports.verifyJWTLocal=G,exports.version=Kn,exports.warn=function(e,...t){j.warn(e,...t)};