@onyxsecurity/mcp-gateway 1.0.140 → 1.0.142
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/mcp-gateway.js +2 -2
- package/dist/{cli-Cj_W_Rxw.js → cli-zo_V88bm.js} +2 -2
- package/dist/{cli-Cj_W_Rxw.js.map → cli-zo_V88bm.js.map} +1 -1
- package/dist/{env-CvPQLLkW.js → env-DIGv2S-i.js} +1 -1
- package/dist/{env-DKEqpop9.js → env-DPSRbWel.js} +2 -2
- package/dist/{env-DKEqpop9.js.map → env-DPSRbWel.js.map} +1 -1
- package/dist/index.js +1 -1
- package/dist/{logger-jKh1IKjp.js → logger-DZU_dw5Y.js} +2 -2
- package/dist/{logger-jKh1IKjp.js.map → logger-DZU_dw5Y.js.map} +1 -1
- package/dist/{main-CsDKLUsa.js → main-Ck-SM96t.js} +2 -2
- package/dist/{main-CsDKLUsa.js.map → main-Ck-SM96t.js.map} +1 -1
- package/dist/{oauthProvidersClient-T6ZhWZr8.js → oauthProvidersClient-CQuqN4P3.js} +2 -2
- package/dist/{oauthProvidersClient-T6ZhWZr8.js.map → oauthProvidersClient-CQuqN4P3.js.map} +1 -1
- package/dist/oauthProvidersClient-SZpBDyav.js +1 -0
- package/dist/{providers-CR3DqjRH.js → providers-RVkZKJJk.js} +2 -2
- package/dist/{providers-CR3DqjRH.js.map → providers-RVkZKJJk.js.map} +1 -1
- package/dist/{stdio-DDsYWNYz.js → stdio-xswu-UH5.js} +2 -2
- package/dist/{stdio-DDsYWNYz.js.map → stdio-xswu-UH5.js.map} +1 -1
- package/dist/{transportDetection-D45i4vIF.js → transportDetection-DC3XFjls.js} +2 -2
- package/dist/{transportDetection-D45i4vIF.js.map → transportDetection-DC3XFjls.js.map} +1 -1
- package/package.json +1 -1
- package/dist/oauthProvidersClient-DEQn3MwK.js +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{logger as e}from"./logger-
|
|
2
|
-
//# sourceMappingURL=oauthProvidersClient-
|
|
1
|
+
import{logger as e}from"./logger-DZU_dw5Y.js";import{setOAuthProviders as t}from"./providers-RVkZKJJk.js";async function n(e){let t=new URL(e.url),n=t.hostname===`localhost`||t.hostname===`127.0.0.1`||t.hostname===`::1`||t.hostname===`[::1]`;if(t.protocol!==`https:`&&!n)throw Error(`OAuth providers URL must use HTTPS, got ${t.protocol}`);let r=new AbortController,i=setTimeout(()=>r.abort(),e.timeoutMs);try{let t=await fetch(e.url,{headers:{Accept:`application/json`,apikey:e.apiKey},method:`GET`,signal:r.signal});if(!t.ok)throw Error(`OAuth providers service returned ${t.status}: ${t.statusText}`);let n=await t.json();return Array.isArray(n.providers)?n.providers:[]}catch(t){throw t instanceof Error&&t.name===`AbortError`?Error(`OAuth providers fetch timed out after ${e.timeoutMs}ms`):t}finally{clearTimeout(i)}}async function r(r){if(!r.enabled||!r.url||!r.apiKey){t([]),e.debug(`OAuth providers fetch disabled (missing URL or API key); skipping`);return}try{let i=await n({apiKey:r.apiKey,timeoutMs:r.timeoutMs,url:r.url});t(i),e.info(`OAuth providers loaded`,{count:i.length,ids:i.map(e=>e.id)})}catch(n){t([]),e.warn(`OAuth providers fetch failed; falling back to DCR`,{error:String(n),url:r.url})}}export{n as fetchOAuthProviders,r as initializeOAuthProviders};
|
|
2
|
+
//# sourceMappingURL=oauthProvidersClient-CQuqN4P3.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"oauthProvidersClient-
|
|
1
|
+
{"version":3,"file":"oauthProvidersClient-CQuqN4P3.js","names":[],"sources":["../src/auth/oauthProvidersClient.ts"],"sourcesContent":["import type { OAuthProviderConfig } from \"../config/config.js\";\n\nimport { logger } from \"../lib/logger.js\";\nimport { setOAuthProviders } from \"./providers.js\";\n\nexport interface InitializeOAuthProvidersConfig {\n apiKey: string | undefined;\n enabled: boolean;\n timeoutMs: number;\n url: null | string;\n}\n\nexport interface OAuthProvidersClientConfig {\n apiKey: string;\n timeoutMs: number;\n url: string;\n}\n\ninterface OAuthProvidersResponse {\n providers?: OAuthProviderConfig[];\n}\n\n/**\n * Fetches the OAuth provider list from the web extension service.\n *\n * The endpoint is gated by Kong's key-auth plugin, which validates the\n * `apikey` header and forwards a per-tenant `x-consumer-username` header\n * (e.g. `mcp-gateway@<tenantUUID>`) to the backend.\n *\n * Throws on network error, timeout, or non-2xx response. Callers are\n * expected to handle errors and decide on a fallback (initializeOAuthProviders\n * fails open by emptying the in-memory provider list, which causes the OAuth\n * flow to fall through to Dynamic Client Registration).\n */\nexport async function fetchOAuthProviders(\n cfg: OAuthProvidersClientConfig\n): Promise<OAuthProviderConfig[]> {\n // Reject non-HTTPS URLs before sending the API key over the wire.\n // Loopback addresses are allowed for local development against a non-TLS\n // stub: \"localhost\", IPv4 (127.0.0.1), and IPv6 (::1). Node returns the\n // bracketed form (\"[::1]\") for IPv6 hosts in URL.hostname, so match both.\n const parsed = new URL(cfg.url);\n const isLocal =\n parsed.hostname === \"localhost\" ||\n parsed.hostname === \"127.0.0.1\" ||\n parsed.hostname === \"::1\" ||\n parsed.hostname === \"[::1]\";\n if (parsed.protocol !== \"https:\" && !isLocal) {\n throw new Error(`OAuth providers URL must use HTTPS, got ${parsed.protocol}`);\n }\n\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), cfg.timeoutMs);\n\n try {\n const response = await fetch(cfg.url, {\n // GET with no body — Accept signals the desired response format,\n // Content-Type would be misleading.\n headers: {\n Accept: \"application/json\",\n apikey: cfg.apiKey,\n },\n method: \"GET\",\n signal: controller.signal,\n });\n\n if (!response.ok) {\n throw new Error(`OAuth providers service returned ${response.status}: ${response.statusText}`);\n }\n\n const body = (await response.json()) as OAuthProvidersResponse;\n return Array.isArray(body.providers) ? body.providers : [];\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n throw new Error(`OAuth providers fetch timed out after ${cfg.timeoutMs}ms`);\n }\n throw error;\n } finally {\n clearTimeout(timer);\n }\n}\n\n/**\n * Initializes the in-memory OAuth provider store at gateway startup.\n *\n * On a successful fetch, populates the store with the providers returned by\n * the web extension service. On any failure (disabled config, network error,\n * timeout, malformed body), empties the store and logs a warning. The OAuth\n * flow at oauthFlow.ts then falls through to Dynamic Client Registration,\n * matching the gateway's \"fail-safe by default\" convention.\n */\nexport async function initializeOAuthProviders(cfg: InitializeOAuthProvidersConfig): Promise<void> {\n if (!cfg.enabled || !cfg.url || !cfg.apiKey) {\n setOAuthProviders([]);\n logger.debug(\"OAuth providers fetch disabled (missing URL or API key); skipping\");\n return;\n }\n\n try {\n const providers = await fetchOAuthProviders({\n apiKey: cfg.apiKey,\n timeoutMs: cfg.timeoutMs,\n url: cfg.url,\n });\n setOAuthProviders(providers);\n logger.info(\"OAuth providers loaded\", {\n count: providers.length,\n ids: providers.map((p) => p.id),\n });\n } catch (error) {\n setOAuthProviders([]);\n logger.warn(\"OAuth providers fetch failed; falling back to DCR\", {\n error: String(error),\n url: cfg.url,\n });\n }\n}\n"],"mappings":"0GAkCA,eAAsB,EACpB,EACgC,CAKhC,IAAM,EAAS,IAAI,IAAI,EAAI,IAAI,CACzB,EACJ,EAAO,WAAa,aACpB,EAAO,WAAa,aACpB,EAAO,WAAa,OACpB,EAAO,WAAa,QACtB,GAAI,EAAO,WAAa,UAAY,CAAC,EACnC,MAAU,MAAM,2CAA2C,EAAO,WAAW,CAG/E,IAAM,EAAa,IAAI,gBACjB,EAAQ,eAAiB,EAAW,OAAO,CAAE,EAAI,UAAU,CAEjE,GAAI,CACF,IAAM,EAAW,MAAM,MAAM,EAAI,IAAK,CAGpC,QAAS,CACP,OAAQ,mBACR,OAAQ,EAAI,OACb,CACD,OAAQ,MACR,OAAQ,EAAW,OACpB,CAAC,CAEF,GAAI,CAAC,EAAS,GACZ,MAAU,MAAM,oCAAoC,EAAS,OAAO,IAAI,EAAS,aAAa,CAGhG,IAAM,EAAQ,MAAM,EAAS,MAAM,CACnC,OAAO,MAAM,QAAQ,EAAK,UAAU,CAAG,EAAK,UAAY,EAAE,OACnD,EAAO,CAId,MAHI,aAAiB,OAAS,EAAM,OAAS,aACjC,MAAM,yCAAyC,EAAI,UAAU,IAAI,CAEvE,SACE,CACR,aAAa,EAAM,EAavB,eAAsB,EAAyB,EAAoD,CACjG,GAAI,CAAC,EAAI,SAAW,CAAC,EAAI,KAAO,CAAC,EAAI,OAAQ,CAC3C,EAAkB,EAAE,CAAC,CACrB,EAAO,MAAM,oEAAoE,CACjF,OAGF,GAAI,CACF,IAAM,EAAY,MAAM,EAAoB,CAC1C,OAAQ,EAAI,OACZ,UAAW,EAAI,UACf,IAAK,EAAI,IACV,CAAC,CACF,EAAkB,EAAU,CAC5B,EAAO,KAAK,yBAA0B,CACpC,MAAO,EAAU,OACjB,IAAK,EAAU,IAAK,GAAM,EAAE,GAAG,CAChC,CAAC,OACK,EAAO,CACd,EAAkB,EAAE,CAAC,CACrB,EAAO,KAAK,oDAAqD,CAC/D,MAAO,OAAO,EAAM,CACpB,IAAK,EAAI,IACV,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./env-DPSRbWel.js";import"./logger-DZU_dw5Y.js";import"./providers-RVkZKJJk.js";import{fetchOAuthProviders as e,initializeOAuthProviders as t}from"./oauthProvidersClient-CQuqN4P3.js";export{t as initializeOAuthProviders};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{logger as e}from"./logger-
|
|
2
|
-
//# sourceMappingURL=providers-
|
|
1
|
+
import{logger as e}from"./logger-DZU_dw5Y.js";let t=[];function n(n){let r=typeof n==`string`?new URL(n):n,o=r.hostname.toLowerCase();for(let n of t)for(let t of n.urlPatterns){let r=t.toLowerCase();if(a(o,r))return e.debug(`Found matching OAuth provider for URL`,{hostname:o,pattern:t,providerId:n.id,providerName:n.name}),i(n)}e.debug(`No pre-configured OAuth provider found for URL`,{hostname:o,serverUrl:r.toString()})}function r(e){t=e.map(i)}function i(e){return{...e,scopes:e.scopes?[...e.scopes]:void 0,urlPatterns:[...e.urlPatterns]}}function a(e,t){return!!(e===t||e.endsWith(`.${t}`))}export{n as findProviderForUrl,r as setOAuthProviders};
|
|
2
|
+
//# sourceMappingURL=providers-RVkZKJJk.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"providers-
|
|
1
|
+
{"version":3,"file":"providers-RVkZKJJk.js","names":["oauthProviders: OAuthProviderConfig[]"],"sources":["../src/auth/providers.ts"],"sourcesContent":["import type { OAuthProviderConfig } from \"../config/config.js\";\n\nimport { logger } from \"../lib/logger.js\";\n\n// Mutable store. Populated by setOAuthProviders() during startup once the\n// gateway has fetched provider config from the web extension service.\n// Pre-startup or when the fetch fails, the array stays empty and OAuth flows\n// fall through to Dynamic Client Registration via oauthFlow.ts.\nlet oauthProviders: OAuthProviderConfig[] = [];\n\n/**\n * Finds a pre-configured OAuth provider that matches the given server URL.\n *\n * @param serverUrl The MCP server URL to match against provider URL patterns\n * @returns The matching provider config, or undefined if no match found\n */\nexport function findProviderForUrl(serverUrl: string | URL): OAuthProviderConfig | undefined {\n const serverUrlObj = typeof serverUrl === \"string\" ? new URL(serverUrl) : serverUrl;\n const hostname = serverUrlObj.hostname.toLowerCase();\n\n for (const provider of oauthProviders) {\n for (const pattern of provider.urlPatterns) {\n // Pattern can be a hostname or a hostname with path prefix\n const patternLower = pattern.toLowerCase();\n\n // Check if pattern matches hostname (with or without subdomains)\n if (matchesHostname(hostname, patternLower)) {\n logger.debug(\"Found matching OAuth provider for URL\", {\n hostname,\n pattern,\n providerId: provider.id,\n providerName: provider.name,\n });\n // Return a defensive clone — callers in oauthFlow.ts must not be\n // able to corrupt the in-memory store via the returned reference.\n return cloneProvider(provider);\n }\n }\n }\n\n logger.debug(\"No pre-configured OAuth provider found for URL\", {\n hostname,\n serverUrl: serverUrlObj.toString(),\n });\n return undefined;\n}\n\n/**\n * Gets a provider by its ID.\n *\n * @param providerId The provider ID (e.g., \"github\")\n * @returns The provider config, or undefined if not found\n */\nexport function getProviderById(providerId: string): OAuthProviderConfig | undefined {\n const found = oauthProviders.find((p) => p.id === providerId);\n return found ? cloneProvider(found) : undefined;\n}\n\n/**\n * Lists all configured OAuth providers.\n * Useful for debugging and admin interfaces.\n *\n * @returns Array of provider summaries (without secrets)\n */\nexport function listProviders(): Array<{\n hasClientSecret: boolean;\n id: string;\n name: string;\n urlPatterns: string[];\n}> {\n return oauthProviders.map((p) => ({\n hasClientSecret: !!p.clientSecret,\n id: p.id,\n name: p.name,\n urlPatterns: [...p.urlPatterns],\n }));\n}\n\n/**\n * Replaces the in-memory OAuth provider list. Called once at gateway startup\n * after fetching from the web extension service. Pass an empty array to clear.\n *\n * Stores defensive shallow copies of each provider so that callers cannot\n * mutate the in-memory store via the references they passed in. The\n * urlPatterns array is also cloned for the same reason.\n */\nexport function setOAuthProviders(providers: OAuthProviderConfig[]): void {\n oauthProviders = providers.map(cloneProvider);\n}\n\n// cloneProvider returns a defensive shallow copy with array fields cloned,\n// so callers can read and even mutate the result without corrupting the\n// in-memory store. Used on every read path (findProviderForUrl,\n// getProviderById) to match the write-side contract in setOAuthProviders.\nfunction cloneProvider(p: OAuthProviderConfig): OAuthProviderConfig {\n return {\n ...p,\n scopes: p.scopes ? [...p.scopes] : undefined,\n urlPatterns: [...p.urlPatterns],\n };\n}\n\n/**\n * Checks if a hostname matches a pattern.\n * Supports exact matches and subdomain matches.\n *\n * @param hostname The hostname to check (e.g., \"api.github.com\")\n * @param pattern The pattern to match against (e.g., \"github.com\")\n * @returns true if the hostname matches the pattern\n */\nfunction matchesHostname(hostname: string, pattern: string): boolean {\n // Exact match\n if (hostname === pattern) {\n return true;\n }\n\n // Subdomain match: hostname ends with \".pattern\"\n // e.g., \"api.github.com\" matches \"github.com\"\n if (hostname.endsWith(`.${pattern}`)) {\n return true;\n }\n\n return false;\n}\n"],"mappings":"8CAQA,IAAIA,EAAwC,EAAE,CAQ9C,SAAgB,EAAmB,EAA0D,CAC3F,IAAM,EAAe,OAAO,GAAc,SAAW,IAAI,IAAI,EAAU,CAAG,EACpE,EAAW,EAAa,SAAS,aAAa,CAEpD,IAAK,IAAM,KAAY,EACrB,IAAK,IAAM,KAAW,EAAS,YAAa,CAE1C,IAAM,EAAe,EAAQ,aAAa,CAG1C,GAAI,EAAgB,EAAU,EAAa,CASzC,OARA,EAAO,MAAM,wCAAyC,CACpD,WACA,UACA,WAAY,EAAS,GACrB,aAAc,EAAS,KACxB,CAAC,CAGK,EAAc,EAAS,CAKpC,EAAO,MAAM,iDAAkD,CAC7D,WACA,UAAW,EAAa,UAAU,CACnC,CAAC,CA2CJ,SAAgB,EAAkB,EAAwC,CACxE,EAAiB,EAAU,IAAI,EAAc,CAO/C,SAAS,EAAc,EAA6C,CAClE,MAAO,CACL,GAAG,EACH,OAAQ,EAAE,OAAS,CAAC,GAAG,EAAE,OAAO,CAAG,IAAA,GACnC,YAAa,CAAC,GAAG,EAAE,YAAY,CAChC,CAWH,SAAS,EAAgB,EAAkB,EAA0B,CAYnE,MAJA,GANI,IAAa,GAMb,EAAS,SAAS,IAAI,IAAU"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__commonJSMin as e,__require as t,__toESM as n}from"./chunk-CrDKVgUD.js";import{CallToolRequestSchema as r,CallToolResultSchema as i,CancelTaskRequestSchema as a,CancelTaskResultSchema as o,CancelledNotificationSchema as s,CompleteRequestSchema as c,CompleteResultSchema as l,CreateMessageRequestSchema as u,CreateMessageResultSchema as d,CreateMessageResultWithToolsSchema as f,CreateTaskResultSchema as p,DEFAULT_NEGOTIATED_PROTOCOL_VERSION as m,ElicitRequestSchema as h,ElicitResultSchema as g,EmptyResultSchema as _,ErrorCode as v,GetPromptRequestSchema as y,GetPromptResultSchema as b,GetTaskPayloadRequestSchema as x,GetTaskRequestSchema as S,GetTaskResultSchema as C,InitializeRequestSchema as w,InitializeResultSchema as T,InitializedNotificationSchema as E,JSONRPCMessageSchema as D,LATEST_PROTOCOL_VERSION as O,ListChangedOptionsBaseSchema as k,ListPromptsRequestSchema as A,ListPromptsResultSchema as ee,ListResourceTemplatesRequestSchema as te,ListResourceTemplatesResultSchema as ne,ListResourcesRequestSchema as j,ListResourcesResultSchema as re,ListRootsResultSchema as ie,ListTasksRequestSchema as M,ListTasksResultSchema as ae,ListToolsRequestSchema as oe,ListToolsResultSchema as se,LoggingLevelSchema as ce,LoggingMessageNotificationSchema as le,McpError as N,PingRequestSchema as ue,ProgressNotificationSchema as de,PromptListChangedNotificationSchema as fe,RELATED_TASK_META_KEY as P,ReadResourceRequestSchema as pe,ReadResourceResultSchema as me,ResourceListChangedNotificationSchema as he,ResourceUpdatedNotificationSchema as ge,SUPPORTED_PROTOCOL_VERSIONS as _e,SetLevelRequestSchema as ve,SubscribeRequestSchema as ye,TaskStatusNotificationSchema as be,ToolListChangedNotificationSchema as xe,UnsubscribeRequestSchema as Se,isInitializeRequest as Ce,isJSONRPCErrorResponse as we,isJSONRPCNotification as Te,isJSONRPCRequest as F,isJSONRPCResultResponse as I,isTaskAugmentedRequestParams as Ee,safeParse as De}from"./normalizeUrl-BrUSzVK4.js";import{SESSION_ID as Oe,config as ke}from"./env-
|
|
1
|
+
import{__commonJSMin as e,__require as t,__toESM as n}from"./chunk-CrDKVgUD.js";import{CallToolRequestSchema as r,CallToolResultSchema as i,CancelTaskRequestSchema as a,CancelTaskResultSchema as o,CancelledNotificationSchema as s,CompleteRequestSchema as c,CompleteResultSchema as l,CreateMessageRequestSchema as u,CreateMessageResultSchema as d,CreateMessageResultWithToolsSchema as f,CreateTaskResultSchema as p,DEFAULT_NEGOTIATED_PROTOCOL_VERSION as m,ElicitRequestSchema as h,ElicitResultSchema as g,EmptyResultSchema as _,ErrorCode as v,GetPromptRequestSchema as y,GetPromptResultSchema as b,GetTaskPayloadRequestSchema as x,GetTaskRequestSchema as S,GetTaskResultSchema as C,InitializeRequestSchema as w,InitializeResultSchema as T,InitializedNotificationSchema as E,JSONRPCMessageSchema as D,LATEST_PROTOCOL_VERSION as O,ListChangedOptionsBaseSchema as k,ListPromptsRequestSchema as A,ListPromptsResultSchema as ee,ListResourceTemplatesRequestSchema as te,ListResourceTemplatesResultSchema as ne,ListResourcesRequestSchema as j,ListResourcesResultSchema as re,ListRootsResultSchema as ie,ListTasksRequestSchema as M,ListTasksResultSchema as ae,ListToolsRequestSchema as oe,ListToolsResultSchema as se,LoggingLevelSchema as ce,LoggingMessageNotificationSchema as le,McpError as N,PingRequestSchema as ue,ProgressNotificationSchema as de,PromptListChangedNotificationSchema as fe,RELATED_TASK_META_KEY as P,ReadResourceRequestSchema as pe,ReadResourceResultSchema as me,ResourceListChangedNotificationSchema as he,ResourceUpdatedNotificationSchema as ge,SUPPORTED_PROTOCOL_VERSIONS as _e,SetLevelRequestSchema as ve,SubscribeRequestSchema as ye,TaskStatusNotificationSchema as be,ToolListChangedNotificationSchema as xe,UnsubscribeRequestSchema as Se,isInitializeRequest as Ce,isJSONRPCErrorResponse as we,isJSONRPCNotification as Te,isJSONRPCRequest as F,isJSONRPCResultResponse as I,isTaskAugmentedRequestParams as Ee,safeParse as De}from"./normalizeUrl-BrUSzVK4.js";import{SESSION_ID as Oe,config as ke}from"./env-DPSRbWel.js";import{extractTraceIdFromHeaders as Ae,gatewayCorrelationId as je,logger as L,require_inherits as Me,runWithTraceContextAsync as Ne}from"./logger-DZU_dw5Y.js";import Pe,{randomUUID as Fe}from"crypto";import{homedir as Ie,hostname as Le,userInfo as Re}from"node:os";import{join as ze}from"node:path";import{randomUUID as Be}from"node:crypto";import{existsSync as Ve,readFileSync as He}from"node:fs";import{Readable as Ue}from"stream";import We from"ps-list";import{deflateSync as Ge}from"node:zlib";import{URL as Ke}from"node:url";import{Http2ServerRequest as qe,constants as Je}from"http2";import Ye from"node:http";import Xe from"node:process";var Ze=class{counter=0;events=new Map;async replayEventsAfter(e,{send:t}){if(!e||!this.events.has(e))return``;let n=this.getStreamIdFromEventId(e);if(!n)return``;let r=!1,i=[...this.events.entries()].sort((e,t)=>e[0].localeCompare(t[0]));for(let[a,{message:o,streamId:s}]of i){if(s!==n)continue;if(a===e){r=!0;continue}r&&await t(a,o)}return n}async storeEvent(e,t){let n=this.generateEventId(e);return this.events.set(n,{message:t,streamId:e}),n}generateEventId(e){let t=(++this.counter).toString().padStart(12,`0`);return`${e}_${Date.now()}_${t}_${Math.random().toString(36).substring(2,10)}`}getStreamIdFromEventId(e){let t=e.split(`_`);return t.length<4?``:t.slice(0,-3).join(`_`)}},Qe=class extends Error{extra;tags;constructor(e,t,n={},r={}){super(t),this.name=e,this.tags=n,this.extra=r}},$e=class extends Qe{constructor(e,t=`access_denied`,n={}){super(`AccessControlBlockError`,e,{feature:`access_control`,module:`security`,operation:`block`},{reason:t,...n}),this.reason=t}},et=class extends Qe{constructor(e,t,n={}){super(`ConfigurationError`,e,{feature:`configuration`,module:`cli`,operation:`validate`},{configKey:t,...n})}},tt=class extends Qe{constructor(e,t,n,r={},i){super(`ProxyConnectionError`,e,{feature:`connection`,module:`proxy`,operation:`connect`,transport:n||`unknown`},{url:t?(()=>{try{return new URL(t).origin}catch{return t}})():void 0,...r}),i!==void 0&&(this.cause=i)}};const nt=ke.clientAppName;let rt=null;const it=async()=>(rt||=await import(`systeminformation`),rt);function at(e){return typeof e==`string`&&e!==``&&e.includes(`@`)}function ot(){try{let e=ut();if(!Ve(e))return null;let t=He(e,`utf-8`),n=!1;for(let e of t.split(`
|
|
2
2
|
`)){let t=e.trim();if(t.startsWith(`#`)||t.startsWith(`;`))continue;if(t.startsWith(`[`)){n=t.toLowerCase()===`[user]`;continue}if(n){let e=t.match(/^email\s*=\s*(.+)/i);if(e)return e[1].replace(/\s+[#;].*$/,``).trim()||null}}return null}catch{return null}}function st(){return ze(Ie(),`.claude.json`)}function ct(){return ze(Ie(),`.codex`,`auth.json`)}function lt(){try{return Le()}catch{return`unknown-device`}}function ut(){return ze(Ie(),`.gitconfig`)}async function dt(e){try{return(await We()).find(t=>t.pid===e)?.name||`unknown`}catch{return`unknown`}}async function ft(){try{let e=(await(await it()).system()).serial;return e&&e!==``&&e!==`0`&&!e.toLowerCase().includes(`to be filled`)?e:void 0}catch{return}}function pt(){try{let e=ht()?.oauthAccount?.emailAddress;if(at(e))return e;let t=gt();if(at(t))return t;let n=ot();return at(n)?n:void 0}catch{return}}function mt(){try{let e=Re();if(e.username)return e.username;throw Error(`userInfo() returned empty username`)}catch{return process.env.USER||process.env.USERNAME||process.env.LOGNAME}}function ht(){try{let e=st();if(!Ve(e))return null;let t=He(e,`utf-8`);return JSON.parse(t)}catch{return null}}function gt(){try{let e=ct();if(!Ve(e))return null;let t=He(e,`utf-8`),n=JSON.parse(t)?.tokens?.id_token;if(!n)return null;let r=n.split(`.`);if(r.length!==3)return null;let i=Buffer.from(r[1],`base64url`).toString(`utf-8`);return JSON.parse(i).email||null}catch{return null}}const _t=()=>{if(!Ve(`/.dockerenv`))return null;try{let e=He(ze(Ie(),`.onyx`,`container-context.json`),`utf8`),t=JSON.parse(e);return t.container_id?t:null}catch{return null}},vt=e=>{let t=process.env.ONYX_DOCKER_CONTAINER_ID,n=t?null:_t(),r=t||n?.container_id;return r?{...e,containerRuntime:process.env.ONYX_CONTAINER_RUNTIME||void 0,deviceName:process.env.ONYX_HOST_DEVICE_NAME||n?.host_device_name||e.deviceName,dockerContainerId:r,dockerContainerName:process.env.ONYX_DOCKER_CONTAINER_NAME||n?.container_name||void 0,dockerImage:process.env.ONYX_DOCKER_IMAGE||n?.image||void 0,dockerImageId:process.env.ONYX_DOCKER_IMAGE_ID||n?.image_id||void 0,inDockerContainer:!0,systemSerialNumber:process.env.ONYX_HOST_SERIAL_NUMBER||n?.host_serial_number||e.systemSerialNumber}:e},yt=async()=>{let e=process.pid,t=process.ppid;try{let n=lt(),[r,i]=await Promise.all([ft(),dt(t)]),a=pt(),o=mt();return vt({clientAppName:nt||`unknown`,deviceName:n,email:a,gatewayVersion:ke.appVersion,parentProcessId:t,parentProcessName:i,processId:e,systemSerialNumber:r,username:o})}catch{return vt({clientAppName:nt||`unknown`,deviceName:`unknown-device`,email:void 0,gatewayVersion:ke.appVersion,parentProcessId:t,parentProcessName:`unknown`,processId:e,systemSerialNumber:void 0,username:void 0})}},bt=`[REDACTED]`,xt=new Set([`api_key`,`api-key`,`apikey`,`authorization`,`bearer`,`credential`,`credentials`,`header`,`headers`,`key`,`pass`,`passwd`,`password`,`pwd`,`secret`,`token`]);function St(e){let t=[],n=!1;for(let r of e){if(n){t.push(bt),n=!1;continue}if(r.startsWith(`-H`)&&r.length>2&&!r.startsWith(`--`)&&r[2]!==`=`){t.push(`-H`+bt);continue}let e=Ct(r);if(e!==null&&wt(e))if(r.includes(`=`)){let e=r.indexOf(`=`);t.push(r.slice(0,e+1)+bt)}else t.push(r),n=!0;else t.push(r)}return t}function Ct(e){if(!e.startsWith(`-`))return null;let t=e.replace(/^-{1,2}/,``),n=t.indexOf(`=`);return n>=0?t.slice(0,n):t}function wt(e){return e===`H`?!0:xt.has(e.toLowerCase())}const Tt=`onyx.security`;function Et(e){if(!e)return e;let t;try{t=new URL(e)}catch{return e}if(!t.host||t.pathname===``||t.pathname===`/`)return e;let n=t.hostname.toLowerCase().replace(/\.$/,``);if(n!==Tt&&!n.endsWith(`.${Tt}`))return e;let r=t.pathname.split(`/`),i=r.findIndex(e=>e.length>0);if(i===-1)return e;r[i]=`[REDACTED]`;let a=r.join(`/`);return`${t.protocol}//${t.host}${a}${t.search}${t.hash}`}function Dt(e){let t=Ge(JSON.stringify(e));return Buffer.from(t).toString(`base64url`)}var Ot=class{clientAppName;clientInfoBase64;sessionData;get scannerConfig(){return{apiKey:this.config.scanApiKey,enabled:this.config.scanEnabled,failOpen:this.config.scanFailOpen,headers:this.config.scanHeaders,timeoutMs:this.config.scanTimeoutMs,url:this.config.scanUrl}}config;constructor(e,t){this.config=e,this.sessionData=t,this.clientAppName=t.clientAppName||``,this.clientInfoBase64=this.getClientInfoBase64()}async evaluate(e){let t={action:`allow`};if(this.isScanEnabled())try{if(t=await this.scan({data:e.data,id:e.id,method:e.method,originalRequestId:e.originalRequestId,timestamp:e.timestamp,type:e.type}),L.info(`Scan result`,{action:t.action,id:e.id,method:e.method,originalRequestId:e.originalRequestId}),t.action===`block`)return L.warn(`Request blocked by security policy`),t}catch(t){if(L.error(`Scanning failed`,{error:t,method:e.method,requestType:e.type,scannerUrl:this.config.scanUrl}),!this.config.scanFailOpen)return L.warn(`Scanning service unavailable, blocking traffic (fail-closed)`),{action:`block`};L.warn(`Scanning service unavailable, allowing traffic (fail-open)`)}return t}isEnabled(){return this.isScanEnabled()}isScanEnabled(){return this.config.scanEnabled&&!!this.config.scanUrl}async scan(e){if(!this.isScanEnabled())return{action:`allow`};let t={data:e.data,id:e.id,metadata:this.sessionData,method:e.method,originalRequestId:e.originalRequestId,type:e.type};L.info(`Scanning traffic`,{id:e.id,method:e.method,originalRequestId:e.originalRequestId,type:e.type});let n=await this.sendScanRequest(t);return L.info(`Scan result`,{action:n.action,blockReason:n.block_reason,hasModifiedData:!!n.modified_data,id:e.id,originalRequestId:e.originalRequestId}),n}updateConfig(e){this.config={...this.config,...e}}getClientInfoBase64(){return Dt(this.sessionData)}async sendScanRequest(e){let t=new AbortController,n=setTimeout(()=>t.abort(),this.config.scanTimeoutMs);try{let n=`${this.config.scanUrl}/${this.config.scanApiKey}/mcp/${this.clientInfoBase64}`,r={data:e.data,id:e.id,metadata:e.metadata,method:e.method,sessionId:Oe,...e.originalRequestId&&{original_request_id:String(e.originalRequestId)},type:e.type},i=await fetch(n,{body:JSON.stringify(r),headers:{"Content-Type":`application/json`,...this.config.scanHeaders},method:`POST`,signal:t.signal});if(!i.ok)throw Error(`Sanitization service returned ${i.status}: ${i.statusText}`);let a=await i.json();if(!a.action||![`allow`,`block`,`modify`].includes(a.action))throw Error(`Invalid scan response format: action="${a.action}"`);return a}catch(e){throw e instanceof Error&&e.name===`AbortError`?Error(`Scan request timed out after ${this.config.scanTimeoutMs}ms`):e}finally{clearTimeout(n)}}};let kt=null;const At=async e=>{let t=await yt(),n=e.cliArgs.proxyType,r=n===`stdio`?{...e.cliArgs,args:St(e.cliArgs.args)}:e.cliArgs,i={...t,proxyType:n,remoteCliArgs:n===`remote`?r:void 0,stdioCliArgs:n===`stdio`?r:void 0},a=n===`remote`?{...i,remoteCliArgs:{...r,url:Et(r.url)}}:i;return L.setSessionData(a),kt=new Ot(e,i),kt},jt=()=>kt,Mt=e=>{if(e.maxTotalTimeoutMs<0)throw Error(`maxTotalTimeoutMs must be >= 0 (0 disables the cap), got ${e.maxTotalTimeoutMs}`);let t={resetTimeoutOnProgress:e.resetTimeoutOnProgress,timeout:e.timeoutMs};return e.maxTotalTimeoutMs>0&&(t.maxTotalTimeout=e.maxTotalTimeoutMs),t},Nt=new class{counts=new Map;lastLogTime=Date.now();logIntervalMs=6e4;increment(e){this.counts.set(e,(this.counts.get(e)||0)+1),this.maybeLog()}logAndReset(){if(this.counts.size===0)return;let e=(Array.from(this.counts.values()).reduce((e,t)=>e+t,0));L.info(`Requests intercepted`,{byMethod:Object.fromEntries(this.counts),eventType:`mcp_requests_intercepted`,totalCount:e}),this.counts.clear(),this.lastLogTime=Date.now()}maybeLog(){Date.now()-this.lastLogTime>=this.logIntervalMs&&this.logAndReset()}},Pt=()=>{Nt.logAndReset()},Ft=e=>e.length>1&&e[1]&&typeof e[1]==`object`&&`requestId`in e[1]?e[1].requestId:void 0,R=(e,t,n,r)=>async(...i)=>{Nt.increment(e);let a=jt(),o=e,s=i[0],c=Fe(),l=Ft(i)?.toString();s&&typeof s==`object`&&`method`in s&&typeof s.method==`string`&&(o=s.method);let u=async(e,t,n)=>{try{if(!a?.isEnabled()&&!a?.isScanEnabled())return;let r;try{r=await a.evaluate({data:t,id:c,method:o,originalRequestId:l,timestamp:new Date().toISOString(),type:e})}catch(t){if(L.error(`${e} evaluation failed, applying fail-safe`,{error:t}),a?.isScanEnabled()&&!a.scannerConfig?.failOpen)throw Error(`Security scanning service unavailable`);return}if(L.info(`${e} scan result`,{action:r.action,id:c,method:o,...e===`request`&&{originalRequestId:l}}),r.action===`block`||r.action===`modify`){let t=r.action===`block`?`blocked`:`modified`,i=r.action===`block`&&e===`request`?`warn`:`log`;if(r.modified_data){if(r.action===`block`){let n=`${e} ${t} by security policy${e===`request`?`, returning error response`:``}`;return i===`warn`?L.warn(n):L.info(n),r.modified_data}if(n){let a=`${e} ${t} by security policy`;i===`warn`?L.warn(a):L.info(a),n(r.modified_data);return}return r.modified_data}L.warn(`${r.action} action without modified_data, allowing original ${e}`)}return}catch(t){if(L.error(`Unexpected error during ${e} processing`,{error:t}),e===`request`&&t instanceof Error&&t.message===`Security scanning service unavailable`)throw t;return}},d;try{d=await u(`request`,s,e=>{i[0]=e})}catch(n){if(n instanceof Error&&n.message===`Security scanning service unavailable`)throw L.error(`Security scanning unavailable (fail-closed)`,{error:n.message,handlerName:e,operation:t}),n;L.error(`Unexpected error during request processing, continuing`,{error:n,handlerName:e,operation:t})}if(d!==void 0)return d;if(r&&!await r.isAllowed()){let n=r.getBlockReason();throw L.warn(`MCP server blocked by access control`,{handlerName:e,operation:t,reason:n}),new $e(n,`policy_block`)}try{let e=await n(...i);try{if(e){let t=await u(`response`,e);if(t!==void 0)return t}}catch(e){L.error(`Error during response processing, returning original result`,{error:e})}return e}catch(n){if(n instanceof $e)throw L.info(`Request blocked by access control`,{error:n.message,handlerName:e,operation:t,reason:n.reason}),n;try{await u(`error`,{error:n instanceof Error?n.message:String(n),stack:n instanceof Error?n.stack:void 0})}catch(e){L.warn(`Failed to evaluate error`,{evalError:e})}throw L.error(`Handler error in ${e}`,{argsCount:i.length,errorMessage:n instanceof Error?n.message:String(n),operation:t}),n}},It=async({authorizer:e,client:t,forwarding:n=ke.toolCall,server:i,serverCapabilities:a})=>{let o=Mt(n);a?.logging&&(i.setNotificationHandler(le,R(`notifications/message`,`server-to-client`,async e=>t.notification(e),e)),t.setNotificationHandler(le,R(`notifications/message`,`client-to-server`,async e=>i.notification(e),e))),a?.prompts&&(i.setRequestHandler(y,R(`prompts/get`,`get`,async e=>t.getPrompt(e.params,o),e)),i.setRequestHandler(A,R(`prompts/list`,`list`,async e=>t.listPrompts(e.params,o),e))),a?.resources&&(i.setRequestHandler(j,R(`resources/list`,`list`,async e=>t.listResources(e.params,o),e)),i.setRequestHandler(te,R(`resources/templates/list`,`list`,async e=>t.listResourceTemplates(e.params,o),e)),i.setRequestHandler(pe,R(`resources/read`,`read`,async e=>t.readResource(e.params,o),e)),a?.resources.subscribe&&(i.setNotificationHandler(ge,R(`notifications/resources/updated`,`notify`,async e=>t.notification(e),e)),i.setRequestHandler(ye,R(`resources/subscribe`,`subscribe`,async e=>t.subscribeResource(e.params,o),e)),i.setRequestHandler(Se,R(`resources/unsubscribe`,`unsubscribe`,async e=>t.unsubscribeResource(e.params,o),e)))),a?.tools&&(i.setRequestHandler(r,R(`tools/call`,`call`,async(e,n)=>{let r=n._meta?.progressToken,i=r===void 0?void 0:e=>{n.sendNotification({method:`notifications/progress`,params:{...e,progressToken:r}}).catch(e=>{L.warn(`Failed to forward progress notification to client`,{error:e})})};return t.callTool(e.params,void 0,{...o,onprogress:i})},e)),i.setRequestHandler(oe,R(`tools/list`,`list`,async e=>t.listTools(e.params,o),e))),a?.completions&&i.setRequestHandler(c,R(`completion/complete`,`complete`,async e=>t.complete(e.params,o),e))};var Lt=e(((exports,t)=>{t.exports=o,t.exports.format=s,t.exports.parse=c;var n=/\B(?=(\d{3})+(?!\d))/g,r=/(?:\.0*|(\.[^0]+)0+)$/,i={b:1,kb:1024,mb:1<<20,gb:1<<30,tb:1024**4,pb:1024**5},a=/^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i;function o(e,t){return typeof e==`string`?c(e):typeof e==`number`?s(e,t):null}function s(e,t){if(!Number.isFinite(e))return null;var a=Math.abs(e),o=t&&t.thousandsSeparator||``,s=t&&t.unitSeparator||``,c=t&&t.decimalPlaces!==void 0?t.decimalPlaces:2,l=!!(t&&t.fixedDecimals),u=t&&t.unit||``;(!u||!i[u.toLowerCase()])&&(u=a>=i.pb?`PB`:a>=i.tb?`TB`:a>=i.gb?`GB`:a>=i.mb?`MB`:a>=i.kb?`KB`:`B`);var d=(e/i[u.toLowerCase()]).toFixed(c);return l||(d=d.replace(r,`$1`)),o&&(d=d.split(`.`).map(function(e,t){return t===0?e.replace(n,o):e}).join(`.`)),d+s+u}function c(e){if(typeof e==`number`&&!isNaN(e))return e;if(typeof e!=`string`)return null;var t=a.exec(e),n,r=`b`;return t?(n=parseFloat(t[1]),r=t[4].toLowerCase()):(n=parseInt(e,10),r=`b`),isNaN(n)?null:Math.floor(i[r]*n)}})),Rt=e(((exports,n)=>{
|
|
3
3
|
/*!
|
|
4
4
|
* depd
|
|
@@ -28,4 +28,4 @@ return fn.apply(this, arguments)
|
|
|
28
28
|
deps: ${r}}`};let i={keyword:`dependencies`,type:`object`,schemaType:`object`,error:exports.error,code(e){let[t,n]=a(e);o(e,t),s(e,n)}};function a({schema:e}){let t={},n={};for(let r in e){if(r===`__proto__`)continue;let i=Array.isArray(e[r])?t:n;i[r]=e[r]}return[t,n]}function o(e,n=e.schema){let{gen:i,data:a,it:o}=e;if(Object.keys(n).length===0)return;let s=i.let(`missing`);for(let c in n){let l=n[c];if(l.length===0)continue;let u=(0,r.propertyInData)(i,a,c,o.opts.ownProperties);e.setParams({property:c,depsCount:l.length,deps:l.join(`, `)}),o.allErrors?i.if(u,()=>{for(let t of l)(0,r.checkReportMissingProp)(e,t)}):(i.if((0,t._)`${u} && (${(0,r.checkMissingProp)(e,l,s)})`),(0,r.reportMissingProp)(e,s),i.else())}}exports.validatePropertyDeps=o;function s(e,t=e.schema){let{gen:i,data:a,keyword:o,it:s}=e,c=i.name(`valid`);for(let l in t){if((0,n.alwaysValidSchema)(s,t[l]))continue;i.if((0,r.propertyInData)(i,a,l,s.opts.ownProperties),()=>{let t=e.subschema({keyword:o,schemaProp:l},c);e.mergeValidEvaluated(t,c)},()=>i.var(c,!0)),e.ok(c)}}exports.validateSchemaDeps=s,exports.default=i})),ri=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0});let t=X(),n=Z();exports.default={keyword:`propertyNames`,type:`object`,schemaType:[`object`,`boolean`],error:{message:`property name must be valid`,params:({params:e})=>(0,t._)`{propertyName: ${e.propertyName}}`},code(e){let{gen:r,schema:i,data:a,it:o}=e;if((0,n.alwaysValidSchema)(o,i))return;let s=r.name(`valid`);r.forIn(`key`,a,n=>{e.setParams({propertyName:n}),e.subschema({keyword:`propertyNames`,data:n,dataTypes:[`string`],propertyName:n,compositeRule:!0},s),r.if((0,t.not)(s),()=>{e.error(!0),o.allErrors||r.break()})}),e.ok(s)}}})),ii=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0});let t=$(),n=X(),r=Q(),i=Z();exports.default={keyword:`additionalProperties`,type:[`object`],schemaType:[`boolean`,`object`],allowUndefined:!0,trackErrors:!0,error:{message:`must NOT have additional properties`,params:({params:e})=>(0,n._)`{additionalProperty: ${e.additionalProperty}}`},code(e){let{gen:a,schema:o,parentSchema:s,data:c,errsCount:l,it:u}=e;if(!l)throw Error(`ajv implementation error`);let{allErrors:d,opts:f}=u;if(u.props=!0,f.removeAdditional!==`all`&&(0,i.alwaysValidSchema)(u,o))return;let p=(0,t.allSchemaProperties)(s.properties),m=(0,t.allSchemaProperties)(s.patternProperties);h(),e.ok((0,n._)`${l} === ${r.default.errors}`);function h(){a.forIn(`key`,c,e=>{!p.length&&!m.length?v(e):a.if(g(e),()=>v(e))})}function g(r){let o;if(p.length>8){let e=(0,i.schemaRefOrVal)(u,s.properties,`properties`);o=(0,t.isOwnProperty)(a,e,r)}else o=p.length?(0,n.or)(...p.map(e=>(0,n._)`${r} === ${e}`)):n.nil;return m.length&&(o=(0,n.or)(o,...m.map(i=>(0,n._)`${(0,t.usePattern)(e,i)}.test(${r})`))),(0,n.not)(o)}function _(e){a.code((0,n._)`delete ${c}[${e}]`)}function v(t){if(f.removeAdditional===`all`||f.removeAdditional&&o===!1){_(t);return}if(o===!1){e.setParams({additionalProperty:t}),e.error(),d||a.break();return}if(typeof o==`object`&&!(0,i.alwaysValidSchema)(u,o)){let r=a.name(`valid`);f.removeAdditional===`failing`?(y(t,r,!1),a.if((0,n.not)(r),()=>{e.reset(),_(t)})):(y(t,r),d||a.if((0,n.not)(r),()=>a.break()))}}function y(t,n,r){let a={keyword:`additionalProperties`,dataProp:t,dataPropType:i.Type.Str};r===!1&&Object.assign(a,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(a,n)}}}})),ai=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0});let t=Tr(),n=$(),r=Z(),i=ii();exports.default={keyword:`properties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,parentSchema:s,data:c,it:l}=e;l.opts.removeAdditional===`all`&&s.additionalProperties===void 0&&i.default.code(new t.KeywordCxt(l,i.default,`additionalProperties`));let u=(0,n.allSchemaProperties)(o);for(let e of u)l.definedProperties.add(e);l.opts.unevaluated&&u.length&&l.props!==!0&&(l.props=r.mergeEvaluated.props(a,(0,r.toHash)(u),l.props));let d=u.filter(e=>!(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0)return;let f=a.name(`valid`);for(let t of d)p(t)?m(t):(a.if((0,n.propertyInData)(a,c,t,l.opts.ownProperties)),m(t),l.allErrors||a.else().var(f,!0),a.endIf()),e.it.definedProperties.add(t),e.ok(f);function p(e){return l.opts.useDefaults&&!l.compositeRule&&o[e].default!==void 0}function m(t){e.subschema({keyword:`properties`,schemaProp:t,dataProp:t},f)}}}})),oi=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0});let t=$(),n=X(),r=Z(),i=Z();exports.default={keyword:`patternProperties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,data:s,parentSchema:c,it:l}=e,{opts:u}=l,d=(0,t.allSchemaProperties)(o),f=d.filter(e=>(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0||f.length===d.length&&(!l.opts.unevaluated||l.props===!0))return;let p=u.strictSchema&&!u.allowMatchingProperties&&c.properties,m=a.name(`valid`);l.props!==!0&&!(l.props instanceof n.Name)&&(l.props=(0,i.evaluatedPropsToName)(a,l.props));let{props:h}=l;g();function g(){for(let e of d)p&&_(e),l.allErrors?v(e):(a.var(m,!0),v(e),a.if(m))}function _(e){for(let t in p)new RegExp(e).test(t)&&(0,r.checkStrictMode)(l,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function v(r){a.forIn(`key`,s,o=>{a.if((0,n._)`${(0,t.usePattern)(e,r)}.test(${o})`,()=>{let t=f.includes(r);t||e.subschema({keyword:`patternProperties`,schemaProp:r,dataProp:o,dataPropType:i.Type.Str},m),l.opts.unevaluated&&h!==!0?a.assign((0,n._)`${h}[${o}]`,!0):!t&&!l.allErrors&&a.if((0,n.not)(m),()=>a.break())})})}}}})),si=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0});let t=Z();exports.default={keyword:`not`,schemaType:[`object`,`boolean`],trackErrors:!0,code(e){let{gen:n,schema:r,it:i}=e;if((0,t.alwaysValidSchema)(i,r)){e.fail();return}let a=n.name(`valid`);e.subschema({keyword:`not`,compositeRule:!0,createErrors:!1,allErrors:!1},a),e.failResult(a,()=>e.reset(),()=>e.error())},error:{message:`must NOT be valid`}}})),ci=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:$().validateUnion,error:{message:`must match a schema in anyOf`}}})),li=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0});let t=X(),n=Z();exports.default={keyword:`oneOf`,schemaType:`array`,trackErrors:!0,error:{message:`must match exactly one schema in oneOf`,params:({params:e})=>(0,t._)`{passingSchemas: ${e.passing}}`},code(e){let{gen:r,schema:i,parentSchema:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(o.opts.discriminator&&a.discriminator)return;let s=i,c=r.let(`valid`,!1),l=r.let(`passing`,null),u=r.name(`_valid`);e.setParams({passing:l}),r.block(d),e.result(c,()=>e.reset(),()=>e.error(!0));function d(){s.forEach((i,a)=>{let s;(0,n.alwaysValidSchema)(o,i)?r.var(u,!0):s=e.subschema({keyword:`oneOf`,schemaProp:a,compositeRule:!0},u),a>0&&r.if((0,t._)`${u} && ${c}`).assign(c,!1).assign(l,(0,t._)`[${l}, ${a}]`).else(),r.if(u,()=>{r.assign(c,!0),r.assign(l,a),s&&e.mergeEvaluated(s,t.Name)})})}}}})),ui=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0});let t=Z();exports.default={keyword:`allOf`,schemaType:`array`,code(e){let{gen:n,schema:r,it:i}=e;if(!Array.isArray(r))throw Error(`ajv implementation error`);let a=n.name(`valid`);r.forEach((n,r)=>{if((0,t.alwaysValidSchema)(i,n))return;let o=e.subschema({keyword:`allOf`,schemaProp:r},a);e.ok(a),e.mergeEvaluated(o)})}}})),di=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0});let t=X(),n=Z(),r={keyword:`if`,schemaType:[`object`,`boolean`],trackErrors:!0,error:{message:({params:e})=>(0,t.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,t._)`{failingKeyword: ${e.ifClause}}`},code(e){let{gen:r,parentSchema:a,it:o}=e;a.then===void 0&&a.else===void 0&&(0,n.checkStrictMode)(o,`"if" without "then" and "else" is ignored`);let s=i(o,`then`),c=i(o,`else`);if(!s&&!c)return;let l=r.let(`valid`,!0),u=r.name(`_valid`);if(d(),e.reset(),s&&c){let t=r.let(`ifClause`);e.setParams({ifClause:t}),r.if(u,f(`then`,t),f(`else`,t))}else s?r.if(u,f(`then`)):r.if((0,t.not)(u),f(`else`));e.pass(l,()=>e.error(!0));function d(){let t=e.subschema({keyword:`if`,compositeRule:!0,createErrors:!1,allErrors:!1},u);e.mergeEvaluated(t)}function f(n,i){return()=>{let a=e.subschema({keyword:n},u);r.assign(l,u),e.mergeValidEvaluated(a,l),i?r.assign(i,(0,t._)`${n}`):e.setParams({ifClause:n})}}}};function i(e,t){let r=e.schema[t];return r!==void 0&&!(0,n.alwaysValidSchema)(e,r)}exports.default=r})),fi=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0});let t=Z();exports.default={keyword:[`then`,`else`],schemaType:[`object`,`boolean`],code({keyword:e,parentSchema:n,it:r}){n.if===void 0&&(0,t.checkStrictMode)(r,`"${e}" without "if" is ignored`)}}})),pi=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0});let t=Zr(),n=$r(),r=Qr(),i=ei(),a=ti(),o=ni(),s=ri(),c=ii(),l=ai(),u=oi(),d=si(),f=ci(),p=li(),m=ui(),h=di(),g=fi();function _(e=!1){let _=[d.default,f.default,p.default,m.default,h.default,g.default,s.default,c.default,o.default,l.default,u.default];return e?_.push(n.default,i.default):_.push(t.default,r.default),_.push(a.default),_}exports.default=_})),mi=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0});let t=X();exports.default={keyword:`format`,type:[`number`,`string`],schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,t._)`{format: ${e}}`},code(e,n){let{gen:r,data:i,$data:a,schema:o,schemaCode:s,it:c}=e,{opts:l,errSchemaPath:u,schemaEnv:d,self:f}=c;if(!l.validateFormats)return;a?p():m();function p(){let a=r.scopeValue(`formats`,{ref:f.formats,code:l.code.formats}),o=r.const(`fDef`,(0,t._)`${a}[${s}]`),c=r.let(`fType`),u=r.let(`format`);r.if((0,t._)`typeof ${o} == "object" && !(${o} instanceof RegExp)`,()=>r.assign(c,(0,t._)`${o}.type || "string"`).assign(u,(0,t._)`${o}.validate`),()=>r.assign(c,(0,t._)`"string"`).assign(u,o)),e.fail$data((0,t.or)(p(),m()));function p(){return l.strictSchema===!1?t.nil:(0,t._)`${s} && !${u}`}function m(){let e=d.$async?(0,t._)`(${o}.async ? await ${u}(${i}) : ${u}(${i}))`:(0,t._)`${u}(${i})`,r=(0,t._)`(typeof ${u} == "function" ? ${e} : ${u}.test(${i}))`;return(0,t._)`${u} && ${u} !== true && ${c} === ${n} && !${r}`}}function m(){let a=f.formats[o];if(!a){m();return}if(a===!0)return;let[s,c,p]=h(a);s===n&&e.pass(g());function m(){if(l.strictSchema===!1){f.logger.warn(e());return}throw Error(e());function e(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function h(e){let n=e instanceof RegExp?(0,t.regexpCode)(e):l.code.formats?(0,t._)`${l.code.formats}${(0,t.getProperty)(o)}`:void 0,i=r.scopeValue(`formats`,{key:o,ref:e,code:n});return typeof e==`object`&&!(e instanceof RegExp)?[e.type||`string`,e.validate,(0,t._)`${i}.validate`]:[`string`,e,i]}function g(){if(typeof a==`object`&&!(a instanceof RegExp)&&a.async){if(!d.$async)throw Error(`async format in sync schema`);return(0,t._)`await ${p}(${i})`}return typeof c==`function`?(0,t._)`${p}(${i})`:(0,t._)`${p}.test(${i})`}}}}})),hi=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.default=[mi().default]})),gi=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.metadataVocabulary=[`title`,`description`,`default`,`deprecated`,`readOnly`,`writeOnly`,`examples`],exports.contentVocabulary=[`contentMediaType`,`contentEncoding`,`contentSchema`]})),_i=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0});let t=Lr(),n=Xr(),r=pi(),i=hi(),a=gi();exports.default=[t.default,n.default,(0,r.default)(),i.default,a.metadataVocabulary,a.contentVocabulary]})),vi=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0});var t;(function(e){e.Tag=`tag`,e.Mapping=`mapping`})(t||(exports.DiscrError=t={}))})),yi=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0});let t=X(),n=vi(),r=Or(),i=Dr(),a=Z();exports.default={keyword:`discriminator`,type:`object`,schemaType:`object`,error:{message:({params:{discrError:e,tagName:t}})=>e===n.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:n,tagName:r}})=>(0,t._)`{error: ${e}, tag: ${r}, tagValue: ${n}}`},code(e){let{gen:o,data:s,schema:c,parentSchema:l,it:u}=e,{oneOf:d}=l;if(!u.opts.discriminator)throw Error(`discriminator: requires discriminator option`);let f=c.propertyName;if(typeof f!=`string`)throw Error(`discriminator: requires propertyName`);if(c.mapping)throw Error(`discriminator: mapping is not supported`);if(!d)throw Error(`discriminator: requires oneOf keyword`);let p=o.let(`valid`,!1),m=o.const(`tag`,(0,t._)`${s}${(0,t.getProperty)(f)}`);o.if((0,t._)`typeof ${m} == "string"`,()=>h(),()=>e.error(!1,{discrError:n.DiscrError.Tag,tag:m,tagName:f})),e.ok(p);function h(){let r=_();for(let e in o.if(!1),r)o.elseIf((0,t._)`${m} === ${e}`),o.assign(p,g(r[e]));o.else(),e.error(!1,{discrError:n.DiscrError.Mapping,tag:m,tagName:f}),o.endIf()}function g(n){let r=o.name(`valid`),i=e.subschema({keyword:`oneOf`,schemaProp:n},r);return e.mergeEvaluated(i,t.Name),r}function _(){let e={},t=o(l),n=!0;for(let e=0;e<d.length;e++){let c=d[e];if(c?.$ref&&!(0,a.schemaHasRulesButRef)(c,u.self.RULES)){let e=c.$ref;if(c=r.resolveRef.call(u.self,u.schemaEnv.root,u.baseId,e),c instanceof r.SchemaEnv&&(c=c.schema),c===void 0)throw new i.default(u.opts.uriResolver,u.baseId,e)}let l=c?.properties?.[f];if(typeof l!=`object`)throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${f}"`);n&&=t||o(c),s(l,e)}if(!n)throw Error(`discriminator: "${f}" must be required`);return e;function o({required:e}){return Array.isArray(e)&&e.includes(f)}function s(e,t){if(e.const)c(e.const,t);else if(e.enum)for(let n of e.enum)c(n,t);else throw Error(`discriminator: "properties/${f}" must have "const" or "enum"`)}function c(t,n){if(typeof t!=`string`||t in e)throw Error(`discriminator: "${f}" values must be unique strings`);e[t]=n}}}}})),bi=e(((exports,t)=>{t.exports={$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}})),xi=e(((exports,t)=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.MissingRefError=exports.ValidationError=exports.CodeGen=exports.Name=exports.nil=exports.stringify=exports.str=exports._=exports.KeywordCxt=exports.Ajv=void 0;let n=Pr(),r=_i(),i=yi(),a=bi(),o=[`/properties`],s=`http://json-schema.org/draft-07/schema`;var c=class extends n.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(i.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(a,o):a;this.addMetaSchema(e,s,!1),this.refs[`http://json-schema.org/schema`]=s}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(s)?s:void 0)}};exports.Ajv=c,t.exports=exports=c,t.exports.Ajv=c,Object.defineProperty(exports,`__esModule`,{value:!0}),exports.default=c;var l=Tr();Object.defineProperty(exports,`KeywordCxt`,{enumerable:!0,get:function(){return l.KeywordCxt}});var u=X();Object.defineProperty(exports,`_`,{enumerable:!0,get:function(){return u._}}),Object.defineProperty(exports,`str`,{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(exports,`stringify`,{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(exports,`nil`,{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(exports,`Name`,{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(exports,`CodeGen`,{enumerable:!0,get:function(){return u.CodeGen}});var d=Er();Object.defineProperty(exports,`ValidationError`,{enumerable:!0,get:function(){return d.default}});var f=Dr();Object.defineProperty(exports,`MissingRefError`,{enumerable:!0,get:function(){return f.default}})})),Si=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.formatNames=exports.fastFormats=exports.fullFormats=void 0;function t(e,t){return{validate:e,compare:t}}exports.fullFormats={date:t(a,o),time:t(c(!0),l),"date-time":t(f(!0),p),"iso-time":t(c(),u),"iso-date-time":t(f(),m),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:_,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:E,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:y,int32:{type:`number`,validate:S},int64:{type:`number`,validate:C},float:{type:`number`,validate:w},double:{type:`number`,validate:w},password:!0,binary:!0},exports.fastFormats={...exports.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,o),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,l),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,p),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,m),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},exports.formatNames=Object.keys(exports.fullFormats);function n(e){return e%4==0&&(e%100!=0||e%400==0)}let r=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,i=[0,31,28,31,30,31,30,31,31,30,31,30,31];function a(e){let t=r.exec(e);if(!t)return!1;let a=+t[1],o=+t[2],s=+t[3];return o>=1&&o<=12&&s>=1&&s<=(o===2&&n(a)?29:i[o])}function o(e,t){if(e&&t)return e>t?1:e<t?-1:0}let s=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function c(e){return function(t){let n=s.exec(t);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=n[4],c=n[5]===`-`?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||u>59||e&&!o)return!1;if(r<=23&&i<=59&&a<60)return!0;let d=i-u*c,f=r-l*c-(d<0?1:0);return(f===23||f===-1)&&(d===59||d===-1)&&a<61}}function l(e,t){if(!(e&&t))return;let n=new Date(`2020-01-01T`+e).valueOf(),r=new Date(`2020-01-01T`+t).valueOf();if(n&&r)return n-r}function u(e,t){if(!(e&&t))return;let n=s.exec(e),r=s.exec(t);if(n&&r)return e=n[1]+n[2]+n[3],t=r[1]+r[2]+r[3],e>t?1:e<t?-1:0}let d=/t|\s/i;function f(e){let t=c(e);return function(e){let n=e.split(d);return n.length===2&&a(n[0])&&t(n[1])}}function p(e,t){if(!(e&&t))return;let n=new Date(e).valueOf(),r=new Date(t).valueOf();if(n&&r)return n-r}function m(e,t){if(!(e&&t))return;let[n,r]=e.split(d),[i,a]=t.split(d),s=o(n,i);if(s!==void 0)return s||l(r,a)}let h=/\/|:/,g=/^(?:[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;function _(e){return h.test(e)&&g.test(e)}let v=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function y(e){return v.lastIndex=0,v.test(e)}let b=-(2**31),x=2**31-1;function S(e){return Number.isInteger(e)&&e<=x&&e>=b}function C(e){return Number.isInteger(e)}function w(){return!0}let T=/[^\\]\\Z/;function E(e){if(T.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}})),Ci=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.formatLimitDefinition=void 0;let t=xi(),n=X(),r=n.operators,i={formatMaximum:{okStr:`<=`,ok:r.LTE,fail:r.GT},formatMinimum:{okStr:`>=`,ok:r.GTE,fail:r.LT},formatExclusiveMaximum:{okStr:`<`,ok:r.LT,fail:r.GTE},formatExclusiveMinimum:{okStr:`>`,ok:r.GT,fail:r.LTE}};exports.formatLimitDefinition={keyword:Object.keys(i),type:`string`,schemaType:`string`,$data:!0,error:{message:({keyword:e,schemaCode:t})=>(0,n.str)`should be ${i[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,n._)`{comparison: ${i[e].okStr}, limit: ${t}}`},code(e){let{gen:r,data:a,schemaCode:o,keyword:s,it:c}=e,{opts:l,self:u}=c;if(!l.validateFormats)return;let d=new t.KeywordCxt(c,u.RULES.all.format.definition,`format`);d.$data?f():p();function f(){let t=r.scopeValue(`formats`,{ref:u.formats,code:l.code.formats}),i=r.const(`fmt`,(0,n._)`${t}[${d.schemaCode}]`);e.fail$data((0,n.or)((0,n._)`typeof ${i} != "object"`,(0,n._)`${i} instanceof RegExp`,(0,n._)`typeof ${i}.compare != "function"`,m(i)))}function p(){let t=d.schema,i=u.formats[t];if(!i||i===!0)return;if(typeof i!=`object`||i instanceof RegExp||typeof i.compare!=`function`)throw Error(`"${s}": format "${t}" does not define "compare" function`);let a=r.scopeValue(`formats`,{key:t,ref:i,code:l.code.formats?(0,n._)`${l.code.formats}${(0,n.getProperty)(t)}`:void 0});e.fail$data(m(a))}function m(e){return(0,n._)`${e}.compare(${a}, ${o}) ${i[s].fail} 0`}},dependencies:[`format`]},exports.default=t=>(t.addKeyword(exports.formatLimitDefinition),t)})),wi=e(((exports,t)=>{Object.defineProperty(exports,`__esModule`,{value:!0});let n=Si(),r=Ci(),i=X(),a=new i.Name(`fullFormats`),o=new i.Name(`fastFormats`),s=(e,t={keywords:!0})=>{if(Array.isArray(t))return c(e,t,n.fullFormats,a),e;let[i,s]=t.mode===`fast`?[n.fastFormats,o]:[n.fullFormats,a],l=t.formats||n.formatNames;return c(e,l,i,s),t.keywords&&(0,r.default)(e),e};s.get=(e,t=`full`)=>{let r=(t===`fast`?n.fastFormats:n.fullFormats)[e];if(!r)throw Error(`Unknown format "${e}"`);return r};function c(e,t,n,r){var a;(a=e.opts.code).formats??(a.formats=(0,i._)`require("ajv-formats/dist/formats").${r}`);for(let r of t)e.addFormat(r,n[r])}t.exports=exports=s,Object.defineProperty(exports,`__esModule`,{value:!0}),exports.default=s})),Ti=n(xi(),1),Ei=n(wi(),1);function Di(){let e=new Ti.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Ei.default)(e),e}var Oi=class{constructor(e){this._ajv=e??Di()}getValidator(e){let t=`$id`in e&&typeof e.$id==`string`?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}},ki=class{constructor(e){this._client=e}async*callToolStream(e,t=i,n){let r=this._client,a={...n,task:n?.task??(r.isToolTask(e.name)?{}:void 0)},o=r.requestStream({method:`tools/call`,params:e},t,a),s=r.getToolOutputValidator(e.name);for await(let t of o){if(t.type===`result`&&s){let n=t.result;if(!n.structuredContent&&!n.isError){yield{type:`error`,error:new N(v.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(n.structuredContent)try{let e=s(n.structuredContent);if(!e.valid){yield{type:`error`,error:new N(v.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)};return}}catch(e){if(e instanceof N){yield{type:`error`,error:e};return}yield{type:`error`,error:new N(v.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)};return}}yield t}}async getTask(e,t){return this._client.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._client.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._client.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._client.cancelTask({taskId:e},t)}requestStream(e,t,n){return this._client.requestStream(e,t,n)}};function Ai(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`tools/call`:if(!e.tools?.call)throw Error(`${n} does not support task creation for tools/call (required for ${t})`);break;default:break}}function ji(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`sampling/createMessage`:if(!e.sampling?.createMessage)throw Error(`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case`elicitation/create`:if(!e.elicitation?.create)throw Error(`${n} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}function Mi(e,t){if(!(!e||typeof t!=`object`||!t)){if(e.type===`object`&&e.properties&&typeof e.properties==`object`){let n=t,r=e.properties;for(let e of Object.keys(r)){let t=r[e];n[e]===void 0&&Object.prototype.hasOwnProperty.call(t,`default`)&&(n[e]=t.default),n[e]!==void 0&&Mi(t,n[e])}}if(Array.isArray(e.anyOf))for(let n of e.anyOf)typeof n!=`boolean`&&Mi(n,t);if(Array.isArray(e.oneOf))for(let n of e.oneOf)typeof n!=`boolean`&&Mi(n,t)}}function Ni(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};let t=e.form!==void 0,n=e.url!==void 0;return{supportsFormMode:t||!t&&!n,supportsUrlMode:n}}var Pi=class extends lr{constructor(e,t){super(t),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=t?.capabilities??{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new Oi,t?.listChanged&&(this._pendingListChangedConfig=t.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler(`tools`,xe,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler(`prompts`,fe,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler(`resources`,he,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||={tasks:new ki(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=dr(this._capabilities,e)}setRequestHandler(e,t){let n=ar(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r;if(q(n)){let e=n;r=e._zod?.def?.value??e.value}else{let e=n;r=e._def?.value??e.value}if(typeof r!=`string`)throw Error(`Schema method literal must be a string`);let i=r;return i===`elicitation/create`?super.setRequestHandler(e,async(e,n)=>{let r=J(h,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new N(v.InvalidParams,`Invalid elicitation request: ${e}`)}let{params:i}=r.data;i.mode=i.mode??`form`;let{supportsFormMode:a,supportsUrlMode:o}=Ni(this._capabilities.elicitation);if(i.mode===`form`&&!a)throw new N(v.InvalidParams,`Client does not support form-mode elicitation requests`);if(i.mode===`url`&&!o)throw new N(v.InvalidParams,`Client does not support URL-mode elicitation requests`);let s=await Promise.resolve(t(e,n));if(i.task){let e=J(p,s);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new N(v.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let c=J(g,s);if(!c.success){let e=c.error instanceof Error?c.error.message:String(c.error);throw new N(v.InvalidParams,`Invalid elicitation result: ${e}`)}let l=c.data,u=i.mode===`form`?i.requestedSchema:void 0;if(i.mode===`form`&&l.action===`accept`&&l.content&&u&&this._capabilities.elicitation?.form?.applyDefaults)try{Mi(u,l.content)}catch{}return l}):i===`sampling/createMessage`?super.setRequestHandler(e,async(e,n)=>{let r=J(u,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new N(v.InvalidParams,`Invalid sampling request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=J(p,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new N(v.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=i.tools||i.toolChoice?f:d,s=J(o,a);if(!s.success){let e=s.error instanceof Error?s.error.message:String(s.error);throw new N(v.InvalidParams,`Invalid sampling result: ${e}`)}return s.data}):super.setRequestHandler(e,t)}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw Error(`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(await super.connect(e),e.sessionId===void 0)try{let n=await this.request({method:`initialize`,params:{protocolVersion:O,capabilities:this._capabilities,clientInfo:this._clientInfo}},T,t);if(n===void 0)throw Error(`Server sent invalid initialize result: ${n}`);if(!_e.includes(n.protocolVersion))throw Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:`notifications/initialized`}),this._pendingListChangedConfig&&=(this._setupListChangedHandlers(this._pendingListChangedConfig),void 0)}catch(e){throw this.close(),e}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case`logging/setLevel`:if(!this._serverCapabilities?.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._serverCapabilities?.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:case`resources/subscribe`:case`resources/unsubscribe`:if(!this._serverCapabilities?.resources)throw Error(`Server does not support resources (required for ${e})`);if(e===`resources/subscribe`&&!this._serverCapabilities.resources.subscribe)throw Error(`Server does not support resource subscriptions (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._serverCapabilities?.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`completion/complete`:if(!this._serverCapabilities?.completions)throw Error(`Server does not support completions (required for ${e})`);break;case`initialize`:break;case`ping`:break}}assertNotificationCapability(e){switch(e){case`notifications/roots/list_changed`:if(!this._capabilities.roots?.listChanged)throw Error(`Client does not support roots list changed notifications (required for ${e})`);break;case`notifications/initialized`:break;case`notifications/cancelled`:break;case`notifications/progress`:break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`sampling/createMessage`:if(!this._capabilities.sampling)throw Error(`Client does not support sampling capability (required for ${e})`);break;case`elicitation/create`:if(!this._capabilities.elicitation)throw Error(`Client does not support elicitation capability (required for ${e})`);break;case`roots/list`:if(!this._capabilities.roots)throw Error(`Client does not support roots capability (required for ${e})`);break;case`tasks/get`:case`tasks/list`:case`tasks/result`:case`tasks/cancel`:if(!this._capabilities.tasks)throw Error(`Client does not support tasks capability (required for ${e})`);break;case`ping`:break}}assertTaskCapability(e){Ai(this._serverCapabilities?.tasks?.requests,e,`Server`)}assertTaskHandlerCapability(e){this._capabilities&&ji(this._capabilities.tasks?.requests,e,`Client`)}async ping(e){return this.request({method:`ping`},_,e)}async complete(e,t){return this.request({method:`completion/complete`,params:e},l,t)}async setLoggingLevel(e,t){return this.request({method:`logging/setLevel`,params:{level:e}},_,t)}async getPrompt(e,t){return this.request({method:`prompts/get`,params:e},b,t)}async listPrompts(e,t){return this.request({method:`prompts/list`,params:e},ee,t)}async listResources(e,t){return this.request({method:`resources/list`,params:e},re,t)}async listResourceTemplates(e,t){return this.request({method:`resources/templates/list`,params:e},ne,t)}async readResource(e,t){return this.request({method:`resources/read`,params:e},me,t)}async subscribeResource(e,t){return this.request({method:`resources/subscribe`,params:e},_,t)}async unsubscribeResource(e,t){return this.request({method:`resources/unsubscribe`,params:e},_,t)}async callTool(e,t=i,n){if(this.isToolTaskRequired(e.name))throw new N(v.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let r=await this.request({method:`tools/call`,params:e},t,n),a=this.getToolOutputValidator(e.name);if(a){if(!r.structuredContent&&!r.isError)throw new N(v.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(r.structuredContent)try{let e=a(r.structuredContent);if(!e.valid)throw new N(v.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)}catch(e){throw e instanceof N?e:new N(v.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)}}return r}isToolTask(e){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let t of e){if(t.outputSchema){let e=this._jsonSchemaValidator.getValidator(t.outputSchema);this._cachedToolOutputValidators.set(t.name,e)}let e=t.execution?.taskSupport;(e===`required`||e===`optional`)&&this._cachedKnownTaskTools.add(t.name),e===`required`&&this._cachedRequiredTaskTools.add(t.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,t){let n=await this.request({method:`tools/list`,params:e},se,t);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(e,t,n,r){let i=k.safeParse(n);if(!i.success)throw Error(`Invalid ${e} listChanged options: ${i.error.message}`);if(typeof n.onChanged!=`function`)throw Error(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:a,debounceMs:o}=i.data,{onChanged:s}=n,c=async()=>{if(!a){s(null,null);return}try{let e=await r();s(null,e)}catch(e){let t=e instanceof Error?e:Error(String(e));s(t,null)}};this.setNotificationHandler(t,()=>{if(o){let t=this._listChangedDebounceTimers.get(e);t&&clearTimeout(t);let n=setTimeout(c,o);this._listChangedDebounceTimers.set(e,n)}else c()})}async sendRootsListChanged(){return this.notification({method:`notifications/roots/list_changed`})}},Fi=class{constructor(e){this._server=e}requestStream(e,t,n){return this._server.requestStream(e,t,n)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._server.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}},Ii=class extends lr{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ce.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{let n=this._loggingLevels.get(t);return n?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(n):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new Oi,this.setRequestHandler(w,e=>this._oninitialize(e)),this.setNotificationHandler(E,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(ve,async(e,t)=>{let n=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:r}=e.params,i=ce.safeParse(r);return i.success&&this._loggingLevels.set(n,i.data),{}})}get experimental(){return this._experimental||={tasks:new Fi(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=dr(this._capabilities,e)}setRequestHandler(e,t){let n=ar(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let a;if(q(n)){let e=n;a=e._zod?.def?.value??e.value}else{let e=n;a=e._def?.value??e.value}if(typeof a!=`string`)throw Error(`Schema method literal must be a string`);return a===`tools/call`?super.setRequestHandler(e,async(e,n)=>{let a=J(r,e);if(!a.success){let e=a.error instanceof Error?a.error.message:String(a.error);throw new N(v.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:o}=a.data,s=await Promise.resolve(t(e,n));if(o.task){let e=J(p,s);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new N(v.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let c=J(i,s);if(!c.success){let e=c.error instanceof Error?c.error.message:String(c.error);throw new N(v.InvalidParams,`Invalid tools/call result: ${e}`)}return c.data}):super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`);break;case`ping`:break}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/elicitation/complete`:if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`);break;case`notifications/cancelled`:break;case`notifications/progress`:break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`completion/complete`:if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`tasks/get`:case`tasks/list`:case`tasks/result`:case`tasks/cancel`:if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`);break;case`ping`:case`initialize`:break}}assertTaskCapability(e){ji(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){this._capabilities&&Ai(this._capabilities.tasks?.requests,e,`Server`)}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:_e.includes(t)?t:O,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:`ping`},_)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return e.tools?this.request({method:`sampling/createMessage`,params:e},f,t):this.request({method:`sampling/createMessage`,params:e},d,t)}async elicitInput(e,t){switch(e.mode??`form`){case`url`:{if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support url elicitation.`);let n=e;return this.request({method:`elicitation/create`,params:n},g,t)}case`form`:{if(!this._clientCapabilities?.elicitation?.form)throw Error(`Client does not support form elicitation.`);let n=e.mode===`form`?e:{...e,mode:`form`},r=await this.request({method:`elicitation/create`,params:n},g,t);if(r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new N(v.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof N?e:new N(v.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for notifications/elicitation/complete)`);return()=>this.notification({method:`notifications/elicitation/complete`,params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:`roots/list`,params:e},ie,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:`notifications/message`,params:e})}async sendResourceUpdated(e){return this.notification({method:`notifications/resources/updated`,params:e})}async sendResourceListChanged(){return this.notification({method:`notifications/resources/list_changed`})}async sendToolListChanged(){return this.notification({method:`notifications/tools/list_changed`})}async sendPromptListChanged(){return this.notification({method:`notifications/prompts/list_changed`})}},Li=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
29
29
|
`);if(e===-1)return null;let t=this._buffer.toString(`utf8`,0,e).replace(/\r$/,``);return this._buffer=this._buffer.subarray(e+1),Ri(t)}clear(){this._buffer=void 0}};function Ri(e){return D.parse(JSON.parse(e))}function zi(e){return JSON.stringify(e)+`
|
|
30
30
|
`}var Bi=class{constructor(e=Xe.stdin,t=Xe.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new Li,this._started=!1,this._ondata=e=>{this._readBuffer.append(e),this.processReadBuffer()},this._onerror=e=>{this.onerror?.(e)}}async start(){if(this._started)throw Error(`StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.`);this._started=!0,this._stdin.on(`data`,this._ondata),this._stdin.on(`error`,this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off(`data`,this._ondata),this._stdin.off(`error`,this._onerror),this._stdin.listenerCount(`data`)===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(t=>{let n=zi(e);this._stdout.write(n)?t():this._stdout.once(`drain`,t)})}};export{$e as AccessControlBlockError,Pi as Client,et as ConfigurationError,Ze as InMemoryEventStore,tt as ProxyConnectionError,Li as ReadBuffer,Ii as Server,Bi as StdioServerTransport,Dt as compressClientInfo,yt as getSessionData,At as initializeTrafficMirror,Pt as logRequestCounts,It as proxyServer,St as redactCliArgs,zi as serializeMessage,ir as startHTTPServer};
|
|
31
|
-
//# sourceMappingURL=stdio-
|
|
31
|
+
//# sourceMappingURL=stdio-xswu-UH5.js.map
|